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('Setting the system clock to UTC')
94 """Set the hardware clock to UTC"""
96 path = r'HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation'
98 r'REG ADD %s /v RealTimeIsUniversal /t REG_DWORD /d 1 /f' % path)
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.
107 self._guest_exec(r'C:\Windows\system32\sysprep\sysprep '
108 r'/quiet /generalize /oobe /shutdown')
109 self.syspreped = True
111 def do_sysprep(self):
112 """Prepare system for image creation."""
114 if getattr(self, 'syspreped', False):
115 raise FatalError("Image is already syspreped!")
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])
122 self.mount(readonly=False)
124 disabled_uac = self._update_uac_remote_setting(1)
125 token = self._enable_os_monitor()
127 # disable the firewalls
128 firewall_states = self._update_firewalls(0, 0, 0)
130 # Delete the pagefile. It will be recreated when the system boots
131 systemroot = self.g.inspect_get_windows_systemroot(self.root)
132 pagefile = "%s/pagefile.sys" % systemroot
133 self.g.rm_rf(self.g.case_sensitive_path(pagefile))
138 self.out.output("Shutting down helper VM ...", False)
140 # guestfs_shutdown which is the prefered way to shutdown the backend
141 # process was introduced in version 1.19.16
142 if check_guestfs_version(self.g, 1, 19, 16) >= 0:
143 ret = self.g.shutdown()
145 ret = self.g.kill_subprocess()
147 self.out.success('done')
152 self.out.output("Starting windows VM ...", False)
153 monitorfd, monitor = tempfile.mkstemp()
155 vm, display = self._create_vm(monitor)
156 self.out.success("started (console on vnc display: %d)." % display)
158 self.out.output("Waiting for OS to boot ...", False)
159 if not self._wait_on_file(monitor, token):
160 raise FatalError("Windows booting timed out.")
162 self.out.success('done')
164 self.out.output("Disabling automatic logon ...", False)
165 self._disable_autologon()
166 self.out.success('done')
168 self.out.output('Preparing system from image creation:')
170 tasks = self.list_syspreps()
171 enabled = filter(lambda x: x.enabled, tasks)
175 # Make sure the ms sysprep is the last task to run if it is enabled
177 lambda x: x.im_func.func_name != 'microsoft_sysprep', enabled)
179 ms_sysprep_enabled = False
180 if len(enabled) != size:
181 enabled.append(self.microsoft_sysprep)
182 ms_sysprep_enabled = True
187 self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False)
189 setattr(task.im_func, 'executed', True)
191 self.out.output("Sending shut down command ...", False)
192 if not ms_sysprep_enabled:
194 self.out.success("done")
196 self.out.output("Waiting for windows to shut down ...", False)
198 self.out.success("done")
200 if monitor is not None:
206 self.out.output("Relaunching helper VM (may take a while) ...",
209 self.out.success('done')
211 self.mount(readonly=False)
214 self._update_uac_remote_setting(0)
216 self._update_firewalls(*firewall_states)
220 def _create_vm(self, monitor):
221 """Create a VM with the image attached as the disk
223 monitor: a file to be used to monitor when the OS is up
227 mac = [0x00, 0x16, 0x3e,
228 random.randint(0x00, 0x7f),
229 random.randint(0x00, 0xff),
230 random.randint(0x00, 0xff)]
232 return ':'.join(map(lambda x: "%02x" % x, mac))
234 # Use ganeti's VNC port range for a random vnc port
235 vnc_port = random.randint(11000, 14999)
236 display = vnc_port - 5900
238 vm = kvm('-smp', '1', '-m', '1024', '-drive',
239 'file=%s,format=raw,cache=none,if=virtio' % self.image.device,
240 '-netdev', 'type=user,hostfwd=tcp::445-:445,id=netdev0',
241 '-device', 'virtio-net-pci,mac=%s,netdev=netdev0' %
242 random_mac(), '-vnc', ':%d' % display, '-serial',
243 'file:%s' % monitor, _bg=True)
247 def _destroy_vm(self, vm):
248 """Destroy a VM previously created by _create_vm"""
253 """Shuts down the windows VM"""
254 self._guest_exec(r'shutdown /s /t 5')
256 def _wait_on_file(self, fname, msg):
257 """Wait until a message appears on a file"""
259 for i in range(BOOT_TIMEOUT):
261 with open(fname) as f:
263 if line.startswith(msg):
267 def _disable_autologon(self):
268 """Disable automatic logon on the windows image"""
271 r'"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"'
273 self._guest_exec('REG DELETE %s /v DefaultUserName /f' % winlogon)
274 self._guest_exec('REG DELETE %s /v DefaultPassword /f' % winlogon)
275 self._guest_exec('REG DELETE %s /v AutoAdminLogon /f' % winlogon)
277 def _registry_file_path(self, regfile):
278 """Retrieves the case sensitive path to a registry file"""
280 systemroot = self.g.inspect_get_windows_systemroot(self.root)
281 path = "%s/system32/config/%s" % (systemroot, regfile)
283 path = self.g.case_sensitive_path(path)
284 except RuntimeError as e:
285 raise FatalError("Unable to retrieve registry file: %s. Reason: %s"
289 def _enable_os_monitor(self):
290 """Add a script in the registry that will send a random string to the
291 first serial port when the windows image finishes booting.
294 token = "".join(random.choice(string.ascii_letters) for x in range(16))
296 path = self._registry_file_path('SOFTWARE')
297 softwarefd, software = tempfile.mkstemp()
300 self.g.download(path, software)
302 h = hivex.Hivex(software, write=True)
304 # Enable automatic logon.
305 # This is needed because we need to execute a script that we add in
306 # the RunOnce registry entry and those programs only get executed
307 # when a user logs on. There is a RunServicesOnce registry entry
308 # whose keys get executed in the background when the logon dialog
309 # box first appears, but they seem to only work with services and
310 # not arbitrary command line expressions :-(
312 # Instructions on how to turn on automatic logon in Windows can be
313 # found here: http://support.microsoft.com/kb/324737
315 # Warning: Registry change will not work if the “Logon Banner” is
316 # defined on the server either by a Group Policy object (GPO) or by
320 for child in ('Microsoft', 'Windows NT', 'CurrentVersion',
322 winlogon = h.node_get_child(winlogon, child)
326 {'key': 'DefaultUserName', 't': 1,
327 'value': "Administrator".encode('utf-16le')})
330 {'key': 'DefaultPassword', 't': 1,
331 'value': self.sysprep_params['password'].encode('utf-16le')})
334 {'key': 'AutoAdminLogon', 't': 1,
335 'value': "1".encode('utf-16le')})
338 for child in ('Microsoft', 'Windows', 'CurrentVersion'):
339 key = h.node_get_child(key, child)
341 runonce = h.node_get_child(key, "RunOnce")
343 runonce = h.node_add_child(key, "RunOnce")
346 r'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe '
347 r'-ExecutionPolicy RemoteSigned '
348 r'"&{$port=new-Object System.IO.Ports.SerialPort COM1,9600,'
349 r'None,8,one;$port.open();$port.WriteLine(\"' + token + r'\");'
350 r'$port.Close()}"').encode('utf-16le')
352 h.node_set_value(runonce,
353 {'key': "BootMonitor", 't': 1, 'value': value})
357 self.g.upload(software, path)
363 def _update_firewalls(self, domain, public, standard):
364 """Enables or disables the firewall for the Domain, the Public and the
365 Standard profile. Returns a triplete with the old values.
367 1 will enable a firewall and 0 will disable it
370 if domain not in (0, 1):
371 raise ValueError("Valid values for domain parameter are 0 and 1")
373 if public not in (0, 1):
374 raise ValueError("Valid values for public parameter are 0 and 1")
376 if standard not in (0, 1):
377 raise ValueError("Valid values for standard parameter are 0 and 1")
379 path = self._registry_file_path("SYSTEM")
380 systemfd, system = tempfile.mkstemp()
383 self.g.download(path, system)
385 h = hivex.Hivex(system, write=True)
387 select = h.node_get_child(h.root(), 'Select')
388 current_value = h.node_get_value(select, 'Current')
390 # expecting a little endian dword
391 assert h.value_type(current_value)[1] == 4
392 current = "%03d" % h.value_dword(current_value)
394 firewall_policy = h.root()
395 for child in ('ControlSet%s' % current, 'services', 'SharedAccess',
396 'Parameters', 'FirewallPolicy'):
397 firewall_policy = h.node_get_child(firewall_policy, child)
400 new_values = [domain, public, standard]
401 for profile in ('Domain', 'Public', 'Standard'):
402 node = h.node_get_child(firewall_policy, '%sProfile' % profile)
404 old_value = h.node_get_value(node, 'EnableFirewall')
406 # expecting a little endian dword
407 assert h.value_type(old_value)[1] == 4
408 old_values.append(h.value_dword(old_value))
410 new_value = '\x00' if new_values.pop(0) == 0 else '\x01'
411 h.node_set_value(node, {'key': 'EnableFirewall', 't': 4L,
412 'value': '%s\x00\x00\x00' % new_value})
415 self.g.upload(system, path)
422 def _update_uac_remote_setting(self, value):
423 """Updates the registry key value:
424 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies
425 \System]"LocalAccountTokenFilterPolicy"
427 value = 1 will disable the UAC remote restrictions
428 value = 0 will enable the UAC remote restrictions
430 For more info see here: http://support.microsoft.com/kb/951016
433 True if the key is changed
434 False if the key is unchanged
437 if value not in (0, 1):
438 raise ValueError("Valid values for value parameter are 0 and 1")
440 path = self._registry_file_path('SOFTWARE')
441 softwarefd, software = tempfile.mkstemp()
444 self.g.download(path, software)
446 h = hivex.Hivex(software, write=True)
449 for child in ('Microsoft', 'Windows', 'CurrentVersion', 'Policies',
451 key = h.node_get_child(key, child)
454 for val in h.node_values(key):
455 if h.value_key(val) == "LocalAccountTokenFilterPolicy":
458 if policy is not None:
459 dword = h.value_dword(policy)
466 'key': "LocalAccountTokenFilterPolicy", 't': 4L,
467 'value': '%s\x00\x00\x00' % '\x00' if value == 0 else '\x01'}
469 h.node_set_value(key, new_value)
472 self.g.upload(software, path)
479 def _do_collect_metadata(self):
480 """Collect metadata about the OS"""
481 super(Windows, self)._do_collect_metadata()
482 self.meta["USERS"] = " ".join(self._get_users())
484 def _get_users(self):
485 """Returns a list of users found in the images"""
486 path = self._registry_file_path('SAM')
487 samfd, sam = tempfile.mkstemp()
490 self.g.download(path, sam)
495 # Navigate to /SAM/Domains/Account/Users/Names
496 for child in ('SAM', 'Domains', 'Account', 'Users', 'Names'):
497 key = h.node_get_child(key, child)
499 users = [h.node_name(x) for x in h.node_children(key)]
504 # Filter out the guest account
505 return filter(lambda x: x != "Guest", users)
507 def _guest_exec(self, command, fatal=True):
508 """Execute a command on a windows VM"""
510 user = "Administrator%" + self.sysprep_params['password']
512 runas = '--runas=%s' % user
513 winexe = subprocess.Popen(
514 ['winexe', '-U', user, "//%s" % addr, runas, command],
515 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
517 stdout, stderr = winexe.communicate()
520 if rc != 0 and fatal:
521 reason = stderr if len(stderr) else stdout
522 raise FatalError("Command: `%s' failed. Reason: %s" %
525 return (stdout, stderr, rc)
527 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :