3e38aa3bf8cfda2aba2d3cf28b568aa5a39ec0e0
[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
42 import hivex
43 import tempfile
44 import os
45 import time
46 import random
47 import string
48 import subprocess
49
50 kvm = get_command('kvm')
51
52 BOOT_TIMEOUT = 300
53
54
55 class Windows(OSBase):
56     """OS class for Windows"""
57
58     def needed_sysprep_params(self):
59         """Returns a list of needed sysprep parameters. Each element in the
60         list is a SysprepParam object.
61         """
62         password = self.SysprepParam(
63             'password', 'Image Administrator Password', 20, lambda x: True)
64
65         return [password]
66
67     @sysprep('Disabling IPv6 privacy extensions')
68     def disable_ipv6_privacy_extensions(self):
69         """Disable IPv6 privacy extensions"""
70
71         self._guest_exec('netsh interface ipv6 set global '
72                          'randomizeidentifiers=disabled store=persistent')
73
74     @sysprep('Disabling Teredo interface')
75     def disable_teredo(self):
76         """Disable Teredo interface"""
77
78         self._guest_exec('netsh interface teredo set state disabled')
79
80     @sysprep('Disabling ISATAP Adapters')
81     def disable_isatap(self):
82         """Disable ISATAP Adapters"""
83
84         self._guest_exec('netsh interface isa set state disabled')
85
86     @sysprep('Enabling ping responses')
87     def enable_pings(self):
88         """Enable ping responces"""
89
90         self._guest_exec('netsh firewall set icmpsetting 8')
91
92     @sysprep('Disabling hibernation support')
93     def disable_hibernation(self):
94         """Disable hibernation support and remove the hibernation file"""
95
96         self._guest_exec(r'powercfg.exe /hibernate off')
97
98     @sysprep('Setting the system clock to UTC')
99     def utc(self):
100         """Set the hardware clock to UTC"""
101
102         path = r'HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation'
103         self._guest_exec(
104             r'REG ADD %s /v RealTimeIsUniversal /t REG_DWORD /d 1 /f' % path)
105
106     @sysprep('Executing sysprep on the image (may take more that 10 minutes)')
107     def microsoft_sysprep(self):
108         """Run the Microsoft System Preparation Tool. This will remove
109         system-specific data and will make the image ready to be deployed.
110         After this no other task may run.
111         """
112
113         self._guest_exec(r'C:\Windows\system32\sysprep\sysprep '
114                          r'/quiet /generalize /oobe /shutdown')
115         self.syspreped = True
116
117     def do_sysprep(self):
118         """Prepare system for image creation."""
119
120         if getattr(self, 'syspreped', False):
121             raise FatalError("Image is already syspreped!")
122
123         txt = "System preparation parameter: `%s' is needed but missing!"
124         for param in self.needed_sysprep_params():
125             if param[0] not in self.sysprep_params:
126                 raise FatalError(txt % param[0])
127
128         self.mount(readonly=False)
129         try:
130             disabled_uac = self._update_uac_remote_setting(1)
131             token = self._enable_os_monitor()
132
133             # disable the firewalls
134             firewall_states = self._update_firewalls(0, 0, 0)
135
136             # Delete the pagefile. It will be recreated when the system boots
137             systemroot = self.g.inspect_get_windows_systemroot(self.root)
138             pagefile = "%s/pagefile.sys" % systemroot
139             self.g.rm_rf(self.g.case_sensitive_path(pagefile))
140
141         finally:
142             self.umount()
143
144         self.out.output("Shutting down helper VM ...", False)
145         self.g.sync()
146         # guestfs_shutdown which is the prefered way to shutdown the backend
147         # process was introduced in version 1.19.16
148         if check_guestfs_version(self.g, 1, 19, 16) >= 0:
149             ret = self.g.shutdown()
150         else:
151             ret = self.g.kill_subprocess()
152
153         self.out.success('done')
154
155         vm = None
156         monitor = None
157         try:
158             self.out.output("Starting windows VM ...", False)
159             monitorfd, monitor = tempfile.mkstemp()
160             os.close(monitorfd)
161             vm, display = self._create_vm(monitor)
162             self.out.success("started (console on vnc display: %d)." % display)
163
164             self.out.output("Waiting for OS to boot ...", False)
165             if not self._wait_on_file(monitor, token):
166                 raise FatalError("Windows booting timed out.")
167             else:
168                 self.out.success('done')
169
170             self.out.output("Disabling automatic logon ...", False)
171             self._disable_autologon()
172             self.out.success('done')
173
174             self.out.output('Preparing system from image creation:')
175
176             tasks = self.list_syspreps()
177             enabled = filter(lambda x: x.enabled, tasks)
178
179             size = len(enabled)
180
181             # Make sure the ms sysprep is the last task to run if it is enabled
182             enabled = filter(
183                 lambda x: x.im_func.func_name != 'microsoft_sysprep', enabled)
184
185             ms_sysprep_enabled = False
186             if len(enabled) != size:
187                 enabled.append(self.microsoft_sysprep)
188                 ms_sysprep_enabled = True
189
190             cnt = 0
191             for task in enabled:
192                 cnt += 1
193                 self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False)
194                 task()
195                 setattr(task.im_func, 'executed', True)
196
197             self.out.output("Sending shut down command ...", False)
198             if not ms_sysprep_enabled:
199                 self._shutdown()
200             self.out.success("done")
201
202             self.out.output("Waiting for windows to shut down ...", False)
203             vm.wait()
204             self.out.success("done")
205         finally:
206             if monitor is not None:
207                 os.unlink(monitor)
208
209             if vm is not None:
210                 self._destroy_vm(vm)
211
212             self.out.output("Relaunching helper VM (may take a while) ...",
213                             False)
214             self.g.launch()
215             self.out.success('done')
216
217             self.mount(readonly=False)
218             try:
219                 if disabled_uac:
220                     self._update_uac_remote_setting(0)
221
222                 self._update_firewalls(*firewall_states)
223             finally:
224                 self.umount()
225
226     def _create_vm(self, monitor):
227         """Create a VM with the image attached as the disk
228
229             monitor: a file to be used to monitor when the OS is up
230         """
231
232         def random_mac():
233             mac = [0x00, 0x16, 0x3e,
234                    random.randint(0x00, 0x7f),
235                    random.randint(0x00, 0xff),
236                    random.randint(0x00, 0xff)]
237
238             return ':'.join(map(lambda x: "%02x" % x, mac))
239
240         # Use ganeti's VNC port range for a random vnc port
241         vnc_port = random.randint(11000, 14999)
242         display = vnc_port - 5900
243
244         vm = kvm('-smp', '1', '-m', '1024', '-drive',
245                  'file=%s,format=raw,cache=none,if=virtio' % self.image.device,
246                  '-netdev', 'type=user,hostfwd=tcp::445-:445,id=netdev0',
247                  '-device', 'virtio-net-pci,mac=%s,netdev=netdev0' %
248                  random_mac(), '-vnc', ':%d' % display, '-serial',
249                  'file:%s' % monitor, _bg=True)
250
251         return vm, display
252
253     def _destroy_vm(self, vm):
254         """Destroy a VM previously created by _create_vm"""
255         if vm.process.alive:
256             vm.terminate()
257
258     def _shutdown(self):
259         """Shuts down the windows VM"""
260         self._guest_exec(r'shutdown /s /t 5')
261
262     def _wait_on_file(self, fname, msg):
263         """Wait until a message appears on a file"""
264
265         for i in range(BOOT_TIMEOUT):
266             time.sleep(1)
267             with open(fname) as f:
268                 for line in f:
269                     if line.startswith(msg):
270                         return True
271         return False
272
273     def _disable_autologon(self):
274         """Disable automatic logon on the windows image"""
275
276         winlogon = \
277             r'"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"'
278
279         self._guest_exec('REG DELETE %s /v DefaultUserName /f' % winlogon)
280         self._guest_exec('REG DELETE %s /v DefaultPassword /f' % winlogon)
281         self._guest_exec('REG DELETE %s /v AutoAdminLogon /f' % winlogon)
282
283     def _registry_file_path(self, regfile):
284         """Retrieves the case sensitive path to a registry file"""
285
286         systemroot = self.g.inspect_get_windows_systemroot(self.root)
287         path = "%s/system32/config/%s" % (systemroot, regfile)
288         try:
289             path = self.g.case_sensitive_path(path)
290         except RuntimeError as e:
291             raise FatalError("Unable to retrieve registry file: %s. Reason: %s"
292                              % (regfile, str(e)))
293         return path
294
295     def _enable_os_monitor(self):
296         """Add a script in the registry that will send a random string to the
297         first serial port when the windows image finishes booting.
298         """
299
300         token = "".join(random.choice(string.ascii_letters) for x in range(16))
301
302         path = self._registry_file_path('SOFTWARE')
303         softwarefd, software = tempfile.mkstemp()
304         try:
305             os.close(softwarefd)
306             self.g.download(path, software)
307
308             h = hivex.Hivex(software, write=True)
309
310             # Enable automatic logon.
311             # This is needed because we need to execute a script that we add in
312             # the RunOnce registry entry and those programs only get executed
313             # when a user logs on. There is a RunServicesOnce registry entry
314             # whose keys get executed in the background when the logon dialog
315             # box first appears, but they seem to only work with services and
316             # not arbitrary command line expressions :-(
317             #
318             # Instructions on how to turn on automatic logon in Windows can be
319             # found here: http://support.microsoft.com/kb/324737
320             #
321             # Warning: Registry change will not work if the “Logon Banner” is
322             # defined on the server either by a Group Policy object (GPO) or by
323             # a local policy.
324
325             winlogon = h.root()
326             for child in ('Microsoft', 'Windows NT', 'CurrentVersion',
327                           'Winlogon'):
328                 winlogon = h.node_get_child(winlogon, child)
329
330             h.node_set_value(
331                 winlogon,
332                 {'key': 'DefaultUserName', 't': 1,
333                  'value': "Administrator".encode('utf-16le')})
334             h.node_set_value(
335                 winlogon,
336                 {'key': 'DefaultPassword', 't': 1,
337                  'value':  self.sysprep_params['password'].encode('utf-16le')})
338             h.node_set_value(
339                 winlogon,
340                 {'key': 'AutoAdminLogon', 't': 1,
341                  'value': "1".encode('utf-16le')})
342
343             key = h.root()
344             for child in ('Microsoft', 'Windows', 'CurrentVersion'):
345                 key = h.node_get_child(key, child)
346
347             runonce = h.node_get_child(key, "RunOnce")
348             if runonce is None:
349                 runonce = h.node_add_child(key, "RunOnce")
350
351             value = (
352                 r'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe '
353                 r'-ExecutionPolicy RemoteSigned '
354                 r'"&{$port=new-Object System.IO.Ports.SerialPort COM1,9600,'
355                 r'None,8,one;$port.open();$port.WriteLine(\"' + token + r'\");'
356                 r'$port.Close()}"').encode('utf-16le')
357
358             h.node_set_value(runonce,
359                              {'key': "BootMonitor", 't': 1, 'value': value})
360
361             h.commit(None)
362
363             self.g.upload(software, path)
364         finally:
365             os.unlink(software)
366
367         return token
368
369     def _update_firewalls(self, domain, public, standard):
370         """Enables or disables the firewall for the Domain, the Public and the
371         Standard profile. Returns a triplete with the old values.
372
373         1 will enable a firewall and 0 will disable it
374         """
375
376         if domain not in (0, 1):
377             raise ValueError("Valid values for domain parameter are 0 and 1")
378
379         if public not in (0, 1):
380             raise ValueError("Valid values for public parameter are 0 and 1")
381
382         if standard not in (0, 1):
383             raise ValueError("Valid values for standard parameter are 0 and 1")
384
385         path = self._registry_file_path("SYSTEM")
386         systemfd, system = tempfile.mkstemp()
387         try:
388             os.close(systemfd)
389             self.g.download(path, system)
390
391             h = hivex.Hivex(system, write=True)
392
393             select = h.node_get_child(h.root(), 'Select')
394             current_value = h.node_get_value(select, 'Current')
395
396             # expecting a little endian dword
397             assert h.value_type(current_value)[1] == 4
398             current = "%03d" % h.value_dword(current_value)
399
400             firewall_policy = h.root()
401             for child in ('ControlSet%s' % current, 'services', 'SharedAccess',
402                           'Parameters', 'FirewallPolicy'):
403                 firewall_policy = h.node_get_child(firewall_policy, child)
404
405             old_values = []
406             new_values = [domain, public, standard]
407             for profile in ('Domain', 'Public', 'Standard'):
408                 node = h.node_get_child(firewall_policy, '%sProfile' % profile)
409
410                 old_value = h.node_get_value(node, 'EnableFirewall')
411
412                 # expecting a little endian dword
413                 assert h.value_type(old_value)[1] == 4
414                 old_values.append(h.value_dword(old_value))
415
416                 new_value = '\x00' if new_values.pop(0) == 0 else '\x01'
417                 h.node_set_value(node, {'key': 'EnableFirewall', 't': 4L,
418                                         'value': '%s\x00\x00\x00' % new_value})
419
420             h.commit(None)
421             self.g.upload(system, path)
422
423         finally:
424             os.unlink(system)
425
426         return old_values
427
428     def _update_uac_remote_setting(self, value):
429         """Updates the registry key value:
430         [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies
431         \System]"LocalAccountTokenFilterPolicy"
432
433         value = 1 will disable the UAC remote restrictions
434         value = 0 will enable the UAC remote restrictions
435
436         For more info see here: http://support.microsoft.com/kb/951016
437
438         Returns:
439             True if the key is changed
440             False if the key is unchanged
441         """
442
443         if value not in (0, 1):
444             raise ValueError("Valid values for value parameter are 0 and 1")
445
446         path = self._registry_file_path('SOFTWARE')
447         softwarefd, software = tempfile.mkstemp()
448         try:
449             os.close(softwarefd)
450             self.g.download(path, software)
451
452             h = hivex.Hivex(software, write=True)
453
454             key = h.root()
455             for child in ('Microsoft', 'Windows', 'CurrentVersion', 'Policies',
456                           'System'):
457                 key = h.node_get_child(key, child)
458
459             policy = None
460             for val in h.node_values(key):
461                 if h.value_key(val) == "LocalAccountTokenFilterPolicy":
462                     policy = val
463
464             if policy is not None:
465                 dword = h.value_dword(policy)
466                 if dword == value:
467                     return False
468             elif value == 0:
469                 return False
470
471             new_value = {
472                 'key': "LocalAccountTokenFilterPolicy", 't': 4L,
473                 'value': '%s\x00\x00\x00' % '\x00' if value == 0 else '\x01'}
474
475             h.node_set_value(key, new_value)
476             h.commit(None)
477
478             self.g.upload(software, path)
479
480         finally:
481             os.unlink(software)
482
483         return True
484
485     def _do_collect_metadata(self):
486         """Collect metadata about the OS"""
487         super(Windows, self)._do_collect_metadata()
488         self.meta["USERS"] = " ".join(self._get_users())
489
490     def _get_users(self):
491         """Returns a list of users found in the images"""
492         path = self._registry_file_path('SAM')
493         samfd, sam = tempfile.mkstemp()
494         try:
495             os.close(samfd)
496             self.g.download(path, sam)
497
498             h = hivex.Hivex(sam)
499
500             key = h.root()
501             # Navigate to /SAM/Domains/Account/Users/Names
502             for child in ('SAM', 'Domains', 'Account', 'Users', 'Names'):
503                 key = h.node_get_child(key, child)
504
505             users = [h.node_name(x) for x in h.node_children(key)]
506
507         finally:
508             os.unlink(sam)
509
510         # Filter out the guest account
511         return filter(lambda x: x != "Guest", users)
512
513     def _guest_exec(self, command, fatal=True):
514         """Execute a command on a windows VM"""
515
516         user = "Administrator%" + self.sysprep_params['password']
517         addr = 'localhost'
518         runas = '--runas=%s' % user
519         winexe = subprocess.Popen(
520             ['winexe', '-U', user, "//%s" % addr, runas, command],
521             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
522
523         stdout, stderr = winexe.communicate()
524         rc = winexe.poll()
525
526         if rc != 0 and fatal:
527             reason = stderr if len(stderr) else stdout
528             raise FatalError("Command: `%s' failed. Reason: %s" %
529                              (command, reason))
530
531         return (stdout, stderr, rc)
532
533 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :