public static PrivilegeHolder?EnablePrivilege(string privilegeName) { var luid = LuidFromPrivilege(privilegeName, out var luidSuccess); if (!luidSuccess) { return(null); } PrivilegeHolder?holder = null; var success = false; try { // The payload is entirely in the finally block // This is how we ensure that the code will not be // interrupted by catastrophic exceptions } finally { try { // Retrieve TLS state var tlsContents = _ttlsSlotData; if (tlsContents == null) { _ttlsSlotData = tlsContents = TlsContents.Create(); } else { tlsContents.IncrementReferenceCount(); } if (tlsContents != null) { holder = new PrivilegeHolder(tlsContents, luid); if (holder.ObtainPrivilege()) { success = true; } } } finally { if (holder?._needToRevert == false) { holder.Reset(); } if (!success) { holder?.Dispose(); holder = null; } } } return(holder); }
public static TlsContents?Create() { if (_processHandle.IsInvalid) { lock (SyncRoot) { if (_processHandle.IsInvalid && NativeMethods.OpenProcessToken( NativeMethods.GetCurrentProcess(), TokenAccessLevels.Duplicate, out var localProcessHandle)) { _processHandle = localProcessHandle; } } } var success = true; // ReSharper disable once SuggestVarOrType_SimpleTypes TlsContents?result = new TlsContents(); try { // Make the sequence non-interruptible } finally { try { success = result.OpenThreadToken(); } finally { if (!success) { result.Dispose(); result = null; } } } return(result); }
private PrivilegeHolder(TlsContents contents, in Luid luid)