5732d6b98c7dd8345eece1969a465f708d40cbbe
[snf-image-creator] / image_creator / os_type / windows.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright 2012 GRNET S.A. All rights reserved.
4 #
5 # Redistribution and use in source and binary forms, with or
6 # without modification, are permitted provided that the following
7 # conditions are met:
8 #
9 #   1. Redistributions of source code must retain the above
10 #      copyright notice, this list of conditions and the following
11 #      disclaimer.
12 #
13 #   2. Redistributions in binary form must reproduce the above
14 #      copyright notice, this list of conditions and the following
15 #      disclaimer in the documentation and/or other materials
16 #      provided with the distribution.
17 #
18 # THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
19 # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21 # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
22 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
25 # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26 # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 # POSSIBILITY OF SUCH DAMAGE.
30 #
31 # The views and conclusions contained in the software and
32 # documentation are those of the authors and should not be
33 # interpreted as representing official policies, either expressed
34 # or implied, of GRNET S.A.
35
36 """This module hosts OS-specific code common for the various Microsoft
37 Windows OSs."""
38
39 from image_creator.os_type import OSBase, sysprep
40 from image_creator.util import FatalError, check_guestfs_version, get_command
41 from image_creator.winexe import WinEXE, WinexeTimeout
42
43 import hivex
44 import tempfile
45 import os
46 import time
47 import random
48 import string
49 import subprocess
50 import struct
51
52 kvm = get_command('kvm')
53
54 BOOT_TIMEOUT = 300
55
56 # For more info see: http://technet.microsoft.com/en-us/library/jj612867.aspx
57 KMS_CLIENT_SETUP_KEYS = {
58     "Windows 8 Professional": "NG4HW-VH26C-733KW-K6F98-J8CK4",
59     "Windows 8 Professional N": "XCVCF-2NXM9-723PB-MHCB7-2RYQQ",
60     "Windows 8 Enterprise": "32JNW-9KQ84-P47T8-D8GGY-CWCK7",
61     "Windows 8 Enterprise N": "JMNMF-RHW7P-DMY6X-RF3DR-X2BQT",
62     "Windows Server 2012 Core": "BN3D2-R7TKB-3YPBD-8DRP2-27GG4",
63     "Windows Server 2012 Core N": "8N2M2-HWPGY-7PGT9-HGDD8-GVGGY",
64     "Windows Server 2012 Core Single Language":
65     "2WN2H-YGCQR-KFX6K-CD6TF-84YXQ",
66     "Windows Server 2012 Core Country Specific":
67     "4K36P-JN4VD-GDC6V-KDT89-DYFKP",
68     "Windows Server 2012 Server Standard": "XC9B7-NBPP2-83J2H-RHMBY-92BT4",
69     "Windows Server 2012 Standard Core": "XC9B7-NBPP2-83J2H-RHMBY-92BT4",
70     "Windows Server 2012 MultiPoint Standard": "HM7DN-YVMH3-46JC3-XYTG7-CYQJJ",
71     "Windows Server 2012 MultiPoint Premium": "XNH6W-2V9GX-RGJ4K-Y8X6F-QGJ2G",
72     "Windows Server 2012 Datacenter": "48HP8-DN98B-MYWDG-T2DCC-8W83P",
73     "Windows Server 2012 Datacenter Core": "48HP8-DN98B-MYWDG-T2DCC-8W83P",
74     "Windows 7 Professional": "FJ82H-XT6CR-J8D7P-XQJJ2-GPDD4",
75     "Windows 7 Professional N": "MRPKT-YTG23-K7D7T-X2JMM-QY7MG",
76     "Windows 7 Professional E": "W82YF-2Q76Y-63HXB-FGJG9-GF7QX",
77     "Windows 7 Enterprise": "33PXH-7Y6KF-2VJC9-XBBR8-HVTHH",
78     "Windows 7 Enterprise N": "YDRBP-3D83W-TY26F-D46B2-XCKRJ",
79     "Windows 7 Enterprise E": "C29WB-22CC8-VJ326-GHFJW-H9DH4",
80     "Windows Server 2008 R2 Web": "6TPJF-RBVHG-WBW2R-86QPH-6RTM4",
81     "Windows Server 2008 R2 HPC edition": "TT8MH-CG224-D3D7Q-498W2-9QCTX",
82     "Windows Server 2008 R2 Standard": "YC6KT-GKW9T-YTKYR-T4X34-R7VHC",
83     "Windows Server 2008 R2 Enterprise": "489J6-VHDMP-X63PK-3K798-CPX3Y",
84     "Windows Server 2008 R2 Datacenter": "74YFP-3QFB3-KQT8W-PMXWJ-7M648",
85     "Windows Server 2008 R2 for Itanium-based Systems":
86     "GT63C-RJFQ3-4GMB6-BRFB9-CB83V",
87     "Windows Vista Business": "YFKBB-PQJJV-G996G-VWGXY-2V3X8",
88     "Windows Vista Business N": "HMBQG-8H2RH-C77VX-27R82-VMQBT",
89     "Windows Vista Enterprise": "VKK3X-68KWM-X2YGT-QR4M6-4BWMV",
90     "Windows Vista Enterprise N": "VTC42-BM838-43QHV-84HX6-XJXKV",
91     "Windows Web Server 2008": "WYR28-R7TFJ-3X2YQ-YCY4H-M249D",
92     "Windows Server 2008 Standard": "TM24T-X9RMF-VWXK6-X8JC9-BFGM2",
93     "Windows Server 2008 Standard without Hyper-V":
94     "W7VD6-7JFBR-RX26B-YKQ3Y-6FFFJ",
95     "Windows Server 2008 Enterprise":
96     "YQGMW-MPWTJ-34KDK-48M3W-X4Q6V",
97     "Windows Server 2008 Enterprise without Hyper-V":
98     "39BXF-X8Q23-P2WWT-38T2F-G3FPG",
99     "Windows Server 2008 HPC": "RCTX3-KWVHP-BR6TB-RB6DM-6X7HP",
100     "Windows Server 2008 Datacenter": "7M67G-PC374-GR742-YH8V4-TCBY3",
101     "Windows Server 2008 Datacenter without Hyper-V":
102     "22XQ2-VRXRG-P8D42-K34TD-G3QQC",
103     "Windows Server 2008 for Itanium-Based Systems":
104     "4DWFP-JF3DJ-B7DTH-78FJB-PDRHK"}
105
106
107 class Windows(OSBase):
108     """OS class for Windows"""
109     def __init__(self, image, **kargs):
110         super(Windows, self).__init__(image, **kargs)
111
112         device = self.g.part_to_dev(self.root)
113
114         self.last_part_num = self.g.part_list(device)[-1]['part_num']
115         self.last_drive = None
116         self.system_drive = None
117
118         for drive, partition in self.g.inspect_get_drive_mappings(self.root):
119             if partition == "%s%d" % (device, self.last_part_num):
120                 self.last_drive = drive
121             if partition == self.root:
122                 self.system_drive = drive
123
124         assert self.system_drive
125
126         self.product_name = self.g.inspect_get_product_name(self.root)
127
128     def needed_sysprep_params(self):
129         """Returns a list of needed sysprep parameters. Each element in the
130         list is a SysprepParam object.
131         """
132         password = self.SysprepParam(
133             'password', 'Image Administrator Password', 20, lambda x: True)
134
135         return [password]
136
137     @sysprep('Disabling IPv6 privacy extensions')
138     def disable_ipv6_privacy_extensions(self):
139         """Disable IPv6 privacy extensions"""
140
141         self._guest_exec('netsh interface ipv6 set global '
142                          'randomizeidentifiers=disabled store=persistent')
143
144     @sysprep('Disabling Teredo interface')
145     def disable_teredo(self):
146         """Disable Teredo interface"""
147
148         self._guest_exec('netsh interface teredo set state disabled')
149
150     @sysprep('Disabling ISATAP Adapters')
151     def disable_isatap(self):
152         """Disable ISATAP Adapters"""
153
154         self._guest_exec('netsh interface isa set state disabled')
155
156     @sysprep('Enabling ping responses')
157     def enable_pings(self):
158         """Enable ping responses"""
159
160         self._guest_exec('netsh firewall set icmpsetting 8')
161
162     @sysprep('Disabling hibernation support')
163     def disable_hibernation(self):
164         """Disable hibernation support and remove the hibernation file"""
165
166         self._guest_exec(r'powercfg.exe /hibernate off')
167
168     @sysprep('Setting the system clock to UTC')
169     def utc(self):
170         """Set the hardware clock to UTC"""
171
172         path = r'HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation'
173         self._guest_exec(
174             r'REG ADD %s /v RealTimeIsUniversal /t REG_DWORD /d 1 /f' % path)
175
176     @sysprep('Clearing the event logs')
177     def clear_logs(self):
178         """Clear all the event logs"""
179
180         self._guest_exec(
181             r"cmd /q /c for /f %l in ('wevtutil el') do wevtutil cl %l")
182
183     @sysprep('Executing Sysprep on the image (may take more that 10 minutes)')
184     def microsoft_sysprep(self):
185         """Run the Microsoft System Preparation Tool. This will remove
186         system-specific data and will make the image ready to be deployed.
187         After this no other task may run.
188         """
189
190         self._guest_exec(r'C:\Windows\system32\sysprep\sysprep '
191                          r'/quiet /generalize /oobe /shutdown')
192         self.syspreped = True
193
194     @sysprep('Converting the image into a KMS client', enabled=False)
195     def kms_client_setup(self):
196         """Install the appropriate KMS client setup key to the image to convert
197         it to a KMS client. Computers that are running volume licensing
198         editions of Windows 8, Windows Server 2012, Windows 7, Windows Server
199         2008 R2, Windows Vista, and Windows Server 2008 are, by default, KMS
200         clients with no additional configuration needed.
201         """
202         try:
203             setup_key = KMS_CLIENT_SETUP_KEYS[self.product_name]
204         except KeyError:
205             self.out.warn(
206                 "Don't know the KMS client setup key for product: `%s'" %
207                 self.product_name)
208             return
209
210         self._guest_exec(
211             "cscript \Windows\system32\slmgr.vbs /ipk %s" % setup_key)
212
213     @sysprep('Shrinking the last filesystem')
214     def shrink(self):
215         """Shrink the last filesystem. Make sure the filesystem is defragged"""
216
217         # Query for the maximum number of reclaimable bytes
218         cmd = (
219             r'cmd /Q /C "SET SCRIPT=%TEMP%\QUERYMAX_%RANDOM%.TXT & ' +
220             r'ECHO SELECT DISK 0 > %SCRIPT% & ' +
221             'ECHO SELECT PARTITION %d >> %%SCRIPT%% & ' % self.last_part_num +
222             r'ECHO SHRINK QUERYMAX >> %SCRIPT% & ' +
223             r'ECHO EXIT >> %SCRIPT% & ' +
224             r'DISKPART /S %SCRIPT% & ' +
225             r'IF ERRORLEVEL 1 EXIT /B 1 & ' +
226             r'DEL /Q %SCRIPT%"')
227
228         stdout, stderr, rc = self._guest_exec(cmd)
229
230         querymax = None
231         for line in stdout.splitlines():
232             # diskpart will return something like this:
233             #
234             #   The maximum number of reclaimable bytes is: xxxx MB
235             #
236             if line.find('reclaimable') >= 0:
237                 querymax = line.split(':')[1].split()[0].strip()
238                 assert querymax.isdigit(), \
239                     "Number of reclaimable bytes not a number"
240
241         if querymax is None:
242             FatalError("Error in shrinking! "
243                        "Couldn't find the max number of reclaimable bytes!")
244
245         querymax = int(querymax)
246         # From ntfsresize:
247         # Practically the smallest shrunken size generally is at around
248         # "used space" + (20-200 MB). Please also take into account that
249         # Windows might need about 50-100 MB free space left to boot safely.
250         # I'll give 100MB extra space just to be sure
251         querymax -= 100
252
253         if querymax < 0:
254             self.out.warn("Not enought available space to shrink the image!")
255             return
256
257         cmd = (
258             r'cmd /Q /C "SET SCRIPT=%TEMP%\QUERYMAX_%RANDOM%.TXT & ' +
259             r'ECHO SELECT DISK 0 > %SCRIPT% & ' +
260             'ECHO SELECT PARTITION %d >> %%SCRIPT%% & ' % self.last_part_num +
261             'ECHO SHRINK DESIRED=%d >> %%SCRIPT%% & ' % querymax +
262             r'ECHO EXIT >> %SCRIPT% & ' +
263             r'DISKPART /S %SCRIPT% & ' +
264             r'IF ERRORLEVEL 1 EXIT /B 1 & ' +
265             r'DEL /Q %SCRIPT%"')
266
267         stdout, stderr, rc = self._guest_exec(cmd)
268
269         for line in stdout.splitlines():
270             if line.find('shrunk') >= 0:
271                 self.out.output(line)
272
273     def do_sysprep(self):
274         """Prepare system for image creation."""
275
276         if getattr(self, 'syspreped', False):
277             raise FatalError("Image is already syspreped!")
278
279         txt = "System preparation parameter: `%s' is needed but missing!"
280         for param in self.needed_sysprep_params():
281             if param[0] not in self.sysprep_params:
282                 raise FatalError(txt % param[0])
283
284         self.mount(readonly=False)
285         try:
286             disabled_uac = self._update_uac_remote_setting(1)
287             token = self._enable_os_monitor()
288
289             # disable the firewalls
290             firewall_states = self._update_firewalls(0, 0, 0)
291
292             # Delete the pagefile. It will be recreated when the system boots
293             systemroot = self.g.inspect_get_windows_systemroot(self.root)
294             pagefile = "%s/pagefile.sys" % systemroot
295             self.g.rm_rf(self.g.case_sensitive_path(pagefile))
296
297         finally:
298             self.umount()
299
300         self.out.output("Shutting down helper VM ...", False)
301         self.g.sync()
302         # guestfs_shutdown which is the prefered way to shutdown the backend
303         # process was introduced in version 1.19.16
304         if check_guestfs_version(self.g, 1, 19, 16) >= 0:
305             ret = self.g.shutdown()
306         else:
307             ret = self.g.kill_subprocess()
308
309         self.out.success('done')
310
311         vm = None
312         monitor = None
313         try:
314             self.out.output("Starting windows VM ...", False)
315             monitorfd, monitor = tempfile.mkstemp()
316             os.close(monitorfd)
317             vm, display = self._create_vm(monitor)
318             self.out.success("started (console on vnc display: %d)." % display)
319
320             self.out.output("Waiting for OS to boot ...", False)
321             if not self._wait_on_file(monitor, token):
322                 raise FatalError("Windows booting timed out.")
323             else:
324                 time.sleep(10)  # Just to be sure everything is up
325                 self.out.success('done')
326
327             self.out.output("Disabling automatic logon ...", False)
328             self._disable_autologon()
329             self.out.success('done')
330
331             self.out.output('Preparing system from image creation:')
332
333             tasks = self.list_syspreps()
334             enabled = filter(lambda x: x.enabled, tasks)
335             size = len(enabled)
336
337             # Make sure shrink runs in the end, before ms sysprep
338             enabled = filter(lambda x: self.sysprep_info(x).name != 'shrink',
339                              enabled)
340
341             shrink_enabled = False
342             if len(enabled) != size:
343                 enabled.append(self.shrink)
344                 shrink_enabled = True
345
346             # Make sure the ms sysprep is the last task to run if it is enabled
347             enabled = filter(
348                 lambda x: self.sysprep_info(x).name != 'microsoft-sysprep',
349                 enabled)
350
351             ms_sysprep_enabled = False
352             if len(enabled) != size:
353                 enabled.append(self.microsoft_sysprep)
354                 ms_sysprep_enabled = True
355
356             cnt = 0
357             for task in enabled:
358                 cnt += 1
359                 self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False)
360                 task()
361                 setattr(task.im_func, 'executed', True)
362
363             self.out.output("Sending shut down command ...", False)
364             if not ms_sysprep_enabled:
365                 self._shutdown()
366             self.out.success("done")
367
368             self.out.output("Waiting for windows to shut down ...", False)
369             vm.wait()
370             self.out.success("done")
371         finally:
372             if monitor is not None:
373                 os.unlink(monitor)
374
375             if vm is not None:
376                 self._destroy_vm(vm)
377
378             self.out.output("Relaunching helper VM (may take a while) ...",
379                             False)
380             self.g.launch()
381             self.out.success('done')
382
383             self.mount(readonly=False)
384             try:
385                 if disabled_uac:
386                     self._update_uac_remote_setting(0)
387
388                 self._update_firewalls(*firewall_states)
389             finally:
390                 self.umount()
391
392     def _create_vm(self, monitor):
393         """Create a VM with the image attached as the disk
394
395             monitor: a file to be used to monitor when the OS is up
396         """
397
398         def random_mac():
399             mac = [0x00, 0x16, 0x3e,
400                    random.randint(0x00, 0x7f),
401                    random.randint(0x00, 0xff),
402                    random.randint(0x00, 0xff)]
403
404             return ':'.join(map(lambda x: "%02x" % x, mac))
405
406         # Use ganeti's VNC port range for a random vnc port
407         vnc_port = random.randint(11000, 14999)
408         display = vnc_port - 5900
409
410         vm = kvm(
411             '-smp', '1', '-m', '1024', '-drive',
412             'file=%s,format=raw,cache=unsafe,if=virtio' % self.image.device,
413             '-netdev', 'type=user,hostfwd=tcp::445-:445,id=netdev0',
414             '-device', 'virtio-net-pci,mac=%s,netdev=netdev0' % random_mac(),
415             '-vnc', ':%d' % display, '-serial', 'file:%s' % monitor, _bg=True)
416
417         return vm, display
418
419     def _destroy_vm(self, vm):
420         """Destroy a VM previously created by _create_vm"""
421         if vm.process.alive:
422             vm.terminate()
423
424     def _shutdown(self):
425         """Shuts down the windows VM"""
426         self._guest_exec(r'shutdown /s /t 5')
427
428     def _wait_on_file(self, fname, msg):
429         """Wait until a message appears on a file"""
430
431         for i in range(BOOT_TIMEOUT):
432             time.sleep(1)
433             with open(fname) as f:
434                 for line in f:
435                     if line.startswith(msg):
436                         return True
437         return False
438
439     def _disable_autologon(self):
440         """Disable automatic logon on the windows image"""
441
442         winlogon = \
443             r'"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"'
444
445         self._guest_exec('REG DELETE %s /v DefaultUserName /f' % winlogon)
446         self._guest_exec('REG DELETE %s /v DefaultPassword /f' % winlogon)
447         self._guest_exec('REG DELETE %s /v AutoAdminLogon /f' % winlogon)
448
449     def _registry_file_path(self, regfile):
450         """Retrieves the case sensitive path to a registry file"""
451
452         systemroot = self.g.inspect_get_windows_systemroot(self.root)
453         path = "%s/system32/config/%s" % (systemroot, regfile)
454         try:
455             path = self.g.case_sensitive_path(path)
456         except RuntimeError as e:
457             raise FatalError("Unable to retrieve registry file: %s. Reason: %s"
458                              % (regfile, str(e)))
459         return path
460
461     def _enable_os_monitor(self):
462         """Add a script in the registry that will send a random string to the
463         first serial port when the windows image finishes booting.
464         """
465
466         token = "".join(random.choice(string.ascii_letters) for x in range(16))
467
468         path = self._registry_file_path('SOFTWARE')
469         softwarefd, software = tempfile.mkstemp()
470         try:
471             os.close(softwarefd)
472             self.g.download(path, software)
473
474             h = hivex.Hivex(software, write=True)
475
476             # Enable automatic logon.
477             # This is needed because we need to execute a script that we add in
478             # the RunOnce registry entry and those programs only get executed
479             # when a user logs on. There is a RunServicesOnce registry entry
480             # whose keys get executed in the background when the logon dialog
481             # box first appears, but they seem to only work with services and
482             # not arbitrary command line expressions :-(
483             #
484             # Instructions on how to turn on automatic logon in Windows can be
485             # found here: http://support.microsoft.com/kb/324737
486             #
487             # Warning: Registry change will not work if the “Logon Banner” is
488             # defined on the server either by a Group Policy object (GPO) or by
489             # a local policy.
490
491             winlogon = h.root()
492             for child in ('Microsoft', 'Windows NT', 'CurrentVersion',
493                           'Winlogon'):
494                 winlogon = h.node_get_child(winlogon, child)
495
496             h.node_set_value(
497                 winlogon,
498                 {'key': 'DefaultUserName', 't': 1,
499                  'value': "Administrator".encode('utf-16le')})
500             h.node_set_value(
501                 winlogon,
502                 {'key': 'DefaultPassword', 't': 1,
503                  'value':  self.sysprep_params['password'].encode('utf-16le')})
504             h.node_set_value(
505                 winlogon,
506                 {'key': 'AutoAdminLogon', 't': 1,
507                  'value': "1".encode('utf-16le')})
508
509             key = h.root()
510             for child in ('Microsoft', 'Windows', 'CurrentVersion'):
511                 key = h.node_get_child(key, child)
512
513             runonce = h.node_get_child(key, "RunOnce")
514             if runonce is None:
515                 runonce = h.node_add_child(key, "RunOnce")
516
517             value = (
518                 r'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe '
519                 r'-ExecutionPolicy RemoteSigned '
520                 r'"&{$port=new-Object System.IO.Ports.SerialPort COM1,9600,'
521                 r'None,8,one;$port.open();$port.WriteLine(\"' + token + r'\");'
522                 r'$port.Close()}"').encode('utf-16le')
523
524             h.node_set_value(runonce,
525                              {'key': "BootMonitor", 't': 1, 'value': value})
526
527             value = (
528                 r'REG ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion'
529                 r'\policies\system /v LocalAccountTokenFilterPolicy'
530                 r' /t REG_DWORD /d 1 /f').encode('utf-16le')
531
532             h.node_set_value(runonce,
533                              {'key': "UpdateRegistry", 't': 1, 'value': value})
534
535             h.commit(None)
536
537             self.g.upload(software, path)
538         finally:
539             os.unlink(software)
540
541         return token
542
543     def _update_firewalls(self, domain, public, standard):
544         """Enables or disables the firewall for the Domain, the Public and the
545         Standard profile. Returns a triplete with the old values.
546
547         1 will enable a firewall and 0 will disable it
548         """
549
550         if domain not in (0, 1):
551             raise ValueError("Valid values for domain parameter are 0 and 1")
552
553         if public not in (0, 1):
554             raise ValueError("Valid values for public parameter are 0 and 1")
555
556         if standard not in (0, 1):
557             raise ValueError("Valid values for standard parameter are 0 and 1")
558
559         path = self._registry_file_path("SYSTEM")
560         systemfd, system = tempfile.mkstemp()
561         try:
562             os.close(systemfd)
563             self.g.download(path, system)
564
565             h = hivex.Hivex(system, write=True)
566
567             select = h.node_get_child(h.root(), 'Select')
568             current_value = h.node_get_value(select, 'Current')
569
570             # expecting a little endian dword
571             assert h.value_type(current_value)[1] == 4
572             current = "%03d" % h.value_dword(current_value)
573
574             firewall_policy = h.root()
575             for child in ('ControlSet%s' % current, 'services', 'SharedAccess',
576                           'Parameters', 'FirewallPolicy'):
577                 firewall_policy = h.node_get_child(firewall_policy, child)
578
579             old_values = []
580             new_values = [domain, public, standard]
581             for profile in ('Domain', 'Public', 'Standard'):
582                 node = h.node_get_child(firewall_policy, '%sProfile' % profile)
583
584                 old_value = h.node_get_value(node, 'EnableFirewall')
585
586                 # expecting a little endian dword
587                 assert h.value_type(old_value)[1] == 4
588                 old_values.append(h.value_dword(old_value))
589
590                 h.node_set_value(
591                     node, {'key': 'EnableFirewall', 't': 4L,
592                            'value': struct.pack("<I", new_values.pop(0))})
593
594             h.commit(None)
595             self.g.upload(system, path)
596
597         finally:
598             os.unlink(system)
599
600         return old_values
601
602     def _update_uac_remote_setting(self, value):
603         """Updates the registry key value:
604         [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies
605         \System]"LocalAccountTokenFilterPolicy"
606
607         value = 1 will disable the UAC remote restrictions
608         value = 0 will enable the UAC remote restrictions
609
610         For more info see here: http://support.microsoft.com/kb/951016
611
612         Returns:
613             True if the key is changed
614             False if the key is unchanged
615         """
616
617         if value not in (0, 1):
618             raise ValueError("Valid values for value parameter are 0 and 1")
619
620         path = self._registry_file_path('SOFTWARE')
621         softwarefd, software = tempfile.mkstemp()
622         try:
623             os.close(softwarefd)
624             self.g.download(path, software)
625
626             h = hivex.Hivex(software, write=True)
627
628             key = h.root()
629             for child in ('Microsoft', 'Windows', 'CurrentVersion', 'Policies',
630                           'System'):
631                 key = h.node_get_child(key, child)
632
633             policy = None
634             for val in h.node_values(key):
635                 if h.value_key(val) == "LocalAccountTokenFilterPolicy":
636                     policy = val
637
638             if policy is not None:
639                 dword = h.value_dword(policy)
640                 if dword == value:
641                     return False
642             elif value == 0:
643                 return False
644
645             new_value = {'key': "LocalAccountTokenFilterPolicy", 't': 4L,
646                          'value': struct.pack("<I", value)}
647
648             h.node_set_value(key, new_value)
649             h.commit(None)
650
651             self.g.upload(software, path)
652
653         finally:
654             os.unlink(software)
655
656         return True
657
658     def _do_collect_metadata(self):
659         """Collect metadata about the OS"""
660         super(Windows, self)._do_collect_metadata()
661         self.meta["USERS"] = " ".join(self._get_users())
662
663     def _get_users(self):
664         """Returns a list of users found in the images"""
665         path = self._registry_file_path('SAM')
666         samfd, sam = tempfile.mkstemp()
667         try:
668             os.close(samfd)
669             self.g.download(path, sam)
670
671             h = hivex.Hivex(sam)
672
673             key = h.root()
674             # Navigate to /SAM/Domains/Account/Users/Names
675             for child in ('SAM', 'Domains', 'Account', 'Users', 'Names'):
676                 key = h.node_get_child(key, child)
677
678             users = [h.node_name(x) for x in h.node_children(key)]
679
680         finally:
681             os.unlink(sam)
682
683         # Filter out the guest account
684         return filter(lambda x: x != "Guest", users)
685
686     def _guest_exec(self, command, fatal=True):
687         """Execute a command on a windows VM"""
688
689         passwd = self.sysprep_params['password']
690
691         winexe = WinEXE('Administrator', passwd, 'localhost')
692         winexe.runas('Administrator', passwd).uninstall()
693
694         try:
695             (stdout, stderr, rc) = winexe.run(command)
696         except WinexeTimeout:
697             FatalError("Command: `%s' timeout out." % command)
698
699         if rc != 0 and fatal:
700             reason = stderr if len(stderr) else stdout
701             self.out.output("Command: `%s' failed (rc=%d). Reason: %s" %
702                             (command, rc, reason))
703             raise FatalError("Command: `%s' failed (rc=%d). Reason: %s" %
704                              (command, rc, reason))
705
706         return (stdout, stderr, rc)
707
708 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :