c78c9477811a79e252e0576e37109123829ed890
[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('Setting the system clock to UTC')
93     def utc(self):
94         """Set the hardware clock to UTC"""
95
96         path = r'HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation'
97         self._guest_exec(
98             r'REG ADD %s /v RealTimeIsUniversal /t REG_DWORD /d 1 /f' % path)
99
100     @sysprep('Executing sysprep on the image (may take more that 10 minutes)')
101     def microsoft_sysprep(self):
102         """Run the Microsoft System Preparation Tool. This will remove
103         system-specific data and will make the image ready to be deployed.
104         After this no other task may run.
105         """
106
107         self._guest_exec(r'C:\Windows\system32\sysprep\sysprep '
108                          r'/quiet /generalize /oobe /shutdown')
109         self.syspreped = True
110
111     def do_sysprep(self):
112         """Prepare system for image creation."""
113
114         if getattr(self, 'syspreped', False):
115             raise FatalError("Image is already syspreped!")
116
117         txt = "System preparation parameter: `%s' is needed but missing!"
118         for param in self.needed_sysprep_params():
119             if param[0] not in self.sysprep_params:
120                 raise FatalError(txt % param[0])
121
122         self.mount(readonly=False)
123         try:
124             disabled_uac = self._update_uac_remote_setting(1)
125             token = self._enable_os_monitor()
126         finally:
127             self.umount()
128
129         self.out.output("Shutting down helper VM ...", False)
130         self.g.sync()
131         # guestfs_shutdown which is the prefered way to shutdown the backend
132         # process was introduced in version 1.19.16
133         if check_guestfs_version(self.g, 1, 19, 16) >= 0:
134             ret = self.g.shutdown()
135         else:
136             ret = self.g.kill_subprocess()
137
138         self.out.success('done')
139
140         vm = None
141         monitor = None
142         try:
143             self.out.output("Starting windows VM ...", False)
144             monitorfd, monitor = tempfile.mkstemp()
145             os.close(monitorfd)
146             vm, display = self._create_vm(monitor)
147             self.out.success("started (console on vnc display: %d)." % display)
148
149             self.out.output("Waiting for OS to boot ...", False)
150             if not self._wait_on_file(monitor, token):
151                 raise FatalError("Windows booting timed out.")
152             else:
153                 self.out.success('done')
154
155             self.out.output("Disabling automatic logon ...", False)
156             self._disable_autologon()
157             self.out.success('done')
158
159             self.out.output('Preparing system from image creation:')
160
161             tasks = self.list_syspreps()
162             enabled = filter(lambda x: x.enabled, tasks)
163
164             size = len(enabled)
165
166             # Make sure the ms sysprep is the last task to run if it is enabled
167             enabled = filter(
168                 lambda x: x.im_func.func_name != 'microsoft_sysprep', enabled)
169
170             ms_sysprep_enabled = False
171             if len(enabled) != size:
172                 enabled.append(self.microsoft_sysprep)
173                 ms_sysprep_enabled = True
174
175             cnt = 0
176             for task in enabled:
177                 cnt += 1
178                 self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False)
179                 task()
180                 setattr(task.im_func, 'executed', True)
181
182             self.out.output("Shutting down windows VM ...", False)
183             if not ms_sysprep_enabled:
184                 self._shutdown()
185             self.out.success("done")
186
187             vm.wait()
188         finally:
189             if monitor is not None:
190                 os.unlink(monitor)
191
192             if vm is not None:
193                 self._destroy_vm(vm)
194
195             self.out.output("Relaunching helper VM (may take a while) ...",
196                             False)
197             self.g.launch()
198             self.out.success('done')
199
200         if disabled_uac:
201             self._update_uac_remote_setting(0)
202
203     def _create_vm(self, monitor):
204         """Create a VM with the image attached as the disk
205
206             monitor: a file to be used to monitor when the OS is up
207         """
208
209         def random_mac():
210             mac = [0x00, 0x16, 0x3e,
211                    random.randint(0x00, 0x7f),
212                    random.randint(0x00, 0xff),
213                    random.randint(0x00, 0xff)]
214
215             return ':'.join(map(lambda x: "%02x" % x, mac))
216
217         # Use ganeti's VNC port range for a random vnc port
218         vnc_port = random.randint(11000, 14999)
219         display = vnc_port - 5900
220
221         vm = kvm('-smp', '1', '-m', '1024', '-drive',
222                  'file=%s,format=raw,cache=none,if=virtio' % self.image.device,
223                  '-netdev', 'type=user,hostfwd=tcp::445-:445,id=netdev0',
224                  '-device', 'virtio-net-pci,mac=%s,netdev=netdev0' %
225                  random_mac(), '-vnc', ':%d' % display, '-serial',
226                  'file:%s' % monitor, _bg=True)
227
228         return vm, display
229
230     def _destroy_vm(self, vm):
231         """Destroy a VM previously created by _create_vm"""
232         if vm.process.alive:
233             vm.terminate()
234
235     def _shutdown(self):
236         """Shuts down the windows VM"""
237         self._guest_exec(r'shutdown /s /t 5')
238
239     def _wait_on_file(self, fname, msg):
240         """Wait until a message appears on a file"""
241
242         for i in range(BOOT_TIMEOUT):
243             time.sleep(1)
244             with open(fname) as f:
245                 for line in f:
246                     if line.startswith(msg):
247                         return True
248         return False
249
250     def _disable_autologon(self):
251         """Disable automatic logon on the windows image"""
252
253         winlogon = \
254             r'"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"'
255
256         self._guest_exec('REG DELETE %s /v DefaultUserName /f' % winlogon)
257         self._guest_exec('REG DELETE %s /v DefaultPassword /f' % winlogon)
258         self._guest_exec('REG DELETE %s /v AutoAdminLogon /f' % winlogon)
259
260     def _registry_file_path(self, regfile):
261         """Retrieves the case sensitive path to a registry file"""
262
263         systemroot = self.g.inspect_get_windows_systemroot(self.root)
264         path = "%s/system32/config/%s" % (systemroot, regfile)
265         try:
266             path = self.g.case_sensitive_path(path)
267         except RuntimeError as e:
268             raise FatalError("Unable to retrieve registry file: %s. Reason: %s"
269                              % (regfile, str(e)))
270         return path
271
272     def _enable_os_monitor(self):
273         """Add a script in the registry that will send a random string to the
274         first serial port when the windows image finishes booting.
275         """
276
277         token = "".join(random.choice(string.ascii_letters) for x in range(16))
278
279         path = self._registry_file_path('SOFTWARE')
280         softwarefd, software = tempfile.mkstemp()
281         try:
282             os.close(softwarefd)
283             self.g.download(path, software)
284
285             h = hivex.Hivex(software, write=True)
286
287             # Enable automatic logon.
288             # This is needed because we need to execute a script that we add in
289             # the RunOnce registry entry and those programs only get executed
290             # when a user logs on. There is a RunServicesOnce registry entry
291             # whose keys get executed in the background when the logon dialog
292             # box first appears, but they seem to only work with services and
293             # not arbitrary command line expressions :-(
294             #
295             # Instructions on how to turn on automatic logon in Windows can be
296             # found here: http://support.microsoft.com/kb/324737
297             #
298             # Warning: Registry change will not work if the “Logon Banner” is
299             # defined on the server either by a Group Policy object (GPO) or by
300             # a local policy.
301
302             winlogon = h.root()
303             for child in ('Microsoft', 'Windows NT', 'CurrentVersion',
304                           'Winlogon'):
305                 winlogon = h.node_get_child(winlogon, child)
306
307             h.node_set_value(
308                 winlogon,
309                 {'key': 'DefaultUserName', 't': 1,
310                  'value': "Administrator".encode('utf-16le')})
311             h.node_set_value(
312                 winlogon,
313                 {'key': 'DefaultPassword', 't': 1,
314                  'value':  self.sysprep_params['password'].encode('utf-16le')})
315             h.node_set_value(
316                 winlogon,
317                 {'key': 'AutoAdminLogon', 't': 1,
318                  'value': "1".encode('utf-16le')})
319
320             key = h.root()
321             for child in ('Microsoft', 'Windows', 'CurrentVersion'):
322                 key = h.node_get_child(key, child)
323
324             runonce = h.node_get_child(key, "RunOnce")
325             if runonce is None:
326                 runonce = h.node_add_child(key, "RunOnce")
327
328             value = (
329                 r'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe '
330                 r'-ExecutionPolicy RemoteSigned '
331                 r'"&{$port=new-Object System.IO.Ports.SerialPort COM1,9600,'
332                 r'None,8,one;$port.open();$port.WriteLine(\"' + token + r'\");'
333                 r'$port.Close()}"').encode('utf-16le')
334
335             h.node_set_value(runonce,
336                              {'key': "BootMonitor", 't': 1, 'value': value})
337
338             h.commit(None)
339
340             self.g.upload(software, path)
341         finally:
342             os.unlink(software)
343
344         return token
345
346     def _update_uac_remote_setting(self, value):
347         """Updates the registry key value:
348         [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies
349         \System]"LocalAccountTokenFilterPolicy"
350
351         value = 1 will disable the UAC remote restrictions
352         value = 0 will enable the UAC remote restrictions
353
354         For more info see here: http://support.microsoft.com/kb/951016
355
356         Returns:
357             True if the key is changed
358             False if the key is unchanged
359         """
360
361         if value not in (0, 1):
362             raise ValueError("Valid values for value parameter are 0 and 1")
363
364         path = self._registry_file_path('SOFTWARE')
365         softwarefd, software = tempfile.mkstemp()
366         try:
367             os.close(softwarefd)
368             self.g.download(path, software)
369
370             h = hivex.Hivex(software, write=True)
371
372             key = h.root()
373             for child in ('Microsoft', 'Windows', 'CurrentVersion', 'Policies',
374                           'System'):
375                 key = h.node_get_child(key, child)
376
377             policy = None
378             for val in h.node_values(key):
379                 if h.value_key(val) == "LocalAccountTokenFilterPolicy":
380                     policy = val
381
382             if policy is not None:
383                 dword = h.value_dword(policy)
384                 if dword == value:
385                     return False
386             elif value == 0:
387                 return False
388
389             new_value = {
390                 'key': "LocalAccountTokenFilterPolicy", 't': 4L,
391                 'value': '%s\x00\x00\x00' % '\x00' if value == 0 else '\x01'}
392
393             h.node_set_value(key, new_value)
394             h.commit(None)
395
396             self.g.upload(software, path)
397
398         finally:
399             os.unlink(software)
400
401         return True
402
403     def _do_collect_metadata(self):
404         """Collect metadata about the OS"""
405         super(Windows, self)._do_collect_metadata()
406         self.meta["USERS"] = " ".join(self._get_users())
407
408     def _get_users(self):
409         """Returns a list of users found in the images"""
410         path = self._registry_file_path('SAM')
411         samfd, sam = tempfile.mkstemp()
412         try:
413             os.close(samfd)
414             self.g.download(path, sam)
415
416             h = hivex.Hivex(sam)
417
418             key = h.root()
419             # Navigate to /SAM/Domains/Account/Users/Names
420             for child in ('SAM', 'Domains', 'Account', 'Users', 'Names'):
421                 key = h.node_get_child(key, child)
422
423             users = [h.node_name(x) for x in h.node_children(key)]
424
425         finally:
426             os.unlink(sam)
427
428         # Filter out the guest account
429         return filter(lambda x: x != "Guest", users)
430
431     def _guest_exec(self, command, fatal=True):
432         """Execute a command on a windows VM"""
433
434         user = "Administrator%" + self.sysprep_params['password']
435         addr = 'localhost'
436         runas = '--runas=%s' % user
437         winexe = subprocess.Popen(
438             ['winexe', '-U', user, "//%s" % addr, runas, command],
439             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
440
441         stdout, stderr = winexe.communicate()
442         rc = winexe.poll()
443
444         if rc != 0 and fatal:
445             reason = stderr if len(stderr) else stdout
446             raise FatalError("Command: `%s' failed. Reason: %s" %
447                              (command, reason))
448
449         return (stdout, stderr, rc)
450
451 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :