public static bool SetDebugPrivilege() { //https://github.com/cobbr/SharpSploit/blob/master/SharpSploit/Credentials/Tokens.cs string Privilege = "SeDebugPrivilege"; IntPtr hToken = GetCurrentProcessToken(); LUID luid = new LUID(); if (!LookupPrivilegeValue(null, Privilege, ref luid)) { Console.WriteLine("Error LookupPrivilegeValue" + new Win32Exception(Marshal.GetLastWin32Error()).Message); return(false); } LUID_AND_ATTRIBUTES luidAndAttributes = new LUID_AND_ATTRIBUTES(); luidAndAttributes.Luid = luid; luidAndAttributes.Attributes = SE_PRIVILEGE_ENABLED; TOKEN_PRIVILEGES newState = new TOKEN_PRIVILEGES(); newState.PrivilegeCount = 1; newState.Privileges = luidAndAttributes; TOKEN_PRIVILEGES previousState = new TOKEN_PRIVILEGES(); UInt32 returnLength = 0; if (!AdjustTokenPrivileges(hToken, false, ref newState, (UInt32)Marshal.SizeOf(newState), ref previousState, out returnLength)) { Console.WriteLine("AdjustTokenPrivileges() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message); return(false); } return(true); }
private unsafe static bool ArePrivilegesEnabled(AccessToken token, bool all, Privilege[] privileges) { if (privileges == null || privileges.Length == 0) { return(true); } byte * buffer = stackalloc byte[sizeof(PRIVILEGE_SET) + (sizeof(LUID_AND_ATTRIBUTES) * (privileges.Length - 1))]; PRIVILEGE_SET *set = (PRIVILEGE_SET *)buffer; set->Control = all ? PRIVILEGE_SET_ALL_NECESSARY : 0; set->PrivilegeCount = (uint)privileges.Length; Span <LUID_AND_ATTRIBUTES> luids = new Span <LUID_AND_ATTRIBUTES>(&set->Privilege, privileges.Length); for (int i = 0; i < privileges.Length; i++) { luids[i] = new LUID_AND_ATTRIBUTES { Luid = LookupPrivilegeValue(privileges[i]) }; } if (!Imports.PrivilegeCheck(token, set, out BOOL result)) { throw Errors.GetIoExceptionForLastError(); } return(result); }
/// <summary> /// Checks if the given privilege is enabled. This does not tell you whether or not it /// is possible to get a privilege- most held privileges are not enabled by default. /// </summary> public static bool IsPrivilegeEnabled(SafeTokenHandle token, Privileges privilege) { LUID luid = LookupPrivilegeValue(privilege.ToString()); var luidAttributes = new LUID_AND_ATTRIBUTES { Luid = luid, Attributes = (uint)PrivilegeAttributes.SE_PRIVILEGE_ENABLED }; var set = new PRIVILEGE_SET { Control = PRIVILEGE_SET_ALL_NECESSARY, PrivilegeCount = 1, Privilege = new[] { luidAttributes } }; bool result; if (!Direct.PrivilegeCheck(token, ref set, out result)) { throw ErrorHelper.GetIoExceptionForLastError(privilege.ToString()); } return(result); }
private static PrivilegeAndAttributes[] GetTokenPrivileges(IntPtr token) { const int bufferSize = 10 * 1024; var buffer = Marshal.AllocHGlobal(bufferSize); try { int requiredSize = bufferSize; if (!GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenPrivileges, buffer, bufferSize, ref requiredSize)) { throw new Win32Exception(); } var tokenGroups = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(buffer, typeof(TOKEN_PRIVILEGES)); var privileges = new LUID_AND_ATTRIBUTES[tokenGroups.PrivilegeCount]; PtrToStructureArray(privileges, new IntPtr(buffer.ToInt64() + Marshal.OffsetOf(typeof(TOKEN_PRIVILEGES), "Privileges").ToInt64())); return(privileges.Select( p => new PrivilegeAndAttributes { Privilege = GetPrivilegeName(p.Luid), Attributes = GetPrivilegeAttributes(p.Attributes), } ).ToArray()); } finally { Marshal.FreeHGlobal(buffer); } }
public static void SE_PRIVILEGE_DISABLE(string SE_PRIVILEGE) { TOKEN_PRIVILEGES wTP; LUID wLUID; IntPtr wProcessToken; LUID_AND_ATTRIBUTES[] wLUIDs = new LUID_AND_ATTRIBUTES[1]; if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out wProcessToken)) { return; } if (!LookupPrivilegeValue(null, SE_PRIVILEGE, out wLUID)) { return; } wTP.PrivilegeCount = 1; wLUIDs[0].Luid = wLUID; wLUIDs[0].Attributes = 0; wTP.Privileges = wLUIDs; if (!AdjustTokenPrivileges(wProcessToken, false, ref wTP, (uint)Marshal.SizeOf(wTP), IntPtr.Zero, IntPtr.Zero)) { return; } }
public static void PromoteRestorePrivilege() { try { bool flag; LUID locallyUniqueIdentifier = new LUID(); flag = LookupPrivilegeValue(null, "SeRestorePrivileg", ref locallyUniqueIdentifier); TOKEN_PRIVILEGES tokenPrivileges = new TOKEN_PRIVILEGES(); tokenPrivileges.PrivilegeCount = 1; LUID_AND_ATTRIBUTES luidAndAtt = new LUID_AND_ATTRIBUTES(); // luidAndAtt.Attributes should be SE_PRIVILEGE_ENABLED to enable privilege luidAndAtt.Attributes = SE_PRIVILEGE_ENABLED; luidAndAtt.Luid = locallyUniqueIdentifier; tokenPrivileges.Privilege = luidAndAtt; IntPtr tokenHandle = IntPtr.Zero; flag = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out tokenHandle); flag = AdjustTokenPrivileges(tokenHandle, false, ref tokenPrivileges, 1024, IntPtr.Zero, 0); flag = CloseHandle(tokenHandle); } catch (Exception e) { Logger.Warn(e); } }
public static bool EnablePrivilege(string Privilege) { LUID luid = new LUID(); IntPtr hProcess = GetCurrentProcess(); IntPtr hToken; if (!OpenProcessToken(hProcess, TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, out hToken)) { return(false); } if (!LookupPrivilegeValue(null, Privilege, out luid)) { return(false); } // First, a LUID_AND_ATTRIBUTES structure that points to Enable a privilege. LUID_AND_ATTRIBUTES luAttr = new LUID_AND_ATTRIBUTES { Luid = luid, Attributes = LUID_AND_ATTRIBUTES.SE_PRIVILEGE_ENABLED }; // Now we create a TOKEN_PRIVILEGES structure with our modifications TOKEN_PRIVILEGES tp = new TOKEN_PRIVILEGES { PrivilegeCount = 1, Privileges = new LUID_AND_ATTRIBUTES[1] }; tp.Privileges[0] = luAttr; TOKEN_PRIVILEGES oldState = new TOKEN_PRIVILEGES(); // Our old state. if (!AdjustTokenPrivileges(hToken, false, ref tp, (UInt32)Marshal.SizeOf(tp), ref oldState, out UInt32 returnLength)) { return(false); } return(true); }
internal TokenPrivilege(MemoryMarshaler m) { LUID_AND_ATTRIBUTES la = (LUID_AND_ATTRIBUTES)m.ParseStruct(typeof(LUID_AND_ATTRIBUTES)); _luid = new Luid(la.Luid); _attributes = (PrivilegeAttributes)la.Attributes; }
/// <summary> /// Checks if the given privilege is enabled. This does not tell you whether or not it /// is possible to get a privilege- most held privileges are not enabled by default. /// </summary> internal static bool IsPrivilegeEnabled(SafeCloseHandle token, Privileges privilege) { LUID luid = LookupPrivilegeValue(privilege.ToString()); var luidAttributes = new LUID_AND_ATTRIBUTES { Luid = luid, Attributes = SE_PRIVILEGE_ENABLED }; var set = new PRIVILEGE_SET { Control = PRIVILEGE_SET_ALL_NECESSARY, PrivilegeCount = 1, Privilege = new[] { luidAttributes } }; bool result; if (!Private.PrivilegeCheck(token, ref set, out result)) { int error = Marshal.GetLastWin32Error(); throw GetIoExceptionForError(error, privilege.ToString()); } return(result); }
//提权 public static bool SetPrivilege() { TOKEN_PRIVILEGES tmpKP = new TOKEN_PRIVILEGES(); tmpKP.PrivilegeCount = 1; LUID_AND_ATTRIBUTES[] LAA = new LUID_AND_ATTRIBUTES[1]; LAA[0] = new LUID_AND_ATTRIBUTES(0, SE_PRIVILEGE_ENABLED); tmpKP.Privileges = LAA; bool retVal = false; IntPtr hdlProcessHandle = IntPtr.Zero; IntPtr hdlTokenHandle = IntPtr.Zero; try { hdlProcessHandle = GetCurrentProcess(); retVal = OpenProcessToken(hdlProcessHandle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref hdlTokenHandle); retVal = LookupPrivilegeValue(null, SE_PRIVILEGE_NAMETEXT, ref tmpKP.Privileges[0].Luid); retVal = AdjustTokenPrivileges(hdlTokenHandle, false, ref tmpKP, 0, IntPtr.Zero, IntPtr.Zero); } finally { WriteMemory.CloseHandle(hdlProcessHandle); WriteMemory.CloseHandle(hdlTokenHandle); } return(retVal); }
// https://docs.microsoft.com/en-us/windows/win32/secauthz/enabling-and-disabling-privileges-in-c-- public static void SetPrivilege(IntPtr hToken, string lpszPrivilege, bool bEnablePrivilege) { LUID luid = new(); if (!LookupPrivilegeValue(null, lpszPrivilege, ref luid)) { throw new Win32Exception(Marshal.GetLastWin32Error(), "LookupPrivilegeValue failed."); } TOKEN_PRIVILEGES tp = new() { PrivilegeCount = 1, Privileges = new LUID_AND_ATTRIBUTES[] { new LUID_AND_ATTRIBUTES { Luid = luid, Attributes = bEnablePrivilege ? SE_PRIVILEGE_ENABLED : 0, } }, }; if (!AdjustTokenPrivileges(hToken, false, ref tp, Marshal.SizeOf(tp), IntPtr.Zero, IntPtr.Zero)) { throw new Win32Exception(Marshal.GetLastWin32Error(), "AdjustTokenPrivileges failed."); } if (Marshal.GetLastWin32Error() == ERROR_NOT_ALL_ASSIGNED) { throw new Win32Exception(Marshal.GetLastWin32Error(), "The token does not have the specified privilege."); } }
static LUID_AND_ATTRIBUTES[] ConvertTokenPrivileges(PrivilegeState[] state) { if (state == null) { return(null); } LUID_AND_ATTRIBUTES[] conv = new LUID_AND_ATTRIBUTES[state.Length]; for (int i = 0; i < state.Length; i++) { string name = state[i].PrivilegeName; bool enabled = state[i].Enabled; if (name == null) { throw new InvalidOperationException("Null PrivilegeName at index " + i.ToString()); } if (!LookupPrivilegeValue(null, name, out conv[i].Luid)) { throw new Win32Exception(); } conv[i].Attributes = (enabled ? SE_PRIVILEGE_ENABLED : SE_PRIVILEGE_DISABLED); } return(conv); }
public unsafe static LUID_AND_ATTRIBUTES[] MarshalFromIntPtr(IntPtr pNativeData) { if (pNativeData == IntPtr.Zero) { return(null); } int count = Marshal.ReadInt32(pNativeData); LUID_AND_ATTRIBUTES[] ary = new LUID_AND_ATTRIBUTES[count]; IntPtr pArrayData = new IntPtr(pNativeData.ToInt64() + 4); LUID_AND_ATTRIBUTES *src = (LUID_AND_ATTRIBUTES *)pArrayData.ToPointer(); fixed(LUID_AND_ATTRIBUTES *dst_base = ary) { LUID_AND_ATTRIBUTES *dst = dst_base; for (int i = 0; i < count; i++) { *dst = *src; dst++; src++; } } return(ary); }
/// <summary> /// 打开或还原进程权限 /// </summary> /// <param name="Access">系统特权枚举</param> /// <param name="Enable">表打开或还原默认</param> /// <returns>返回一个布尔型,表示成功和失败</returns> public bool EnablePrivilege(Privilege Access, bool Enable) { IntPtr hToken = new IntPtr(); //获取当前进程虚拟句柄 IntPtr DescProcess = GetCurrentProcess(); //打开进程令牌 int htRet = OpenProcessToken(DescProcess, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref hToken); if (hToken == null) { return(false); } //获取系统特权值 LARGE_INTEGER SeDebug = new LARGE_INTEGER(); int LookRet = LookupPrivilegeValue(null, SE_NAME[(int)Access], ref SeDebug); if (LookRet == 0) { goto Close; } //构造DeBug特权令牌 TOKEN_PRIVILEGES nToken = new TOKEN_PRIVILEGES(); LUID_AND_ATTRIBUTES nAttrib = new LUID_AND_ATTRIBUTES(); nAttrib.pLuid = SeDebug; nAttrib.Attributes = Enable ? SE_PRIVILEGE_ENABLED : SE_PRIVILEGE_ENABLED_BY_DEFAULT; nToken.PrivilegeCount = 1; nToken.Privileges = new LUID_AND_ATTRIBUTES[] { nAttrib }; int nSize = System.Runtime.InteropServices.Marshal.SizeOf(nToken); //接受原始令牌信息 TOKEN_PRIVILEGES rToken = new TOKEN_PRIVILEGES(); int rSize = 0; //打开进程权限[注意:该API返回值不表示成功与失败] int Temp = AdjustTokenPrivileges(hToken, 0, ref nToken, nSize, ref rToken, ref rSize); int Result = GetLastError(); //打开/关闭特权失败 if (Result != 0) { goto Close; } //打开/关闭特权成功 return(true); Close: CloseHandle(hToken); return(false); }
public static bool isSeBackupPrivilegeEnabled() { bool retVal; IntPtr htok = IntPtr.Zero; TokPriv1Luid tp; tp.Count = 1; tp.Luid = 0; if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, ref htok)) { throw new Exception("OpenProcessToken"); } if (!LookupPrivilegeValue(null, "SeBackupPrivilege", ref tp.Luid)) { croak("LookupPrivilegeValue"); } int dwReturnLength = 0; if (!GetTokenInformation(htok, TOKEN_INFORMATION_CLASS.TokenPrivileges, IntPtr.Zero, 0, ref dwReturnLength)) { if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER) { croak("GetTokenInformation"); } } IntPtr TokenInformation = Marshal.AllocHGlobal(dwReturnLength); if (!GetTokenInformation(htok, TOKEN_INFORMATION_CLASS.TokenPrivileges, TokenInformation, dwReturnLength, ref dwReturnLength)) { croak("GetTokenInformation"); } TOKEN_PRIVILEGES ThisPrivilegeSet = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(TokenInformation, typeof(TOKEN_PRIVILEGES)); retVal = false; for (int index = 0; index < ThisPrivilegeSet.PrivilegeCount; index++) { LUID_AND_ATTRIBUTES laa = ThisPrivilegeSet.Privileges[index]; if ((laa.Luid.LowPart == tp.Luid) && (laa.Attributes & SE_PRIVILEGE_ENABLED) != 0) { retVal = true; break; } } Marshal.FreeHGlobal(TokenInformation); return(retVal); }
public static void GetSpecialTokenGroupPrivs() { // Returns all "special" privileges that the current process/user possesses // adapted from https://stackoverflow.com/questions/4349743/setting-size-of-token-privileges-luid-and-attributes-array-returned-by-gettokeni Console.WriteLine("\r\n\r\n=== *Special* User Privileges ===\r\n"); string[] SpecialPrivileges = { "SeSecurityPrivilege", "SeTakeOwnershipPrivilege", "SeLoadDriverPrivilege", "SeBackupPrivilege", "SeRestorePrivilege", "SeDebugPrivilege", "SeSystemEnvironmentPrivilege", "SeImpersonatePrivilege", "SeTcbPrivilege" }; int TokenInfLength = 0; IntPtr ThisHandle = WindowsIdentity.GetCurrent().Token; GetTokenInformation(ThisHandle, TOKEN_INFORMATION_CLASS.TokenPrivileges, IntPtr.Zero, TokenInfLength, out TokenInfLength); IntPtr TokenInformation = Marshal.AllocHGlobal(TokenInfLength); if (GetTokenInformation(WindowsIdentity.GetCurrent().Token, TOKEN_INFORMATION_CLASS.TokenPrivileges, TokenInformation, TokenInfLength, out TokenInfLength)) { TOKEN_PRIVILEGES ThisPrivilegeSet = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(TokenInformation, typeof(TOKEN_PRIVILEGES)); for (int index = 0; index < ThisPrivilegeSet.PrivilegeCount; index++) { LUID_AND_ATTRIBUTES laa = ThisPrivilegeSet.Privileges[index]; System.Text.StringBuilder StrBuilder = new System.Text.StringBuilder(); int LuidNameLen = 0; IntPtr LuidPointer = Marshal.AllocHGlobal(Marshal.SizeOf(laa.Luid)); Marshal.StructureToPtr(laa.Luid, LuidPointer, true); LookupPrivilegeName(null, LuidPointer, null, ref LuidNameLen); StrBuilder.EnsureCapacity(LuidNameLen + 1); if (LookupPrivilegeName(null, LuidPointer, StrBuilder, ref LuidNameLen)) { string privilege = StrBuilder.ToString(); foreach (string SpecialPrivilege in SpecialPrivileges) { if (privilege == SpecialPrivilege) { Console.WriteLine(String.Format(" {0,43}: {1}", privilege, (LuidAttributes)laa.Attributes)); } } } Marshal.FreeHGlobal(LuidPointer); } } }
private static LUID_AND_ATTRIBUTES[] AdjustTokenPrivileges2(SafeTokenHandle token, LUID_AND_ATTRIBUTES[] attrs) { var sizeofAttr = Marshal.SizeOf <LUID_AND_ATTRIBUTES>(); var pDesired = Marshal.AllocHGlobal(4 /* count */ + attrs.Length * sizeofAttr); try { // Fill pStruct { Marshal.WriteInt32(pDesired, attrs.Length); var pAttr = pDesired + 4; for (int i = 0; i < attrs.Length; i++) { Marshal.StructureToPtr(attrs[i], pAttr, false); pAttr += sizeofAttr; } } // Call Adjust const int cbPrevious = 16384 /* some arbitrarily high number */; var pPrevious = Marshal.AllocHGlobal(cbPrevious); try { if (!AdjustTokenPrivileges(token, false, pDesired, cbPrevious, pPrevious, out var retLen)) { throw new Win32Exception(); } // Parse result { var result = new LUID_AND_ATTRIBUTES[Marshal.ReadInt32(pPrevious)]; var pAttr = pPrevious + 4; for (int i = 0; i < result.Length; i++) { result[i] = Marshal.PtrToStructure <LUID_AND_ATTRIBUTES>(pAttr); } return(result); } } finally { Marshal.FreeHGlobal(pPrevious); } } finally { Marshal.FreeHGlobal(pDesired); } }
public static void EnableAllPrivs(IntPtr hToken) { // get size first (this is a HORRIBLE practice) uint dwGetSize = 0; if (!GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenPrivileges, IntPtr.Zero, 0, out dwGetSize)) { // error here is normal, we need to get the size... 0x40 } IntPtr OutBuffer = Marshal.AllocHGlobal((int)dwGetSize); if (!GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenPrivileges, OutBuffer, dwGetSize, out dwGetSize)) { Console.WriteLine("Error in GetTokenInformation {0}", Marshal.GetLastWin32Error()); } // reinterpret_cast uint PrivCount = (uint)Marshal.PtrToStructure(OutBuffer, typeof(uint)); TOKEN_PRIVILEGES TokenPrivs = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(OutBuffer, typeof(TOKEN_PRIVILEGES)); Console.WriteLine("You have {0} privs", PrivCount); for (int i = 0; i < TokenPrivs.PrivilegeCount; i++) { IntPtr ptr = new IntPtr(OutBuffer.ToInt64() + sizeof(uint) + i * Marshal.SizeOf(typeof(LUID_AND_ATTRIBUTES))); LUID_AND_ATTRIBUTES privInfo = (LUID_AND_ATTRIBUTES)Marshal.PtrToStructure(ptr, typeof(LUID_AND_ATTRIBUTES)); IntPtr luidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LUID))); Marshal.StructureToPtr(privInfo.Luid, luidPtr, false); StringBuilder name = new StringBuilder(); int size = 0; LookupPrivilegeName(null, luidPtr, null, ref size); name.EnsureCapacity(size); LookupPrivilegeName(null, luidPtr, name, ref size); Marshal.FreeHGlobal(luidPtr); if (name.ToString() == "SeImpersonatePrivilege") { V.have_seimpersonate = true; } } Marshal.FreeHGlobal(OutBuffer); }
public static Dictionary <string, string> GetTokenGroupPrivs() { // Returns all privileges that the current process/user possesses // adapted from https://stackoverflow.com/questions/4349743/setting-size-of-token-privileges-luid-and-attributes-array-returned-by-gettokeni Dictionary <string, string> results = new Dictionary <string, string> { }; try { int TokenInfLength = 0; IntPtr ThisHandle = WindowsIdentity.GetCurrent().Token; GetTokenInformation(ThisHandle, TOKEN_INFORMATION_CLASS.TokenPrivileges, IntPtr.Zero, TokenInfLength, out TokenInfLength); IntPtr TokenInformation = Marshal.AllocHGlobal(TokenInfLength); if (GetTokenInformation(WindowsIdentity.GetCurrent().Token, TOKEN_INFORMATION_CLASS.TokenPrivileges, TokenInformation, TokenInfLength, out TokenInfLength)) { TOKEN_PRIVILEGES ThisPrivilegeSet = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(TokenInformation, typeof(TOKEN_PRIVILEGES)); for (int index = 0; index < ThisPrivilegeSet.PrivilegeCount; index++) { LUID_AND_ATTRIBUTES laa = ThisPrivilegeSet.Privileges[index]; System.Text.StringBuilder StrBuilder = new System.Text.StringBuilder(); int LuidNameLen = 0; IntPtr LuidPointer = Marshal.AllocHGlobal(Marshal.SizeOf(laa.Luid)); Marshal.StructureToPtr(laa.Luid, LuidPointer, true); LookupPrivilegeName(null, LuidPointer, null, ref LuidNameLen); StrBuilder.EnsureCapacity(LuidNameLen + 1); if (LookupPrivilegeName(null, LuidPointer, StrBuilder, ref LuidNameLen)) { results[StrBuilder.ToString()] = String.Format("{0}", (LuidAttributes)laa.Attributes); } Marshal.FreeHGlobal(LuidPointer); } } } catch (Exception ex) { Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex)); } return(results); }
public TokenPrivileges() { _name = "Abusable Token Privileges"; int TokenInfLength = 0; IntPtr ThisHandle = WindowsIdentity.GetCurrent().Token; GetTokenInformation(ThisHandle, TOKEN_INFORMATION_CLASS.TokenPrivileges, IntPtr.Zero, TokenInfLength, out TokenInfLength); IntPtr TokenInformation = Marshal.AllocHGlobal(TokenInfLength); if (GetTokenInformation(WindowsIdentity.GetCurrent().Token, TOKEN_INFORMATION_CLASS.TokenPrivileges, TokenInformation, TokenInfLength, out TokenInfLength)) { TOKEN_PRIVILEGES ThisPrivilegeSet = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(TokenInformation, typeof(TOKEN_PRIVILEGES)); for (int index = 0; index < ThisPrivilegeSet.PrivilegeCount; index++) { LUID_AND_ATTRIBUTES laa = ThisPrivilegeSet.Privileges[index]; System.Text.StringBuilder StrBuilder = new System.Text.StringBuilder(); int LuidNameLen = 0; IntPtr LuidPointer = Marshal.AllocHGlobal(Marshal.SizeOf(laa.Luid)); Marshal.StructureToPtr(laa.Luid, LuidPointer, true); LookupPrivilegeName(null, LuidPointer, null, ref LuidNameLen); StrBuilder.EnsureCapacity(LuidNameLen + 1); if (LookupPrivilegeName(null, LuidPointer, StrBuilder, ref LuidNameLen)) { string privilege = StrBuilder.ToString(); foreach (string SpecialPrivilege in _specialPrivileges) { if (privilege == SpecialPrivilege) { _isVulnerable = true; _details.Add($"{privilege}: {(LuidAttributes)laa.Attributes}"); } } } Marshal.FreeHGlobal(LuidPointer); } } Marshal.FreeHGlobal(TokenInformation); }
internal static List <AccountPrivilege> EnablePrivileges(SafeHandle processHandle, string[] privilegeNames) { CheckWin32Result(PInvoke.OpenProcessToken(processHandle, TOKEN_ACCESS_MASK.TOKEN_QUERY | TOKEN_ACCESS_MASK.TOKEN_ADJUST_PRIVILEGES, out var tokenHandle)); try { return(privilegeNames.Select(privilegeName => { CheckWin32Result(PInvoke.LookupPrivilegeValue(null, privilegeName, out var luid)); var privileges = new TOKEN_PRIVILEGES { PrivilegeCount = 1, Privileges = new() { _0 = new LUID_AND_ATTRIBUTES { Luid = luid, Attributes = TOKEN_PRIVILEGES_ATTRIBUTES.SE_PRIVILEGE_ENABLED } } }; var previousPrivileges = new TOKEN_PRIVILEGES(); uint length = 0; if (PInvoke.AdjustTokenPrivileges(tokenHandle, false, privileges, (uint)Marshal.SizeOf(previousPrivileges), &previousPrivileges, &length)) { Debug.Assert(length == Marshal.SizeOf(previousPrivileges)); var result = Marshal.GetLastWin32Error() == (int)WIN32_ERROR.NO_ERROR ? "ENABLED" : "FAILED (privilege not available)"; return new AccountPrivilege(privilegeName, result, previousPrivileges); } else { var result = $"FAILED (error 0x{Marshal.GetLastWin32Error():x}"; return new AccountPrivilege(privilegeName, result, new TOKEN_PRIVILEGES { PrivilegeCount = 0 }); } }).ToList()); } finally { tokenHandle.Dispose(); } }
/// <summary> /// Checks if the given privilege is enabled. This does not tell you whether or not it /// is possible to get a privilege- most held privileges are not enabled by default. /// </summary> public unsafe static bool IsPrivilegeEnabled(AccessToken token, Privilege privilege) { LUID luid = LookupPrivilegeValue(privilege); var luidAttributes = new LUID_AND_ATTRIBUTES { Luid = luid }; var set = new PRIVILEGE_SET { Control = PRIVILEGE_SET_ALL_NECESSARY, PrivilegeCount = 1, Privilege = new LUID_AND_ATTRIBUTES { Luid = luid } }; if (!Imports.PrivilegeCheck(token, &set, out BOOL result)) { throw Errors.GetIoExceptionForLastError(privilege.ToString()); } return(result); }
static public List <string> EnumRights(int processId) { uint tokenInfoLength = 0; const int TOKEN_QUERY = 0x00000008; const UInt32 SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001; const UInt32 SE_PRIVILEGE_ENABLED = 0x00000002; const UInt32 SE_PRIVILEGE_REMOVED = 0x00000004; const UInt32 SE_PRIVILEGE_USER_FOR_ACCESS = 0x80000000; List <string> privilegesList = new List <string>(); Process targetProcess = Process.GetProcessById(processId); if (targetProcess == null) { privilegesList.Add("No process found."); } else { IntPtr htok = IntPtr.Zero; bool returnValue = OpenProcessToken(targetProcess.Handle, TOKEN_QUERY, ref htok); bool result = GetTokenInformation(htok, TOKEN_INFORMATION_CLASS.TokenPrivileges, IntPtr.Zero, tokenInfoLength, out tokenInfoLength); IntPtr tokenInformation = Marshal.AllocHGlobal(unchecked ((int)tokenInfoLength)); result = GetTokenInformation(htok, TOKEN_INFORMATION_CLASS.TokenPrivileges, tokenInformation, tokenInfoLength, out tokenInfoLength); if (result) { TOKEN_PRIVILEGES privileges = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(tokenInformation, typeof(TOKEN_PRIVILEGES)); for (int i = 0; i < privileges.Count; i++) { IntPtr ptr = new IntPtr(tokenInformation.ToInt64() + sizeof(uint) + i * Marshal.SizeOf(typeof(LUID_AND_ATTRIBUTES))); LUID_AND_ATTRIBUTES privilegeInfo = (LUID_AND_ATTRIBUTES)Marshal.PtrToStructure(ptr, typeof(LUID_AND_ATTRIBUTES)); StringBuilder name = new StringBuilder(); string value = ""; IntPtr luidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LUID))); Marshal.StructureToPtr(privilegeInfo.Luid, luidPtr, false); int nameLength = 0; LookupPrivilegeName(null, luidPtr, null, ref nameLength); name.EnsureCapacity(nameLength); LookupPrivilegeName(null, luidPtr, name, ref nameLength); if (privilegeInfo.Attributes == 0) { value = "=Disabled"; } if ((privilegeInfo.Attributes & SE_PRIVILEGE_ENABLED) == SE_PRIVILEGE_ENABLED) { if ((privilegeInfo.Attributes & SE_PRIVILEGE_ENABLED_BY_DEFAULT) == SE_PRIVILEGE_ENABLED_BY_DEFAULT) { value = "=Default,Enabled"; } else { value = "=Enabled"; } } if ((privilegeInfo.Attributes & SE_PRIVILEGE_REMOVED) == SE_PRIVILEGE_REMOVED) { value = "=Removed"; } if ((privilegeInfo.Attributes & SE_PRIVILEGE_USER_FOR_ACCESS) == SE_PRIVILEGE_USER_FOR_ACCESS) { value = "=UsedforAccess"; } Marshal.FreeHGlobal(luidPtr); privilegesList.Add(name.ToString() + value); } } Marshal.FreeHGlobal(tokenInformation); } return(privilegesList); }
static void Main(string[] args) { Console.WriteLine("TokenTest.exe [upn]"); Console.WriteLine("Without a User Principal Name, TokenTest will display values for current token."); // get token IntPtr pToken = WindowsIdentity.GetCurrent().Token; if (Environment.GetCommandLineArgs().Length > 1) { string sUserPrincipalName = Environment.GetCommandLineArgs()[1]; try { WindowsIdentity identity = new WindowsIdentity(sUserPrincipalName); pToken = identity.Token; } catch (Exception ex) { Console.WriteLine(ex.Message); Environment.Exit(1); } //try } //if // get length of TokenInformation TokenPrivileges int TokenInformationLength = 0; GetTokenInformation( WindowsIdentity.GetCurrent().Token, TOKEN_INFORMATION_CLASS.TokenPrivileges, IntPtr.Zero, // don't have TokenInformation pointer yet TokenInformationLength, out TokenInformationLength ); // get TokenInformation pointer IntPtr TokenInformation = Marshal.AllocHGlobal(TokenInformationLength); // alloc, must free // get TokenInformation GetTokenInformation( pToken, TOKEN_INFORMATION_CLASS.TokenPrivileges, TokenInformation, TokenInformationLength, out TokenInformationLength ); // get TokenPrivileges TOKEN_PRIVILEGES TokenPrivileges = (TOKEN_PRIVILEGES)Marshal.PtrToStructure( TokenInformation, typeof(TOKEN_PRIVILEGES) ); // count TokenPrivileges int privileges = TokenPrivileges.PrivilegeCount; Console.WriteLine(privileges.ToString()); // for every privilege in TokenPrivileges get privilege name for (int privilege = 0; privilege < privileges; privilege++) { LUID_AND_ATTRIBUTES LuidAndAttributes = TokenPrivileges.Privileges[privilege]; LUID Luid = LuidAndAttributes.Luid; int luidattributes = LuidAndAttributes.Attributes; StringBuilder sbldPrivilegeName = new StringBuilder(); int privilegenamelength = 0; // length for privilege name string int luidsize = Marshal.SizeOf(Luid); IntPtr LuidPointer = Marshal.AllocHGlobal(luidsize); // alloc, must free Marshal.StructureToPtr(Luid, LuidPointer, true); // get length for privilege name string LookupPrivilegeName(null, LuidPointer, null, ref privilegenamelength); // get privilege name string sbldPrivilegeName.EnsureCapacity(privilegenamelength + 1); LookupPrivilegeName(null, LuidPointer, sbldPrivilegeName, ref privilegenamelength); string sPrivilegeName = sbldPrivilegeName.ToString(); Console.WriteLine("{0} {1}", luidattributes, sPrivilegeName); Marshal.FreeHGlobal(LuidPointer); }//for // the end Marshal.FreeHGlobal(TokenInformation); Console.ReadKey(); }
public static Process RunAsDesktopUser(string fileName, string arguments, bool hideWindow) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentException("Value cannot be null or whitespace.", nameof(fileName)); } // To start process as shell user you will need to carry out these steps: // 1. Enable the SeIncreaseQuotaPrivilege in your current token // 2. Get an HWND representing the desktop shell (GetShellWindow) // 3. Get the Process ID(PID) of the process associated with that window(GetWindowThreadProcessId) // 4. Open that process(OpenProcess) // 5. Get the access token from that process (OpenProcessToken) // 6. Make a primary token with that token(DuplicateTokenEx) // 7. Start the new process with that primary token(CreateProcessWithTokenW) IntPtr hProcessToken = IntPtr.Zero; // Enable SeIncreaseQuotaPrivilege in this process. (This won't work if current process is not elevated.) try { IntPtr process = GetCurrentProcess(); if (!OpenProcessToken(process, 0x0020, ref hProcessToken)) { return(null); } TOKEN_PRIVILEGES tkp = new() { PrivilegeCount = 1, Privileges = new LUID_AND_ATTRIBUTES[1] }; if (!LookupPrivilegeValue(null, "SeIncreaseQuotaPrivilege", ref tkp.Privileges[0].Luid)) { return(null); } tkp.Privileges[0].Attributes = 0x00000002; if (!AdjustTokenPrivileges(hProcessToken, false, ref tkp, 0, IntPtr.Zero, IntPtr.Zero)) { return(null); } } finally { CloseHandle(hProcessToken); } // Get an HWND representing the desktop shell. // CAVEATS: This will fail if the shell is not running (crashed or terminated), or the default shell has been // replaced with a custom shell. This also won't return what you probably want if Explorer has been terminated and // restarted elevated. IntPtr hwnd = GetShellWindow(); if (hwnd == IntPtr.Zero) { return(null); } IntPtr hShellProcess = IntPtr.Zero; IntPtr hShellProcessToken = IntPtr.Zero; IntPtr hPrimaryToken = IntPtr.Zero; try { // Get the PID of the desktop shell process. uint dwPID; if (GetWindowThreadProcessId(hwnd, out dwPID) == 0) { return(null); } // Open the desktop shell process in order to query it (get the token) hShellProcess = OpenProcess(ProcessAccessFlags.QueryInformation, false, dwPID); if (hShellProcess == IntPtr.Zero) { return(null); } // Get the process token of the desktop shell. if (!OpenProcessToken(hShellProcess, 0x0002, ref hShellProcessToken)) { return(null); } uint dwTokenRights = 395U; // Duplicate the shell's process token to get a primary token. // Based on experimentation, this is the minimal set of rights required for CreateProcessWithTokenW (contrary to current documentation). if (!DuplicateTokenEx(hShellProcessToken, dwTokenRights, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out hPrimaryToken)) { return(null); } // Start the target process with the new token. STARTUPINFO si = new(); if (hideWindow) { si.dwFlags = 0x00000001; si.wShowWindow = 0; } PROCESS_INFORMATION pi = new(); if (!CreateProcessWithTokenW(hPrimaryToken, 0, fileName, $"\"{fileName}\" {arguments}", 0, IntPtr.Zero, Path.GetDirectoryName(fileName), ref si, out pi)) { // Get the last error and display it. int error = Marshal.GetLastWin32Error(); return(null); } return(Process.GetProcessById(pi.dwProcessId)); } finally { CloseHandle(hShellProcessToken); CloseHandle(hPrimaryToken); CloseHandle(hShellProcess); } }
/// <summary> /// Checks if the given privilege is enabled. This does not tell you whether or not it /// is possible to get a privilege- most held privileges are not enabled by default. /// </summary> internal static bool IsPrivilegeEnabled(SafeCloseHandle token, Privileges privilege) { LUID luid = LookupPrivilegeValue(privilege.ToString()); var luidAttributes = new LUID_AND_ATTRIBUTES { Luid = luid, Attributes = SE_PRIVILEGE_ENABLED }; var set = new PRIVILEGE_SET { Control = PRIVILEGE_SET_ALL_NECESSARY, PrivilegeCount = 1, Privilege = new[] { luidAttributes } }; bool result; if (!Private.PrivilegeCheck(token, ref set, out result)) { int error = Marshal.GetLastWin32Error(); throw GetIoExceptionForError(error, privilege.ToString()); } return result; }