Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Impersonation and CurrentUser Registry Access

Environment: Windows XP SP3, C#, .Net 4.0

Problem:

I'm attempting to add access to an impersonated users registry hive in an impersonation class and I'm running into issues based on the type of user being impersonated (or more accurately the limitation seems to be on the impersonating user).

I was originally following an impersonation example from CodeProject which showed a call to LoadUserProfile() taking place after impersonation was started using a duplicate token generated througha call to DuplcateToken() from the original token obtained from LogonUser(). I was not able to get this example working in my environment impersonating a limited user from an administrator account (From the screen shots included in the example it appears as though it was done on a windows Vista\7 system and no details were given about the account types involved).

The call to LoadUserProfile() was throwing an error of "Access Denied". Looking at userenv.log showed the line "LoadUserProfile: failed to enable the restore privilege. error c0000022". The LoadUserProfile documentation on MSDN shows that the calling process must posses the SE_RESTORE_NAME and SE_BACKUP_NAME privileges which by default only members of the Administrators and Backup Operators groups have. (As a side note when I attempted to add these two privileges later on to the Users group i still received Access Denied but the userenv.log showed "DropClientContext: Client [number] does not have enough permission. error 5" which I couldn't find any information on)

Given that the user I was impersonating did not have these privileges I moved the call to LoadUserProfile() up to before starting the impersonation and this time it loaded without a problem and I was able to read and write to it in this test. Thinking that I had discovered my answer I created a conditional check for the type of account so that LoadUserProfile() would be called before impersonation if the current user was a member of Administrators or wait until after impersonation if the member was not a member of Administrators (in the later instance I would be relying on the impersonated user having these privileges). Unfortunately I was wrong; I had not discovered my answer. When I tested the call with the role reversed (User > Administrator) The call to LoadUserProfile() still failed again with the Access Denied error and userenv.log showed the same "LoadUserProfile: failed to enable the restore privilege. error c0000061" but with a different error number this time.

Thinking that the privileges may not be enabled by default on the tokens returned from LogonUser() and\or DuplicateToken() I added two calls to AdjustTokenPrivilege() on the current users token (taking place after impersonation) obtained from WindowsIdentity.GetCurrent(TokenAccessLevels.AdjustPrivileges | TokenAccessLevels.Query).Token. TokenAccessLevels.AdjustPrivileges and TokenAccessLevels.Query were specified because the documentation for AdjustTokenPrivilege on MSDN specifies that they are needed on the token being adjusted (I also tried obtaining the token through a call to OpenProcessToken() using a handle retrieved from System.Diagnostics.Process.GetCurrentProcess().Handle but that failed when called from the User both inside and outside of impersonation with GetCurrentProcess() being the function that threw access denied)

AdjustTokenPrivilege() returned successfully when used with the WindowsIdentity...Token but LoadUserProfile() still resulted in Access Denied (restore privilege). At this point I was not convinced that AdjustTokenPrivilege() was doing it's job so I set out to determine what privileges were available and what state they were in for a particular token with GetTokenInformation() which resulted in it's own little bag of fun. After learning some new things I was able to call GetTokenInformation() and print out a list of privileges and their current status but the results were somewhat inconclusive since both Restore and Backup showed an attribute of 0 before and after calling AdjustTokenPrivilege() both as the administrator and while impersonating the administrator (Strangely three other privileges changed from 2 to 1 on the token when calling AdjustTokenPrivilege() but not the ones actually being adjusted which remained at a value of 0)

I removed the call to DuplicateToken() and replaced all of the places it was being used with the token returned from LogonUser() to see if that would help though in testing the privileges on the tokens the LogonUser() and DuplicateToken() tokens were identical. When I initially wrote the impersonation class I had been using the primary token in my call to WindowsImpersonationContext.Impersonate() without any problems and figured it was worth a try.

In the code example I've provided below I am able to impersonate and access the registry of a User when run as an Administrator but not the other way around. Any help would be greatly appreciated.

Pre-Post Edit:

I've also tried using the RegOpenCurrentUser() API in place of LoadUserProfile() and had success with Administrator > self and Administrator > User impersonation but when impersonating an Administrator from either another Administrator account or a User RegOpenCurrentUser() returns a pointer to HKEY_USERS\S-1-5-18 (what ever that is) instead of the actual account hive. I'm guessing because it is not actually loaded which brings me back to square one with needing to use LoadUserProfile()

From RegOpenCurrentUser documentation (MSDN):

RegOpenCurrentUser uses the thread's token to access the appropriate key, or the default if the profile is not loaded.

Code Snippet:

// Private variables used by class
private IntPtr tokenHandle;
private PROFILEINFO pInfo;
private WindowsImpersonationContext thisUser;
private string sDomain = string.Empty;
private string sUsername = string.Empty;
private string sPassword = string.Empty;
private bool bDisposed = false;
private RegistryKey rCurrentUser = null;
private SafeRegistryHandle safeHandle = null;

//Constants used for privilege adjustment
private const string SE_RESTORE_NAME = "SeRestorePrivilege";
private const string SE_BACKUP_NAME = "SeBackupPrivilege";
private const UInt32 SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001;
private const UInt32 SE_PRIVILEGE_ENABLED = 0x00000002;
private const UInt32 SE_PRIVILEGE_REMOVED = 0x00000004;
private const UInt32 SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000;

[StructLayout(LayoutKind.Sequential)]
protected struct PROFILEINFO {
  public int dwSize;
  public int dwFlags;
  [MarshalAs(UnmanagedType.LPTStr)]
  public String lpUserName;
  [MarshalAs(UnmanagedType.LPTStr)]
  public String lpProfilePath;
  [MarshalAs(UnmanagedType.LPTStr)]
  public String lpDefaultPath;
  [MarshalAs(UnmanagedType.LPTStr)]
  public String lpServerName;
  [MarshalAs(UnmanagedType.LPTStr)]
  public String lpPolicyPath;
  public IntPtr hProfile;
}

protected struct TOKEN_PRIVILEGES {
  public UInt32 PrivilegeCount;
  [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
  public LUID_AND_ATTRIBUTES[] Privileges;
}

[StructLayout(LayoutKind.Sequential)]
protected struct LUID_AND_ATTRIBUTES {
  public LUID Luid;
  public  UInt32 Attributes;
}

[StructLayout(LayoutKind.Sequential)]
protected struct LUID {
  public uint LowPart;
  public int HighPart;
}


// Private API calls used by class
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
protected static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); 

[DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Auto)]
protected static extern bool LoadUserProfile(IntPtr hToken, ref PROFILEINFO lpProfileInfo);

[DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Auto)]
protected static extern bool UnloadUserProfile(IntPtr hToken, IntPtr hProfile);

[DllImport("kernel32.dll", SetLastError = true)][return: MarshalAs(UnmanagedType.Bool)]
protected static extern bool CloseHandle(IntPtr hObject);

[DllImport("advapi32.dll", SetLastError = true)][return: MarshalAs(UnmanagedType.Bool)]
protected static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, [MarshalAs(UnmanagedType.Bool)]bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, UInt32 Zero, IntPtr Null1, IntPtr Null2);

[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)][return: MarshalAs(UnmanagedType.Bool)]
protected static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, ref LUID lpLuid);


[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public void Start() {

  tokenHandle = IntPtr.Zero; // set the pointer to nothing
  if (!LogonUser(sUsername, sDomain, sPassword, 2, 0, ref tokenHandle)) {
    throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
  } // end if !LogonUser returned false

  try { //All of this is for loading the registry and is not required for impersonation to start
    LUID LuidRestore = new LUID();
    LUID LuidBackup = new LUID();
    if(LookupPrivilegeValue(null, SE_RESTORE_NAME, ref LuidRestore) && LookupPrivilegeValue(null, SE_BACKUP_NAME, ref LuidBackup)) {
      //Create the TokenPrivileges array to pass to AdjustTokenPrivileges
      LUID_AND_ATTRIBUTES[] LuidAndAttributes = new LUID_AND_ATTRIBUTES[2];
      LuidAndAttributes[0].Luid = LuidRestore;
      LuidAndAttributes[0].Attributes = SE_PRIVILEGE_ENABLED;
      LuidAndAttributes[1].Luid = LuidBackup;
      LuidAndAttributes[1].Attributes = SE_PRIVILEGE_ENABLED;

      TOKEN_PRIVILEGES TokenPrivileges = new TOKEN_PRIVILEGES();
      TokenPrivileges.PrivilegeCount = 2;
      TokenPrivileges.Privileges = LuidAndAttributes;

      IntPtr procHandle = WindowsIdentity.GetCurrent(TokenAccessLevels.AdjustPrivileges | TokenAccessLevels.Query).Token;

      if(AdjustTokenPrivileges(procHandle, false, ref TokenPrivileges, 0, IntPtr.Zero, IntPtr.Zero)) {
        pInfo = new PROFILEINFO();
        pInfo.dwSize = Marshal.SizeOf(pInfo);
        pInfo.lpUserName = sUsername;
        pInfo.dwFlags = 1;

        LoadUserProfile(tokenHandle, ref pInfo); //this is not required to take place
        if(pInfo.hProfile != IntPtr.Zero) {
          safeHandle = new SafeRegistryHandle(pInfo.hProfile, true);
          rCurrentUser = RegistryKey.FromHandle(safeHandle);
        }//end if pInfo.hProfile
      }//end if AdjustTokenPrivileges
    }//end if LookupPrivilegeValue 1 & 2
  }catch{
    //We don't really care that this didn't work but we don't want to throw any errors at this point as it would stop impersonation
  }//end try

  WindowsIdentity thisId = new WindowsIdentity(tokenHandle);
  thisUser = thisId.Impersonate();

} // end function Start
like image 928
JoshHetland Avatar asked Dec 08 '10 20:12

JoshHetland


People also ask

What is impersonation in authentication?

Impersonation is the process of assigning a user account to an unknown user.

What is impersonation user?

User impersonation allows you to temporarily sign in as a different user in your network. Users with full impersonation permissions can impersonate all other users in their network and take any action, regardless of the impersonating user's own permission level.

What is impersonate user C#?

Impersonation is the process of executing code in the context of another user identity. By default, all ASP.NET code is executed using a fixed machine-specific account. To execute code using another identity we can use the built-in impersonation capabilities of ASP.NET.

What is selected to impersonate users?

To impersonate another user, the impersonator selects the Impersonate icon on the far right of the Tab Bar and selects the user from the Impersonate drop-down list.


2 Answers

From the LoadUserProfile docs:

Starting with Windows XP Service Pack 2 (SP2) and Windows Server 2003, the caller must be an administrator or the LocalSystem account. It is not sufficient for the caller to merely impersonate the administrator or LocalSystem account.

If your process starts as a regular user you're out of luck. You could possibly launch a new process (under the admin credentials) to load the profile.

like image 128
arx Avatar answered Oct 25 '22 04:10

arx


I found that the logon type set in the call to LogonUser() can be a factor. Even when running as an administrator I couldn't get past the error unless I switched from LOGON32_LOGON_INTERACTIVE to LOGON32_LOGON_BATCH. You would need to be sure the "Log on as a batch job" group policy doesn't interfere though.

like image 28
David Avatar answered Oct 25 '22 03:10

David