1 # -*- coding: utf-8 -*-
3 # Copyright 2012 GRNET S.A. All rights reserved.
5 # Redistribution and use in source and binary forms, with or
6 # without modification, are permitted provided that the following
9 # 1. Redistributions of source code must retain the above
10 # copyright notice, this list of conditions and the following
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.
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.
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.
36 """This module hosts OS-specific code common for the various Microsoft
39 from image_creator.os_type import OSBase, sysprep
40 from image_creator.util import FatalError, check_guestfs_version, get_command
50 kvm = get_command('kvm')
55 class Windows(OSBase):
56 """OS class for Windows"""
58 def needed_sysprep_params(self):
59 """Returns a list of needed sysprep parameters. Each element in the
60 list is a SysprepParam object.
62 password = self.SysprepParam(
63 'password', 'Image Administrator Password', 20, lambda x: True)
67 @sysprep('Disabling IPv6 privacy extensions')
68 def disable_ipv6_privacy_extensions(self):
69 """Disable IPv6 privacy extensions"""
71 self._guest_exec('netsh interface ipv6 set global '
72 'randomizeidentifiers=disabled store=persistent')
74 @sysprep('Disabling Teredo interface')
75 def disable_teredo(self):
76 """Disable Teredo interface"""
78 self._guest_exec('netsh interface teredo set state disabled')
80 @sysprep('Disabling ISATAP Adapters')
81 def disable_isatap(self):
82 """Disable ISATAP Adapters"""
84 self._guest_exec('netsh interface isa set state disabled')
86 @sysprep('Enabling ping responses')
87 def enable_pings(self):
88 """Enable ping responces"""
90 self._guest_exec('netsh firewall set icmpsetting 8')
92 @sysprep('Disabling hibernation support')
93 def disable_hibernation(self):
94 """Disable hibernation support and remove the hibernation file"""
96 self._guest_exec(r'powercfg.exe /hibernate off')
98 @sysprep('Setting the system clock to UTC')
100 """Set the hardware clock to UTC"""
102 path = r'HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation'
104 r'REG ADD %s /v RealTimeIsUniversal /t REG_DWORD /d 1 /f' % path)
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.
113 self._guest_exec(r'C:\Windows\system32\sysprep\sysprep '
114 r'/quiet /generalize /oobe /shutdown')
115 self.syspreped = True
117 def do_sysprep(self):
118 """Prepare system for image creation."""
120 if getattr(self, 'syspreped', False):
121 raise FatalError("Image is already syspreped!")
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])
128 self.mount(readonly=False)
130 disabled_uac = self._update_uac_remote_setting(1)
131 token = self._enable_os_monitor()
133 # disable the firewalls
134 firewall_states = self._update_firewalls(0, 0, 0)
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))
144 self.out.output("Shutting down helper VM ...", False)
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()
151 ret = self.g.kill_subprocess()
153 self.out.success('done')
158 self.out.output("Starting windows VM ...", False)
159 monitorfd, monitor = tempfile.mkstemp()
161 vm, display = self._create_vm(monitor)
162 self.out.success("started (console on vnc display: %d)." % display)
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.")
168 self.out.success('done')
170 self.out.output("Disabling automatic logon ...", False)
171 self._disable_autologon()
172 self.out.success('done')
174 self.out.output('Preparing system from image creation:')
176 tasks = self.list_syspreps()
177 enabled = filter(lambda x: x.enabled, tasks)
181 # Make sure the ms sysprep is the last task to run if it is enabled
183 lambda x: x.im_func.func_name != 'microsoft_sysprep', enabled)
185 ms_sysprep_enabled = False
186 if len(enabled) != size:
187 enabled.append(self.microsoft_sysprep)
188 ms_sysprep_enabled = True
193 self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False)
195 setattr(task.im_func, 'executed', True)
197 self.out.output("Sending shut down command ...", False)
198 if not ms_sysprep_enabled:
200 self.out.success("done")
202 self.out.output("Waiting for windows to shut down ...", False)
204 self.out.success("done")
206 if monitor is not None:
212 self.out.output("Relaunching helper VM (may take a while) ...",
215 self.out.success('done')
217 self.mount(readonly=False)
220 self._update_uac_remote_setting(0)
222 self._update_firewalls(*firewall_states)
226 def _create_vm(self, monitor):
227 """Create a VM with the image attached as the disk
229 monitor: a file to be used to monitor when the OS is up
233 mac = [0x00, 0x16, 0x3e,
234 random.randint(0x00, 0x7f),
235 random.randint(0x00, 0xff),
236 random.randint(0x00, 0xff)]
238 return ':'.join(map(lambda x: "%02x" % x, mac))
240 # Use ganeti's VNC port range for a random vnc port
241 vnc_port = random.randint(11000, 14999)
242 display = vnc_port - 5900
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)
253 def _destroy_vm(self, vm):
254 """Destroy a VM previously created by _create_vm"""
259 """Shuts down the windows VM"""
260 self._guest_exec(r'shutdown /s /t 5')
262 def _wait_on_file(self, fname, msg):
263 """Wait until a message appears on a file"""
265 for i in range(BOOT_TIMEOUT):
267 with open(fname) as f:
269 if line.startswith(msg):
273 def _disable_autologon(self):
274 """Disable automatic logon on the windows image"""
277 r'"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"'
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)
283 def _registry_file_path(self, regfile):
284 """Retrieves the case sensitive path to a registry file"""
286 systemroot = self.g.inspect_get_windows_systemroot(self.root)
287 path = "%s/system32/config/%s" % (systemroot, regfile)
289 path = self.g.case_sensitive_path(path)
290 except RuntimeError as e:
291 raise FatalError("Unable to retrieve registry file: %s. Reason: %s"
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.
300 token = "".join(random.choice(string.ascii_letters) for x in range(16))
302 path = self._registry_file_path('SOFTWARE')
303 softwarefd, software = tempfile.mkstemp()
306 self.g.download(path, software)
308 h = hivex.Hivex(software, write=True)
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 :-(
318 # Instructions on how to turn on automatic logon in Windows can be
319 # found here: http://support.microsoft.com/kb/324737
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
326 for child in ('Microsoft', 'Windows NT', 'CurrentVersion',
328 winlogon = h.node_get_child(winlogon, child)
332 {'key': 'DefaultUserName', 't': 1,
333 'value': "Administrator".encode('utf-16le')})
336 {'key': 'DefaultPassword', 't': 1,
337 'value': self.sysprep_params['password'].encode('utf-16le')})
340 {'key': 'AutoAdminLogon', 't': 1,
341 'value': "1".encode('utf-16le')})
344 for child in ('Microsoft', 'Windows', 'CurrentVersion'):
345 key = h.node_get_child(key, child)
347 runonce = h.node_get_child(key, "RunOnce")
349 runonce = h.node_add_child(key, "RunOnce")
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')
358 h.node_set_value(runonce,
359 {'key': "BootMonitor", 't': 1, 'value': value})
363 self.g.upload(software, path)
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.
373 1 will enable a firewall and 0 will disable it
376 if domain not in (0, 1):
377 raise ValueError("Valid values for domain parameter are 0 and 1")
379 if public not in (0, 1):
380 raise ValueError("Valid values for public parameter are 0 and 1")
382 if standard not in (0, 1):
383 raise ValueError("Valid values for standard parameter are 0 and 1")
385 path = self._registry_file_path("SYSTEM")
386 systemfd, system = tempfile.mkstemp()
389 self.g.download(path, system)
391 h = hivex.Hivex(system, write=True)
393 select = h.node_get_child(h.root(), 'Select')
394 current_value = h.node_get_value(select, 'Current')
396 # expecting a little endian dword
397 assert h.value_type(current_value)[1] == 4
398 current = "%03d" % h.value_dword(current_value)
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)
406 new_values = [domain, public, standard]
407 for profile in ('Domain', 'Public', 'Standard'):
408 node = h.node_get_child(firewall_policy, '%sProfile' % profile)
410 old_value = h.node_get_value(node, 'EnableFirewall')
412 # expecting a little endian dword
413 assert h.value_type(old_value)[1] == 4
414 old_values.append(h.value_dword(old_value))
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})
421 self.g.upload(system, path)
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"
433 value = 1 will disable the UAC remote restrictions
434 value = 0 will enable the UAC remote restrictions
436 For more info see here: http://support.microsoft.com/kb/951016
439 True if the key is changed
440 False if the key is unchanged
443 if value not in (0, 1):
444 raise ValueError("Valid values for value parameter are 0 and 1")
446 path = self._registry_file_path('SOFTWARE')
447 softwarefd, software = tempfile.mkstemp()
450 self.g.download(path, software)
452 h = hivex.Hivex(software, write=True)
455 for child in ('Microsoft', 'Windows', 'CurrentVersion', 'Policies',
457 key = h.node_get_child(key, child)
460 for val in h.node_values(key):
461 if h.value_key(val) == "LocalAccountTokenFilterPolicy":
464 if policy is not None:
465 dword = h.value_dword(policy)
472 'key': "LocalAccountTokenFilterPolicy", 't': 4L,
473 'value': '%s\x00\x00\x00' % '\x00' if value == 0 else '\x01'}
475 h.node_set_value(key, new_value)
478 self.g.upload(software, path)
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())
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()
496 self.g.download(path, sam)
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)
505 users = [h.node_name(x) for x in h.node_children(key)]
510 # Filter out the guest account
511 return filter(lambda x: x != "Guest", users)
513 def _guest_exec(self, command, fatal=True):
514 """Execute a command on a windows VM"""
516 user = "Administrator%" + self.sysprep_params['password']
518 runas = '--runas=%s' % user
519 winexe = subprocess.Popen(
520 ['winexe', '-U', user, "//%s" % addr, runas, command],
521 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
523 stdout, stderr = winexe.communicate()
526 if rc != 0 and fatal:
527 reason = stderr if len(stderr) else stdout
528 raise FatalError("Command: `%s' failed. Reason: %s" %
531 return (stdout, stderr, rc)
533 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :