Phillip Pearson - web + electronics notes

tech notes and web hackery from a new zealander who was vaguely useful on the web back in 2002 (see: python community server, the blogging ecosystem, the new zealand coffee review, the internet topic exchange).

2008-6-3

Sneaky tricks with NUL characters in Windows Registry keys

Something interesting I found out yesterday. Various bits of software create keys in the Windows Registry with embedded NUL characters to hide information about themselves or make themselves difficult to delete. If you try to view or delete these keys using regedit.exe or regedt32.exe, or using the Win32 Registry API (RegOpenKey etc), it'll fail, as the Win32 API uses null-terminated strings. However, NT (thus 2000/XP/Vista) has a mostly-undocumented "native API" that uses length-based rather than null-terminated strings, and this API is quite capable of creating/editing/deleting keys and values with names containing \0 characters.

SysInternals used to have an example Native API app for download, but Microsoft seems to have nixed this since acquiring Winternals. There's still a nice article about native applications and how to create them but the actual example code is gone.

If the Registry is what you care about, however, there's another way. CodeProject has Turion's Windows NT Native API Wrapper Library, which nicely wraps the native registry API, and comes with a registry editor based on the native API as an example app (in VB.Net, but I didn't have any trouble linking the library into a C# app). I see also that Dan Madden has written a registry editor in C++ that uses the native API.

Here's some C++ code that searches through the registry and deletes all "values" with a certain name. Say you have an app that creates a randomly named key (with an embedded NUL, so you can't delete it normally) somewhere in the registry, then puts a binary-type key called FOOFOOFOOFOOFOO inside the random key, the following code (with NAME_OF_VALUE_TO_DELETE const'd to "FOOFOOFOOFOOFOO") will delete all such keys.

    NtRegistryKey registry = NtRegistryKey.OpenRegistry();
    foreach (NtRegistryKey.MatchResult match in registry.GetMatches(false, true, false,
        new System.Text.RegularExpressions.Regex(NAME_OF_VALUE_TO_DELETE),
        NtRegistryKey.RecursionOptions.ChildrenFirst, System.WindowsNT.AllowedObjectAttributes.None))
    {
        Console.WriteLine("Found one: " + match.KeyPath);
        NtRegistryKey badkey = NtRegistryKey.OpenKey(match.KeyPath, KeyAccessMask.AllAccess, System.WindowsNT.AllowedObjectAttributes.None);
        badkey.Values.Remove(NAME_OF_VALUE_TO_DELETE);
    }


To build, you'll want to add a reference to the "NT Library.dll" built by Turon's library and a 'using System.WindowsNT.Registry;' line into the file containing the above code.