root / image_creator / os_type / windows.py @ 28d354ce
History | View | Annotate | Download (18.9 kB)
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 |
import struct |
50 |
|
51 |
kvm = get_command('kvm')
|
52 |
|
53 |
BOOT_TIMEOUT = 300
|
54 |
|
55 |
|
56 |
class Windows(OSBase): |
57 |
"""OS class for Windows"""
|
58 |
|
59 |
def needed_sysprep_params(self): |
60 |
"""Returns a list of needed sysprep parameters. Each element in the
|
61 |
list is a SysprepParam object.
|
62 |
"""
|
63 |
password = self.SysprepParam(
|
64 |
'password', 'Image Administrator Password', 20, lambda x: True) |
65 |
|
66 |
return [password]
|
67 |
|
68 |
@sysprep('Disabling IPv6 privacy extensions') |
69 |
def disable_ipv6_privacy_extensions(self): |
70 |
"""Disable IPv6 privacy extensions"""
|
71 |
|
72 |
self._guest_exec('netsh interface ipv6 set global ' |
73 |
'randomizeidentifiers=disabled store=persistent')
|
74 |
|
75 |
@sysprep('Disabling Teredo interface') |
76 |
def disable_teredo(self): |
77 |
"""Disable Teredo interface"""
|
78 |
|
79 |
self._guest_exec('netsh interface teredo set state disabled') |
80 |
|
81 |
@sysprep('Disabling ISATAP Adapters') |
82 |
def disable_isatap(self): |
83 |
"""Disable ISATAP Adapters"""
|
84 |
|
85 |
self._guest_exec('netsh interface isa set state disabled') |
86 |
|
87 |
@sysprep('Enabling ping responses') |
88 |
def enable_pings(self): |
89 |
"""Enable ping responces"""
|
90 |
|
91 |
self._guest_exec('netsh firewall set icmpsetting 8') |
92 |
|
93 |
@sysprep('Disabling hibernation support') |
94 |
def disable_hibernation(self): |
95 |
"""Disable hibernation support and remove the hibernation file"""
|
96 |
|
97 |
self._guest_exec(r'powercfg.exe /hibernate off') |
98 |
|
99 |
@sysprep('Setting the system clock to UTC') |
100 |
def utc(self): |
101 |
"""Set the hardware clock to UTC"""
|
102 |
|
103 |
path = r'HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation'
|
104 |
self._guest_exec(
|
105 |
r'REG ADD %s /v RealTimeIsUniversal /t REG_DWORD /d 1 /f' % path)
|
106 |
|
107 |
@sysprep('Executing sysprep on the image (may take more that 10 minutes)') |
108 |
def microsoft_sysprep(self): |
109 |
"""Run the Microsoft System Preparation Tool. This will remove
|
110 |
system-specific data and will make the image ready to be deployed.
|
111 |
After this no other task may run.
|
112 |
"""
|
113 |
|
114 |
self._guest_exec(r'C:\Windows\system32\sysprep\sysprep ' |
115 |
r'/quiet /generalize /oobe /shutdown')
|
116 |
self.syspreped = True |
117 |
|
118 |
def do_sysprep(self): |
119 |
"""Prepare system for image creation."""
|
120 |
|
121 |
if getattr(self, 'syspreped', False): |
122 |
raise FatalError("Image is already syspreped!") |
123 |
|
124 |
txt = "System preparation parameter: `%s' is needed but missing!"
|
125 |
for param in self.needed_sysprep_params(): |
126 |
if param[0] not in self.sysprep_params: |
127 |
raise FatalError(txt % param[0]) |
128 |
|
129 |
self.mount(readonly=False) |
130 |
try:
|
131 |
disabled_uac = self._update_uac_remote_setting(1) |
132 |
token = self._enable_os_monitor()
|
133 |
|
134 |
# disable the firewalls
|
135 |
firewall_states = self._update_firewalls(0, 0, 0) |
136 |
|
137 |
# Delete the pagefile. It will be recreated when the system boots
|
138 |
systemroot = self.g.inspect_get_windows_systemroot(self.root) |
139 |
pagefile = "%s/pagefile.sys" % systemroot
|
140 |
self.g.rm_rf(self.g.case_sensitive_path(pagefile)) |
141 |
|
142 |
finally:
|
143 |
self.umount()
|
144 |
|
145 |
self.out.output("Shutting down helper VM ...", False) |
146 |
self.g.sync()
|
147 |
# guestfs_shutdown which is the prefered way to shutdown the backend
|
148 |
# process was introduced in version 1.19.16
|
149 |
if check_guestfs_version(self.g, 1, 19, 16) >= 0: |
150 |
ret = self.g.shutdown()
|
151 |
else:
|
152 |
ret = self.g.kill_subprocess()
|
153 |
|
154 |
self.out.success('done') |
155 |
|
156 |
vm = None
|
157 |
monitor = None
|
158 |
try:
|
159 |
self.out.output("Starting windows VM ...", False) |
160 |
monitorfd, monitor = tempfile.mkstemp() |
161 |
os.close(monitorfd) |
162 |
vm, display = self._create_vm(monitor)
|
163 |
self.out.success("started (console on vnc display: %d)." % display) |
164 |
|
165 |
self.out.output("Waiting for OS to boot ...", False) |
166 |
if not self._wait_on_file(monitor, token): |
167 |
raise FatalError("Windows booting timed out.") |
168 |
else:
|
169 |
self.out.success('done') |
170 |
|
171 |
self.out.output("Disabling automatic logon ...", False) |
172 |
self._disable_autologon()
|
173 |
self.out.success('done') |
174 |
|
175 |
self.out.output('Preparing system from image creation:') |
176 |
|
177 |
tasks = self.list_syspreps()
|
178 |
enabled = filter(lambda x: x.enabled, tasks) |
179 |
size = len(enabled)
|
180 |
|
181 |
# Make sure the ms sysprep is the last task to run if it is enabled
|
182 |
enabled = filter(
|
183 |
lambda x: x.im_func.func_name != 'microsoft_sysprep', enabled) |
184 |
|
185 |
ms_sysprep_enabled = False
|
186 |
if len(enabled) != size: |
187 |
enabled.append(self.microsoft_sysprep)
|
188 |
ms_sysprep_enabled = True
|
189 |
|
190 |
cnt = 0
|
191 |
for task in enabled: |
192 |
cnt += 1
|
193 |
self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False) |
194 |
task() |
195 |
setattr(task.im_func, 'executed', True) |
196 |
|
197 |
self.out.output("Sending shut down command ...", False) |
198 |
if not ms_sysprep_enabled: |
199 |
self._shutdown()
|
200 |
self.out.success("done") |
201 |
|
202 |
self.out.output("Waiting for windows to shut down ...", False) |
203 |
vm.wait() |
204 |
self.out.success("done") |
205 |
finally:
|
206 |
if monitor is not None: |
207 |
os.unlink(monitor) |
208 |
|
209 |
if vm is not None: |
210 |
self._destroy_vm(vm)
|
211 |
|
212 |
self.out.output("Relaunching helper VM (may take a while) ...", |
213 |
False)
|
214 |
self.g.launch()
|
215 |
self.out.success('done') |
216 |
|
217 |
self.mount(readonly=False) |
218 |
try:
|
219 |
if disabled_uac:
|
220 |
self._update_uac_remote_setting(0) |
221 |
|
222 |
self._update_firewalls(*firewall_states)
|
223 |
finally:
|
224 |
self.umount()
|
225 |
|
226 |
def _create_vm(self, monitor): |
227 |
"""Create a VM with the image attached as the disk
|
228 |
|
229 |
monitor: a file to be used to monitor when the OS is up
|
230 |
"""
|
231 |
|
232 |
def random_mac(): |
233 |
mac = [0x00, 0x16, 0x3e, |
234 |
random.randint(0x00, 0x7f), |
235 |
random.randint(0x00, 0xff), |
236 |
random.randint(0x00, 0xff)] |
237 |
|
238 |
return ':'.join(map(lambda x: "%02x" % x, mac)) |
239 |
|
240 |
# Use ganeti's VNC port range for a random vnc port
|
241 |
vnc_port = random.randint(11000, 14999) |
242 |
display = vnc_port - 5900
|
243 |
|
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) |
250 |
|
251 |
return vm, display
|
252 |
|
253 |
def _destroy_vm(self, vm): |
254 |
"""Destroy a VM previously created by _create_vm"""
|
255 |
if vm.process.alive:
|
256 |
vm.terminate() |
257 |
|
258 |
def _shutdown(self): |
259 |
"""Shuts down the windows VM"""
|
260 |
self._guest_exec(r'shutdown /s /t 5') |
261 |
|
262 |
def _wait_on_file(self, fname, msg): |
263 |
"""Wait until a message appears on a file"""
|
264 |
|
265 |
for i in range(BOOT_TIMEOUT): |
266 |
time.sleep(1)
|
267 |
with open(fname) as f: |
268 |
for line in f: |
269 |
if line.startswith(msg):
|
270 |
return True |
271 |
return False |
272 |
|
273 |
def _disable_autologon(self): |
274 |
"""Disable automatic logon on the windows image"""
|
275 |
|
276 |
winlogon = \ |
277 |
r'"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"'
|
278 |
|
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) |
282 |
|
283 |
def _registry_file_path(self, regfile): |
284 |
"""Retrieves the case sensitive path to a registry file"""
|
285 |
|
286 |
systemroot = self.g.inspect_get_windows_systemroot(self.root) |
287 |
path = "%s/system32/config/%s" % (systemroot, regfile)
|
288 |
try:
|
289 |
path = self.g.case_sensitive_path(path)
|
290 |
except RuntimeError as e: |
291 |
raise FatalError("Unable to retrieve registry file: %s. Reason: %s" |
292 |
% (regfile, str(e)))
|
293 |
return path
|
294 |
|
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.
|
298 |
"""
|
299 |
|
300 |
token = "".join(random.choice(string.ascii_letters) for x in range(16)) |
301 |
|
302 |
path = self._registry_file_path('SOFTWARE') |
303 |
softwarefd, software = tempfile.mkstemp() |
304 |
try:
|
305 |
os.close(softwarefd) |
306 |
self.g.download(path, software)
|
307 |
|
308 |
h = hivex.Hivex(software, write=True)
|
309 |
|
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 :-(
|
317 |
#
|
318 |
# Instructions on how to turn on automatic logon in Windows can be
|
319 |
# found here: http://support.microsoft.com/kb/324737
|
320 |
#
|
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
|
323 |
# a local policy.
|
324 |
|
325 |
winlogon = h.root() |
326 |
for child in ('Microsoft', 'Windows NT', 'CurrentVersion', |
327 |
'Winlogon'):
|
328 |
winlogon = h.node_get_child(winlogon, child) |
329 |
|
330 |
h.node_set_value( |
331 |
winlogon, |
332 |
{'key': 'DefaultUserName', 't': 1, |
333 |
'value': "Administrator".encode('utf-16le')}) |
334 |
h.node_set_value( |
335 |
winlogon, |
336 |
{'key': 'DefaultPassword', 't': 1, |
337 |
'value': self.sysprep_params['password'].encode('utf-16le')}) |
338 |
h.node_set_value( |
339 |
winlogon, |
340 |
{'key': 'AutoAdminLogon', 't': 1, |
341 |
'value': "1".encode('utf-16le')}) |
342 |
|
343 |
key = h.root() |
344 |
for child in ('Microsoft', 'Windows', 'CurrentVersion'): |
345 |
key = h.node_get_child(key, child) |
346 |
|
347 |
runonce = h.node_get_child(key, "RunOnce")
|
348 |
if runonce is None: |
349 |
runonce = h.node_add_child(key, "RunOnce")
|
350 |
|
351 |
value = ( |
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') |
357 |
|
358 |
h.node_set_value(runonce, |
359 |
{'key': "BootMonitor", 't': 1, 'value': value}) |
360 |
|
361 |
value = ( |
362 |
r'REG ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion'
|
363 |
r'\policies\system /v LocalAccountTokenFilterPolicy'
|
364 |
r' /t REG_DWORD /d 1 /f').encode('utf-16le') |
365 |
|
366 |
h.node_set_value(runonce, |
367 |
{'key': "UpdateRegistry", 't': 1, 'value': value}) |
368 |
|
369 |
h.commit(None)
|
370 |
|
371 |
self.g.upload(software, path)
|
372 |
finally:
|
373 |
os.unlink(software) |
374 |
|
375 |
return token
|
376 |
|
377 |
def _update_firewalls(self, domain, public, standard): |
378 |
"""Enables or disables the firewall for the Domain, the Public and the
|
379 |
Standard profile. Returns a triplete with the old values.
|
380 |
|
381 |
1 will enable a firewall and 0 will disable it
|
382 |
"""
|
383 |
|
384 |
if domain not in (0, 1): |
385 |
raise ValueError("Valid values for domain parameter are 0 and 1") |
386 |
|
387 |
if public not in (0, 1): |
388 |
raise ValueError("Valid values for public parameter are 0 and 1") |
389 |
|
390 |
if standard not in (0, 1): |
391 |
raise ValueError("Valid values for standard parameter are 0 and 1") |
392 |
|
393 |
path = self._registry_file_path("SYSTEM") |
394 |
systemfd, system = tempfile.mkstemp() |
395 |
try:
|
396 |
os.close(systemfd) |
397 |
self.g.download(path, system)
|
398 |
|
399 |
h = hivex.Hivex(system, write=True)
|
400 |
|
401 |
select = h.node_get_child(h.root(), 'Select')
|
402 |
current_value = h.node_get_value(select, 'Current')
|
403 |
|
404 |
# expecting a little endian dword
|
405 |
assert h.value_type(current_value)[1] == 4 |
406 |
current = "%03d" % h.value_dword(current_value)
|
407 |
|
408 |
firewall_policy = h.root() |
409 |
for child in ('ControlSet%s' % current, 'services', 'SharedAccess', |
410 |
'Parameters', 'FirewallPolicy'): |
411 |
firewall_policy = h.node_get_child(firewall_policy, child) |
412 |
|
413 |
old_values = [] |
414 |
new_values = [domain, public, standard] |
415 |
for profile in ('Domain', 'Public', 'Standard'): |
416 |
node = h.node_get_child(firewall_policy, '%sProfile' % profile)
|
417 |
|
418 |
old_value = h.node_get_value(node, 'EnableFirewall')
|
419 |
|
420 |
# expecting a little endian dword
|
421 |
assert h.value_type(old_value)[1] == 4 |
422 |
old_values.append(h.value_dword(old_value)) |
423 |
|
424 |
h.node_set_value( |
425 |
node, {'key': 'EnableFirewall', 't': 4L, |
426 |
'value': struct.pack("<I", new_values.pop(0))}) |
427 |
|
428 |
h.commit(None)
|
429 |
self.g.upload(system, path)
|
430 |
|
431 |
finally:
|
432 |
os.unlink(system) |
433 |
|
434 |
return old_values
|
435 |
|
436 |
def _update_uac_remote_setting(self, value): |
437 |
"""Updates the registry key value:
|
438 |
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies
|
439 |
\System]"LocalAccountTokenFilterPolicy"
|
440 |
|
441 |
value = 1 will disable the UAC remote restrictions
|
442 |
value = 0 will enable the UAC remote restrictions
|
443 |
|
444 |
For more info see here: http://support.microsoft.com/kb/951016
|
445 |
|
446 |
Returns:
|
447 |
True if the key is changed
|
448 |
False if the key is unchanged
|
449 |
"""
|
450 |
|
451 |
if value not in (0, 1): |
452 |
raise ValueError("Valid values for value parameter are 0 and 1") |
453 |
|
454 |
path = self._registry_file_path('SOFTWARE') |
455 |
softwarefd, software = tempfile.mkstemp() |
456 |
try:
|
457 |
os.close(softwarefd) |
458 |
self.g.download(path, software)
|
459 |
|
460 |
h = hivex.Hivex(software, write=True)
|
461 |
|
462 |
key = h.root() |
463 |
for child in ('Microsoft', 'Windows', 'CurrentVersion', 'Policies', |
464 |
'System'):
|
465 |
key = h.node_get_child(key, child) |
466 |
|
467 |
policy = None
|
468 |
for val in h.node_values(key): |
469 |
if h.value_key(val) == "LocalAccountTokenFilterPolicy": |
470 |
policy = val |
471 |
|
472 |
if policy is not None: |
473 |
dword = h.value_dword(policy) |
474 |
if dword == value:
|
475 |
return False |
476 |
elif value == 0: |
477 |
return False |
478 |
|
479 |
new_value = {'key': "LocalAccountTokenFilterPolicy", 't': 4L, |
480 |
'value': struct.pack("<I", value)} |
481 |
|
482 |
h.node_set_value(key, new_value) |
483 |
h.commit(None)
|
484 |
|
485 |
self.g.upload(software, path)
|
486 |
|
487 |
finally:
|
488 |
os.unlink(software) |
489 |
|
490 |
return True |
491 |
|
492 |
def _do_collect_metadata(self): |
493 |
"""Collect metadata about the OS"""
|
494 |
super(Windows, self)._do_collect_metadata() |
495 |
self.meta["USERS"] = " ".join(self._get_users()) |
496 |
|
497 |
def _get_users(self): |
498 |
"""Returns a list of users found in the images"""
|
499 |
path = self._registry_file_path('SAM') |
500 |
samfd, sam = tempfile.mkstemp() |
501 |
try:
|
502 |
os.close(samfd) |
503 |
self.g.download(path, sam)
|
504 |
|
505 |
h = hivex.Hivex(sam) |
506 |
|
507 |
key = h.root() |
508 |
# Navigate to /SAM/Domains/Account/Users/Names
|
509 |
for child in ('SAM', 'Domains', 'Account', 'Users', 'Names'): |
510 |
key = h.node_get_child(key, child) |
511 |
|
512 |
users = [h.node_name(x) for x in h.node_children(key)] |
513 |
|
514 |
finally:
|
515 |
os.unlink(sam) |
516 |
|
517 |
# Filter out the guest account
|
518 |
return filter(lambda x: x != "Guest", users) |
519 |
|
520 |
def _guest_exec(self, command, fatal=True): |
521 |
"""Execute a command on a windows VM"""
|
522 |
|
523 |
user = "Administrator%" + self.sysprep_params['password'] |
524 |
addr = 'localhost'
|
525 |
runas = '--runas=%s' % user
|
526 |
winexe = subprocess.Popen( |
527 |
['winexe', '-U', user, "//%s" % addr, runas, command], |
528 |
stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
529 |
|
530 |
stdout, stderr = winexe.communicate() |
531 |
rc = winexe.poll() |
532 |
|
533 |
if rc != 0 and fatal: |
534 |
reason = stderr if len(stderr) else stdout |
535 |
raise FatalError("Command: `%s' failed. Reason: %s" % |
536 |
(command, reason)) |
537 |
|
538 |
return (stdout, stderr, rc)
|
539 |
|
540 |
# vim: set sta sts=4 shiftwidth=4 sw=4 et ai :
|