Кто может предоставить C# invoke win32 setnamedsecurityinfo полную демонстрацию
I have a problem: in the case of non-system administrators unsuccessful, modify the registry and operation services (install | uninstall | start | stop), I know that there are win32 Api SetNamedSecurityInfo can make the current user has operational permissions, I wrote some Without a successful example, who can provide a complete example, thank you
Что я уже пробовал:
public class dongge { [StructLayout(LayoutKind.Sequential)] public struct AUTHZ_ACCESS_REQUEST { public int DesiredAccess; public byte[] PrincipalSelfSid; public OBJECT_TYPE_LIST[] ObjectTypeList; public int ObjectTypeListLength; public IntPtr OptionalArguments; }; [StructLayout(LayoutKind.Sequential)] public struct OBJECT_TYPE_LIST { OBJECT_TYPE_LEVEL Level; int Sbz; IntPtr ObjectType; }; [StructLayout(LayoutKind.Sequential)] public struct AUTHZ_ACCESS_REPLY { public int ResultListLength; public IntPtr GrantedAccessMask; public IntPtr SaclEvaluationResults; public IntPtr Error; }; public enum OBJECT_TYPE_LEVEL : int { ACCESS_OBJECT_GUID = 0, ACCESS_PROPERTY_SET_GUID = 1, ACCESS_PROPERTY_GUID = 2, ACCESS_MAX_LEVEL = 4 }; enum AUTHZ_RM_FLAG : uint { AUTHZ_RM_FLAG_NO_AUDIT = 1, AUTHZ_RM_FLAG_INITIALIZE_UNDER_IMPERSONATION = 2, AUTHZ_RM_FLAG_NO_CENTRAL_ACCESS_POLICIES = 4, } [StructLayoutAttribute(LayoutKind.Sequential)] public struct LUID { public uint LowPart; public int HighPart; } [DllImport("advapi32.dll", CharSet = CharSet.Auto)] static extern uint GetNamedSecurityInfo( string pObjectName, SE_OBJECT_TYPE ObjectType, SECURITY_INFORMATION SecurityInfo, out IntPtr pSidOwner, out IntPtr pSidGroup, out IntPtr pDacl, out IntPtr pSacl, out IntPtr pSecurityDescriptor); [DllImport("authz.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzInitializeContextFromSid", CharSet = CharSet.Unicode)] static extern public bool AuthzInitializeContextFromSid( int Flags, IntPtr UserSid, IntPtr AuthzResourceManager, IntPtr pExpirationTime, LUID Identitifier, IntPtr DynamicGroupArgs, out IntPtr pAuthzClientContext ); [DllImport("authz.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzInitializeResourceManager", CharSet = CharSet.Unicode)] static extern public bool AuthzInitializeResourceManager( int flags, IntPtr pfnAccessCheck, IntPtr pfnComputeDynamicGroups, IntPtr pfnFreeDynamicGroups, string name, out IntPtr rm ); [DllImport("authz.dll", EntryPoint = "AuthzAccessCheck", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] private static extern bool AuthzAccessCheck(int flags, IntPtr hAuthzClientContext, ref AUTHZ_ACCESS_REQUEST pRequest, IntPtr AuditEvent, IntPtr pSecurityDescriptor, byte[] OptionalSecurityDescriptorArray, int OptionalSecurityDescriptorCount, ref AUTHZ_ACCESS_REPLY pReply, out IntPtr phAccessCheckResults); enum ACCESS_MASK : uint { FILE_TRAVERSE = 0x20, FILE_LIST_DIRECTORY = 0x1, FILE_READ_DATA = 0x1, FILE_READ_ATTRIBUTES = 0x80, FILE_READ_EA = 0x8, FILE_ADD_FILE = 0x2, FILE_WRITE_DATA = 0x2, FILE_ADD_SUBDIRECTORY = 0x4, FILE_APPEND_DATA = 0x4, FILE_WRITE_ATTRIBUTES = 0x100, FILE_WRITE_EA = 0x10, FILE_DELETE_CHILD = 0x40, DELETE = 0x10000, READ_CONTROL = 0x20000, WRITE_DAC = 0x40000, WRITE_OWNER = 0x80000, } private enum ACCESS_MODE:uint { NOT_USED_ACCESS=0, GRANT_ACCESS=1, SET_ACCESS, DENY_ACCESS, REVOKE_ACCESS, SET_AUDIT_SUCCESS, SET_AUDIT_FAILURE } [Flags] enum SECURITY_INFORMATION : uint { OWNER_SECURITY_INFORMATION = 0x00000001, GROUP_SECURITY_INFORMATION = 0x00000002, DACL_SECURITY_INFORMATION = 0x00000004, SACL_SECURITY_INFORMATION = 0x00000008, UNPROTECTED_SACL_SECURITY_INFORMATION = 0x10000000, UNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000, PROTECTED_SACL_SECURITY_INFORMATION = 0x40000000, PROTECTED_DACL_SECURITY_INFORMATION = 0x80000000 } public enum SE_OBJECT_TYPE { SE_UNKNOWN_OBJECT_TYPE = 0, SE_FILE_OBJECT, SE_SERVICE, SE_PRINTER, SE_REGISTRY_KEY, SE_LMSHARE, SE_KERNEL_OBJECT, SE_WINDOW_OBJECT, SE_DS_OBJECT, SE_DS_OBJECT_ALL, SE_PROVIDER_DEFINED_OBJECT, SE_WMIGUID_OBJECT, SE_REGISTRY_WOW64_32KEY } enum Inheritance:uint { CONTAINER_INHERIT_ACE=0, INHERIT_ONLY_ACE, NO_PROPAGATE_INHERIT_ACE, OBJECT_INHERIT_ACE, SUB_CONTAINERS_AND_OBJECTS_INHERIT, SUB_CONTAINERS_ONLY_INHERIT, SUB_OBJECTS_ONLY_INHERIT } [DllImportAttribute("advapi32.dll", EntryPoint = "OpenProcessToken")] [return: MarshalAsAttribute(UnmanagedType.Bool)] private static extern bool OpenProcessToken( [InAttribute] IntPtr ProcessHandle, uint DesiredAccess, out IntPtr TokenHandle); [DllImportAttribute("kernel32.dll", EntryPoint = "GetCurrentProcess")] private static extern IntPtr GetCurrentProcess(); [DllImport("kernel32.dll")] static extern uint GetLastError(); [DllImport("advapi32.dll")] static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, ref LUID lpLuid); [DllImportAttribute("kernel32.dll", EntryPoint = "CloseHandle")] [return: MarshalAsAttribute(UnmanagedType.Bool)] private static extern bool CloseHandle([InAttribute] IntPtr hObject); [StructLayoutAttribute(LayoutKind.Sequential)] private struct TOKEN_PRIVILEGES { public uint PrivilegeCount; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 1, ArraySubType = UnmanagedType.Struct)] public LUID_AND_ATTRIBUTES[] Privileges; } [StructLayoutAttribute(LayoutKind.Sequential)] private struct LUID_AND_ATTRIBUTES { public LUID Luid; public uint Attributes; } [DllImportAttribute("advapi32.dll", EntryPoint = "AdjustTokenPrivileges")] [return: MarshalAsAttribute(UnmanagedType.Bool)] private static extern bool AdjustTokenPrivileges( [InAttribute()] IntPtr TokenHandle, [MarshalAsAttribute(UnmanagedType.Bool)] bool DisableAllPrivileges, [InAttribute()] ref TOKEN_PRIVILEGES NewState, uint BufferLength, IntPtr PreviousState, IntPtr ReturnLength); [DllImport("Advapi32.dll", CharSet = CharSet.Auto)] public static extern int LookupAccountName([In, MarshalAs(UnmanagedType.LPTStr)] string systemName,[In, MarshalAs(UnmanagedType.LPTStr)] string accountName,IntPtr Sid,ref int cbSid, StringBuilder domainName, ref int cbDomainName, ref int use); [DllImport("Advapi32.dll", EntryPoint = "GetUserName",ExactSpelling = false, SetLastError = true)] static extern bool GetUserName([MarshalAs(UnmanagedType.LPArray)] byte[] lpBuffer,[MarshalAs(UnmanagedType.LPArray)] Int32[] nSize); [DllImport("Advapi32.dll", EntryPoint = "SetEntriesInAclA", CallingConvention = CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Ansi)] private static extern int SetEntriesInAcl( int CountofExplicitEntries, ref EXPLICIT_ACCESS ea, IntPtr OldAcl, ref IntPtr NewAcl); [DllImport("advapi32.dll", CharSet = CharSet.Unicode)] private static extern uint SetNamedSecurityInfoW(String pObjectName, SE_OBJECT_TYPE ObjectType, SECURITY_INFORMATION SecurityInfo, IntPtr psidOwner, IntPtr psidGroup, IntPtr pDacl, IntPtr pSacl); [DllImport("kernel32.dll", EntryPoint = "LocalFree", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Unicode)] private static extern IntPtr LocalFree(IntPtr hMem); [StructLayoutAttribute(LayoutKind.Sequential)] private struct SID_IDENTIFIER_AUTHORITY { [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.I1)] public byte[] Value; } [DllImportAttribute("advapi32.dll", EntryPoint = "AllocateAndInitializeSid")] [return: MarshalAsAttribute(UnmanagedType.Bool)] 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); [DllImport("advapi32.dll", SetLastError = true)] static extern Boolean InitializeAcl( [In, Out] ref IntPtr pAcl, [In] UInt32 nAclLength, [In] UInt32 dwAclRevision ); [DllImport("advapi32.dll", SetLastError = true)] static extern bool AddAccessAllowedAce(IntPtr pAcl, uint dwAceRevision, ACCESS_MASK AccessMask, IntPtr pSid); #region BuildExplicitAccessWithName private enum MULTIPLE_TRUSTEE_OPERATION { NO_MULTIPLE_TRUSTEE, TRUSTEE_IS_IMPERSONATE } private enum TRUSTEE_FORM { TRUSTEE_IS_SID, TRUSTEE_IS_NAME, TRUSTEE_BAD_FORM, TRUSTEE_IS_OBJECTS_AND_SID, TRUSTEE_IS_OBJECTS_AND_NAME } private enum TRUSTEE_TYPE { TRUSTEE_IS_UNKNOWN, TRUSTEE_IS_USER, TRUSTEE_IS_GROUP, TRUSTEE_IS_DOMAIN, TRUSTEE_IS_ALIAS, TRUSTEE_IS_WELL_KNOWN_GROUP, TRUSTEE_IS_DELETED, TRUSTEE_IS_INVALID, TRUSTEE_IS_COMPUTER } //Platform independent (32 & 64 bit) - use Pack = 0 for both platforms. IntPtr works as well. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 0)] private struct TRUSTEE : IDisposable { public IntPtr pMultipleTrustee; public MULTIPLE_TRUSTEE_OPERATION MultipleTrusteeOperation; public TRUSTEE_FORM TrusteeForm; public TRUSTEE_TYPE TrusteeType; private IntPtr ptstrName; void IDisposable.Dispose() { if (ptstrName != IntPtr.Zero) Marshal.Release(ptstrName); } public string Name { get { return Marshal.PtrToStringAuto(ptstrName); } } } public struct EXPLICIT_ACCESS { uint grfAccessPermissions; uint grfAccessMode; uint grfInheritance; TRUSTEE Trustee; } [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] static extern void BuildExplicitAccessWithName(ref EXPLICIT_ACCESS pExplicitAccess,string pTrusteeName,uint AccessPermissions,uint AccessMode,uint Inheritance); #endregion const string SE_CREATE_TOKEN_NAME = "SeCreateTokenPrivilege"; const string SE_ASSIGNPRIMARYTOKEN_NAME = "SeAssignPrimaryTokenPrivilege"; const string SE_LOCK_MEMORY_NAME = "SeLockMemoryPrivilege"; const string SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege"; const string SE_UNSOLICITED_INPUT_NAME = "SeUnsolicitedInputPrivilege"; const string SE_MACHINE_ACCOUNT_NAME = "SeMachineAccountPrivilege"; const string SE_TCB_NAME = "SeTcbPrivilege"; const string SE_SECURITY_NAME = "SeSecurityPrivilege"; const string SE_TAKE_OWNERSHIP_NAME = "SeTakeOwnershipPrivilege"; const string SE_LOAD_DRIVER_NAME = "SeLoadDriverPrivilege"; const string SE_SYSTEM_PROFILE_NAME = "SeSystemProfilePrivilege"; const string SE_SYSTEMTIME_NAME = "SeSystemtimePrivilege"; const string SE_PROF_SINGLE_PROCESS_NAME = "SeProfileSingleProcessPrivilege"; const string SE_INC_BASE_PRIORITY_NAME = "SeIncreaseBasePriorityPrivilege"; const string SE_CREATE_PAGEFILE_NAME = "SeCreatePagefilePrivilege"; const string SE_CREATE_PERMANENT_NAME = "SeCreatePermanentPrivilege"; const string SE_BACKUP_NAME = "SeBackupPrivilege"; const string SE_RESTORE_NAME = "SeRestorePrivilege"; const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege"; const string SE_DEBUG_NAME = "SeDebugPrivilege"; const string SE_AUDIT_NAME = "SeAuditPrivilege"; const string SE_SYSTEM_ENVIRONMENT_NAME = "SeSystemEnvironmentPrivilege"; const string SE_CHANGE_NOTIFY_NAME = "SeChangeNotifyPrivilege"; const string SE_REMOTE_SHUTDOWN_NAME = "SeRemoteShutdownPrivilege"; const uint GENERIC_ALL = 0x10000000; private const UInt32 TOKEN_ADJUST_PRIVILEGES = 0x0020; private const int TOKEN_QUERY = 8; private const int SE_PRIVILEGE_ENABLED = 2; public static bool AdjustPrivileges(string lpName) { IntPtr token = IntPtr.Zero; Log.Write("AdjustPrivileges-> OpenProcessToken Result "); if (!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out token)) { if (GetLastError() == 120) return true; else return false; } LUID luid = new LUID(); Log.Write("AdjustPrivileges-> LookupPrivilegeValue Result "); if (!LookupPrivilegeValue(null, lpName, ref luid)) { CloseHandle(token); return false; } TOKEN_PRIVILEGES tokenPrivileges = new TOKEN_PRIVILEGES(); tokenPrivileges.PrivilegeCount = 1; tokenPrivileges.Privileges = new LUID_AND_ATTRIBUTES[1]; tokenPrivileges.Privileges[0].Luid = luid; tokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; Log.Write("AdjustPrivileges-> AdjustTokenPrivileges Result "); if (!AdjustTokenPrivileges(token, false, ref tokenPrivileges, 0,IntPtr.Zero, IntPtr.Zero)) { CloseHandle(token); return false; } CloseHandle(token); return true; //IntPtr pSidOwner, pSidGroup, pDacl, pSacl, pSecurityDescriptor; //ACCESS_MASK mask = new ACCESS_MASK(); //uint ret = GetNamedSecurityInfo(objName, // seObjType, // SECURITY_INFORMATION.DACL_SECURITY_INFORMATION | SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION | SECURITY_INFORMATION.GROUP_SECURITY_INFORMATION, // out pSidOwner, // out pSidGroup, // out pDacl, // out pSacl, // out pSecurityDescriptor); //return false; } public static void Changeee(string pObjName,SE_OBJECT_TYPE ObjType) { Log.Write("Changeee-> AdjustPrivileges Result "); if (AdjustPrivileges(SE_TAKE_OWNERSHIP_NAME)) { byte[] str = new byte[256]; Int32[] len = new Int32[1]; len[0] = 256; GetUserName(str, len); string UserName = System.Text.Encoding.ASCII.GetString(str); UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString(); IntPtr Sid = IntPtr.Zero; int cbSid = 0; StringBuilder domainName = null; int cbDomainName = 0; int use = 0; IntPtr oldDacl,psd,psacl,sidOwn,sidGroup; IntPtr newDacl=IntPtr.Zero; EXPLICIT_ACCESS ea = new EXPLICIT_ACCESS(); IntPtr sidAdmin = IntPtr.Zero; Log.Write("Changeee-> LookupAccountName Result "); if (LookupAccountName(null, UserName,Sid,ref cbSid,domainName,ref cbDomainName,ref use)==0) { var gnsiResult = GetNamedSecurityInfo(pObjName, ObjType, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, out sidOwn, out sidGroup, out oldDacl,out psacl, out psd); Log.Write("Changeee-> GetNamedSecurityInfo Result :: " + gnsiResult); Log.Write("Changeee-> BuildExplicitAccessWithName "); BuildExplicitAccessWithName(ref ea, "Administrators", GENERIC_ALL, (uint)ACCESS_MODE.GRANT_ACCESS, (uint)Inheritance.SUB_CONTAINERS_AND_OBJECTS_INHERIT); var seia = SetEntriesInAcl(1, ref ea, oldDacl, ref newDacl); Log.Write("Changeee-> SetEntriesInAcl :"+seia); if (seia == 0) { var snsi = SetNamedSecurityInfoW(pObjName, ObjType, SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION, Sid, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); Log.Write("Changeee-> SetNamedSecurityInfoW Result :: " + snsi); snsi = SetNamedSecurityInfoW(pObjName, ObjType, SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION | SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, Sid, IntPtr.Zero, newDacl, IntPtr.Zero); Log.Write("Changeee-> SetNamedSecurityInfoW Result :: " + snsi); if (snsi == 0) { } } } } } public static bool SetRegPrivilege(string pObjName,SE_OBJECT_TYPE objType) { IntPtr sidOwn,sidGroup,pDacl,pSacl,pSD; IntPtr newDacl=IntPtr.Zero; var ret = GetNamedSecurityInfo(pObjName, objType, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, out sidOwn, out sidGroup, out pDacl, out pSacl, out pSD); Log.Write("SetRegPrivilege-> GetNamedSecurityInfo Result :: " + ret); if (ret != 0) { return false; } EXPLICIT_ACCESS ea = new EXPLICIT_ACCESS(); BuildExplicitAccessWithName(ref ea, "Administrators", GENERIC_ALL, (uint)ACCESS_MODE.GRANT_ACCESS, (uint)Inheritance.SUB_CONTAINERS_AND_OBJECTS_INHERIT); var dwRet = SetEntriesInAcl(1, ref ea, pDacl, ref newDacl); Log.Write("SetRegPrivilege-> SetEntriesInAcl Result :: " + dwRet); if (dwRet != 0) return false; var uRet = SetNamedSecurityInfoW(pObjName, objType, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, IntPtr.Zero, IntPtr.Zero, newDacl, IntPtr.Zero); Log.Write("SetRegPrivilege-> SetNamedSecurityInfoW Result :: " + uRet); if (uRet != 0) { return false; } LocalFree(newDacl); LocalFree(pDacl); LocalFree(pSD); return true; } struct _ACL { byte AclRevision; byte Sbz1; UInt16 AclSize; UInt16 AceCount; UInt16 Sbz2; } private const int SECURITY_BUILTIN_DOMAIN_RID = 0x00000020; private const int DOMAIN_ALIAS_RID_ADMINS = 0x00000220; private static SID_IDENTIFIER_AUTHORITY SECURITY_NT_AUTHORITY = new SID_IDENTIFIER_AUTHORITY() { Value = new byte[] { 0, 0, 0, 0, 0, 5 } }; const UInt32 ACL_REVISION_DS = 4; public static void SetRegSecurity() { SID_IDENTIFIER_AUTHORITY sidNTAuthority = SECURITY_NT_AUTHORITY; // Create a SID for the BUILTIN\Administrators group. IntPtr sidAdmin = IntPtr.Zero; if (!AllocateAndInitializeSid(ref sidNTAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, ref sidAdmin)) return; IntPtr acl = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(_ACL))); InitializeAcl(ref acl, 0, ACL_REVISION_DS); //AddAccessAllowedAce(acl,) } }