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()
129 self.out.output("Shutting down helper VM ...", False)
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()
136 ret = self.g.kill_subprocess()
138 self.out.success('done')
143 self.out.output("Starting windows VM ...", False)
144 monitorfd, monitor = tempfile.mkstemp()
146 vm, display = self._create_vm(monitor)
147 self.out.success("started (console on vnc display: %d)." % display)
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.")
153 self.out.success('done')
155 self.out.output("Disabling automatic logon ...", False)
156 self._disable_autologon()
157 self.out.success('done')
159 self.out.output('Preparing system from image creation:')
161 tasks = self.list_syspreps()
162 enabled = filter(lambda x: x.enabled, tasks)
166 # Make sure the ms sysprep is the last task to run if it is enabled
168 lambda x: x.im_func.func_name != 'microsoft_sysprep', enabled)
170 ms_sysprep_enabled = False
171 if len(enabled) != size:
172 enabled.append(self.microsoft_sysprep)
173 ms_sysprep_enabled = True
178 self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False)
180 setattr(task.im_func, 'executed', True)
182 self.out.output("Shutting down windows VM ...", False)
183 if not ms_sysprep_enabled:
185 self.out.success("done")
189 if monitor is not None:
195 self.out.output("Relaunching helper VM (may take a while) ...",
198 self.out.success('done')
201 self._update_uac_remote_setting(0)
203 def _create_vm(self, monitor):
204 """Create a VM with the image attached as the disk
206 monitor: a file to be used to monitor when the OS is up
210 mac = [0x00, 0x16, 0x3e,
211 random.randint(0x00, 0x7f),
212 random.randint(0x00, 0xff),
213 random.randint(0x00, 0xff)]
215 return ':'.join(map(lambda x: "%02x" % x, mac))
217 # Use ganeti's VNC port range for a random vnc port
218 vnc_port = random.randint(11000, 14999)
219 display = vnc_port - 5900
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)
230 def _destroy_vm(self, vm):
231 """Destroy a VM previously created by _create_vm"""
236 """Shuts down the windows VM"""
237 self._guest_exec(r'shutdown /s /t 5')
239 def _wait_on_file(self, fname, msg):
240 """Wait until a message appears on a file"""
242 for i in range(BOOT_TIMEOUT):
244 with open(fname) as f:
246 if line.startswith(msg):
250 def _disable_autologon(self):
251 """Disable automatic logon on the windows image"""
254 r'"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"'
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)
260 def _registry_file_path(self, regfile):
261 """Retrieves the case sensitive path to a registry file"""
263 systemroot = self.g.inspect_get_windows_systemroot(self.root)
264 path = "%s/system32/config/%s" % (systemroot, regfile)
266 path = self.g.case_sensitive_path(path)
267 except RuntimeError as e:
268 raise FatalError("Unable to retrieve registry file: %s. Reason: %s"
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.
277 token = "".join(random.choice(string.ascii_letters) for x in range(16))
279 path = self._registry_file_path('SOFTWARE')
280 softwarefd, software = tempfile.mkstemp()
283 self.g.download(path, software)
285 h = hivex.Hivex(software, write=True)
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 :-(
295 # Instructions on how to turn on automatic logon in Windows can be
296 # found here: http://support.microsoft.com/kb/324737
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
303 for child in ('Microsoft', 'Windows NT', 'CurrentVersion',
305 winlogon = h.node_get_child(winlogon, child)
309 {'key': 'DefaultUserName', 't': 1,
310 'value': "Administrator".encode('utf-16le')})
313 {'key': 'DefaultPassword', 't': 1,
314 'value': self.sysprep_params['password'].encode('utf-16le')})
317 {'key': 'AutoAdminLogon', 't': 1,
318 'value': "1".encode('utf-16le')})
321 for child in ('Microsoft', 'Windows', 'CurrentVersion'):
322 key = h.node_get_child(key, child)
324 runonce = h.node_get_child(key, "RunOnce")
326 runonce = h.node_add_child(key, "RunOnce")
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')
335 h.node_set_value(runonce,
336 {'key': "BootMonitor", 't': 1, 'value': value})
340 self.g.upload(software, path)
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"
351 value = 1 will disable the UAC remote restrictions
352 value = 0 will enable the UAC remote restrictions
354 For more info see here: http://support.microsoft.com/kb/951016
357 True if the key is changed
358 False if the key is unchanged
361 if value not in (0, 1):
362 raise ValueError("Valid values for value parameter are 0 and 1")
364 path = self._registry_file_path('SOFTWARE')
365 softwarefd, software = tempfile.mkstemp()
368 self.g.download(path, software)
370 h = hivex.Hivex(software, write=True)
373 for child in ('Microsoft', 'Windows', 'CurrentVersion', 'Policies',
375 key = h.node_get_child(key, child)
378 for val in h.node_values(key):
379 if h.value_key(val) == "LocalAccountTokenFilterPolicy":
382 if policy is not None:
383 dword = h.value_dword(policy)
390 'key': "LocalAccountTokenFilterPolicy", 't': 4L,
391 'value': '%s\x00\x00\x00' % '\x00' if value == 0 else '\x01'}
393 h.node_set_value(key, new_value)
396 self.g.upload(software, path)
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())
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()
414 self.g.download(path, sam)
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)
423 users = [h.node_name(x) for x in h.node_children(key)]
428 # Filter out the guest account
429 return filter(lambda x: x != "Guest", users)
431 def _guest_exec(self, command, fatal=True):
432 """Execute a command on a windows VM"""
434 user = "Administrator%" + self.sysprep_params['password']
436 runas = '--runas=%s' % user
437 winexe = subprocess.Popen(
438 ['winexe', '-U', user, "//%s" % addr, runas, command],
439 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
441 stdout, stderr = winexe.communicate()
444 if rc != 0 and fatal:
445 reason = stderr if len(stderr) else stdout
446 raise FatalError("Command: `%s' failed. Reason: %s" %
449 return (stdout, stderr, rc)
451 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :