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);
public static extern bool AuthzAccessCheck( AuthzACFlags flags, SafeAuthzContextHandle hAuthzClientContext, ref AUTHZ_ACCESS_REQUEST pRequest, AUTHZ_AUDIT_EVENT_HANDLE AuditEvent, byte[] rawSecurityDescriptor, PSECURITY_DESCRIPTOR[] OptionalSecurityDescriptorArray, DWORD OptionalSecurityDescriptorCount, ref AUTHZ_ACCESS_REPLY pReply, AUTHZ_ACCESS_CHECK_RESULTS_HANDLE cachedResults);
internal static extern bool AuthzAccessCheck( AuthzACFlags flags, AUTHZ_CLIENT_CONTEXT_HANDLE hAuthzClientContext, ref AUTHZ_ACCESS_REQUEST pRequest, AUTHZ_AUDIT_EVENT_HANDLE AuditEvent, byte[] rawSecurityDescriptor, PSECURITY_DESCRIPTOR[] OptionalSecurityDescriptorArray, DWORD OptionalSecurityDescriptorCount, ref AUTHZ_ACCESS_REPLY pReply, AUTHZ_ACCESS_CHECK_RESULTS_HANDLE cachedResults);
public static extern bool AuthzAccessCheck( AuthzACFlags flags, IntPtr hAuthzClientContext, ref AUTHZ_ACCESS_REQUEST pRequest, IntPtr AuditEvent, byte[] rawSecurityDescriptor, IntPtr[] OptionalSecurityDescriptorArray, UInt32 OptionalSecurityDescriptorCount, ref AUTHZ_ACCESS_REPLY pReply, IntPtr cachedResults);
/// <summary> /// Perform an Access Check. /// </summary> /// <param name="sd">The security descriptor for the check.</param> /// <param name="optional_sd">Optional list of security descriptors to merge.</param> /// <param name="desired_access">The desired access.</param> /// <param name="principal">Optional Principal SID.</param> /// <param name="object_types">Optional list of object types.</param> /// <param name="type">NT Type for access checking.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The list of access check results.</returns> /// <remarks>The list of object types is restricted to 256 entries for remote access checks.</remarks> public NtResult <AuthZAccessCheckResult[]> AccessCheck(SecurityDescriptor sd, IEnumerable <SecurityDescriptor> optional_sd, AccessMask desired_access, Sid principal, IEnumerable <ObjectTypeEntry> object_types, NtType type, bool throw_on_error) { if (sd is null) { throw new ArgumentNullException(nameof(sd)); } if (type is null) { throw new ArgumentNullException(nameof(type)); } using (var list = new DisposableList()) { AUTHZ_ACCESS_REQUEST request = new AUTHZ_ACCESS_REQUEST(); request.DesiredAccess = desired_access; if (principal != null) { request.PrincipalSelfSid = list.AddResource(principal.ToSafeBuffer()).DangerousGetHandle(); } int result_count = 1; var object_list = NtSecurity.ConvertObjectTypes(object_types, list); if (object_list?.Length > 0) { result_count = object_list.Length; request.ObjectTypeList = list.AddResource(object_list.ToBuffer()).DangerousGetHandle(); request.ObjectTypeListLength = object_list.Length; } var sd_buffer = list.AddResource(sd.ToSafeBuffer()); int optional_sd_count = optional_sd?.Count() ?? 0; IntPtr[] optional_sd_buffers = null; if (optional_sd_count > 0) { optional_sd_buffers = optional_sd.Select(s => list.AddResource(s.ToSafeBuffer()).DangerousGetHandle()).ToArray(); } AUTHZ_ACCESS_REPLY reply = new AUTHZ_ACCESS_REPLY(); reply.ResultListLength = result_count; var error_buffer = list.AddResource(new int[result_count].ToBuffer()); reply.Error = error_buffer.DangerousGetHandle(); var access_buffer = list.AddResource(new AccessMask[result_count].ToBuffer()); reply.GrantedAccessMask = access_buffer.DangerousGetHandle(); var audit_buffer = list.AddResource(new int[result_count].ToBuffer()); reply.SaclEvaluationResults = audit_buffer.DangerousGetHandle(); return(SecurityNativeMethods.AuthzAccessCheck(AuthZAccessCheckFlags.None, _handle, ref request, IntPtr.Zero, sd_buffer, optional_sd_buffers, optional_sd_count, ref reply, IntPtr.Zero).CreateWin32Result(throw_on_error, () => CreateResult(result_count, error_buffer, access_buffer, object_types?.ToArray(), type))); } }
public void AuthzAccessCheckAndCachedTest() { using (var hRM = GetAuthzInitializeResourceManager()) using (var hCtx = GetCurrentUserAuthContext(hRM)) using (var hEvt = GetAuthzInitializeObjectAccessAuditEvent()) using (var psd = AdvApi32Tests.GetSD(@"C:\Temp\help.ico")) using (var reply = new AUTHZ_ACCESS_REPLY(1)) { var req = new AUTHZ_ACCESS_REQUEST((uint)ACCESS_MASK.MAXIMUM_ALLOWED); var b = AuthzAccessCheck(AuthzAccessCheckFlags.NONE, hCtx, req, hEvt, psd, null, 0, reply, out var hRes); if (!b) { TestContext.WriteLine($"AuthzAccessCheck:{Win32Error.GetLastError()}"); } Assert.That(b); Assert.That(reply.GrantedAccessMask, Is.Not.EqualTo(IntPtr.Zero)); TestContext.WriteLine($"Access:{string.Join(",", reply.GrantedAccessMaskValues.Select(u => ((FileAccess)u).ToString()))}"); Assert.That(AuthzCachedAccessCheck(0, hRes, req, default, reply), Is.True);
private int GetEffectivePermissions_AuthzAccessCheck(ObjectSecurity sd) { var request = new AUTHZ_ACCESS_REQUEST(); request.DesiredAccess = StdAccess.MAXIMUM_ALLOWED; request.PrincipalSelfSid = null; request.ObjectTypeList = IntPtr.Zero; request.ObjectTypeListLength = 0; request.OptionalArguments = IntPtr.Zero; var reply = new AUTHZ_ACCESS_REPLY(); reply.ResultListLength = 1; reply.SaclEvaluationResults = IntPtr.Zero; reply.GrantedAccessMask = pGrantedAccess = Marshal.AllocHGlobal(sizeof(uint)); reply.Error = pErrorSecObj = Marshal.AllocHGlobal(sizeof(uint)); byte[] rawSD = sd.GetSecurityDescriptorBinaryForm(); if (!AuthzAccessCheck( AuthzACFlags.None, userClientCtxt, ref request, IntPtr.Zero, rawSD, null, 0, ref reply, IntPtr.Zero)) { var error = Marshal.GetLastWin32Error(); if (error != 0) { throw new Win32Exception(); } } var grantedAccess = Marshal.ReadInt32(pGrantedAccess); return(grantedAccess); }
public ACLTestResult(String InputPath, String InputIdentity) { Path = InputPath; Identity = InputIdentity; IntPtr pSidOwner, pSidGroup, pDacl, pSacl, pSecurityDescriptor; ACCESS_MASK mask = new ACCESS_MASK(); uint ret = GetNamedSecurityInfo(InputPath, SE_OBJECT_TYPE.SE_FILE_OBJECT, 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); IntPtr hManager = IntPtr.Zero; bool f = AuthzInitializeResourceManager(1, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, null, out hManager); NTAccount ac = new NTAccount(InputIdentity); SecurityIdentifier sid = (SecurityIdentifier)ac.Translate(typeof(SecurityIdentifier)); byte[] bytes = new byte[sid.BinaryLength]; sid.GetBinaryForm(bytes, 0); String _psUserSid = ""; foreach (byte si in bytes) { _psUserSid += si; } LUID unusedSid = new LUID(); IntPtr UserSid = Marshal.AllocHGlobal(bytes.Length); Marshal.Copy(bytes, 0, UserSid, bytes.Length); IntPtr pClientContext = IntPtr.Zero; if (f) { f = AuthzInitializeContextFromSid(0, UserSid, hManager, IntPtr.Zero, unusedSid, IntPtr.Zero, out pClientContext); AUTHZ_ACCESS_REQUEST request = new AUTHZ_ACCESS_REQUEST(); request.DesiredAccess = 0x02000000; request.PrincipalSelfSid = null; request.ObjectTypeList = null; request.ObjectTypeListLength = 0; request.OptionalArguments = IntPtr.Zero; AUTHZ_ACCESS_REPLY reply = new AUTHZ_ACCESS_REPLY(); reply.GrantedAccessMask = IntPtr.Zero; reply.ResultListLength = 0; reply.SaclEvaluationResults = IntPtr.Zero; IntPtr AccessReply = IntPtr.Zero; reply.Error = Marshal.AllocHGlobal(1020); reply.GrantedAccessMask = Marshal.AllocHGlobal(sizeof(uint)); reply.ResultListLength = 1; int i = 0; f = AuthzAccessCheck(0, pClientContext, ref request, IntPtr.Zero, pSecurityDescriptor, null, 0, ref reply, out AccessReply); if (f) { int granted_access = Marshal.ReadInt32(reply.GrantedAccessMask); mask = (ACCESS_MASK)granted_access; foreach (ACCESS_MASK item in Enum.GetValues(typeof(ACCESS_MASK))) { if ((mask & item) == item) { switch (item) { case ACCESS_MASK.FILE_TRAVERSE: TraverseFolderAndExecuteFile = true; break; case ACCESS_MASK.FILE_LIST_DIRECTORY: ListFolderAndReadData = true; break; case ACCESS_MASK.FILE_READ_ATTRIBUTES: ReadAttributes = true; break; case ACCESS_MASK.FILE_READ_EA: ReadExtendedAttributes = true; break; case ACCESS_MASK.FILE_ADD_FILE: CreateFilesAndWriteData = true; break; case ACCESS_MASK.FILE_ADD_SUBDIRECTORY: CreateFoldersAndAppendData = true; break; case ACCESS_MASK.FILE_WRITE_ATTRIBUTES: WriteAttributes = true; break; case ACCESS_MASK.FILE_WRITE_EA: WriteExtendedAttributes = true; break; case ACCESS_MASK.FILE_DELETE_CHILD: DeleteSubfoldersAndFiles = true; break; case ACCESS_MASK.DELETE: Delete = true; break; case ACCESS_MASK.READ_CONTROL: ReadPermissions = true; break; case ACCESS_MASK.WRITE_DAC: ChangePermissions = true; break; case ACCESS_MASK.WRITE_OWNER: TakeOwnership = true; break; default: break; } i++; } } } else { Marshal.FreeHGlobal(reply.GrantedAccessMask); throw new UnauthorizedAccessException(); } Marshal.FreeHGlobal(reply.GrantedAccessMask); if (i == 16) { FullControl = true; } } }
public void ComputeEffectivePermissionWithSecondarySecurity(PSID pSid, PSID pDeviceSid, string pszServerName, SECURITY_OBJECT[] pSecurityObjects, uint dwSecurityObjectCount, ref TOKEN_GROUPS pUserGroups, AUTHZ_SID_OPERATION[] pAuthzUserGroupsOperations, ref TOKEN_GROUPS pDeviceGroups, AUTHZ_SID_OPERATION[] pAuthzDeviceGroupsOperations, ref AUTHZ_SECURITY_ATTRIBUTES_INFORMATION pAuthzUserClaims, AUTHZ_SECURITY_ATTRIBUTE_OPERATION[] pAuthzUserClaimsOperations, ref AUTHZ_SECURITY_ATTRIBUTES_INFORMATION pAuthzDeviceClaims, AUTHZ_SECURITY_ATTRIBUTE_OPERATION[] pAuthzDeviceClaimsOperations, EFFPERM_RESULT_LIST[] pEffpermResultLists) { System.Diagnostics.Debug.WriteLine($"ComputeEffectivePermissionWithSecondarySecurity({dwSecurityObjectCount}):{new SecurityIdentifier((IntPtr)pSid).Value};{new SecurityIdentifier((IntPtr)pDeviceSid).Value}"); if (dwSecurityObjectCount != 1) { ThrowException(HRESULT.E_FAIL, new ArgumentOutOfRangeException(nameof(dwSecurityObjectCount), @"Only a single object can be computed.")); } if (pSecurityObjects[0].Id != (uint)SECURITY_OBJECT_ID.SECURITY_OBJECT_ID_OBJECT_SD) { ThrowException(HRESULT.E_FAIL, new ArgumentException(@"Unexpected value.", nameof(pSecurityObjects))); } if (pSid == null || pSid.IsInvalid) { ThrowException(HRESULT.E_INVALIDARG, new ArgumentNullException(nameof(pSid))); } SafeAUTHZ_RESOURCE_MANAGER_HANDLE hAuthzResourceManager; if (!AuthzInitializeResourceManager(AuthzResourceManagerFlags.AUTHZ_RM_FLAG_NO_AUDIT, null, null, null, prov.ToString(), out hAuthzResourceManager)) { return; } var identifier = new LUID(); SafeAUTHZ_CLIENT_CONTEXT_HANDLE hAuthzUserContext; SafeAUTHZ_CLIENT_CONTEXT_HANDLE hAuthzCompoundContext = null; if (!AuthzInitializeContextFromSid(AuthzContextFlags.NONE, pSid, hAuthzResourceManager, IntPtr.Zero, identifier, IntPtr.Zero, out hAuthzUserContext)) { return; } if (pDeviceSid != null && !pDeviceSid.IsInvalid) { SafeAUTHZ_CLIENT_CONTEXT_HANDLE hAuthzDeviceContext; if (AuthzInitializeContextFromSid(AuthzContextFlags.NONE, pDeviceSid, hAuthzResourceManager, IntPtr.Zero, identifier, IntPtr.Zero, out hAuthzDeviceContext)) { if (AuthzInitializeCompoundContext(hAuthzUserContext, hAuthzDeviceContext, out hAuthzCompoundContext)) { if (pAuthzDeviceClaims.Version != 0) { AuthzModifyClaims(hAuthzCompoundContext, AUTHZ_CONTEXT_INFORMATION_CLASS.AuthzContextInfoDeviceClaims, pAuthzDeviceClaimsOperations, ref pAuthzDeviceClaims); } } } } else { hAuthzCompoundContext = hAuthzUserContext; } if (hAuthzCompoundContext == null) { return; } if (pAuthzUserClaims.Version != 0) { if (!AuthzModifyClaims(hAuthzCompoundContext, AUTHZ_CONTEXT_INFORMATION_CLASS.AuthzContextInfoUserClaims, pAuthzUserClaimsOperations, ref pAuthzUserClaims)) { return; } } if (pDeviceGroups.GroupCount != 0) { if (!AuthzModifySids(hAuthzCompoundContext, AUTHZ_CONTEXT_INFORMATION_CLASS.AuthzContextInfoDeviceSids, pAuthzDeviceGroupsOperations, ref pDeviceGroups)) { return; } } if (pUserGroups.GroupCount != 0 && pAuthzUserGroupsOperations != null) { if (!AuthzModifySids(hAuthzCompoundContext, AUTHZ_CONTEXT_INFORMATION_CLASS.AuthzContextInfoGroupsSids, pAuthzUserGroupsOperations, ref pUserGroups)) { return; } } var request = new AUTHZ_ACCESS_REQUEST(AccessTypes.MAXIMUM_ALLOWED); var sd = pSecurityObjects[0].pData.ToStructure <SECURITY_DESCRIPTOR>(); var reply = new AUTHZ_ACCESS_REPLY(1); SafeAUTHZ_ACCESS_CHECK_RESULTS_HANDLE phAccessCheckResults; if (!AuthzAccessCheck(AuthzAccessCheckFlags.NONE, hAuthzCompoundContext, ref request, null, ref sd, null, 0, reply, out phAccessCheckResults)) { return; } pEffpermResultLists[0].fEvaluated = true; pEffpermResultLists[0].pGrantedAccessList = reply.GrantedAccessMaskValues; pEffpermResultLists[0].pObjectTypeList = new[] { OBJECT_TYPE_LIST.Self }; pEffpermResultLists[0].cObjectTypeListLength = 1; }
public void ReadEffectivePermissions(string folder, string username, ref AppsClient.AppsResult result) { ////String UserName = "******"; //do //{ // Console.WriteLine("UserName:"******"rbrooks"; // Console.ReadLine(); // Console.WriteLine("Path:"); String Path = folder; // @"D:\Work\Brooksoft\AppsJS\AppsJSCLI2\AppsDesktop\AppFolders\App49\Software\Software19"; // Console.ReadLine(); if (System.IO.Directory.Exists(folder)) { IntPtr pSidOwner, pSidGroup, pDacl, pSacl, pSecurityDescriptor; ACCESS_MASK mask = new ACCESS_MASK(); uint ret = GetNamedSecurityInfo(Path, SE_OBJECT_TYPE.SE_FILE_OBJECT, 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); IntPtr hManager = IntPtr.Zero; bool f = AuthzInitializeResourceManager(1, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, null, out hManager); NTAccount ac = new NTAccount(UserName); SecurityIdentifier sid = (SecurityIdentifier)ac.Translate(typeof(SecurityIdentifier)); byte[] bytes = new byte[sid.BinaryLength]; sid.GetBinaryForm(bytes, 0); String _psUserSid = ""; foreach (byte si in bytes) { _psUserSid += si; } LUID unusedSid = new LUID(); IntPtr UserSid = Marshal.AllocHGlobal(bytes.Length); Marshal.Copy(bytes, 0, UserSid, bytes.Length); IntPtr pClientContext = IntPtr.Zero; if (f) { f = AuthzInitializeContextFromSid(0, UserSid, hManager, IntPtr.Zero, unusedSid, IntPtr.Zero, out pClientContext); AUTHZ_ACCESS_REQUEST request = new AUTHZ_ACCESS_REQUEST(); request.DesiredAccess = 0x02000000; request.PrincipalSelfSid = null; request.ObjectTypeList = null; request.ObjectTypeListLength = 0; request.OptionalArguments = IntPtr.Zero; AUTHZ_ACCESS_REPLY reply = new AUTHZ_ACCESS_REPLY(); reply.GrantedAccessMask = IntPtr.Zero; reply.ResultListLength = 0; reply.SaclEvaluationResults = IntPtr.Zero; IntPtr AccessReply = IntPtr.Zero; reply.Error = Marshal.AllocHGlobal(1020); reply.GrantedAccessMask = Marshal.AllocHGlobal(sizeof(uint)); reply.ResultListLength = 1; int i = 0; Dictionary <String, String> rightsmap = new Dictionary <String, String>(); List <string> effectivePermissionList = new List <string>(); string[] rights = new string[14] { "Full Control", "Traverse Folder / execute file", "List folder / read data", "Read attributes", "Read extended attributes", "Create files / write files", "Create folders / append data", "Write attributes", "Write extended attributes", "Delete subfolders and files", "Delete", "Read permission", "Change permission", "Take ownership" }; rightsmap.Add("FILE_TRAVERSE", "Traverse Folder / execute file"); rightsmap.Add("FILE_LIST_DIRECTORY", "List folder / read data"); rightsmap.Add("FILE_READ_DATA", "List folder / read data"); rightsmap.Add("FILE_READ_ATTRIBUTES", "Read attributes"); rightsmap.Add("FILE_READ_EA", "Read extended attributes"); rightsmap.Add("FILE_ADD_FILE", "Create files / write files"); rightsmap.Add("FILE_WRITE_DATA", "Create files / write files"); rightsmap.Add("FILE_ADD_SUBDIRECTORY", "Create folders / append data"); rightsmap.Add("FILE_APPEND_DATA", "Create folders / append data"); rightsmap.Add("FILE_WRITE_ATTRIBUTES", "Write attributes"); rightsmap.Add("FILE_WRITE_EA", "Write extended attributes"); rightsmap.Add("FILE_DELETE_CHILD", "Delete subfolders and files"); rightsmap.Add("DELETE", "Delete"); rightsmap.Add("READ_CONTROL", "Read permission"); rightsmap.Add("WRITE_DAC", "Change permission"); rightsmap.Add("WRITE_OWNER", "Take ownership"); f = AuthzAccessCheck(0, pClientContext, ref request, IntPtr.Zero, pSecurityDescriptor, null, 0, ref reply, out AccessReply); if (f) { int granted_access = Marshal.ReadInt32(reply.GrantedAccessMask); mask = (ACCESS_MASK)granted_access; foreach (ACCESS_MASK item in Enum.GetValues(typeof(ACCESS_MASK))) { if ((mask & item) == item) { effectivePermissionList.Add(rightsmap[item.ToString()]); i++; } } } Marshal.FreeHGlobal(reply.GrantedAccessMask); if (i == 16) { new AppFlows.Publish.Success("All perms satisfied so adding also full control."); effectivePermissionList.Insert(0, "Full Control"); } // Console.WriteLine("......................."); // foreach (string r in rights) // { // if (effectivePermissionList.Contains(r)) // { // Console.WriteLine(r); // } // } // } // Console.WriteLine("_________________________________________________\n"); //} while (true); //Console.ReadLine(); result.Data = effectivePermissionList; result.Success = true; } } else { new AppFlows.Publish.Fail("Folder provided was not found.", ref result); } }