3 # Copyright (C) 2010 Red Hat Inc.
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 use Sys::Guestfs::Lib qw(open_guest);
25 use Win::Hivex::Regedit qw(reg_import reg_export);
29 use File::Temp qw/tempdir/;
31 use Locale::TextDomain 'libguestfs';
37 virt-win-reg - Export and merge Windows Registry entries from a Windows guest
41 virt-win-reg domname 'HKLM\Path\To\Subkey'
43 virt-win-reg domname 'HKLM\Path\To\Subkey' name
45 virt-win-reg domname 'HKLM\Path\To\Subkey' @
47 virt-win-reg --merge domname [input.reg ...]
49 virt-win-reg [--options] disk.img ... # instead of domname
53 You must I<not> use C<virt-win-reg> with the I<--merge> option on live
54 virtual machines. If you do this, you I<will> get irreversible disk
55 corruption in the VM. C<virt-win-reg> tries to stop you from doing
56 this, but doesn't catch all cases.
58 Modifying the Windows Registry is an inherently risky operation. The format
59 is deliberately obscure and undocumented, and Registry changes
60 can leave the system unbootable. Therefore when using the I<--merge>
61 option, make sure you have a reliable backup first.
65 This program can export and merge Windows Registry entries from a
68 The first parameter is the libvirt guest name or the raw disk image of
71 If I<--merge> is I<not> specified, then the chosen registry
72 key is displayed/exported (recursively). For example:
74 $ virt-win-reg Windows7 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft'
76 You can also display single values from within registry keys,
79 $ cvkey='HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
80 $ virt-win-reg Windows7 $cvkey ProductName
83 With I<--merge>, you can merge a textual regedit file into
86 $ virt-win-reg --merge Windows7 changes.reg
90 This program is only meant for simple access to the registry. If you
91 want to do complicated things with the registry, we suggest you
92 download the Registry hive files from the guest using L<libguestfs(3)>
93 or L<guestfish(1)> and access them locally, eg. using L<hivex(3)>,
94 L<hivexsh(1)> or L<hivexregedit(1)>.
114 Display version number and exit.
122 Enable debugging messages.
128 =item B<--connect URI> | B<-c URI>
130 If using libvirt, connect to the given I<URI>. If omitted, then we
131 connect to the default libvirt hypervisor.
133 If you specify guest block devices directly, then libvirt is not used
140 =item B<--format> raw
142 Specify the format of disk images given on the command line. If this
143 is omitted then the format is autodetected from the content of the
146 If disk images are requested from libvirt, then this program asks
147 libvirt for this information. In this case, the value of the format
148 parameter is ignored.
150 If working with untrusted raw-format guest disk images, you should
151 ensure the format is always specified.
159 In merge mode, this merges a textual regedit file into the Windows
160 Registry of the virtual machine. If this flag is I<not> given then
161 virt-win-reg displays or exports Registry entries instead.
163 Note that I<--merge> is I<unsafe> to use on live virtual machines, and
164 will result in disk corruption. However exporting (without this flag)
171 =item B<--encoding> UTF-16LE|ASCII
173 When merging (only), you may need to specify the encoding for strings
174 to be used in the hive file. This is explained in detail in
175 L<Win::Hivex::Regedit(3)/ENCODING STRINGS>.
177 The default is to use UTF-16LE, which should work with recent versions
184 GetOptions ("help|?" => \$help,
185 "version" => \$version,
186 "connect|c=s" => \$uri,
187 "debug|d" => \$debug,
188 "format=s" => \$format,
190 "encoding=s" => \$encoding,
192 pod2usage (1) if $help;
194 my $g = Sys::Guestfs->new ();
195 my %h = $g->version ();
196 print "$h{major}.$h{minor}.$h{release}$h{extra}\n";
200 # virt-win-reg only takes a single disk image ...
201 die __"no libvirt domain name or disk image given\n" if @ARGV == 0;
202 my $domname_or_image = shift @ARGV;
204 warn "launching libguestfs ..." if $debug;
206 my @lib_args = ([$domname_or_image]);
207 push @lib_args, address => $uri if $uri;
208 push @lib_args, rw => 1 if $merge;
209 push @lib_args, format => $format if defined $format;
210 my $g = open_guest (@lib_args);
213 warn "inspecting guest ..." if $debug;
215 my @roots = $g->inspect_os ();
217 die __x("{prog}: No operating system could be detected inside this disk image.\n\nThis may be because the file is not a disk image, or is not a virtual machine\nimage, or because the OS type is not understood by libguestfs.\n\nIf you feel this is an error, please file a bug report including as much\ninformation about the disk image as possible.\n",
218 prog => basename ($0));
221 die __x("{prog}: multiboot operating systems are not supported.\n",
222 prog => basename ($0))
224 my %fses = $g->inspect_get_mountpoints ($roots[0]);
225 my @fses = sort { length $a <=> length $b } keys %fses;
226 my $mountopts = $merge ? "" : "ro";
228 $g->mount_options ($mountopts, $fses{$_}, $_);
231 my $systemroot = $g->inspect_get_windows_systemroot ($roots[0]);
233 # Create a working directory to store the downloaded registry files.
234 my $tmpdir = tempdir (CLEANUP => 1);
236 # Only used when merging to map downloaded hive names to hive handles.
239 if (!$merge) { # Export mode.
240 die __"expecting 1 or 2 more parameters, subkey path and optionally the value to export\n"
241 if @ARGV < 1 || @ARGV > 2;
243 my $path = shift @ARGV;
244 my $name = shift @ARGV; # or undef
246 # Map this to the hive name. This function dies on failure.
247 my ($hivename, $prefix);
248 ($hivename, $path, $prefix) = map_path_to_hive ($path);
250 # Download the chosen hive.
251 download_hive ($hivename);
254 my $h = Win::Hivex->open ("$tmpdir/$hivename", debug => $debug);
258 warn "exporting $path from $hivename with prefix $prefix ..." if $debug;
259 reg_export ($h, $path, \*STDOUT, prefix => $prefix);
261 # Export a single key using hivexget.
262 my @args = ("hivexget", "$tmpdir/$hivename", $path, $name);
263 warn "running ", join (" ", @args), " ..." if $debug;
264 system (@args) == 0 or die "hivexget failed: $?"
267 else { # Import mode.
269 reg_import (\*STDIN, \&import_mapper, encoding => $encoding);
272 open my $fh, $_ or die "open: $_: $!";
273 reg_import ($fh, \&import_mapper, encoding => $encoding);
277 # Now we've done importing, commit all the hive handles and
279 $_->commit (undef) foreach values %hives;
282 # Look in the tmpdir for all the hive files which have been
283 # downloaded / modified by the import mapper, and upload
285 opendir my $dh, $tmpdir or die "$tmpdir: $!";
286 foreach (readdir $dh) {
299 # map function passed to reg_import.
304 my ($hivename, $path, $prefix) = map_path_to_hive ($_);
306 # Need to download this hive?
307 unless (-f "$tmpdir/$hivename") {
308 download_hive ($hivename);
310 my $h = Win::Hivex->open ("$tmpdir/$hivename",
311 write => 1, debug => $debug);
312 $hives{$hivename} = $h;
315 return ($hives{$hivename}, $path);
318 # Given a path, map that to the name of the hive and the true path
323 my ($hivename, $prefix);
325 if (/^\\?(?:HKEY_LOCAL_MACHINE|HKLM)\\SAM(\\.*)?$/i) {
327 $_ = defined $1 ? $1 : "\\";
328 $prefix = "HKEY_LOCAL_MACHINE\\SAM";
330 elsif (/^\\?(?:HKEY_LOCAL_MACHINE|HKLM)\\SECURITY(\\.*)?$/i) {
331 $hivename = "security";
332 $_ = defined $1 ? $1 : "\\";
333 $prefix = "HKEY_LOCAL_MACHINE\\SECURITY";
335 elsif (/^\\?(?:HKEY_LOCAL_MACHINE|HKLM)\\SOFTWARE(\\.*)?$/i) {
336 $hivename = "software";
337 $_ = defined $1 ? $1 : "\\";
338 $prefix = "HKEY_LOCAL_MACHINE\\SOFTWARE";
340 elsif (/^\\?(?:HKEY_LOCAL_MACHINE|HKLM)\\SYSTEM(\\.*)?$/i) {
341 $hivename = "system";
342 $_ = defined $1 ? $1 : "\\";
343 $prefix = "HKEY_LOCAL_MACHINE\\SYSTEM";
345 elsif (/^\\?(?:HKEY_USERS|HKU)\\.DEFAULT(\\.*)?$/i) {
346 $hivename = "default";
347 $_ = defined $1 ? $1 : "\\";
348 $prefix = "HKEY_LOCAL_MACHINE\\.DEFAULT";
351 die __x("virt-win-reg: {p}: not a supported Windows Registry path\n",
355 return ($hivename, $_, $prefix);
358 # Download a named hive file. Die on failure.
362 my $hivename = shift;
364 my $winfile_before = "$systemroot/system32/config/$hivename";
366 eval { $winfile = $g->case_sensitive_path ($winfile_before); };
368 die __x("virt-win-reg: {p}: file not found in guest: {err}\n",
369 p => $winfile_before, err => $@);
372 warn "downloading $winfile ..." if $debug;
373 eval { $g->download ($winfile, "$tmpdir/$hivename"); };
375 die __x("virt-win-reg: {p}: could not download registry file: {err}\n",
376 p => $winfile, err => $@);
380 # Upload a named hive file. Die on failure.
384 my $hivename = shift;
386 my $winfile_before = "$systemroot/system32/config/$hivename";
388 eval { $winfile = $g->case_sensitive_path ($winfile_before); };
390 die __x("virt-win-reg: {p}: file not found in guest: {err}\n",
391 p => $winfile_before, err => $@);
394 warn "uploading $winfile ..." if $debug;
395 eval { $g->upload ("$tmpdir/$hivename", $winfile); };
397 die __x("virt-win-reg: {p}: could not upload registry file: {err}\n",
398 p => $winfile, err => $@);
402 =head1 SUPPORTED SYSTEMS
404 The program currently supports Windows NT-derived guests starting with
405 Windows XP through to at least Windows 7.
407 Registry support is done for C<HKEY_LOCAL_MACHINE\SAM>,
408 C<HKEY_LOCAL_MACHINE\SECURITY>, C<HKEY_LOCAL_MACHINE\SOFTWARE>,
409 C<HKEY_LOCAL_MACHINE\SYSTEM> and C<HKEY_USERS\.DEFAULT>.
411 You can use C<HKLM> as a shorthand for C<HKEY_LOCAL_MACHINE>, and
412 C<HKU> for C<HKEY_USERS>.
414 C<HKEY_USERS\$SID> and C<HKEY_CURRENT_USER> are B<not> supported at
419 C<virt-win-reg> expects that regedit files have already been reencoded
420 in the local encoding. Usually on Linux hosts, this means UTF-8 with
421 Unix-style line endings. Since Windows regedit files are often in
422 UTF-16LE with Windows-style line endings, you may need to reencode the
423 whole file before or after processing.
425 To reencode a file from Windows format to Linux (before processing it
426 with the I<--merge> option), you would do something like this:
428 iconv -f utf-16le -t utf-8 < win.reg | dos2unix > linux.reg
430 To go in the opposite direction, after exporting and before sending
431 the file to a Windows user, do something like this:
433 unix2dos linux.reg | iconv -f utf-8 -t utf-16le > win.reg
435 For more information about encoding, see L<Win::Hivex::Regedit(3)>.
437 If you are unsure about the current encoding, use the L<file(1)>
438 command. Recent versions of Windows regedit.exe produce a UTF-16LE
439 file with Windows-style (CRLF) line endings, like this:
442 software.reg: Little-endian UTF-16 Unicode text, with very long lines,
443 with CRLF line terminators
445 This file would need conversion before you could I<--merge> it.
447 =head1 CurrentControlSet etc.
449 Registry keys like C<CurrentControlSet> don't really exist in the
450 Windows Registry at the level of the hive file, and therefore you
453 C<CurrentControlSet> is usually an alias for C<ControlSet001>. In
454 some circumstances it might refer to another control set. The way
455 to find out is to look at the C<HKLM\SYSTEM\Select> key:
457 # virt-win-reg WindowsGuest 'HKLM\SYSTEM\Select'
458 [HKEY_LOCAL_MACHINE\SYSTEM\Select]
459 "Current"=dword:00000001
460 "Default"=dword:00000001
461 "Failed"=dword:00000000
462 "LastKnownGood"=dword:00000002
464 "Current" is the one which Windows will choose when it boots.
466 Similarly, other C<Current...> keys in the path may need to
471 Note that some of these tips modify the guest disk image. The guest
472 I<must> be shut off, else you will get disk corruption.
474 =head2 RUNNING A BATCH SCRIPT WHEN A USER LOGS IN
476 Prepare a DOS batch script, VBScript or executable. Upload this using
477 L<guestfish(1)>. For this example the script is called C<test.bat>
478 and it is uploaded into C<C:\>:
480 guestfish -i -d WindowsGuest upload test.bat /test.bat
482 Prepare a regedit file containing the registry change:
484 cat > test.reg <<'EOF'
485 [HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce]
486 "Test"="c:\\test.bat"
489 In this example we use the key C<RunOnce> which means that the script
490 will run precisely once when the first user logs in. If you want it
491 to run every time a user logs in, replace C<RunOnce> with C<Run>.
493 Now update the registry:
495 virt-win-reg --merge WindowsGuest test.reg
497 =head2 INSTALLING A SERVICE
499 This section assumes you are familiar with Windows services, and you
500 either have a program which handles the Windows Service Control
501 Protocol directly or you want to run any program using a service
502 wrapper like SrvAny or the free RHSrvAny.
504 First upload the program and optionally the service wrapper. In this
505 case the test program is called C<test.exe> and we are using the
508 guestfish -i -d WindowsGuest <<EOF
509 upload rhsrvany.exe /rhsrvany.exe
510 upload test.exe /test.exe
513 Prepare a regedit file containing the registry changes. In this
514 example, the first registry change is needed for the service itself or
515 the service wrapper (if used). The second registry change is only
516 needed because I am using the RHSrvAny service wrapper.
518 cat > service.reg <<'EOF'
519 [HKLM\SYSTEM\ControlSet001\services\RHSrvAny]
520 "Type"=dword:00000010
521 "Start"=dword:00000002
522 "ErrorControl"=dword:00000001
523 "ImagePath"="c:\\rhsrvany.exe"
524 "DisplayName"="RHSrvAny"
525 "ObjectName"="NetworkService"
527 [HKLM\SYSTEM\ControlSet001\services\RHSrvAny\Parameters]
528 "CommandLine"="c:\\test.exe"
538 For use of C<ControlSet001> see the section above in this manual page.
539 You may need to adjust this according to the control set that is in
544 C<"ObjectName"> controls the privileges that the service will have.
545 An alternative is C<"ObjectName"="LocalSystem"> which would be the
546 most privileged account.
550 For the meaning of the magic numbers, see this Microsoft KB article:
551 L<http://support.microsoft.com/kb/103000>.
557 virt-win-reg --merge WindowsGuest service.reg
561 Be careful when passing parameters containing C<\> (backslash) in the
562 shell. Usually you will have to use 'single quotes' or double
563 backslashes (but not both) to protect them from the shell.
565 Paths and value names are case-insensitive.
567 Libvirt guest names can contain arbitrary characters, some of which
568 have meaning to the shell such as C<#> and space. You may need to
569 quote or escape these characters on the command line. See the shell
570 manual page L<sh(1)> for details.
581 L<Sys::Guestfs::Lib(3)>,
583 L<Win::Hivex::Regedit(3)>,
585 L<http://libguestfs.org/>.
589 When reporting bugs, please enable debugging and capture the
592 export LIBGUESTFS_DEBUG=1
593 virt-win-reg --debug [... rest ...] > /tmp/virt-win-reg.log 2>&1
595 Attach /tmp/virt-win-reg.log to a new bug report at
596 L<https://bugzilla.redhat.com/>
600 Richard W.M. Jones L<http://people.redhat.com/~rjones/>
604 Copyright (C) 2010 Red Hat Inc.
606 This program is free software; you can redistribute it and/or modify
607 it under the terms of the GNU General Public License as published by
608 the Free Software Foundation; either version 2 of the License, or
609 (at your option) any later version.
611 This program is distributed in the hope that it will be useful,
612 but WITHOUT ANY WARRANTY; without even the implied warranty of
613 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
614 GNU General Public License for more details.
616 You should have received a copy of the GNU General Public License
617 along with this program; if not, write to the Free Software
618 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.