Export (0) Print
Expand All

Administering the Windows NT Registry

Archived content. No warranty is made as to technical accuracy. Content may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.
By Paul Robichaux

Archived content - No warranty is made as to technical accuracy. Content may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

admreg01

Click to Order

Chapter 8, Managing the Windows NT Registry, published by O'Reilly & Associates

When you're responsible for administering computers-whether one or many-you quickly find that much of what you do on a daily basis is miscellanea. You create new accounts, remove old ones, figure out why your backup tape drive is dead, and so forth. It would be nice if your whole career could revolve around orderly, planned upgrades, maintenance, and migrations, but those little tasks are important too. This chapter will introduce you to several small tasks related to managing the NT Registry; while none of them is a full-time activity, all of them are worth doing.

On This Page

Setting Defaults for New User Accounts
Using Initialization File Mapping
Limiting Remote Registry Access
Fixing Registry Security ACLs
Encrypting HKLM\SAM with SYSKEY
Miscellaneous Good Stuff
Using the Resource Kit Utilities
Spying on the Registry with NTREGMON

Setting Defaults for New User Accounts

NT was designed from the start to support multiple user accounts sharing a single computer. Unlike DOS and Windows 3.x, NT provided a way (through the Registry, actually) to keep individual settings for each user. However, the original versions of NT didn't provide any way for these settings to be shared between computers, and there were no mechanisms for collecting all of a user's settings data in a single place.

NT 4.0 was the first version of NT to support the concept of user profiles. Like the profiles in Win95, NT 4.0 profiles capture a user's desktop environment, application settings, and other preferences. These profiles can roam from computer to computer, so that users can have their own personalized environment on every machine they log onto. In addition, administrators can configure these profiles to prevent users from changing all or part of the settings, thus making it easier to set up shared computer labs and other facilities where it's important to protect machines against tampering.

When you install NT on a machine, the system uses a default profile to provide settings for your user accounts. The first time a newly created account logs in, the default profile is copied into HKCU, thus making the new account inherit the default settings. Unfortunately, there's no direct way to change settings in this default profile. You can use the System Policy Editor (as described in Chapter 6, Using the System Policy Editor) to set policies for the "Default User" account, but if you want to change a setting that's not in one of the policy templates-say, the default currency format or the list of predefined URLs that Internet Explorer stores-you have two choices. You can create a new policy template that contains the new settings you want to apply, or you can edit the default user profile directly.

NT stores the default user profile in a file. On individual workstations and servers, the profile is stored in %systemroot%\profiles\Default User. You can also force the default profile to apply to all domain logons by putting it in the NETLOGON share of your domain controller. When it's there, the file must be named Ntuser.dat. Whatever settings are in this file will be applied to new user accounts, but they won't affect existing accounts. Ntuser.dat is really just a Registry hive; when a new account logs on for the first time, NT copies the contents of the hive to HKCU, then writes the changes to the appropriate subkey of HKU. By changing what's in the initial hive, you affect what settings go into that user's HKCU when she logs on.

Because the default user profile is just a Registry hive, you can edit it with RegEdt32. Here's what to do:

  1. Start RegEdt32. When it opens, open up the HKU window and select the HKU root key.

  2. Use the Registry > Load Hive- menu command to select the default user profile you want to edit. You can directly open %systemroot%\profiles\Default User, or you can edit NTuser.man if it's available.

  3. When RegEdt32 asks for a key name, make up any name that will remind you what the hive is for. I usually use "DefaultUserProfile." RegEdt32 will import the hive and attach it under the name you supply.

  4. Select the new hive key and use the Security > Permissions- command to add Everyone:Read access to the key and its subkeys. This enables the profile sharing mechanism to copy keys from the default profile to users' HKCU.

  5. Use RegEdt32 to make the desired changes to subkeys of your new hive. As you make changes, they'll be transparently stored in the hive file.

  6. Once you've finished editing all the hive keys, use the Registry > Unload Hive command to detach the hive. Until you do this, no other computer or user can get access to the changes you've made.

Using Initialization File Mapping

In Chapter 1, A Gentle Introduction to the NT Registry, I described how the Registry evolved from its humble parentage of INI files. Many NT installations are still running 16-bit Win 3.1 applications that don't support the Registry, and a surprising number of 32-bit applications still rely on the old INI file structure-despite the fact that using the Registry is one of the requirements for getting the coveted "Designed for Windows 95" logo from Microsoft.

Since there's no way to upgrade skanky old 16-bit applications to use the Registry, you might think that you're stuck forever with the mess of tracking, backing up, and protecting a mess of INI files. Not so! NT includes a feature called initialization file mapping (I'll call it just "mapping" from now on) that allows you to force Registry-unaware programs to load and save configuration data in the Registry instead of in an INI file.

NT already includes mappings for several system components, including the Windows clock desk accessory, the bundled 32-bit NT tape backup application, and even RegEdt32 ! Mappings aren't just for 16-bit applications; rather, they're for any application-16- or 32-bit-that doesn't include code to read and write Registry data.

Of course, mapping's not required; applications that depend on INI files can work just fine under NT without having the files mapped. In fact, unless you explicitly take action to map these files, they'll remain unmapped, and their normal INI file usage will continue without interruption.

How Does Mapping Work?

NT implements mapping by trapping the private profile API routines I mentioned in Chapter 1. Windows applications and components ordinarily use these calls to get and set data stored in INI files, but when there's a mapping entry, the NT kernel first checks for the presence of a mapping key. If one exists, and if it points to a key that contains data, that data is returned to the caller. If there's no mapping key, or if it points to an empty or non-existent Registry key, NT will go ahead and try to read the data from the INI file. The caller need never be aware that the data didn't come from the requested file.

Mapping only occurs when there's a mapping key in place. These keys are stored beneath the HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\IniFileMapping subkey. If you look there, you'll notice a number of subkeys with names like Clock.INI, Win.INI, and SYSTEM.INI. These keys tie sections of the old Win 3.1-style INI files to keys in the Registry so that old Windows 3.1 components like the Clock and the original media controller interface (MCI) will continue to find their settings.

Application programmers and administrators are free to create new mappings between any INI file and any key in the Registry. This allows you to move settings data to the Registry where it properly belongs; once it's there, you can edit, save, massage, and manage it using the skills you've learned throughout this book.

Time for a real-life story: a client had licensed several hundred seats for a popular email application. This app had a 32-bit version, but it didn't use the Registry. I created a mapping for the program's settings, then built a system policy template (see Chapter 6 for details) so they could centrally control how users set up their mail clients. Everyone walked away happy.

Setting Up Your Own Mappings

In an ideal world, all the applications on your computers would be 32-bit, Registry-aware, NT-native programs. Unfortunately, only people running NT on RISC-based machines that can't run Win95 or Win 3.x programs have that luxury. For the rest of us, though, it's easy to add mapping keys to force NT to use Registry keys instead of sections in an INI file; best of all, you can do so without any changes to the application that owns the INI file.

If you've ever opened an INI file, you know that it's divided into sections. Section names are enclosed by square brackets, and they contain name/value pairs. The whole arrangement looks like this sample from an imaginary data security package's INI file:

[Encryption]

DefaultSigAlgorithm=RSAWithSHA1

DefaultEncryptionAlgorithm=DES3-EDE-CBC

WipeFilesWhenDone=1

In this example, "Encryption" is the section name, and "DefaultSigAlgorithm," "DefaultEncryptionAlgorithm," and "WipeFilesWhenDone" are the value names.

Adding the mapping key

You may map any or all sections of any INI file to a Registry key. To do so, you must add a new subkey to HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\IniFileMapping. This subkey should have the same name as the INI file you're mapping; for example, to remap a file named ccmail.ini you'd add a new subkey with that name to the IniFileMapping key.

If you just add a new mapping key by itself, nothing will happen. This is because the named subkey just tells NT to watch for access to the INI file with the same name; it doesn't tell where the data are actually stored in the Registry. You specify the location (or locations) by creating values underneath the key. Each of these values should have a name that matches a section in the INI file. These section names are combined with the name of the parent key to help the profile API routines figure out what data you're requesting.

To map the key in the example above, you'd create a new key named HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\IniFileMapping\Crypto.INI. Under that key, you'd add a value named Encryption. The combination of these two values tells NT that any attempt to access the "Encryption" section of crypto.ini should instead look in the Registry.

The value you give to these section keys tells NT where the real data is stored in the Registry. Let's say that our data security program stores its data in HKLM\Software\Crypto\CurrentVersion\Settings. To complete the mapping we started in the previous paragraph, we'd specify this Registry key as the contents of the Encryption value. By doing so, we've given NT enough information to translate requests for data in an INI file to a Registry key.

Mapping key tricks

There are a couple of tricks that apply to building mapping key entries. First of all, you can specify a default value that will handle any sections that don't have explicit mappings. Going back to our data security program example, if you added an Encryption key, NT still wouldn't know how to map requests for data in the "Signature" section. However, by adding a default value (which appears as "<No Name>" or "Default") to the subkey, we can tell NT which key to use for any sections that don't have their own section keys defined.

There are also several special symbols that you may use in the values of section keys. Table 8-1 shows these symbols; you'll see them in action in the next section.

Table 8-1 Special Strings for Use in Initialization File Mappings

Symbol

What it means

SYS

Store data under a path relative to HKLM\Software; for example, SYS:Netscape expands to HKLM\Software\Netscape

USR

Store data under a path relative to HKCU; for example, USR:Software\Qualcomm\Eudora expands to HKCU\Software\Qualcomm\Eudora

!

Store data for this named section both in the Registry and the INI file; when data's written to one, it will be written to the other

@

Never read data from the INI file, even if no matching data is found in the Registry

#

When a new user logs in, copy the section's settings from the INI file into the specified Registry location

A mapping sample

The Entrust data security package from Entrust Technologies (http://www.entrust.com/) comes in both 16- and 32-bit versions, as well as versions that run under Unix and the MacOS. To preserve a consistent set of source code, the Entrust engineers decided to stick with INI files instead of using the Registry. Here's the process I followed to build a set of mappings to replace Entrust's INI files with Registry data.

  1. I created a new subkey named entrust.ini under HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\IniFileMapping.

  2. Since Entrust settings are user-specific, I created a new key, HKCU\Software\Entrust, to hold the settings data. I also added subkeys named Other and EntrustSettings to actually hold the data.

  3. The interesting user-specific data in the Entrust INI file is all in the "Entrust Settings" section. To map it, I added a subkey named Entrust Settings under entrust.ini and gave it a default value of @USR:Software\Entrust\EntrustSettings. This makes NT map data stored in the "Entrust Settings" section to the key of the same name; the @ prevents the mapping code from reading data from the INI file.

  4. I gave the entrust.ini subkey a default value of #USR:Software\Entrust\Other. This forces NT to copy the INI file's data for new users and to store data for all other sections of entrust.ini in HKCU\Software\Entrust\Other.

The results of these steps are shown in Figure 8-1. As a finishing touch, I saved the mapping keys to a .REG file using RegEdit so I could quickly distribute them to users throughout our network.

Cc749939.rob_0801(en-us,TechNet.10).gif

Figure 8-1: Adding INI file mappings

Limiting Remote Registry Access

In Windows NT 3.51 and earlier, any user could access the Registry on any machine over the network. From a security standpoint, this was much too liberal; NT 4.0 (and 3.51 with SP4 or SP5) defaults to allowing only members of the Administrators group to access the Registry remotely. This is considerably more secure than the original permissions.

However, this setting may not suit your environment. Sometimes allowing any member of Administrators access is still too permissive, since some high-value machines may warrant the added security of only allowing a single account or group to access their registries over the network. Conversely, you may want to proactively allow other users and groups to remotely connect to, and edit, Registry data on some machines.

You can control which users, groups, and services may access the Registry on a particular machine by setting the ACL for a single Registry key, namely HKLM\SYSTEM\CurrentControlSet\Control\SecurePipeServers\winreg. The NT kernel will grant remote access to a machine's Registry only to those entities named in the access control list attached to the key.

Before proceeding, I should point out that this restriction key controls access to the Registry as a whole. You may still enforce more stringent controls on individual keys. For example, you might grant one group of users access to the Registry by setting the restriction key permissions accordingly, but if you put access controls on other keys that those users can see, the most restrictive set of controls will win out.

Creating the Restriction Key

Before you can take advantage of this restriction feature, you'll need the restriction key. By default, NT Server 4.0 has this key from the moment it's installed, but NT Workstation 4.0 doesn't. Neither do earlier versions of NT; if you want to restrict access, you'll have to manually add the restriction key to your Registry. Here's what to do if you don't already have this key available:

  1. Log in as Administrator (or an account with administrator privileges) and run RegEdt32. Navigate to HKLM\SYSTEM\CurrentControlSet\Control.

  2. Use the Edit > Add Key- command to add a new key named SecurePipeServers, then select it and use Edit > Add Key- again to add a new subkey named winreg to the SecurePipeServers key you just added.

  3. Add a REG_SZ value named "Description" to the winreg subkey. Microsoft recommends that you give the description as "Registry server," but the exact contents are up to you.

Depending on your machine, you may find that you have some parts of the restriction key; for example, NT Workstation 4.0 with no service packs has the HKLM\SYSTEM\CurrentControlSet\Control\SecurePipeServers key itself, but it doesn't have the winreg subkey that's needed to actually make the restrictions work.

Setting Permissions on the Restriction Key

Once you've verified that the winreg key exists, you can use the Security > Permissions- command to give it an access control list. The permissions applied to this key govern which users and groups can access your Registry via the network.

The Registry Key Permissions dialog (shown in Figure 8-2) allows you to change the users and groups that can access the key, as well as modify permissions for those users and groups that you choose to allow access. (If you need a refresher, see the section "Setting Registry Permissions" in Chapter 5, Using RegEdt32.)

Cc749939.rob_0802(en-us,TechNet.10).gif

Figure 8-2: Setting Registry key permissions

NT 4.0 installations will by default have permissions like those shown in Figure 8-2: the Administrators or Domain Admins group will have Full Control rights, as will the system and the account that created the key. You can add new users and groups to this list and give them permissions commensurate with what you want them to be able to do; for example, you might grant read-only access to all domain users while restricting Full Control access to a single named account. Change whatever else you want, but leave the system and CREATOR OWNER permissions alone; the kernel and Registry subsystem depend on these permissions to gain access to the key themselves.

Warning: Some system services, like the directory replicator and the print spooler, require remote access to the Registry. If you change the access control entries on the winreg key, these services may stop working. To avoid this problem, make sure that the accounts used to run the replication service and the print spooler have explicit permissions in the ACL for the winreg key.

Allowing Exceptions

You may also choose to loosen the leash on your Registry a bit by allowing exceptions to the access control rules specified by the permissions on the winreg key. These exceptions can be expressed in two ways: you can provide a list of keys that are exempt from the access controls, or you may specify a list of users who have free access to specific keys and their values.

Both methods are governed by values you add beneath HKLM\SYSTEM\CurrentControlSet\Control\SecurePipeServers\winreg\AllowedPaths.

  • The Machine value, of type REG_MULTI_SZ, accepts a list of Registry paths. Any path listed here will be visible to any machine on the network. By default, NT loads a set of paths that enable the replicator, print spooler, event logger, and kernel to function properly: System\CurrentControlSet\Control\ProductOptions and Software\Microsoft\Windows NT\CurrentVersion for the kernel, System\CurrentControlSet\Control\Print\Printers for the print spooler, System\CurrentControlSet\Services\Eventlog for the event logging service, and System\CurrentControlSet\Services\Replicator for the directory replicator.

  • The Users value (also a REG_MULTI_SZ) lists Registry paths that will be made available to any member of the Users or Domain Users group. This key is empty by default, and you should probably keep it that way unless you have a compelling reason to exempt individual users from the restriction key-imposed controls. In general, if you have a user who needs unusual access, it's better to put the user account into a group and assign the group a permission entry on the restriction key.

Access granted via either of these methods is still subordinate to permissions that you've applied directly to individual keys. For example, if you use the Security > Permissions- command to apply Everyone:Read access to HKLM\Software\Netscape\Netscape Navigator, then add that same path to the Machine value, remote users won't be able to change the values under that subtree: the explicit ACL you've added overrides whatever access was granted by the Machine entry.

Fixing Registry Security ACLs

Every key in the Registry has an ACL. Unfortunately, many of those ACLs are unnecessarily permissive. For example, by default the Everyone account token has write access to several keys that allow untrusted users to execute arbitrary programs-never a good idea. You can significantly improve your NT security posture by paying careful attention to a few simple steps.

First, a brief digression: every authenticated user is automatically a member of the Everyone group. On machines running NT 4.0 SP3 or later, these users are also members of the Authenticated Users group. Everyone also includes anonymous and guest accounts, though, so in general it's a wise idea to never grant Everyone:Full Control access to anything if you can prevent it.

On to the actual steps. First of all, apply the changes suggested earlier in the section "Limiting Remote Registry Access." Once you've done so, make sure that Everyone has only Read access on HKLM\SYSTEM\CurrentControlSet\Control\SecurePipeServers\winreg\AllowedPaths. This prevents an interloper from inserting her own allowed paths for anonymous access.

Next, follow Microsoft's suggestions from knowledge base article 126713 and tighten the permissions on these three keys by limiting Everyone to Read access on them:

HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce

HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

These keys specify programs to run when NT starts (Run and RunOnce) or when a program's uninstalled (Uninstall), so you don't want an attacker to be able to change them.

Likewise, you should remove the Server Operators group's Write permission on HKLM\System\CurrentControlSet\Services\Schedule. Normally, members of the Server Operators group have permission to schedule jobs, but these jobs can be run under the SYSTEM account-making it possible for a Server Operators member to gain Administrator privileges. In the same vein, remove Server Operators' Write privilege on HKLM\Software\Microsoft\WindowsNT\CurrentVersion\Winlogon to prevent a similar attack on the UserInit and BootVerificationProgram values.

The next step is pretty open-ended: you should bolt down your Registry by restricting access wherever possible. The kicker is in knowing what's possible-and that varies from application to application. For example, Office 97 requires Everyone:Read on its own keys under HKLM\Software and HKCU\Software. Remove that permission and some Office features stop working. The same is true for Internet Explorer 4.0 and a wide range of other products. As you make changes to Registry key ACLs, be sure to test the applications you need to run to ensure their correct function before rolling out your changes to the entire network.

A white paper written for Microsoft by Coopers & Lybrand recommends changing HKCR, HKLM\Software\Microsoft\RPC, and HKLM\Software\Microsoft\Windows NT\CurrentVersion to allow Everyone:Special Access. In particular, they recommend granting Everyone the Query Value, Enumerate Subkeys, Notify, and Read Control permissions. I'd extend that recommendation one notch further and suggest replacing Everyone with Authenticated Users. My first awareness of the vulnerability that prompted this change was Kirill Ermakov's security alert (ekv@comp.chem.msu.su). He noted that most keys under HKLM\Software\Microsoft have Everyone:Delete and Everyone:Set Value access-making it possible for users to delete keys necessary for NT's proper operation. For example, you could easily delete the LanmanWorkstation and LanmanServer keys, which would stop you from offering or using SMB shares!

There's always the shotgun approach. David LeBlanc of ISS has written a tool called everyone2user (available at http://www.dsinet.org/tools/Windows/) that recursively descends all six root keys of the Registry and changes access permission from the Everyone group to Domain Users or Users. This approach has generally proven safe in my experience, but it's always risky to make wholesale changes to your Registry. Make a good backup before using everyone2user.

Let me close on a cautionary note. Article 139342 in the knowledge base warns of the consequences of setting improper permissions on LanmanServer. There are no articles (yet!) cautioning you about changing permissions on other keys, but that doesn't mean it's completely safe. Be careful, and keep good backups.

Encrypting HKLM\SAM with SYSKEY

Like Unix, NT doesn't store user or machine passwords. Instead, it takes the passwords and passes them through a scheme called a one-way function, or OWF. The OWF takes a password in and generates a new block of data that is related to, but doesn't contain, the password. The "OW" in OWF comes from the fact that it's infeasible to take the output of the OWF and "go backwards" to derive the original password. NT stores the OWF output instead of the password, so you can't steal an OWF and use it in place of a password.

In the spring of 1997, an enterprising group of hackers from L0pht Heavy Industries (http://www.l0pht.com) publicized the fact that it was possible to get the OWF-generated password values out of an NT SAM database and feed them to a password-cracking tool. These types of attacks have been known for many years in the Unix community, but their appearance in the NT world generated a lot of headlines. In practical terms, the actual risk was fairly low, since only administrators have access to the SAM to get the OWFed passwords in the first place. Because administrators have essentially unlimited access to the system, they already can do things that make password cracking seem trivial.

However, Microsoft took a beating on the Internet and in the press for the perceived insecurity of the SAM password data. To provide a solution, Microsoft introduced a method of protecting the SAM data with strong encryption; the SYSKEY utility installs and controls this extra protective layer. SYSKEY is available with NT 4.0 SP3; it's also included as part of NT Server Enterprise Edition. Because NT 5.0 stores its user account data in the Active Directory, SYSKEY is neither included nor supported in NT 5.0.

What SYSKEY Does

SYSKEY adds an extra layer of security to the password data stored in the SAM database by encrypting the hashed password data using a 128-bit system key. This key (Microsoft calls it the password encryption key, or PEK; so will I) is randomly generated when you install SYSKEY. Once your PEK is generated, NT uses it to encrypt and decrypt all password data (but not the ordinary account data) in the SAM. Because the data's encrypted, it's useless to any thief or cracker who might get it (and getting it still requires you to gain physical and administrative access to a domain controller). As a bonus, because the data is stored in encrypted form, it remains protected when it's backed up to an ERD or a tape.

Once the password data's encrypted, it's stored back into the SAM database, and services (including the local security authority, or LSA) that access the password data must depend on the kernel to decrypt it for them. For this to work, though, the kernel has to know what the PEK is at boot time: the SAM password information includes password data for system services that start when the machine's booted, in addition to the more mundane user password data.

To accomplish this, NT stores the PEK. You might wonder how storing the PEK could possibly increase security; it seems foolish to store the master password used to encrypt the data that's supposed to be protected! The answer is simple: another key is used to encrypt the PEK. This second key is the system key, after which SYSKEY is named. SYSKEY supports three options for storing the system key and making it available to the system when it's needed to decrypt the PEK.

The first, and most secure, option allows you to store the system key on a floppy. When the machine's booted, the floppy must be present so the kernel can retrieve the system key and use it to decrypt the PEK. Without the right floppy, the machine cannot be booted into the version of NT that's protected by that floppy. This introduces a new single point of failure for your machines, so it's critical to keep backup copies of the floppy. In addition, the floppy serves as a token that allows access to the SAM data, so you must control who has access to it.

The next option is to store the system key encrypted with another key. This second key is generated from a passphrase you choose. Instead of inserting the system key floppy at boot time, a human must be present to type in the passphrase. The encrypted version of the system key is stored on the computer so that only the passphrase is required; there's no separate floppy or key disk involved.

Finally, you can choose to have the system key stored on the local machine. NT uses what Microsoft calls a "complex obfuscation algorithm" to hide the key. This is supposed to make it hard to compromise the system key. This reliance on "security through obscurity" offers considerably less security than the other available methods, but it has one saving grace: it allows unattended reboots, since the kernel can derive the PEK when needed without any human intervention. This is critical for some applications; only you can determine whether it's the best choice for your servers.

Before You Install SYSKEY

As with most other NT components, it's tempting to rush out and install SYSKEY now that you know how it can add security to your machines' Registry data. However, in this case it pays to be cautious and make sure you've adequately planned deploying SYSKEY on your network. It's important to understand what SYSKEY will protect you against and what additional problems it can potentially impose. Committing to using SYSKEY is not to be done lightly.

Every NT 4.0 workstation and server can run SYSKEY, and each machine can use any of the three system key storage options mentioned earlier. If you choose to use key floppies or passphrases, remember that the floppy or passphrase is just like an ERD: it's useful only on the machine where it was created, so you'll have one disk or passphrase for every protected machine. (You can cheat and use the same passphrase on all machines, though.)

First of all, let's start with the scariest problem: SYSKEY can make your system more secure, but it's a one-way trip. Once you enable strong encryption of the SAM account database, there's no way to turn off encryption and go back to the old unencrypted version (though you can use an ERD, as described below). In practice, as long as you keep your ERDs up to date, you won't need to go back to the unencrypted version.

The next problem is what security experts call the "steel lock, balsa-wood door" problem. If you have multiple domain controllers for one domain, and one uses SYSKEY but the others don't, you haven't added any security to your network. One machine's SAM database is protected, but-since all the other controllers have replicated copies-the data you wanted to secure is still easy to grab. Ideally, you should implement SYSKEY on every machine that has an accounts database. That means all domain controllers and any NT workstation machine that has local accounts.

The final difficulty posed by SYSKEY is the fact that it adds security by encrypting the data on your machine. As long as you retain access to the system key, NT can decrypt the PEK and use it to access the stored passwords. If you choose to use a passphrase or key floppy, and you lose or forget it, you'll have to restore from an ERD. If the only ERD you have was made after the Registry was encrypted, you still won't be able to get in! It's critical to safeguard the key floppy and make backup copies of it so a bad floppy doesn't take you out of production-but since the key floppy is a security component, you have to keep careful watch over it.

"What I tell you three times is true"

Microsoft recommends making a total of three ERDs when installing SYSKEY: one before installing the SYSKEY hotfix or service pack, one after installing it but before enabling SYSKEY, and one after the first reboot after installing SYSKEY. While this may seem excessive, making all three of these disks maximizes the likelihood that you'll be able to recover your machine if it crashes in the future:

  • The post-SYSKEY ERD contains the encrypted version of your accounts database. As you add and remove accounts, keep this ERD up to date. As long as you have the system key (either stored on the computer or on a floppy), you can restore the account database, and the rest of the Registry, from the ERD.

  • The pre-SYSKEY ERD holds a complete record of your unencrypted Registry. If you ever need to recover the machine but don't have the system key, you have two choices: reinstall NT and lose all of your account data, or recover the Registry from this ERD and lose any changes made after SYSKEY was activated.

  • The preinstall ERD protects you from problems with the hotfix or service pack. In general, you should always update your ERD just before installing any service pack or hotfix-this gives you an escape hatch if you need to back out of a fix that actually makes things worse on your machine.

Keep all three of these ERDs for each machine you might someday need to restore. At a minimum, that means you'll need them for every domain controller on your network, plus one set for any NT Workstation machine that has important local accounts.

Upgrading domain controllers

Microsoft also warns you about installing SYSKEY on your primary domain controller: if something goes wrong with the SYSKEY installation, or if you ever lose the system key for that one machine, no one will be able to log on to your domain! For domains with more than a few users, you should already have a backup domain controller anyway; if you don't, it's worth considering adding one.

The safest way to roll out SYSKEY in a multiple-domain or multiple-controller network is this:

  1. Pick a domain. Make sure it has at least two domain controllers (one primary and one backup).

  2. Demote the primary domain controller to backup status; this will automatically promote an available backup controller to the primary role. (If you need help doing this, see Essential Windows NT System Administration by Æleen Frisch.) This makes the newly promoted controller take charge of validating domain logon requests, and it also ensures that the new primary controller has a complete and correct copy of the domain account database.

  3. Activate SYSKEY on the original primary domain controller. When you're satisfied that everything is working properly, demote the machine that got promoted in step 2. This will restore the original domain controller to primary status and leave your network as it was before you started.

  4. Activate SYSKEY on the other domain controllers in the domain. If you have more than one domain on your network, go back to step 1 and pick another domain.

If you have domains with only one controller, it's probably okay to dispense with these steps and just activate SYSKEY on the controller, as long as you have the recommended set of three ERDs.

Turning On SYSKEY Protection

You control SAM database encryption with the SYSKEY.EXE executable. As you might expect, only administrators may turn on system key protection. The first time you run SYSKEY, you'll see the dialog shown in Figure 8-3. You'll note that the dialog warns you that encryption can't be disabled once you turn it on; you'll see that warning again after you first enable encryption. There are only five controls in the window: the Encryption Enabled and Encryption Disabled radio buttons show the current state of system key encryption on this machine. You can change from disabled to enabled, but not vice versa. The standard OK and Cancel buttons work like they do in every other dialog. The Update button allows you to change the key storage method later (you'll see how to do that in the next section, "Changing the key storage method").

Figure 8-3: Initial SYSKEY dialog

Figure 8-3: Initial SYSKEY dialog

The first step in activating SYSKEY is simple: click the Encryption Enabled radio button, then click the OK button. You'll see a warning dialog reminding you that this conversion can't be undone and suggesting that you ensure that you've got a current ERD before proceeding. When you click OK in that dialog, you'll see the Account Database Key dialog (see Figure 8-4), which you'll use to tell SYSKEY where you want the system key stored after it's generated:

  • If you want to use a passphrase to unlock the system key, click the Password Startup button and type your password into the Password and Confirm fields. You may enter up to 128 characters for a passphrase, and longer phrases are better. Unfortunately, SYSKEY doesn't enforce any minimum length restrictions on the password. Microsoft recommends at least 12 characters, but it's easy to come up with a longer password than that: pick two easy-to-remember adjectives and a noun, then string them together with punctuation or special characters (like "exploding!friendly*holiday" or "galloping_sleepy#motorhome"). NT will feed the passphrase you enter to a special algorithm, which will generate a 128-bit key from it.

    Figure 8-4: Specifying SYSKEY's location

    Figure 8-4: Specifying SYSKEY's location

    If you want the system to generate a password on its own, click the System Generated Password radio button. In this mode, NT will use its own pseudorandom number generator to pick a random 128-bit system key. As you know, that key has to be stored somewhere. You get to choose where:

  • The Store Startup Key on Floppy Disk button instructs NT to keep the encrypted system key on a floppy. The key itself will be stored in a file named StartKey.key. When you choose this option, you'll need a floppy handy to hold the key. Although it may be temptingly close, don't use your ERD to store the key-doing so concentrates both pieces of data needed to steal passwords on a single floppy.

  • The Store Startup Key Locally button will store the obfuscated system key in HKLM\SYSTEM. When you choose this option, you'll be able to reboot the machine without having a human present.

Once you've selected the method you want to use, click the OK button. If you've chosen to store the key on a floppy, SYSKEY will prompt you to insert a floppy, and it will confirm that it's written the key to the disk. Otherwise, the key will be silently updated and SYSKEY will exit.

The next time you boot the machine, SYSKEY protection will be in effect. This means that unless you're storing the system key locally, you'll have to be at the machine every time it's rebooted to either type in the passphrase or stick in the key floppy.

Tip: If you're in a hurry, you can use the -l flag with SYSKEY; this instructs it to silently generate a system key and store it on the local machine. This is a handy trick for use when setting up a new workstation or server; you can add the command to your ordinary setup scripts, then change the key storage method later when you have more time. This gives you immediate protection without any extra effort on your part.

Changing the key storage method

Once you've installed and activated SYSKEY, you're not bound to your initial choice of key storage. You can run SYSKEY again at any time and change from one method to another. When you change methods, SYSKEY generates a new system key and stores it instead of reusing the old key; this helps protect your password data against compromise.

To change the key storage method for a machine, run SYSKEY and click the Update button. The Account Database Key dialog (shown earlier in Figure 8-4) will appear; the radio button corresponding to the currently active storage method will be active. To change to a new method, just click one of the other radio buttons, filling in the password if necessary.

Because SYSKEY generates a new key when you change storage methods, you must supply the old key as part of the change process. This means that what happens after you click "OK" depends on what storage method you were previously using. If you changed from "Store Startup Key Locally" to something else, SYSKEY can get the old key from HKLM\SYSTEM, so you don't have to do anything. If you're changing from storing the password on a floppy or protected by a passphrase, SYSKEY will require you to provide the key disk or passphrase to continue. This prevents an attacker from changing the key, storing on a floppy, and stealing the floppy-thus rendering your machine unbootable.

Figure 8-5 shows the dialog that asks for the key disk, while Figure 8-6 shows the dialog requesting the current passphrase. If you supply the correct passphrase or floppy, SYSKEY will display a confirmation dialog to remind you that it's changed the system key, and the new key will be stored using the method you've chosen. If you don't supply the right information, SYSKEY won't change anything.

Figure 8-5: The key disk dialog

Figure 8-5: The key disk dialog

Cc749939.rob_0806(en-us,TechNet.10).gif

Figure 8-6: The password dialog

Restoring a SYSKEY-Protected Registry

Chapter 3, In Case of Emergency, described the mechanics of restoring a damaged Registry using an ERD. To restore a machine protected with SYSKEY, you follow this same basic procedure, but there are a few new subtleties introduced as a result of SYSKEY 's presence. The golden rule for restoring a SYSKEY-protected machine is simple: use the right ERD.

Restore SYSTEM and SAM hives

Even thought the actual encrypted account information is stored in the HKLM\SAM subtree, the actual PEK, as well as all the other data SYSKEY needs to tell where the system key is stored, lives in HKLM\SYSTEM. To recover an encrypted account database, you must restore both the SYSTEM and SAM hives at the same time-not just SAM. If you don't do this, NT won't be able to decrypt the Registry, either because it can't find the system key (if you don't restore SYSTEM) or because the key doesn't decrypt the data (if you don't restore SAM). Of course, you must restore these hives from the same ERD.

Get the right system components

If you got SYSKEY as the result of installing an NT 4.0 service pack, you may not have noticed that three existing system files were replaced as part of the update: winlogon.exe, samsrv.dll, and samlib.dll. These three files, along with syskey.exe, implement the account database protection. Their presence is required to enable the encrypted SAM data to be read and decrypted by system services that need it.

When you first install NT, it logs the versions of all the components you install in system.log. When you install service packs, hotfixes, or software like Internet Explorer that replaces one or more system files, the installer application is supposed to update the entries in system.log so that it always reflects the current version of all DLLs, drivers, and other operating system components.

What this means is that if you install SYSKEY as part of a hotfix or service pack, the system.log entries for winlogon.exe, samsrv.dll, and samlib.dll will reflect the versions installed with SYSKEY, not the original versions you installed. If you want to restore your machine to its pre-SYSKEY state, you'll need to use the NT setup application's "Repair system files" option to restore the original versions from your NT CD or file server. However, you must be sure to restore the SAM and SYSTEM hives from the pre-SYSKEY ERD: if you revert to the original system components but leave the encrypted Registry in place, nothing will work right.

Warning: If you install SYSKEY but don't turn it on, the winlogon.exe, samsrv.dll, and samlib.dll files won't match your original installation. When you install the new versions of these files, they change the Registry format even when encryption is off. If you use NT setup to restore these three files to their original state by using your pre-SYSKEY ERD, you must also restore SAM and SYSTEM from the same ERD: if you don't, the old components won't be able to read the new Registry format.

Which ERD should I use?

Three ERDs is three more than most NT systems have, and so deciding which one to use may seem a little overwhelming. It's not hard, though: each ERD can put your system back into a particular state. Which one you use depends on what you want the restored system to have on it. Table 8-2 shows your options.

Table 8-2 ERD Restoration Table

To revert to …

Use this ERD

Don't forget …

System as it was before installing SYSKEY

preinstall ERD

You may lose account database changes made since SYSKEY was installed.
You must also choose "repair system files" in NT setup to restore the original versions of winlogon.exe, samsrv.dll, and samlib.dll.
You can always fall back to this level, even without the system key.

System as it was after installing, but before activating, SYSKEY

pre-SYSKEY ERD

You may lose account database changes made since SYSKEY was installed.
You can always fall back to this level, even without the system key.
When using this ERD, do not "repair system files" from CD.

System as it was after activating SYSKEY.

post-SYSKEY ERD

This preserves all account database changes since the ERD was updated.
It requires presence of system key/passphrase on floppy or machine.
When using this ERD, do not "repair system files" from CD.

Miscellaneous Good Stuff

So far in this book, you've learned how to use a variety of tools to modify, back up, and restore the Registry. At this point, though, you might be wondering what you can actually do with some of these tools! There are some common and necessary administrative tasks involving the Registry; knowing how to perform them will help keep the machines under your care stable, secure, and safe.

Changing the Registry Size

Since the Registry is a collection of hives, most of which are actually disk files, you might not realize that NT actually maps the entire Registry into memory. Doing so makes it possible for Registry calls to perform efficiently; however, it means that as the Registry grows it takes up a larger proportion of the virtual memory space in your system. To prevent the Registry from sucking up too much space in the system's page file, NT maintains an internal parameter called the Registry Size Limit, or RSL. The RSL sets an upper bound on how much address space the Registry may occupy; however, as you add software and users to your machines, the Registry gets larger. If it gets so big that it starts to bump up against the RSL, problems will occur. (Go to the Microsoft knowledge base at http://support.microsoft.com/default.aspx?scid=FH;EN-US;KBHOWTO&sd=GN&ln=EN-US and search for "Maximum Registry Size" to see a long list of such problems, most of which are reasonably obscure.)

By default, the RSL is set at about 20-25% of the total virtual memory allocation for the system. This limit is a maximum, not a guarantee, and the limit set by the RSL doesn't actually mean that that much space is reserved, just that the system can't use more than that. There's a complex relationship between the total size of the pool of available virtual memory and the RSL; in general, you should keep the RSL at 80% or less of the total virtual memory allocation. Failure to do so can result in impressive performance losses.

The Virtual Memory dialog (see Figure 8-7) shows you the current RSL and the current amount of space in use by the Registry. If the current size is more than 80% of the RSL, you should increase it. When choosing a new RSL, be sure to keep it below 80% of the total virtual memory size; in general, you shouldn't ever need to increase it above 33% of the virtual memory size. If you need more space even with an RSL 33% as big as your virtual memory stash, consider increasing the size of your virtual memory, then increase the RSL.

Cc749939.rob_0807(en-us,TechNet.10).gif

Figure 8-7: The Virtual Memory dialog

In NT 4.0, you adjust the RSL through the Virtual Memory dialog pictured in Figure 8-7. Here's how to change the RSL if you need to:

  1. Open the System control panel and click on the Performance tab.

  2. Click the Change button; the Virtual Memory dialog will appear.

  3. Type a reasonable value into the Maximum Registry Size field.

  4. Click OK, then close the Virtual Memory dialog, then close the System control panel. You'll be notified that your changes won't take effect until the next restart.

Auditing Registry Access

In "Auditing Registry Key Activity" in Chapter 5, you learned how to apply auditing controls to any key in the Registry. Since NT stores so much critical configuration data in the Registry, auditing some of it is a good idea-there are a number of keys you can audit to keep an eye on potential security problems or to catch users doing things they shouldn't be.

Tip: NT itself often determines whether a specific key is present by trying to read it and noting if the attempt fails. This is normal, and it's so common that I recommend you avoid auditing failed attempts on the Read, Query Value, or Enumerate Subkeys operations-doing so will generate lots of unnecessary audit log entries.

Once you turn on auditing, the events you specify will be stored in the system's event log. Since these files are your record of what auditable events have taken place, you need to make sure that they're protected against tampering too! Set their permissions to include Full Control for CreatorOwner, SYSTEM, and Administrators and Read for Everyone, then make sure no other users have write access to the log files.

Making sense of the audit log

When you enable auditing, NT will write an audit entry to the security event log whenever one of the conditions you specify comes true. Here's a sample entry:

12/2/97 11:27:19 PM Security Success Audit Object Access 560 Administrator BOOMBOX

Object Open:

Object Server: Security

Object Type: Key

Object Name: \REGISTRY\USER\S-1-5-21-34824712-245319459-1244863647-500

New Handle ID: 240

Operation ID: {0,47947}

Process ID: 2161664032

Primary User Name: Administrator

Primary Domain: BOOMBOX

Primary Logon ID: (0x0,0x1E35)

Client User Name: -

Client Domain: -

Client Logon ID: -

Accesses Create sub-key

Privileges -

I got this by turning on file/object access auditing in User Manager, then using RegEdt32 to audit HKCU for successful Create Subkey access requests. Once I did, every time I created any subkey under HKCU I got a new audit record like the one above.

As you can see, this record tells me what key was the target of the request (the Object Name field), what user name made the attempt (along with that user's domain), and what access or privileges were requested. If you want to routinely scan your event logs for Registry accesses, I suggest using a tool like SomarSoft's DumpEvt (http://www.somarsoft.com), or writing your own Perl script to parse the Event Log using functions in the Win32::EventLog module.

Tracking software installations or reinstallations

Any software that uses the Registry (which means any package wearing the "Designed for Windows 95" or "Designed for Windows NT" logo, plus lots of others) will leave tracks in either HKLM\SOFTWARE or HKCU\SOFTWARE. Microsoft's recommendation is that software vendors create their own subkey of one of these two keys, so you'll see lots of entries like HKLM\Software\Netscape and HKLM\SOFTWARE\Qualcomm. You can audit these keys directly, or you can audit only specific subkeys of interest. For example, if you want to see an audit notice whenever someone adds new software to a machine, you could add an audit entry for "Create Subkey" on HKLM\SOFTWARE. If instead you wanted to know when someone installs only software made by Netscape, you could audit "Create Subkey" on HKLM\SOFTWARE\Netscape and HKCU\SOFTWARE\Netscape.

Guarding against Trojan horses

NT allows administrators to install one or more DLLs that validate passwords before passing them on to the logon subsystem. The NetWare gateway tools shipped with NT use such a DLL, and the documentation for what such a DLL should do is available from Microsoft. This opens the potential for a user to install a password-grabbing DLL that just stores the password in a file without changing it, then passes it on to the logon subsystem. NT keeps its list of these DLLs in HKLM\SYSTEM\CurrentControlSet\Control\Lsa\Notification Packages. I strongly recommend that you turn on auditing for this key.

Using the Resource Kit Utilities

Microsoft offers a separate package of NT tools, documentation, and utilities called the Windows NT Resource Kit. There are two versions: the NT Workstation Resource Kit contains tools pertinent to managing NT Workstation, and the NT Server Resource Kit includes server-specific material, plus everything from the Workstation edition. Even though some of the tools are only partly functional (like the "beta" telnet server that's been in beta for about two years now) and most are poorly documented, the Resource Kit is well worth the US$150 or so it costs, since many of its tools are unavailable from any other source.

What's in the Resource Kit

The NT 4.0 Resource Kit CD has a wide variety of tools and documents on it. Table 8-3 summarizes items that have something to do with the Registry. Most of these tools originally shipped with the by-now-ancient NT 3.1 Resource Kit; in summer 1997, Microsoft issued an update to the resource kit (available from http://technet.microsoft.com/en-us/subscriptions/default.aspx), which adds a new tool, reg.exe. reg supersedes a number of other tools, even though they still appear on the resource kit CD. I've noted the superseded tools in the table so you'll know which ones you can safely skip over.

Table 8-3 Resource Kit Registry Tools

Tool

What it does

Notes

compreg.exe

Compares contents of two Registry values you specify-like diff.

See "Comparing Keys and Values" later in this chapter

reg.exe

Everything: add, remove, or change keys; load and unload hives, and lots more.

See "REG: The Swiss Army Knife" later in this chapter

regback.exe and regrest.exe

Backs up and restores Registry keys, values, and hives. Can be used to restore all or part of a damaged Registry.

Covered in Chapter 3

regchg.exe

Changes a single value from the command line.

Superseded by reg.exe

regdel.exe

Deletes the specified subkey of HKLM from the command line.

Superseded by reg.exe

regdir.exe

Provides a directory-style listing of a specified tree or subkey.

 

regdmp.exe

Dumps the specified key, plus its subkeys and values, in text form.

 

regentry.hlp

Documents many of NT's keys and values.

 

regfind.exe

Searches the Registry for a specified value; works like grep or the search function in RegEdit.

See "Searching for Keys" later in this chapter

regini.exe

Adds, removes, or changes keys based on a command script you write.

 

regkey.exe

Offers a GUI to set several trivial parameters (auto-logon, number of cached user profiles, etc.).

Better to use system policies

regread.exe

Reads the specified subkey of HKLM and returns its values.

Superseded by reg.exe

regsec.exe

Sets security descriptors on a key and its subkeys; useful for undoing needlessly permissive default ACLs.

See "Fixing Registry Security ACLs" earlier in this chapter

restkey.exe

Restores a key saved by SAVEKEY.

Superseded by reg.exe

rktools.hlp

Gives a brief description of each tool in the Resource Kit.

 

rregchg.exe

Changes a key's value on a remote machine.

Superseded by reg.exe

savekey.exe

Saves a key's values for later reloading.

Superseded by reg.exe

REG: The Swiss Army Knife

I have been heard to describe the reg.exe utility as "RegEdt32 in a can." It does almost everything RegEdt32 can do, but it allows you to do it from a command line. Not only is this a boon when you want to quickly make a change without firing up RegEdt32 ; it also allows you to embed Registry operations in logon scripts and batch files. (Of course, you learned how to use the Registry from within Perl in Chapter 7, Programming with the Registry, but for the non-Perl-hackers among us reg is a welcome substitute.)

If you've ever used the net command, you'll immediately recognize how reg works. Like net, you use reg by giving it a command from a short list of options (query, add, update, delete, copy, save, backup, restore, load, and unload), followed by one or more optional parameters that the command you specify will interpret. Here's a short example in which reg gets the query command for a specified subkey of HKLM:

C:\ntreskit>F:uireg query HKLM\Software\Qualcomm /s

Listing of [Software\Qualcomm]

[Eudora]

[Eudora\3.0.1]

Querying keys

reg query allows you to query a single key for a single value, or a range of keys for all their values. This provides you with a quick way to check whether a key has the value you think it does, or in fact whether it has any values associated with it at all:

REG QUERY [F:rprootKey\]F:rpkey [\F:rpvalue] [F:rpmachine] [/S]

rootKey

Optional; specifies which root key to use as base of query. May be HKLM, HKCU, HKCR, HKU, or HKCC. Defaults to HKLM if omitted.

key

Specifies the full name of a key under the specified rootKey.

value

Specifies a value under key to query. If omitted, all keys and values under key will be displayed.

machine

Name of a remote machine to query; if omitted, defaults to local machine. You can only query HKLM and HKU on remote machines.

/s Query all subkeys of key.

Adding new keys

reg add adds new keys and values to the Registry. You can add a value to an existing key, add a new key with no values, or create a new key and a value beneath it. If you try to add a key or value that already exists, reg will warn you.

REG ADD [rootKey\]key [\value=newValue] [machine] [dataType]

rootKey

Optional; specifies which root key to add new key under. May be HKLM, HKCU, HKCR, HKU, or HKCC. Defaults to HKLM if omitted.

key

Specifies the full name of the key to add under the specified rootKey.

value

Optionally specifies the name of a value to add under key. If omitted, the key will be created with no value.

newValue

Contents of newly created value. String values may contain spaces and special characters, but must be enclosed in double quotes if they do.

machine

Name of a remote machine to query; if omitted, defaults to local machine. You can only query HKLM and HKU on remote machines.

dataType

Type of the new value to be added. May be REG_SZ, REG_MULTI_SZ, REG_EXPAND_SZ, or REG_DWORD. If omitted, REG_SZ is the default. If you specify REG_DWORD, you must specify newValue as a decimal number.

For example, to add the value that disables Dial-Up Networking's "save password" checkbox, you could use this command:

reg add SYSTEM\CurrentControlSet\Services\

RasMan\Parameters\DisableSavePasswordValue=1

Updating existing keys

reg update updates a single value of an existing key. You can update any value where you have permission according to the parent key's ACL; if you're trying to modify a remote machine's Registry you must have access to it. reg will warn you if you try to modify a nonexistent value.

REG UPDATE [rootKey\]key [\value=newValue] [machine]

rootKey

Optional; specifies which root key holds the targeted key. May be HKLM, HKCU, HKCR, HKU, or HKCC on local machine or HKLM or HKU on remote machine. Defaults to HKLM if omitted.

key

Specifies the full name of the key to update under the specified rootKey.

value

Specifies which value under key to update.

newValue

Contents to use when replacing existing value. String values may contain spaces and special characters, but must be enclosed in double quotes if they do. DWORD values must be specified in decimal.

machine

Name of a remote machine to query; if omitted, defaults to local machine. You can only query HKLM and HKU on remote machines.

Removing a key

reg delete removes a key or value. When removing a key, it will remove all subkeys and values beneath that key; however, it will ask you to confirm your intentions before it actually deletes anything. That notwithstanding, be careful when using this command. As with reg update, you can only delete keys where the ACLs (and/or the remote Registry settings) allow you access.

REG DELETE [rootKey\]key [\value] [machine]

rootKey

Optional; specifies which root key the targeted key lives under. May be HKLM, HKCU, HKCR, HKU, or HKCC on local machine or HKLM or HKU on remote machine. Defaults to HKLM if omitted.

key

Specifies the full name of the key to update under the specified rootKey.

value

Specifies which value under key to remove. If omitted, all keys and values under key will be deleted.

machine

Name of a remote machine to query; if omitted, defaults to local machine. You can only query HKLM and HKU on remote machines.

Copying keys and values

reg copy might be my favorite of all reg 's commands, if only because it greatly eases the process of copying settings from one place to another. You can use the command to copy a single value or an entire hive from its original location to another; the target location can be on the same machine as the source or on any other machine on the network! This command makes short work out of tasks like copying a standard set of file associations to new machines or tweaking one machine so its configuration matches another.

REG COPY [srcRootKey\]srcKey [\srcValue] [srcMachine] [destRootKey\]destKey

[\destValue] [destMachine]

srcRootKey

DEFINITION Optional; specifies which root key holds the source key. May be HKLM, HKCU, HKCR, HKU, or HKCC. Defaults to HKLM if omitted.

srcKey

Specifies the full name of the source key.

srcValue

Optionally specifies a value under srcKey to copy. If omitted, all keys and values under srcKey are copied.

srcMachine

Name of a remote machine to act as copy source; if omitted, defaults to local machine. You can only use remote machines' HKLM and HKU as source roots.

destRootKey

Optional; specifies where copied key should be rooted. May be HKLM or HKU; defaults to HKLM if omitted.

destKey

Specifies the full name of the key to hold the copied data.

destValue

Optionally specifies name for a single copied value; ignored if no srcValue is specified.

destMachine

Name of a remote machine to serve as the copy target; if omitted, defaults to local machine.

When I installed a beta version of a popular Internet mail package, I (rightly, as it turned out) feared that the new version would damage the old version's Registry settings. A quick command saved the day:

reg copy software\qualcomm\eudora software\qualcomm\eudora-3.0

made a backup copy of my existing settings so I could install the new version, secure in the knowledge that I could easily revert back to a previous version if needed.

Saving and restoring keys

The REGBACK and REGREST utilities allow you to back up and restore entire hives, but reg offers a similar pair of functions that add the ability to save and reload individual keys, much like RegEdt32 's commands. To save a key and its values, you can use either reg save or reg backup (they're synonyms):

REG SAVE [rootKey\]key fileName [machine]

rootKey

Optional; specifies under which root key the key to save lives. May be HKLM, HKCU, HKCR, HKU, or HKCC on local machine or HKLM or HKU on remote machine. Defaults to HKLM if omitted.

key

Specifies the full name of the key to update under the specified rootKey. If omitted, all contents of rootKey are saved.

fileName

Names the file that will hold the saved data. fileName may not have an extension specified.

machine

Name of a remote machine to query; if omitted, defaults to local machine.

To quickly store a copy of all of your current settings, you could use this command:

reg save HKLM my-profile then use it anywhere you can use a hive file.

You may also restore a saved hive with the reg restore command. This command overwrites an existing key with a new set of values, so you must be cautious when using it (reg will ask you to confirm your command before it overwrites anything, though):

REG RESTORE fileName [rootKey\]key [machine]

fileName

Names the file that holds the data you want restored, with no extension.

rootKey

Optional; specifies which root key the targeted key lives under. May be HKLM, HKCU, HKCR, HKU, or HKCC on local machine or HKLM or HKU on remote machine. Defaults to HKLM if omitted.

key

Specifies the full name of the key whose subkeys and values will be replaced.

machine

Name of a remote machine to query; if omitted, defaults to local machine. You can only query HKLM and HKU on remote machines.

Loading and unloading hives

The section "Saving and Loading Registry Keys" in Chapter 5 explains how you can use RegEdt32 to load and unload saved keys as hives immediately beneath HKLM or HKU. The reg utility gives you the same ability, albeit with the same limitations.

To load a hive, you use the reg load command. Unlike reg restore, reg load loads the hive by adding it with the key name you specify instead of overwriting the key you specify. This makes it possible for you to use reg load to load a saved hive, edit it, and unload it again without making any changes to the rest of your Registry. (If you're wondering why you might want to do so, go back and reread the section "Setting Defaults for New User Accounts" at the beginning of the chapter.) Here's what the command looks like:

REG LOAD fileName [rootKey\]key [machine]

fileName

Specifies the name of the hive file to load, with no extension. You may specify a full local or UNC path here.

rootKey

Optionally specifies which root key the new hive should be created under. May be HKLM or HKU. Defaults to HKLM if omitted.

key

Specifies the name of the key to receive the new hive; this key will be created and must not already exist. key must be an immediate subkey of HKLM or HKU.

machine

Name of a remote machine to load the hive on.

For example, to load the ntuser.dat hive as suggested in "Setting Defaults for New User Accounts," just copy ntuser.dat to ntuser-default, then use this command:

reg load ntuser-default DefaultProfile then modify the hive as needed.

Once you've finished working with a loaded hive, you may unload it with reg unload. Its command syntax is pretty simple:

REG UNLOAD [rootKey\]key [machine]

rootKey

DEFINITION Optional; specifies which root key holds the hive to unload. May be HKLM, HKCU, HKCR, HKU, or HKCC on local machine or HKLM or HKU on remote machine. Defaults to HKLM if omitted.

key

Specifies the full name of the key to unload. key must be an immediate subkey of HKLM or HKU.

machine

Name of a remote machine on which to unload the hive; if omitted, defaults to local machine

Comparing Keys and Values

When you're trying to troubleshoot a configuration problem, it's often useful to examine the broken machine and one that works to discern what's different between the two. Without the resource kit, doing this with the Registry involves saving suspect portions of the Registry to a text file, then using a difference tool like windiff to highlight differences between the two files. The compreg tool, included for the first time in the NT 4.0 resource kit, provides a command-line tool for comparing differences in Registry keys.

Here's how it works:

COMPREG key1 key2 [-v] [-r] [-e] [-d] [-q] [-n] [-h] [-?]

key1

Specifies the full path to the first key to compare. This path can include a machine name (e.g., \\ENIGMA\HKEY_LOCAL_MACHINE \SOFTWARE \LJL). Instead of spelling out the Registry keys, you may abbreviate them by taking the standard mnemonic we've used in this book and dropping the initial "HK"; for example, you could also specify a path of \\ENIGMA\lm\SOFTWARE\LJL to save some typing. If no root is specified, HKCU is the default.

key2

Specifies the full path to the second key to compare. This can be the same path as key1 but on a different machine, or it can be a different path altogether. If you only specify a machine name, compreg uses the path from key1 but looks for it on the computer specified in key2.

-v

Verbose mode; prints both keys whose values differ and those that match.

-r

Recurse into keys that only have a single subkey.

-e

At exit, sets errorlevel to the last error encountered. This switch lets you test the return value of compreg when using it in scripts or batch files.

-d

Suppresses printing the values of keys whose values differ; just prints the keys themselves.

-n

Monochrome output (the default scheme uses multiple colors).

-?

Displays a short help message.

The ability to find differences between two machines is extremely useful at times. While troubleshooting some of the entries in Chapter 9, Registry Tweaks, I wanted to clone an existing drive restriction and modify it. Unfortunately, after I modified it it didn't work, and I couldn't see what I had done wrong. A quick

compreg software\Microsoft\Windows\CurrentVersion\Policies\Explorer \\armory

showed me my error, and I was able to fix it without any further damage to my Registry or my self-esteem.

Searching for Keys

Sometimes there's no substitute for a little brute-force searching. If you've ever used grep or findstr (the Win32 equivalent) to find something you knew was somewhere on your disk, you'll love regfind. It's very flexible: it can search for value and key names or contents, it can search or search and replace, and it understands all of the common Registry data types. This flexibility makes it a bit more complex than some of the other reskit utilities, though:

REGFIND [-h hiveFile hiveRoot | -w win95Dir | -m \\machine]

[-i tabStop] [-o outputWidth]

[-p keyPath] [-z | -t dataType] [-b | -B] [-y] [-n]

[searchString [-r replacementString]]

-h hiveFile hiveRoot

Specifies the full path to a local hive file (generated with reg save or RegEdt32).

-w win95Dir

Tells regfind to look for Windows 95 user.dat and system.dat hive files in the directory specified by win95Dir.

-m machine

Specifies that regfind should search the NT machine named machine.

-i tabStop

Sets the tabstop width; the default is 4.

-o outputWidth

Tells regfind how wide to make its output. The default is the width of the console window, or 240 if the output's been redirected to a file.

-p keyPath

Directs regfind to start looking in keyPath. You may specify one of HKEY_LOCAL_MACHINE, HKEY_USERS, HKEY_CURRENT_USER, or USER; since HKCR and HKCC are links into HKLM, this is not a big loss. If you omit this switch, regfind will search the entire Registry.

-z

Searches for REG_MULTI_SZ or REG_EXPAND_SZ strings that are missing the required zero terminator or that have illegal lengths.

-t dataType

Forces regfind to look only at values with the specified data type. You may specify any one of REG_SZ, REG_MULTI_SZ, REG_EXPAND_SZ, REG_DWORD, REG_BINARY, and REG_NONE. If no type is specified, regfind will look at all the SZ types.

-b

Tells regfind to look for the specified search string inside of REG_BINARY values in addition to any SZ type specified with -t.

-B

Same as -b, but also searches for ANSI strings in addition to Unicode.

-y

When used during an SZ search, forces regfind to do a case-insensitive search. Ignored for REG_DWORD, REG_BINARY, and REG_NONE searches.

-n

Searches key and value names, not just contents. -n and -t are mutually exclusive.

searchString

String to search for. To search for strings with embedded spaces, brackets, etc., wrap it in double quotes. If no search string is specified, the search will find values of the specified type. When searching for a REG_DWORD, you may specify it in decimal or hex, with a leading 0x. When searching for a binary value, you must provide a length byte, optionally followed by a sequence of DWORDs containing the actual data to search for.

-r replacementString

Replaces any occurrence of searchString with replacementString. searchString and replacementString must be of the same type, but their lengths may differ. There are several constraints that apply to the use of -r:

  • You may specify replacementString the same way as searchString. However, if your searchString is a REG_BINARY length only, you may not use -r.

  • If you specify -z and -r together, the replacement string will be ignored. Instead of replacing anything, regfind will fix any strings with missing terminators or bad lengths.

  • There's no confirmation option with -r, so it's a good idea to run regfind without it until you're sure that what will be replaced is what you want replaced.

Because this is a complicated command, an example may help to clarify how the command works. Let's try finding all the keys whose contents or names include the string "Mac":

C:\ntreskit>F:uiregfind -y -n Mac

Scanning \Registry registry tree

Case Insensitive Search for 'Mac'

Will match values of type: REG_SZ REG_EXPAND_SZ REG_MULTI_SZ

Search will include key or value names

\Registry

Machine

SOFTWARE

Microsoft

AsyncMac

Exchange

Client

Mac File Types

Shared Tools

Text Converters

Export

MSWordMac4

MSWordMac5

MSWordMac51

Import

MSWordMac

SYSTEM

ControlSet001

Services

AsyncMac

AsyncMac2

EventLog

System

AsyncMac

ControlSet003

Services

AsyncMac

AsyncMac2

EventLog

System

AsyncMac

Users

S-1-5-21-1944135612-1199777195-24521265-500

Software

Microsoft

Ntbackup

Backup Engine

Process Macintosh files = 1

Machine Type = 0

Telnet

Machine1 = fly.hiwaay.net

LastMachine = hq

Machine2 = hq

The only real drawback to regfind is that it can't handle regular expressions or wildcards like findstr and grep can. Apart from that limitation, though, it's a valuable tool when you need to find a key whose value you know but whose path you don't.

Spying on the Registry with NTREGMON

Ask a private investigator what the best way to gather evidence is, and you're likely to get a simple answer: watch and wait. Unfortunately, trying to use RegEdt32 or RegEdit to watch the registry as it changes is a difficult and unrewarding way to work. Unless you know ahead of time exactly which keys or values you want to watch, it's difficult to monitor individual changes, and there's no easy way to tell which application, process, or driver changed the setting you're trying to watch.

Mark Russinovich and Bryce Cogswell have solved this problem, to the delight of administrators and programmers everywhere. They wrote a utility called NTREGMON (available with source code from http://www.ddj.com/ftp/1997/1997.01/ntregmon.zip/) that lets you spy on every Registry access made anywhere in the system. It can monitor reads, writes, and queries and record them in a log that you can peruse at will; it can also limit the Registry accesses it records based on filtering criteria that you supply. NTREGMON makes short work of figuring out who modified a particular key or value, and it's a great resource for watching what NT does with Registry data.

NTREGMON works by installing a small device driver when you run the application; this driver installs hooks to all the Registry API routines, so it can see what parameters callers pass in and what results the system returns. The NTREGMON application itself just opens the device driver and waits for it to send along the data it's captured.

Sneaking a Peek with RegEdt32

REGMON isn't the only way to spy on the Registry. Here's a handy trick that will allow you to see even the SAM and SECURITY hives (on NT 3.51 and NT 4 machines), which are normally inaccessible.

  1. Enable the Scheduler service and have it log in as the SYSTEM account by selecting the "System Account" radio button in the Services dialog.

  2. Once the Scheduler is running, open an NT command-line window and use the at command to schedule an invocation of RegEdt32 in the near future. For example, if it's 1:35 P.M. when you start off, schedule RegEdt32 to run at 1:36 P.M. like this:

    at 13:36 /interactive regedt32.exe

At the appointed time, RegEdt32 will open, but it will be running under the SYSTEM account instead of your normal account. HKLM\SYSTEM and HKLM\SAM will be enabled, so you can open and inspect them. Don't expect to see much, since their contents are all binary data. Don't edit anything in these hives.

One extremely valuable thing you can do with this trick is to enable auditing on the SAM hive. This can give you an audit trail of attempted and successful misbehavior, including grabbing the password hashes or changing passwords on the Administrator account.

Learning the NTREGMON Interface

NTREGMON has an extremely simple interface. As you can see in Figure 8-8, it uses a single document window to display the Registry data it captures. The toolbar offers access to all six of the menu commands; the bulk of the window is devoted to the list of captured data. Each column of the list has its own header at the top of the list window; you can resize each column in the list by dragging the small vertical lines next to each header.

Cc749939.rob_0808(en-us,TechNet.10).gif

Figure 8-8: The NTREGMON main interface

Each entry in the list displays six fields' worth of data:

  • ID is a sequence number assigned by NTREGMON. The first thing it logs gets ID #1, and the ID is incremented from there. However, these IDs are assigned by the device driver. If events occur faster than NTREGMON can add them to its display list, you'll notice gaps in the numbering.

  • Process shows the name of the process that made the request. Since DLLs are loaded into a process' address space, NTREGMON only shows the process name, not the name of the individual DLL making the request.

  • Request shows what action the requesting process asked for. Most often, you'll see QueryValue, OpenKey, CloseKey, and SetValue, but NTREGMON also reports enumerations, security changes, and all the other Registry services available through the Registry API documented in Chapter 7.

  • Path shows the path supplied as part of the request. NTREGMON always shows the path including the topmost root key.

  • Result shows the numeric result code returned by whatever Registry API routine was called. You'll see a lot of "SUCCESS" entries here, with an occasional "NOTFOUND." It's rare to see anything other than these two.

  • Other is a catch-all field. For Registry calls that return data, NTREGMON will show the data here as a value of whatever type is appropriate. You'll see string values in quotes, but DWORDs, HKEYs, and other binary data will appear as a block of hex digits. It's up to you to interpret binary data and make sense out of it.

Controlling what you see

Besides dragging the column headers to resize each individual column, NTREGMON doesn't offer much in the way of user interface. The Events > lear Display command erases the current list of logged Registry accesses, and the Events > uto Scroll command toggles whether NTREGMON attempts to automatically scroll the displayed list to always show the most recently added item. Apart from these two commands, NTREGMON is a vanilla application-it follows the Microsoft UI guidelines and doesn't offer any additional bells or whistles.

Capturing and Filtering

Using NTREGMON to figure out what's going on in the Registry is a two-step process. The first step is optional: you may choose which events you want to see (and which you don't) by building a capture filter. NTREGMON will apply this filter during the second step-the actual capture of events.

Turning capture on and off

When you first start NTREGMON, it's in capture mode. If you just sit there for a minute and let it run, you'll see an occasional Registry access recorded in its window; you can see many, many more if you switch to Explorer and open a file, or even click on an icon in your My Computer window. If you leave NTREGMON in capture mode, it's likely to capture an overwhelming amount of data, much of which won't bear any relation to the data you're actually looking for.

The best way to reduce this information overload is simple: turn off capture mode when you don't need it. The Events > Capture Events command toggles capture mode off and on (as does the toolbar button).

Using capture filters

The Events > Filter- command is the first command in the Events menu for a good reason: it's the most useful command in the whole program! The NTRegmon Filter dialog (see Figure 8-9) lets you specify in detail which events you want to see in the capture list and which you don't. Here are the filter criteria you may specify:

Cc749939.rob_0809(en-us,TechNet.10).gif

Figure 8-9: NTREGMON's filter dialog
  • Process filters by the name of the requesting process. In Figure 8-9, I've specified that I only want to see calls made by spoolss.exe and the DLLs it loads into its process space. You may use wildcards in this field, and case distinctions are ignored.

  • Path Include and Path Exclude combine to allow you fairly fine control over what key paths are logged. The path, and its subkeys, you specify in Path Include will be monitored except for whatever paths you list in Path Exclude. For example, if you put HKLM\SOFTWARE in Path Include and HKLM\SOFTWARE\Microsoft in Path Exclude, your log will show accesses to any keys in HKLM\SOFTWARE except keys under Microsoft. These paths may include wildcards, too.

  • History Depth is mislabeled. It should say "Number of entries to keep" or something similar; it actually controls how many lines worth of data NTREGMON keeps before purging its internal list. The default value of 0 means that new data are just added at the end, but you can provide a specific value (say, "10" to have NTREGMON keep only the last 10 audited events).

  • The Log checkboxes let you control what actions NTREGMON will log. By default, it will log reads, writes, successes, and errors, but you may adjust this to narrow down the breadth of the data you have to wade through.

Figure 8-9 shows a set of filter criteria, and Figure 8-10 shows the events captured by the filter criteria; I was trying to determine whether the printer spooler would write out all the printer properties if I changed just one of them.

Cc749939.rob_0810(en-us,TechNet.10).gif

Figure 8-10: Filtered events

Saving your captured data

NTREGMON can save its logged data as a tab-delimited text file. There's no provision for saving part of a log-you can either save every logged event, or none. This is easy to work around, though; all you need to do is define an appropriate capture filter before you capture data, then there won't be any extraneous stuff in your capture log.

The File > Save- and File > Save As- commands let you save logged data to a file you specify. Unlike the Performance Monitor, there's no way to load a file of saved data for further review; you'll have to use a spreadsheet or text editor to view the saved data if you need it later.

About the Author

PAUL ROBICHAUX is an experienced software developer and author. He has worked on UNIX, Macintosh, and Win32 development projects over the past six years, including a stint on Intergraph's OLE team. He is the author of the Windows NT Server 4 Administrator's Guide and a regular contributor to the TechNet site.

© 1998 O'Reilly & Associates. All rights reserved.

We at Microsoft Corporation hope that the information in this work is valuable to you. Your use of the information contained in this work, however, is at your sole risk. All information in this work is provided "as -is", without any warranty, whether express or implied, of its accuracy, completeness, fitness for a particular purpose, title or non-infringement, and none of the third-party products or information mentioned in the work are authored, recommended, supported or guaranteed by Microsoft Corporation. Microsoft Corporation shall not be liable for any damages you may sustain by using this information, whether direct, indirect, special, incidental or consequential, even if it has been advised of the possibility of such damages. All prices for products mentioned in this document are subject to change without notice.

International rights = English only.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft