/// <summary> /// Load RegistryHive from file. /// </summary> /// <param name="hivename">RegistryHive name</param> /// <param name="filepath">RegistyHive filepath</param> /// <param name="rkey">Registrykey</param> /// <returns>When loading is failed, return false. When loading is succeeded, return true.</returns> public static bool LoadHive(string hivename, string filepath, ExRegistryKey rkey) { int tokenHandle = 0; LUID serLuid = new LUID(); LUID sebLuid = new LUID(); OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref tokenHandle); TOKEN_PRIVILEGES tokenp = new TOKEN_PRIVILEGES(); tokenp.PrivilegeCount = 1; LookupPrivilegeValue(null, "SeBackupPrivilege", ref sebLuid); tokenp.Luid = sebLuid; tokenp.Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges(tokenHandle, false, ref tokenp, 0, 0, 0); tokenp.PrivilegeCount = 1; LookupPrivilegeValue(null, "SeRestorePrivilege", ref serLuid); tokenp.Luid = serLuid; tokenp.Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges(tokenHandle, false, ref tokenp, 0, 0, 0); CloseHandle(tokenHandle); int rtn = RegLoadKey((uint)rkey, hivename + "\\", filepath); if (rtn == 0) { return true; } else { return false; } }
public RegistryInterop(RegistryHives hive, string subKey, string filePath) { int token = 0; int retval = 0; TOKEN_PRIVILEGES TP = new TOKEN_PRIVILEGES(); TOKEN_PRIVILEGES TP2 = new TOKEN_PRIVILEGES(); LUID RestoreLuid = new LUID(); LUID BackupLuid = new LUID(); retval = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref token); retval = LookupPrivilegeValue(null, SE_RESTORE_NAME, ref RestoreLuid); retval = LookupPrivilegeValue(null, SE_BACKUP_NAME, ref BackupLuid); TP.PrivilegeCount = 1; TP.Attributes = SE_PRIVILEGE_ENABLED; TP.Luid = RestoreLuid; TP2.PrivilegeCount = 1; TP2.Attributes = SE_PRIVILEGE_ENABLED; TP2.Luid = BackupLuid; retval = AdjustTokenPrivileges(token, 0, ref TP, 1024, 0, 0); retval = AdjustTokenPrivileges(token, 0, ref TP2, 1024, 0, 0); uint regHive = (uint)hive; this.Hive = hive; this.SubKey = subKey; RegLoadKey(regHive, subKey, filePath); this.IsUnloaded = false; }
public static extern bool AuthzInitializeContextFromSid( AuthzInitFlags flags, byte[] rawUserSid, SafeAuthzRMHandle authzRM, PLARGE_INTEGER expirationTime, LUID Identifier, LPVOID DynamicGroupArgs, out SafeAuthzContextHandle authzClientContext);
public static bool SetPrivilege(string lpszPrivilege, bool bEnablePrivilege ) { bool retval = false; int ltkpOld = 0; IntPtr hToken = IntPtr.Zero; TOKEN_PRIVILEGES tkp = new TOKEN_PRIVILEGES(); tkp.Privileges = new int[3]; TOKEN_PRIVILEGES tkpOld = new TOKEN_PRIVILEGES(); tkpOld.Privileges = new int[3]; LUID tLUID = new LUID(); tkp.PrivilegeCount = 1; if (bEnablePrivilege) tkp.Privileges[2] = SE_PRIVILEGE_ENABLED; else tkp.Privileges[2] = 0; if(LookupPrivilegeValue(null , lpszPrivilege , ref tLUID)) { Process proc = Process.GetCurrentProcess(); if(proc.Handle != IntPtr.Zero) { if (OpenProcessToken(proc.Handle, TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, ref hToken) != 0) { tkp.PrivilegeCount = 1; tkp.Privileges[2] = SE_PRIVILEGE_ENABLED; tkp.Privileges[1] = tLUID.HighPart; tkp.Privileges[0] = tLUID.LowPart; const int bufLength = 256; IntPtr tu = Marshal.AllocHGlobal( bufLength ); Marshal.StructureToPtr(tkp, tu, true); if(AdjustTokenPrivileges(hToken, 0, tu, bufLength, IntPtr.Zero, ref ltkpOld) != 0) { // successful AdjustTokenPrivileges doesn't mean privilege could be changed if (Marshal.GetLastWin32Error() == 0) { retval = true; // Token changed } } TOKEN_PRIVILEGES tokp = (TOKEN_PRIVILEGES) Marshal.PtrToStructure(tu, typeof(TOKEN_PRIVILEGES) ); Marshal.FreeHGlobal( tu ); } } } if (hToken != IntPtr.Zero) { CloseHandle(hToken); } return retval; }
/// <summary> /// /// </summary> /// <param name="Base">The existing hive root to load as a subkey of.</param> /// <param name="NewHive">The registry hive file to mount/load.</param> /// <returns>String containing the subkey from the Base where NewHive was mounted. Null if unsuccessful.</returns> public static string LoadHive(RegistryHive Base, string NewHive) { try { int token = 0; LUID RestLUID = new LUID(); LUID BackLUID = new LUID(); TOKEN_PRIVILEGES RestPriv = new TOKEN_PRIVILEGES { Attributes = SE_PRIVILEGE_ENABLED, PrivilegeCount = 1 }; TOKEN_PRIVILEGES BackPriv = new TOKEN_PRIVILEGES { Attributes = SE_PRIVILEGE_ENABLED, PrivilegeCount = 1 }; OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref token); LookupPrivilegeValue(null, SE_RESTORE_NAME, ref RestLUID); LookupPrivilegeValue(null, SE_BACKUP_NAME, ref BackLUID); RestPriv.Luid = RestLUID; BackPriv.Luid = BackLUID; AdjustTokenPrivileges(token, false, ref RestPriv, 0, 0, 0); AdjustTokenPrivileges(token, false, ref BackPriv, 0, 0, 0); string reference = (Path.GetFileNameWithoutExtension(NewHive) + DateTime.Now.Ticks + '-' + new Random().Next()); return RegLoadKey((uint)Base, reference, NewHive) == 0 ? reference : null; } catch (Exception) { return null; } }
/// <summary> /// Checks if the user is admin /// </summary> /// <returns></returns> public Boolean IsAdmin() { IntPtr hToken = IntPtr.Zero; IntPtr hProcess = IntPtr.Zero; LUID tLuid = new LUID(); UInt32 uPriv = (UInt32)(ETOKEN_PRIVILEGES.TOKEN_ADJUST_PRIVILEGES | ETOKEN_PRIVILEGES.TOKEN_QUERY | ETOKEN_PRIVILEGES.TOKEN_QUERY_SOURCE); try { hProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, GetCurrentProcessId()); if (hProcess == IntPtr.Zero) return false; if (OpenProcessToken(hProcess, uPriv, ref hToken) == 0) return false; return (LookupPrivilegeValueW(0, SE_TCB_NAME, ref tLuid) != 0); } finally { if (hToken != IntPtr.Zero) CloseHandle(hToken); if (hProcess != IntPtr.Zero) CloseHandle(hProcess); } }
/// <summary> /// Tries to enable the specified privilege. /// </summary> /// <param name="privilege">The privilege to enable.</param> /// <exception cref="PrivilegeException">There was an error while requesting a required privilege.</exception> /// <remarks>Thanks to Michael S. Muegel for notifying us about a bug in this code.</remarks> private static void EnableToken(string privilege) { if (Environment.OSVersion.Platform != PlatformID.Win32NT || !CheckEntryPoint("advapi32.dll", "AdjustTokenPrivileges")) return; IntPtr tokenHandle = IntPtr.Zero; LUID privilegeLUID = new LUID(); TOKEN_PRIVILEGES newPrivileges = new TOKEN_PRIVILEGES(); TOKEN_PRIVILEGES tokenPrivileges; if (OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref tokenHandle) == 0) throw new PrivilegeException(FormatError(Marshal.GetLastWin32Error())); if (LookupPrivilegeValue("", privilege, ref privilegeLUID) == 0) throw new PrivilegeException(FormatError(Marshal.GetLastWin32Error())); tokenPrivileges.PrivilegeCount = 1; tokenPrivileges.Privileges.Attributes = SE_PRIVILEGE_ENABLED; tokenPrivileges.Privileges.pLuid = privilegeLUID; int size = 4; if (AdjustTokenPrivileges(tokenHandle, 0, ref tokenPrivileges, 4 + (12 * tokenPrivileges.PrivilegeCount), ref newPrivileges, ref size) == 0) throw new PrivilegeException(FormatError(Marshal.GetLastWin32Error())); }
private static void EnableToken(string privilege) { if (!CheckEntryPoint("advapi32.dll", "AdjustTokenPrivileges")) return; IntPtr tokenHandle = IntPtr.Zero; var privilegeLUID = new LUID(); var newPrivileges = new TOKEN_PRIVILEGES(); TOKEN_PRIVILEGES tokenPrivileges = default(TOKEN_PRIVILEGES); if ((OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref tokenHandle)) == 0) throw new PrivilegeException(FormatError(Marshal.GetLastWin32Error())); if ((LookupPrivilegeValue("", privilege, ref privilegeLUID)) == 0) throw new PrivilegeException(FormatError(Marshal.GetLastWin32Error())); tokenPrivileges.PrivilegeCount = 1; tokenPrivileges.Privileges.Attributes = SE_PRIVILEGE_ENABLED; tokenPrivileges.Privileges.pLuid = privilegeLUID; int Size = 4; if ((AdjustTokenPrivileges(tokenHandle, 0, ref tokenPrivileges, 4 + (12 * tokenPrivileges.PrivilegeCount), ref newPrivileges, ref Size)) == 0) throw new PrivilegeException(FormatError(Marshal.GetLastWin32Error())); }
public Luid(LUID luid) { _luid = luid; }
internal static extern int LsaGetLogonSessionData(ref LUID LogonId, ref SafeLsaReturnBufferHandle ppLogonSessionData);
public static void EnableSecurityRights(string desiredAccess, bool on) { IntPtr token = IntPtr.Zero; if (!OpenProcessToken(GetCurrentProcess(), TokenAccessLevels.AdjustPrivileges | TokenAccessLevels.Query, ref token)) { return; } LUID luid = new LUID(); if (!LookupPrivilegeValue(null, desiredAccess, ref luid)) { CloseHandle(token); return; } TOKEN_PRIVILEGE tp = new TOKEN_PRIVILEGE(); tp.PrivilegeCount = 1; tp.Privilege = new LUID_AND_ATTRIBUTES(); tp.Privilege.Attributes = on ? SE_PRIVILEGE_ENABLED : SE_PRIVILEGE_DISABLED; tp.Privilege.Luid = luid; int cbTp = Marshal.SizeOf(tp); if (!AdjustTokenPrivileges(token, false, ref tp, (uint) cbTp, IntPtr.Zero, IntPtr.Zero)) { Debug.WriteLine(new Win32Exception().Message); } CloseHandle(token); }
/// <summary> /// Change process security token access rights /// </summary> /// <param name="Enable">Boolean - Ebnable or disable a privilege</param> /// <returns>Boolean</returns> Boolean adjustToken(Boolean Enable, string[] rights) { IntPtr hToken = IntPtr.Zero; IntPtr hProcess = IntPtr.Zero; LUID tLuid = new LUID(); TOKEN_PRIVILEGES NewState = new TOKEN_PRIVILEGES(); UInt32 uPriv = (UInt32)(ETOKEN_PRIVILEGES.TOKEN_ADJUST_PRIVILEGES | ETOKEN_PRIVILEGES.TOKEN_QUERY | ETOKEN_PRIVILEGES.TOKEN_QUERY_SOURCE); try { hProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, GetCurrentProcessId()); if (hProcess == IntPtr.Zero) return false; if (OpenProcessToken(hProcess, uPriv, ref hToken) == 0) return false; for (Int32 i = 0; i < rights.Length; i++) { // Get the local unique id for the privilege. if (LookupPrivilegeValueW(0, rights[i], ref tLuid) == 0) return false; } // Assign values to the TOKEN_PRIVILEGE structure. NewState.PrivilegesCount = 1; NewState.Privileges.pLuid = tLuid; NewState.Privileges.Attributes = (Enable ? SE_PRIVILEGE_ENABLED : 0); // Adjust the token privilege return (AdjustTokenPrivileges(hToken, false, ref NewState, (uint)Marshal.SizeOf(NewState), IntPtr.Zero, IntPtr.Zero)); } finally { if (hToken != IntPtr.Zero) CloseHandle(hToken); if (hProcess != IntPtr.Zero) CloseHandle(hProcess); } }
static extern bool LookupPrivilegeValue(string host, string name, ref LUID lpLuid);
internal static partial bool LookupPrivilegeValue( [MarshalAs(UnmanagedType.LPTStr)] string?lpSystemName, [MarshalAs(UnmanagedType.LPTStr)] string lpName, out LUID lpLuid);
internal static extern bool LookupPrivilegeValue( [In] string systemName, [In] string name, [In, Out] ref LUID luid);
internal static extern bool LookupPrivilegeName( [In] string systemName, [In] ref LUID luid, [In, Out] StringBuilder name, [In, Out] ref int nameLength);
public LUID_AND_ATTRIBUTES(LUID Luid = default, uint Attributes = default) { this.Luid = Luid; this.Attributes = Attributes; }
public static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, out LUID lpLuid);
private static extern bool LookupPrivilegeValue(string systemName, string name, ref LUID pluid);
public static void EnableSetTimeZonePrivileges() { // We must add the set timezone privilege to the process token or SetTimeZoneInformation will fail IntPtr token; bool retval = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out token); if (!retval) throw new Exception(String.Format("OpenProcessToken failed. GetLastError: {0}", Marshal.GetLastWin32Error())); LUID luid = new LUID(); retval = LookupPrivilegeValue(null, SE_TIME_ZONE_NAME, out luid); if (!retval) throw new Exception(String.Format("LookupPrivilegeValue failed. GetLastError: {0}", Marshal.GetLastWin32Error())); TOKEN_PRIVILEGES tokenPrivs = new TOKEN_PRIVILEGES(); tokenPrivs.PrivilegeCount = 1; tokenPrivs.Privileges = new LUID_AND_ATTRIBUTES[1]; tokenPrivs.Privileges[0].Luid = luid; tokenPrivs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; IntPtr null1 = IntPtr.Zero; IntPtr null2 = IntPtr.Zero; if (!AdjustTokenPrivileges(token, false, ref tokenPrivs, 0, null1, null2)) throw new Exception(String.Format("AdjustTokenPrivileges failed. GetLastError: {0}", Marshal.GetLastWin32Error())); }
internal static bool LookupPrivilegeValue(string lpSystemName, string lpName, ref LUID lpLuid) { return true; }
internal static extern bool LookupPrivilegeValue([MarshalAs(UnmanagedType.LPTStr)] string lpSystemName, [MarshalAs(UnmanagedType.LPTStr)] string lpName, out LUID lpLuid);
private static string MonitorFriendlyName(LUID adapterId, uint targetId) { var deviceName = new DISPLAYCONFIG_TARGET_DEVICE_NAME { header = { size = (uint)Marshal.SizeOf(typeof (DISPLAYCONFIG_TARGET_DEVICE_NAME)), adapterId = adapterId, id = targetId, type = DISPLAYCONFIG_DEVICE_INFO_TYPE.DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME } }; var error = DisplayConfigGetDeviceInfo(ref deviceName); if (error != ERROR_SUCCESS) throw new Win32Exception(error); return deviceName.monitorFriendlyDeviceName; }
/// <summary> /// Internal helper function that returns two values relating to the SeBackupPrivilege /// </summary> /// <param name="hasPrivilege">True if the calling proccess has the SeBackupPrivilege, false otherwise</param> /// <param name="isEnabled">True if the SeBackupPrivilege is enabled, false otherwise</param> private static void GetBackupPrivilege(out bool hasPrivilege, out bool isEnabled) { int token = 0; int outsize = 0; TOKEN_PRIVILEGES TP = new TOKEN_PRIVILEGES(); LUID backupLuid = new LUID(); if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref token) == 0) throw new Win32Exception(Marshal.GetLastWin32Error()); if (LookupPrivilegeValue(null, SE_BACKUP_NAME, ref backupLuid) == 0) throw new Win32Exception(Marshal.GetLastWin32Error()); if (GetTokenInformation(token, TOKEN_INFORMATION_CLASS_PRIVILEGES, ref TP, Marshal.SizeOf(typeof(TOKEN_PRIVILEGES)), ref outsize) == 0) throw new Win32Exception(Marshal.GetLastWin32Error()); #if DEBUG Console.WriteLine("Read token information:"); PrintTokenInformation(TP); #endif for (int i = 0; i < TP.PrivilegeCount; i++) if (TP.Privileges[i].Luid.LowPart == backupLuid.LowPart && TP.Privileges[i].Luid.HighPart == backupLuid.HighPart) { isEnabled = (TP.Privileges[i].Attributes & SE_PRIVILEGE_ENABLED) == SE_PRIVILEGE_ENABLED; hasPrivilege = true; return; } hasPrivilege = false; isEnabled = false; }
internal static extern bool AllocateLocallyUniqueId(out LUID Luid);
private static extern bool LookupPrivilegeValueA(int lpSystemName, [MarshalAs(UnmanagedType.LPStr)]string lpName, ref LUID lpLuid);
public static bool UnloadHive(RegistryHive Base, string Reference) { try { int token = 0; LUID RestLUID = new LUID(); LUID BackLUID = new LUID(); TOKEN_PRIVILEGES RestPriv = new TOKEN_PRIVILEGES { Attributes = SE_PRIVILEGE_ENABLED, PrivilegeCount = 1 }; TOKEN_PRIVILEGES BackPriv = new TOKEN_PRIVILEGES { Attributes = SE_PRIVILEGE_ENABLED, PrivilegeCount = 1 }; OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref token); LookupPrivilegeValue(null, SE_RESTORE_NAME, ref RestLUID); LookupPrivilegeValue(null, SE_BACKUP_NAME, ref BackLUID); RestPriv.Luid = RestLUID; BackPriv.Luid = BackLUID; AdjustTokenPrivileges(token, false, ref RestPriv, 0, 0, 0); AdjustTokenPrivileges(token, false, ref BackPriv, 0, 0, 0); return RegUnLoadKey((uint)Base, Reference) == 0; } catch (Exception) { return false; } }
/// <summary> /// Enable/disable debug level access /// </summary> /// <param name="Enable">bool: enable/disable</param> /// <returns>bool</returns> public bool EnableAccess(bool Enable) { IntPtr hToken = IntPtr.Zero; IntPtr hProcess = IntPtr.Zero; LUID tLuid = new LUID(); TOKEN_PRIVILEGES NewState = new TOKEN_PRIVILEGES(); uint uPriv = (uint)(ETOKEN_PRIVILEGES.TOKEN_ADJUST_PRIVILEGES | ETOKEN_PRIVILEGES.TOKEN_QUERY | ETOKEN_PRIVILEGES.TOKEN_QUERY_SOURCE); try { hProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, GetCurrentProcessId()); if (hProcess == IntPtr.Zero) return false; if (OpenProcessToken(hProcess, uPriv, ref hToken)) return false; // Get the local unique id for the privilege. if (LookupPrivilegeValue(0, SE_DEBUG_NAME, ref tLuid)) return false; // Assign values to the TOKEN_PRIVILEGE structure. NewState.PrivilegeCount = 1; NewState.Privileges.pLuid = tLuid; NewState.Privileges.Attributes = (Enable ? SE_PRIVILEGE_ENABLED : 0); // Adjust the token privilege. return (AdjustTokenPrivileges(hToken, 0, ref NewState, Marshal.SizeOf(NewState), 0, 0)); } finally { if (hToken != IntPtr.Zero) CloseHandle(hToken); if (hProcess != IntPtr.Zero) CloseHandle(hProcess); } }
private static extern int LookupPrivilegeValue( string lpSystemName, string lpName, ref LUID lpLuid);
internal static extern bool LookupPrivilegeValue(string host, string name, ref LUID pluid);
internal static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, ref LUID lpLuid);
public static extern bool LookupPrivilegeName(int SystemName, ref LUID Luid, StringBuilder Name, out int RequiredSize);
static extern Int32 LookupPrivilegeValueW(Int32 lpSystemName, [MarshalAs(UnmanagedType.LPWStr)]string lpName, ref LUID lpLuid);
public static extern bool LookupPrivilegeValue(string SystemName, string PrivilegeName, ref LUID Luid);
private static extern bool LookupPrivilegeValue(IntPtr Null1, string lpName, out LUID lpLuid);