none
How do you unload a Windows 7 registry hive using C#? RRS feed

  • Question

  • Hello, I'm new to C# programming so I haven't learned everything.  For now,
    though, I'm trying to write a program that will--among other things--load a hive
    (i.e. NTUSER.DAT) into the registry, do a search of specified values, then
    unload the hive.  My search code works fine, but I'm having problems figuring
    out how to load and unload Hives.  Shockingly, there is almost nothing on the
    Internet about this.  I would have thought someone else would have tried this by
    now.

    Here is some code I have been able to find, but it doesn't entirely work.  I think it was written over 10 years ago for Windows 2000 or XP, so maybe if works on those OS's, I don't know.  I just need something to work with Windows 7 (32bit).

    There are two classes, a Hives class and a  frmMain class:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.Win32;
    using System.Runtime.InteropServices;
    
    namespace HiveWork
    {
        class Hives
        {
            [StructLayout(LayoutKind.Sequential)]
            public struct LUID
            {
                public int LowPart;
                public int HighPart;
            }
    
            [StructLayout(LayoutKind.Sequential)]
            public struct TOKEN_PRIVILEGES
            {
                public LUID Luid;
                public int Attributes;
                public int PrivilegeCount;
            }
    
            [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
            public static extern int OpenProcessToken(int ProcessHandle, int DesiredAccess, ref int tokenhandle);
    
            [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
            public static extern int GetCurrentProcess();
    
            [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
            public static extern int LookupPrivilegeValue(string lpsystemname, string lpname, [MarshalAs(UnmanagedType.Struct)] ref LUID lpLuid);
    
            [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
            public static extern int AdjustTokenPrivileges(int tokenhandle, int disableprivs, [MarshalAs(UnmanagedType.Struct)] ref TOKEN_PRIVILEGES Newstate, int bufferlength, int PreviousState, int ReturnLength);
    
            [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            public static extern int RegLoadKey(uint hKey, string lpSubKey, string lpFile);
    
            [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            public static extern int RegUnLoadKey(uint hKey, string lpSubKey);
            public const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
            public const int TOKEN_QUERY = 0x00000008;
            public const int SE_PRIVILEGE_ENABLED = 0x00000002;
            public const string SE_RESTORE_NAME = "SeRestorePrivilege";
            public const string SE_BACKUP_NAME = "SeBackupPrivilege";
            public const uint HKEY_USERS = 0x80000003;
            public string shortname;
            bool unloaded = false;
    
      
            
        }
    }
    
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Diagnostics;
    using Microsoft.Win32;
    
    namespace HiveWork
    {
        public partial class frmMain : Form
        {
            public frmMain()
            {
                InitializeComponent();
            }
    
    
            private void btnReg_Click(object sender, EventArgs e)
            {
    
                int token = 0;
                int retval = 0;
                Hives.TOKEN_PRIVILEGES TP = new Hives.TOKEN_PRIVILEGES();
                Hives.TOKEN_PRIVILEGES TP2 = new Hives.TOKEN_PRIVILEGES();
                Hives.LUID RestoreLuid = new Hives.LUID();
                Hives.LUID BackupLuid = new Hives.LUID();
                retval = Hives.OpenProcessToken(Hives.GetCurrentProcess(), Hives.TOKEN_ADJUST_PRIVILEGES | Hives.TOKEN_QUERY, ref token);
                retval = Hives.LookupPrivilegeValue(null, Hives.SE_RESTORE_NAME, ref RestoreLuid);
                retval = Hives.LookupPrivilegeValue(null, Hives.SE_BACKUP_NAME, ref BackupLuid);
                TP.PrivilegeCount = 1;
                TP.Attributes = Hives.SE_PRIVILEGE_ENABLED;
                TP.Luid = RestoreLuid;
                TP2.PrivilegeCount = 1;
                TP2.Attributes = Hives.SE_PRIVILEGE_ENABLED;
                TP2.Luid = BackupLuid;
                retval = Hives.AdjustTokenPrivileges(token, 0, ref TP, 1024, 0, 0);
                retval = Hives.AdjustTokenPrivileges(token, 0, ref TP2, 1024, 0, 0);
    
                Hives.RegLoadKey(Hives.HKEY_USERS, "DEFAULT_USER", @"C:\Users\_winadmin_\NTUSER.DAT");
                richTextBox1.Text = "Hive loaded.";
    
                //Note: Code would go here to search for values in Hive just loaded. It has been omitted to avoid confusion.
    
                Hives.RegUnLoadKey(Hives.HKEY_USERS, "DEFAULT_USER");
                richTextBox1.Text = "Hive unloaded.";
            }
    
            
        }
    }

    As you can see, there are only two objects on the  main form: a button to start the hive load/unload process, and a rich text box to show the progress.  Very basic.

    To test, you will first need to change @"C:\Users\_winadmin_\NTUSER.DAT" to point to an appropriate NTUSER.DAT file on your computer.  I don't think it can be the same one as the profile you are logged in under to run the program.  Also, while running the program, open the Registry editor (regedit.exe).  You will notice that the hive, "Default_User" will load into the registry.  However, it never unloads.  I get no errors in Visual Studio 2010 when I attempt to debug.

    I have no idea what most of this code is doing, since I got it from the Internet and haven't learned in C# what most if it is.  Can anyone help me by point out what is wrong that is preventing the hive to unload or at least point me to an easier way to load/unload hives for Windows 7?




    • Edited by OmegaWulf Thursday, December 12, 2013 9:21 PM
    Thursday, December 12, 2013 9:18 PM

Answers

  • Since you're calling Win32 functions you should be checking for the return values to ensure each call is successful.  When I run the above code it loads and unloads the hive correctly (assuming you are running as an admin and you have permissions to the hive file).

    Michael Taylor
    http://msmvps.com/blogs/p3net

    Friday, December 13, 2013 5:29 PM
    Moderator