public NativeService(NativeSCManager scm, string ServiceName, ACCESS_MASK am) { Handle = NativeServiceFunctions.OpenService( scm.Handle, ServiceName, (uint)am); }
public extern static bool DuplicateTokenEx( IntPtr hExistingToken, ACCESS_MASK dwDesiredAccess, ref SECURITY_ATTRIBUTES lpTokenAttributes, SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, TOKEN_TYPE TokenType, out IntPtr phNewToken);
public void AccessCheckAndAuditAlarmTest() { using (var pSD = AdvApi32Tests.GetSD(AdvApi32Tests.fn, AdvApi32Tests.AllSI)) { var gm = GENERIC_MAPPING.GenericFileMapping; ACCESS_MASK accessMask = ACCESS_MASK.GENERIC_READ; MapGenericMask(ref accessMask, gm); Assert.That(AccessCheckAndAuditAlarm(subSys, IntPtr.Zero, objType, null, pSD, accessMask, gm, false, out var access, out var status, out var gen), ResultIs.FailureCode(Win32Error.ERROR_NO_IMPERSONATION_TOKEN)); //Assert.That(access, Is.EqualTo((uint)FileAccess.FILE_GENERIC_READ)); //Assert.That(status, Is.True); } }
public static NTSTATUS NtCreateThreadEx( out IntPtr hThread, ACCESS_MASK DesiredAccess, IntPtr ObjectAttributes, IntPtr ProcessHandle, IntPtr lpStartAddress, IntPtr lpParameter, bool CreateSuspended, uint StackZeroBits, uint SizeOfStackCommit, uint SizeOfStackReserve, IntPtr lpBytesBuffer ) { // set byte array of bNtCreateThread to new byte array called syscall byte[] syscall = bNtCreateThreadEx; // specify unsafe context unsafe { // create new byte pointer and set value to our syscall byte array fixed(byte *ptr = syscall) { // cast the byte array pointer into a C# IntPtr called memoryAddress IntPtr memoryAddress = (IntPtr)ptr; // Change memory access to RX for our assembly code if (!VirtualProtectEx(Process.GetCurrentProcess().Handle, memoryAddress, (UIntPtr)syscall.Length, (uint)AllocationProtect.PAGE_EXECUTE_READWRITE, out uint oldprotect)) { throw new Win32Exception(); } // Get delegate for NtCreateThread Delegates.NtCreateThreadEx assembledFunction = (Delegates.NtCreateThreadEx)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.NtCreateThreadEx)); return((NTSTATUS)assembledFunction( out hThread, DesiredAccess, ObjectAttributes, ProcessHandle, lpStartAddress, lpParameter, CreateSuspended, StackZeroBits, SizeOfStackCommit, SizeOfStackReserve, lpBytesBuffer )); } } }
/// <inheritdoc cref="CreateFile(char*, ACCESS_MASK, FileShare, SECURITY_ATTRIBUTES*, CreationDisposition, CreateFileFlags, SafeObjectHandle)"/> /// <devremarks> /// This should be removed as part of delivering <see href="https://github.com/dotnet/pinvoke/issues/286">the string-overload codegen feature</see>. /// </devremarks> public static unsafe SafeObjectHandle CreateFile( string filename, ACCESS_MASK access, FileShare share, [Friendly(FriendlyFlags.In | FriendlyFlags.Optional)] SECURITY_ATTRIBUTES *securityAttributes, CreationDisposition creationDisposition, CreateFileFlags flagsAndAttributes, SafeObjectHandle templateFile) { fixed(char *pFileName = filename) { return(CreateFile(pFileName, access, share, securityAttributes, creationDisposition, flagsAndAttributes, templateFile)); } }
public void AccessCheckByTypeResultListTest() { using (var pSD = AdvApi32Tests.GetSD(AdvApi32Tests.fn, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION | SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION | SECURITY_INFORMATION.GROUP_SECURITY_INFORMATION)) using (var hTok = SafeHTOKEN.FromProcess(GetCurrentProcess(), TokenAccess.TOKEN_IMPERSONATE | TokenAccess.TOKEN_DUPLICATE | TokenAccess.TOKEN_READ).Duplicate(SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation)) { var ps = PRIVILEGE_SET.InitializeWithCapacity(100); var psSz = ps.SizeInBytes; var gm = GENERIC_MAPPING.GenericFileMapping; ACCESS_MASK accessMask = ACCESS_MASK.GENERIC_READ; MapGenericMask(ref accessMask, gm); var otl = new[] { new OBJECT_TYPE_LIST(ObjectTypeListLevel.ACCESS_OBJECT_GUID) }; var access = new uint[otl.Length]; var status = new uint[otl.Length]; Assert.That(AccessCheckByTypeResultList(pSD, default, hTok, accessMask, otl, (uint)otl.Length, gm, ps, ref psSz, access, status), ResultIs.Successful);
/// <summary> /// Translate access mask for policy object. /// </summary> /// <param name="accessMask">ACCESS_MASK value to be translated</param> /// <returns>The result of translation to accessMask</returns> private static ACCESS_MASK TranslateAccessMaskForPolicy(ACCESS_MASK accessMask) { switch (accessMask) { case ACCESS_MASK.ValueToBeTranslated0x80000000: accessMask = ACCESS_MASK.POLICY_VIEW_AUDIT_INFORMATION | ACCESS_MASK.POLICY_GET_PRIVATE_INFORMATION | ACCESS_MASK.READ_CONTROL; break; case ACCESS_MASK.ValueToBeTranslated0x40000000: accessMask = ACCESS_MASK.POLICY_TRUST_ADMIN | ACCESS_MASK.POLICY_CREATE_ACCOUNT | ACCESS_MASK.POLICY_CREATE_SECRET | ACCESS_MASK.POLICY_CREATE_PRIVILEGE | ACCESS_MASK.POLICY_SET_DEFAULT_QUOTA_LIMITS | ACCESS_MASK.POLICY_SET_AUDIT_REQUIREMENTS | ACCESS_MASK.POLICY_AUDIT_LOG_ADMIN | ACCESS_MASK.POLICY_SERVER_ADMIN | ACCESS_MASK.READ_CONTROL; break; case ACCESS_MASK.ValueToBeTranslated0x20000000: accessMask = ACCESS_MASK.POLICY_VIEW_LOCAL_INFORMATION | ACCESS_MASK.POLICY_LOOKUP_NAMES | ACCESS_MASK.READ_CONTROL; break; case ACCESS_MASK.ValueToBeTranslated0x10000000: accessMask = ACCESS_MASK.POLICY_VIEW_LOCAL_INFORMATION | ACCESS_MASK.POLICY_VIEW_AUDIT_INFORMATION | ACCESS_MASK.POLICY_GET_PRIVATE_INFORMATION | ACCESS_MASK.POLICY_TRUST_ADMIN | ACCESS_MASK.POLICY_CREATE_ACCOUNT | ACCESS_MASK.POLICY_CREATE_SECRET | ACCESS_MASK.POLICY_CREATE_PRIVILEGE | ACCESS_MASK.POLICY_SET_DEFAULT_QUOTA_LIMITS | ACCESS_MASK.POLICY_SET_AUDIT_REQUIREMENTS | ACCESS_MASK.POLICY_AUDIT_LOG_ADMIN | ACCESS_MASK.POLICY_SERVER_ADMIN | ACCESS_MASK.POLICY_LOOKUP_NAMES | ACCESS_MASK.DELETE | ACCESS_MASK.READ_CONTROL | ACCESS_MASK.WRITE_DAC | ACCESS_MASK.WRITE_OWNER; break; } return(accessMask); }
/// <summary> /// The constructor opens access to the service /// </summary> /// <param name="scm">The SCM instance that contains the service</param> /// <param name="ServiceName">Name of the service</param> /// <param name="am">Access rights required.</param> public NativeService(NativeSCManager scm, string serviceName, ACCESS_MASK am = ACCESS_MASK.STANDARD_RIGHTS_READ | ACCESS_MASK.GENERIC_READ) { ServiceName = serviceName; Handle = NativeServiceFunctions.OpenService( scm.Handle, serviceName, (uint)am); IsValid = (Handle.ToInt32() != 0); if (!IsValid) { NativeHelpers.ReportFailure("OpenService({0}, {1})", serviceName, am); } }
public static IntPtr LsarOpenPolicy2(LsaClient lsadAdapterObj, string strServerName, ACCESS_MASK MAXIMUM_ALLOWED) { _LSAPR_OBJECT_ATTRIBUTES objectAttributes = new _LSAPR_OBJECT_ATTRIBUTES(); objectAttributes.RootDirectory = null; ACCESS_MASK uintAccessMask = (ACCESS_MASK)MAXIMUM_ALLOWED; NtStatus uintMethodStatus = lsadAdapterObj.LsarOpenPolicy2( strServerName, objectAttributes, uintAccessMask, out PolicyHandle); return(PolicyHandle.Value); }
/// <summary> /// Returns the user permissions on a share /// </summary> /// <param name="shareName">the full path to the shaer</param> /// <param name="userName">the user to check for</param> /// <returns>the user rights</returns> public static ACCESS_MASK GetSharePermissions(string shareName, string userName) { IntPtr ownerSid = IntPtr.Zero; IntPtr groupSid = IntPtr.Zero; IntPtr dacl = IntPtr.Zero; IntPtr sacl = IntPtr.Zero; IntPtr securityDescriptor = IntPtr.Zero; try { // get the security informaton of the object int returnValue; SECURITY_INFORMATION flags = SECURITY_INFORMATION.DACL_SECURITY_INFORMATION; returnValue = GetNamedSecurityInfo(shareName, SE_OBJECT_TYPE.SE_LMSHARE, flags, out ownerSid, out groupSid, out dacl, out sacl, out securityDescriptor); if (returnValue != ERROR_SUCCESS) { throw new System.Runtime.InteropServices.ExternalException(string.Format("Cannot retrieve security info entries. Last Error: {0}.", Marshal.GetLastWin32Error())); } // get the user SID byte[] userSID = GetUserSID(userName); // build a trustee object for the user TRUSTEE trustee = new TRUSTEE(); IntPtr pTrustee = Marshal.AllocHGlobal(Marshal.SizeOf(trustee)); Marshal.StructureToPtr(trustee, pTrustee, false); BuildTrusteeWithSid(pTrustee, userSID); // get the access rights ACCESS_MASK accessRights = 0; GetEffectiveRightsFromAcl(dacl, pTrustee, ref accessRights); return(accessRights); } finally { // clean up LocalFree(ownerSid); LocalFree(groupSid); LocalFree(dacl); LocalFree(sacl); LocalFree(securityDescriptor); } }
public void AccessCheckTest() { using (var pSD = GetSD(fn, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION | SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION | SECURITY_INFORMATION.GROUP_SECURITY_INFORMATION)) using (var hTok = SafeHTOKEN.FromProcess(GetCurrentProcess(), TokenAccess.TOKEN_IMPERSONATE | TokenAccess.TOKEN_DUPLICATE | TokenAccess.TOKEN_READ).Duplicate(SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation)) { var ps = PRIVILEGE_SET.InitializeWithCapacity(10); var psSz = ps.SizeInBytes; var gm = GENERIC_MAPPING.GenericFileMapping; ACCESS_MASK accessMask = ACCESS_MASK.GENERIC_READ; MapGenericMask(ref accessMask, gm); var b = AccessCheck(pSD, hTok, accessMask, gm, ref ps, ref psSz, out var access, out var status); if (!b) { TestContext.WriteLine($"AccessCheck failed: {Win32Error.GetLastError()}"); } Assert.That(b, Is.True); TestContext.WriteLine($"Access={(Kernel32.FileAccess)access}; Status={status}"); } }
/// <summary> /// Open a handle to a symbolic link at the given NT path. /// </summary> public static SafeSymbolicLinkObjectHandle OpenSymbolicLinkObject( string path, ACCESS_MASK desiredAccess = ACCESS_MASK.GENERIC_READ) { return((SafeSymbolicLinkObjectHandle)OpenObjectHelper(path, (attributes) => { SafeSymbolicLinkObjectHandle link; NTSTATUS status = Direct.NtOpenSymbolicLinkObject( LinkHandle: out link, DesiredAccess: desiredAccess, ObjectAttributes: ref attributes); if (status != NTSTATUS.STATUS_SUCCESS) { throw ErrorHelper.GetIoExceptionForNTStatus(status, path); } return link; })); }
/// <summary> /// Open a handle to a directory object at the given NT path. /// </summary> public static SafeDirectoryObjectHandle OpenDirectoryObject( string path, ACCESS_MASK desiredAccess = ACCESS_MASK.DIRECTORY_QUERY) { return((SafeDirectoryObjectHandle)OpenObjectHelper(path, (attributes) => { SafeDirectoryObjectHandle directory; NTSTATUS status = Direct.NtOpenDirectoryObject( DirectoryHandle: out directory, DesiredAccess: desiredAccess, ObjectAttributes: ref attributes); if (status != NTSTATUS.STATUS_SUCCESS) { throw ErrorHelper.GetIoExceptionForNTStatus(status, path); } return directory; })); }
static void FindHearthstoneProcess() { int[] pids = GetPids("Hearthstone.exe").ToArray(); if (pids.Length == 0) { Console.WriteLine("Couldn't find Hearthstone.exe"); return; } int pid = pids[0]; ACCESS_MASK accessMask = ProcessAccess.PROCESS_QUERY_INFORMATION | ProcessAccess.PROCESS_VM_READ; using (SafeObjectHandle hProcess = OpenProcess(accessMask, false, pid)) { if (hProcess.IsInvalid) { Console.WriteLine($"Hearthstone process handle is valid: {!hProcess.IsInvalid}"); return; } Console.WriteLine($"Hearthstone process handle is valid: {hProcess.DangerousGetHandle()}"); } }
/// <summary> /// Translate access mask for trusted domain object. /// </summary> /// <param name="accessMask">ACCESS_MASK value to be translated</param> /// <returns>The result of translation to accessMask</returns> private static ACCESS_MASK TranslateAccessMaskForTrustedDomain(ACCESS_MASK accessMask) { switch (accessMask) { case ACCESS_MASK.ValueToBeTranslated0x80000000: accessMask = ACCESS_MASK.TRUSTED_QUERY_DOMAIN_NAME | ACCESS_MASK.READ_CONTROL; break; case ACCESS_MASK.ValueToBeTranslated0x40000000: accessMask = ACCESS_MASK.TRUSTED_SET_CONTROLLERS | ACCESS_MASK.TRUSTED_SET_POSIX | ACCESS_MASK.READ_CONTROL; break; case ACCESS_MASK.ValueToBeTranslated0x20000000: accessMask = ACCESS_MASK.TRUSTED_QUERY_CONTROLLERS | ACCESS_MASK.TRUSTED_QUERY_POSIX | ACCESS_MASK.READ_CONTROL; break; case ACCESS_MASK.ValueToBeTranslated0x10000000: accessMask = ACCESS_MASK.TRUSTED_QUERY_DOMAIN_NAME | ACCESS_MASK.TRUSTED_QUERY_CONTROLLERS | ACCESS_MASK.TRUSTED_SET_CONTROLLERS | ACCESS_MASK.TRUSTED_QUERY_POSIX | ACCESS_MASK.TRUSTED_SET_POSIX | ACCESS_MASK.TRUSTED_SET_AUTH | ACCESS_MASK.TRUSTED_QUERY_AUTH | ACCESS_MASK.DELETE | ACCESS_MASK.READ_CONTROL | ACCESS_MASK.WRITE_DAC | ACCESS_MASK.WRITE_OWNER; break; } return(accessMask); }
public static extern IntPtr OpenInputDesktop(uint dwFlags, bool fInherit, ACCESS_MASK dwDesiredAccess);
public static Win32HidDevice FromPath(string path, ACCESS_MASK accessMode) { return FromPath(path, accessMode, null); }
public static extern IntPtr OpenWindowStation(string lpszWinSta, bool fInherit, ACCESS_MASK dwDesiredAccess);
private static extern int LsaOpenPolicy(IntPtr SystemName, ref LSA_OBJECT_ATTRIBUTES ObjectAttributes, ACCESS_MASK DesiredAccess, out IntPtr PolicyHandle);
public static extern IntPtr CreateFile(string lpFileName, ACCESS_MASK dwDesiredAccess, FILE_SHARE dwShareMode, [In] ref SECURITY_ATTRIBUTES lpSecurityAttributes, FileMode dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);
public static unsafe extern SafeWindowStationHandle CreateWindowStation( string lpwinsta, WindowStationCreationFlags dwFlags, ACCESS_MASK dwDesiredAccess, [Friendly(FriendlyFlags.In | FriendlyFlags.Optional)] Kernel32.SECURITY_ATTRIBUTES* lpsa);
public static extern SafeServiceHandle OpenService(SafeServiceHandle hSCManager, string lpServiceName, ACCESS_MASK dwDesiredAccess);
private static extern IntPtr OpenSCManager(string machineName, string databaseName, ACCESS_MASK dwAccess);
public static extern bool AddAccessAllowedAce(IntPtr pAcl, uint dwAceRevision, ACCESS_MASK AccessMask, IntPtr pSid);
static extern UInt32 GetEffectiveRightsFromAcl( IntPtr pacl, IntPtr pTrustee, ref ACCESS_MASK pAccessRights);
/// <summary> /// Verify permissions on a share /// </summary> /// <param name="userName">usename to check for</param> /// <param name="shareName">the name of the share</param> /// <param name="rights">the expected rights</param> public static void VerifySharePermession(string userName, string shareName, ACCESS_MASK rights) { ACCESS_MASK accessMask = GetSharePermissions(shareName, userName); Assert.True( (accessMask & rights) != 0, String.Format("User '{0}' access rights to Share '{1}' do not match expected. Actual: '{2}'. Expected: '{3}'. ", userName, shareName, accessMask, rights)); }
public static extern IntPtr OpenDesktop(string lpszDesktop, uint dwFlags, bool fInherit, ACCESS_MASK dwDesiredAccess);
public static unsafe extern SafeDesktopHandle CreateDesktopEx( string lpszDesktop, IntPtr lpszDevice, IntPtr pDevmode, DesktopCreationFlags dwFlags, ACCESS_MASK dwDesiredAccess, [Friendly(FriendlyFlags.In | FriendlyFlags.Optional)] Kernel32.SECURITY_ATTRIBUTES* lpsa, uint ulHeapSize, IntPtr pvoid = default(IntPtr));
public static extern SafeServiceHandle OpenSCManager(string lpMachineName, string lpDatabaseName, ACCESS_MASK dwDesiredAccess);
public static extern bool OpenProcessToken( IntPtr processHandle, ACCESS_MASK desiredAccess, out SafeObjectHandle tokenHandle);
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); } }
public static extern SafeServiceHandle CreateService(SafeServiceHandle hSCManager, string lpServiceName, string lpDisplayName, ACCESS_MASK dwDesiredAccess, ServiceType dwServiceType, ServiceStartType dwStartType, ServiceErrorControl dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, int lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword);
public static extern IntPtr CreateFile(string lpFileName, ACCESS_MASK dwDesiredAccess, FILE_SHARE dwShareMode, IntPtr lpSecurityAttributes, FileMode dwCreationDisposition, FileFlagsAndAttributes dwFlagsAndAttributes, IntPtr hTemplateFile);
public static extern IntPtr OpenProcess(ACCESS_MASK dwDesiredAccess, bool bInheritHandle, int dwProcessId);
public static extern uint NtCreateSection( out ulong SectionHandle, ACCESS_MASK DesiredAccess, int ObjectAttributes, out long MaximumSize, NT.MemoryProtection SectionPageProtection, uint AllocationAttributes, ulong FileHandle);
/// <summary> /// Gets the effective permissions for the provided Sid within the Security Descriptor. /// </summary> /// <param name="pUserSid">A pointer to the Sid of the identity to check.</param> /// <param name="serverName">Name of the server. This can be <c>null</c>.</param> /// <param name="pSecurityDescriptor">A pointer to the security descriptor.</param> /// <returns>An array of access masks.</returns> public virtual ACCESS_MASK[] GetEffectivePermission(PSID pUserSid, string serverName, PSECURITY_DESCRIPTOR pSecurityDescriptor) { ACCESS_MASK mask = pUserSid.GetEffectiveRights(pSecurityDescriptor); return(new[] { mask }); }
internal static Win32HidDevice FromPath([NotNull] string path, ACCESS_MASK accessMode, [CanBeNull] Win32HidDeviceInformation knownInformation) { if (path == null) throw new ArgumentNullException(nameof(path)); var handle = OpenHandle(path, accessMode, true); return new Win32HidDevice(path, handle, true, knownInformation); }
public static unsafe extern bool DuplicateTokenEx( SafeObjectHandle hExistingToken, ACCESS_MASK dwDesiredAccess, [Friendly(FriendlyFlags.In | FriendlyFlags.Optional)] SECURITY_ATTRIBUTES* lpTokenAttributes, SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, TOKEN_TYPE TokenType, out SafeObjectHandle phNewToken);
public static Win32HidDevice TryFromPath(string path, ACCESS_MASK accessMode) { var handle = OpenHandle(path, accessMode, false); return handle.IsInvalid ? null : new Win32HidDevice(path, handle, true); }
static extern uint GetEffectiveRightsFromAcl(IntPtr pDacl, ref TRUSTEE pTrustee, ref ACCESS_MASK pAccessRights);
public static extern IntPtr OpenWindowStationW([MarshalAs(UnmanagedType.LPTStr)] string lpszWinSta, [MarshalAs(UnmanagedType.Bool)] bool fInherit, ACCESS_MASK dwDesiredAccess);
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 static extern SafeDesktopHandle OpenInputDesktop( DesktopCreationFlags dwFlags, [MarshalAs(UnmanagedType.Bool)] bool fInherit, ACCESS_MASK dwDesiredAccess);
internal static extern IntPtr OpenProcess( ACCESS_MASK dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwProcessId);
public static unsafe extern SafeDesktopHandle CreateDesktop( string lpszDesktop, string lpszDevice, IntPtr pDevmode, DesktopCreationFlags dwFlags, ACCESS_MASK dwDesiredAccess, [Friendly(FriendlyFlags.In | FriendlyFlags.Optional)] Kernel32.SECURITY_ATTRIBUTES* lpsa);
public static extern SafeWindowStationHandle OpenWindowStation( string lpszWinSta, [MarshalAs(UnmanagedType.Bool)] bool fInherit, ACCESS_MASK dwDesiredAccess);
public static extern Win32ErrorCode RegOpenKeyEx( SafeRegistryHandle hKey, string lpSubKey, RegOpenKeyOptions ulOptions, ACCESS_MASK samDesired, out SafeRegistryHandle phkResult);
public static extern NTSTATUS NtOpenDirectoryObject( out SafeDirectoryObjectHandle DirectoryHandle, ACCESS_MASK DesiredAccess, ref OBJECT_ATTRIBUTES ObjectAttributes);
public static extern Int32 OpenVirtualDisk(ref STORAGE_TYPE Type, String File, ACCESS_MASK Mask, OPEN_FLAG Flag, ref OPEN_PARAMETERS Parameters, ref IntPtr Handle);
unsafe public static extern NTSTATUS NtOpenSymbolicLinkObject( out SafeSymbolicLinkObjectHandle LinkHandle, ACCESS_MASK DesiredAccess, ref OBJECT_ATTRIBUTES ObjectAttributes);