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.
63 password = self.SysprepParam(
64 'password', 'Image Administrator Password', 20, lambda x: True)
68 @sysprep('Disabling IPv6 privacy extensions')
69 def disable_ipv6_privacy_extensions(self):
70 """Disable IPv6 privacy extensions"""
72 self._guest_exec('netsh interface ipv6 set global '
73 'randomizeidentifiers=disabled store=persistent')
75 @sysprep('Executing sysprep on the image (may take more that 10 minutes)')
76 def microsoft_sysprep(self):
77 """Run the Microsoft System Preparation Tool on the Image. This will
78 remove system-specific data and will make the image ready to be
79 deployed. After this no other task may run.
82 self._guest_exec(r'C:\Windows\system32\sysprep\sysprep '
83 r'/quiet /generalize /oobe /shutdown')
87 """Prepare system for image creation."""
89 if getattr(self, 'syspreped', False):
90 raise FatalError("Image is already syspreped!")
92 txt = "System preparation parameter: `%s' is needed but missing!"
93 for param in self.needed_sysprep_params():
94 if param[0] not in self.sysprep_params:
95 raise FatalError(txt % param[0])
97 self.mount(readonly=False)
99 disabled_uac = self._update_uac_remote_setting(1)
100 token = self._enable_os_monitor()
104 self.out.output("Shutting down helper VM ...", False)
106 # guestfs_shutdown which is the prefered way to shutdown the backend
107 # process was introduced in version 1.19.16
108 if check_guestfs_version(self.g, 1, 19, 16) >= 0:
109 ret = self.g.shutdown()
111 ret = self.g.kill_subprocess()
113 self.out.success('done')
118 self.out.output("Starting windows VM ...", False)
119 monitorfd, monitor = tempfile.mkstemp()
121 vm, display = self._create_vm(monitor)
122 self.out.success("started (console on vnc display: %d)." % display)
124 self.out.output("Waiting for OS to boot ...", False)
125 if not self._wait_on_file(monitor, token):
126 raise FatalError("Windows booting timed out.")
128 self.out.success('done')
130 self.out.output("Disabling automatic logon ...", False)
131 self._disable_autologon()
132 self.out.success('done')
134 self.out.output('Preparing system from image creation:')
136 tasks = self.list_syspreps()
137 enabled = filter(lambda x: x.enabled, tasks)
141 # Make sure the ms sysprep is the last task to run if it is enabled
143 lambda x: x.im_func.func_name != 'microsoft_sysprep', enabled)
145 ms_sysprep_enabled = False
146 if len(enabled) != size:
147 enabled.append(self.ms_sysprep)
148 ms_sysprep_enabled = True
153 self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False)
155 setattr(task.im_func, 'executed', True)
157 self.out.output("Shutting down windows VM ...", False)
158 if not ms_sysprep_enabled:
160 self.out.success("done")
164 if monitor is not None:
170 self.out.output("Relaunching helper VM (may take a while) ...",
173 self.out.success('done')
176 self._update_uac_remote_setting(0)
178 def _create_vm(self, monitor):
179 """Create a VM with the image attached as the disk
181 monitor: a file to be used to monitor when the OS is up
185 mac = [0x00, 0x16, 0x3e,
186 random.randint(0x00, 0x7f),
187 random.randint(0x00, 0xff),
188 random.randint(0x00, 0xff)]
190 return ':'.join(map(lambda x: "%02x" % x, mac))
192 # Use ganeti's VNC port range for a random vnc port
193 vnc_port = random.randint(11000, 14999)
194 display = vnc_port - 5900
196 vm = kvm('-smp', '1', '-m', '1024', '-drive',
197 'file=%s,format=raw,cache=none,if=virtio' % self.image.device,
198 '-netdev', 'type=user,hostfwd=tcp::445-:445,id=netdev0',
199 '-device', 'virtio-net-pci,mac=%s,netdev=netdev0' %
200 random_mac(), '-vnc', ':%d' % display, '-serial',
201 'file:%s' % monitor, _bg=True)
205 def _destroy_vm(self, vm):
206 """Destroy a VM previously created by _create_vm"""
211 """Shuts down the windows VM"""
212 self._guest_exec(r'shutdown /s /t 5')
214 def _wait_on_file(self, fname, msg):
215 """Wait until a message appears on a file"""
217 for i in range(BOOT_TIMEOUT):
219 with open(fname) as f:
221 if line.startswith(msg):
225 def _disable_autologon(self):
226 """Disable automatic logon on the windows image"""
229 r'"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"'
231 self._guest_exec('REG DELETE %s /v DefaultUserName /f' % winlogon)
232 self._guest_exec('REG DELETE %s /v DefaultPassword /f' % winlogon)
233 self._guest_exec('REG DELETE %s /v AutoAdminLogon /f' % winlogon)
235 def _registry_file_path(self, regfile):
236 """Retrieves the case sensitive path to a registry file"""
238 systemroot = self.g.inspect_get_windows_systemroot(self.root)
239 path = "%s/system32/config/%s" % (systemroot, regfile)
241 path = self.g.case_sensitive_path(path)
242 except RuntimeError as e:
243 raise FatalError("Unable to retrieve registry file: %s. Reason: %s"
247 def _enable_os_monitor(self):
248 """Add a script in the registry that will send a random string to the
249 first serial port when the windows image finishes booting.
252 token = "".join(random.choice(string.ascii_letters) for x in range(16))
254 path = self._registry_file_path('SOFTWARE')
255 softwarefd, software = tempfile.mkstemp()
258 self.g.download(path, software)
260 h = hivex.Hivex(software, write=True)
262 # Enable automatic logon.
263 # This is needed because we need to execute a script that we add in
264 # the RunOnce registry entry and those programs only get executed
265 # when a user logs on. There is a RunServicesOnce registry entry
266 # whose keys get executed in the background when the logon dialog
267 # box first appears, but they seem to only work with services and
268 # not arbitrary command line expressions :-(
270 # Instructions on how to turn on automatic logon in Windows can be
271 # found here: http://support.microsoft.com/kb/324737
273 # Warning: Registry change will not work if the “Logon Banner” is
274 # defined on the server either by a Group Policy object (GPO) or by
278 for child in ('Microsoft', 'Windows NT', 'CurrentVersion',
280 winlogon = h.node_get_child(winlogon, child)
284 {'key': 'DefaultUserName', 't': 1,
285 'value': "Administrator".encode('utf-16le')})
288 {'key': 'DefaultPassword', 't': 1,
289 'value': self.sysprep_params['password'].encode('utf-16le')})
292 {'key': 'AutoAdminLogon', 't': 1,
293 'value': "1".encode('utf-16le')})
296 for child in ('Microsoft', 'Windows', 'CurrentVersion'):
297 key = h.node_get_child(key, child)
299 runonce = h.node_get_child(key, "RunOnce")
301 runonce = h.node_add_child(key, "RunOnce")
304 r'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe '
305 r'-ExecutionPolicy RemoteSigned '
306 r'"&{$port=new-Object System.IO.Ports.SerialPort COM1,9600,'
307 r'None,8,one;$port.open();$port.WriteLine(\"' + token + r'\");'
308 r'$port.Close()}"').encode('utf-16le')
310 h.node_set_value(runonce,
311 {'key': "BootMonitor", 't': 1, 'value': value})
315 self.g.upload(software, path)
321 def _update_uac_remote_setting(self, value):
322 """Updates the registry key value:
323 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies
324 \System]"LocalAccountTokenFilterPolicy"
326 value = 1 will disable the UAC remote restrictions
327 value = 0 will enable the UAC remote restrictions
329 For more info see here: http://support.microsoft.com/kb/951016
332 True if the key is changed
333 False if the key is unchanged
336 if value not in (0, 1):
337 raise ValueError("Valid values for value parameter are 0 and 1")
339 path = self._registry_file_path('SOFTWARE')
340 softwarefd, software = tempfile.mkstemp()
343 self.g.download(path, software)
345 h = hivex.Hivex(software, write=True)
348 for child in ('Microsoft', 'Windows', 'CurrentVersion', 'Policies',
350 key = h.node_get_child(key, child)
353 for val in h.node_values(key):
354 if h.value_key(val) == "LocalAccountTokenFilterPolicy":
357 if policy is not None:
358 dword = h.value_dword(policy)
365 'key': "LocalAccountTokenFilterPolicy", 't': 4L,
366 'value': '%s\x00\x00\x00' % '\x00' if value == 0 else '\x01'}
368 h.node_set_value(key, new_value)
371 self.g.upload(software, path)
378 def _do_collect_metadata(self):
379 """Collect metadata about the OS"""
380 super(Windows, self)._do_collect_metadata()
381 self.meta["USERS"] = " ".join(self._get_users())
383 def _get_users(self):
384 """Returns a list of users found in the images"""
385 path = self._registry_file_path('SAM')
386 samfd, sam = tempfile.mkstemp()
389 self.g.download(path, sam)
394 # Navigate to /SAM/Domains/Account/Users/Names
395 for child in ('SAM', 'Domains', 'Account', 'Users', 'Names'):
396 key = h.node_get_child(key, child)
398 users = [h.node_name(x) for x in h.node_children(key)]
403 # Filter out the guest account
404 return filter(lambda x: x != "Guest", users)
406 def _guest_exec(self, command, fatal=True):
407 """Execute a command on a windows VM"""
409 user = "Administrator%" + self.sysprep_params['password']
411 runas = '--runas=%s' % user
412 winexe = subprocess.Popen(
413 ['winexe', '-U', user, "//%s" % addr, runas, command],
414 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
416 stdout, stderr = winexe.communicate()
419 if rc != 0 and fatal:
420 reason = stderr if len(stderr) else stdout
421 raise FatalError("Command: `%s' failed. Reason: %s" %
424 return (stdout, stderr, rc)
426 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :