This post originated from an RSS feed registered with Python Buzz
by Phillip Pearson.
Original Post: Sneaky tricks with NUL characters in Windows Registry keys
Feed Title: Second p0st
Feed URL: http://www.myelin.co.nz/post/rss.xml
Feed Description: Tech notes and web hackery from the guy that brought you bzero, Python Community Server, the Blogging Ecosystem and the Internet Topic Exchange
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.
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.