/// <summary> /// Give you an array with all privileges that the account have /// </summary> /// <param name="account">Account name like "Olaf"</param> /// <returns></returns> public Advapi32.LsaUnicodeString[] EnumeratePrivileges(string account) { IntPtr rightsPtr = IntPtr.Zero; try { uint countOfRights; using (var win32Sid = new Win32Sid(account)) { //Enumerate account rights NtStatus ret = Advapi32.LsaEnumerateAccountRights(this, win32Sid.Pointer, out rightsPtr, out countOfRights); if (ret != NtStatus.Success) { throw new Win32Exception(Advapi32.LsaNtStatusToWinError(ret)); } } var privileges = new Advapi32.LsaUnicodeString[countOfRights]; IntPtr tempPtr = rightsPtr; for (var i = 0; i < countOfRights; i++) { privileges[i] = (Advapi32.LsaUnicodeString)Marshal.PtrToStructure(tempPtr, typeof(Advapi32.LsaUnicodeString)); tempPtr = tempPtr + Marshal.SizeOf <Advapi32.LsaUnicodeString>(); } return(privileges); } finally { if (rightsPtr != IntPtr.Zero) { Advapi32.LsaFreeMemory(rightsPtr); } } }
public AccessTokenHandle DuplicateImpersonationToken(params TokenAccess[] desiredAccess) { var defaultAccess = TokenAccess.TOKEN_ALL_ACCESS; uint combinedAccess = (uint)defaultAccess; if (desiredAccess.Length > 0) { combinedAccess = (uint)(new List <TokenAccess>(desiredAccess).Aggregate((x, y) => x | y)); } SECURITY_ATTRIBUTES secAttr = new SECURITY_ATTRIBUTES(); IntPtr newToken; Logger.GetInstance().Debug($"Attempting to duplicate token."); if (!Advapi32.DuplicateTokenEx(this.handle, combinedAccess, ref secAttr, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenImpersonation, out newToken)) { Logger.GetInstance().Error($"Failed to duplicate impersonation token. DuplicateTokenEx failed with error code: {Kernel32.GetLastError()}"); throw new DuplicateTokenException(); } Logger.GetInstance().Debug($"Successfully duplicated token."); if (desiredAccess.Length > 0) { return(new AccessTokenHandle(newToken, desiredAccess)); } else { return(new AccessTokenHandle(newToken, defaultAccess)); } }
/// <summary> /// Delete the service /// </summary> public void DeleteService() { if (!Advapi32.DeleteService(serviceHandle: this)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } }
/// <summary> /// Configure change monitoring for this prefs object /// </summary> /// <param name="subKey"></param> private void ConfigureChangeMonitoring(string subKey) { // assert preconditions Debug.Assert(hPrefsKey == UIntPtr.Zero); Debug.Assert(settingsChangedEvent == null); try { // open handle to registry key int result = Advapi32.RegOpenKeyEx( HKEY.CURRENT_USER, String.Format(CultureInfo.InvariantCulture, @"{0}\{1}\{2}", ApplicationEnvironment.SettingsRootKeyName, ApplicationConstants.PREFERENCES_SUB_KEY, subKey), 0, KEY.READ, out hPrefsKey); if (result != ERROR.SUCCESS) { Trace.Fail("Failed to open registry key"); changeMonitoringDisabled = true; return; } // create settings changed event settingsChangedEvent = new ManualResetEvent(false); // start monitoring changes MonitorChanges(); } catch (Exception e) { // Just being super-paranoid here because this code is likely be called during // application initialization -- if ANY type of error occurs then we disable // change monitoring for the life of this object Trace.WriteLine("Unexpected error occurred during change monitor configuration: " + e.Message + "\r\n" + e.StackTrace); changeMonitoringDisabled = true; } }
public void Put(string key, byte[] blob) { fixed(byte *blobPtr = blob) { var credential = new CREDENTIAL { Flags = 0x0, Type = CRED_TYPE.CRED_TYPE_GENERIC, TargetName = key, Comment = null, TargetAlias = null, CredentialBlobSize = (uint)blob.Length, CredentialBlob = blobPtr, Persist = Advapi32.CRED_PERSIST_LOCAL_MACHINE, AttributesCount = 0, Attributes = IntPtr.Zero, UserName = RuntimeEnvironmentHelper.AccountName }; var success = Advapi32.CredWrite(ref credential, 0); if (!success) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } }
/// <summary> /// Configure change monitoring for this monitor object /// </summary> /// <param name="subKey"></param> private void ConfigureChangeMonitoring(RegistryKeyMonitor monitor, bool throwOnNotExist) { string key = monitor.Key; // assert preconditions Debug.Assert(monitor.hRawKey == UIntPtr.Zero); Debug.Assert(monitor.settingsChangedEvent == null); // open handle to registry key int result = Advapi32.RegOpenKeyEx( monitor.HKey, key, 0, KEY.READ, out monitor.hRawKey); if (result != ERROR.SUCCESS) { if (throwOnNotExist) { throw new Exception("Failed to open registry key :" + key); } else { Debug.WriteLine("ConfigureChangeMonitoring error: " + result); return; } } // create settings changed event monitor.settingsChangedEvent = new ManualResetEvent(false); // start monitoring changes RegisterForRegistryKeyChanged(monitor); }
public bool Remove(string service, string account) { WindowsCredential credential = Enumerate(service, account).FirstOrDefault(); if (credential != null) { int result = Win32Error.GetLastError( Advapi32.CredDelete(credential.TargetName, CredentialType.Generic, 0) ); switch (result) { case Win32Error.Success: return(true); case Win32Error.NotFound: return(false); default: Win32Error.ThrowIfError(result); return(false); } } return(false); }
/// <summary> /// Gets the name of the service from the display name. /// </summary> /// <param name="displayName">The display name of the service.</param> /// <returns></returns> /// <exception cref="Win32Exception"> /// </exception> public string GetServiceName(string displayName) { uint bytesNeeded = 0; //Determine the required buffer size => buffer and bufferSize must be null if (!Advapi32.GetServiceKeyName(this, displayName, IntPtr.Zero, ref bytesNeeded)) { int result = Marshal.GetLastWin32Error(); if (result != Win32ErrorCodes.ERROR_INSUFFICIENT_BUFFER) { throw new Win32Exception(result); } } //+1 for NULL terminator bytesNeeded++; //Allocate the required buffer size IntPtr bufferPtr = Marshal.AllocHGlobal((int)bytesNeeded); try { if (!Advapi32.GetServiceKeyName(this, displayName, bufferPtr, ref bytesNeeded)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } return(Marshal.PtrToStringUni(bufferPtr)); } finally { Marshal.FreeHGlobal(bufferPtr); } }
// Helper function: common routine for acquiring a QUERY_SERVICE_CONFIG struct private Advapi32.QUERY_SERVICE_CONFIG GetQueryServiceConfigStruct(SafeHandle serviceHandle) { int pcbBytesNeeded = 0; IntPtr lpBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Advapi32.QUERY_SERVICE_CONFIG))); /* WORKAROUND: Since Marshal.SizeOf(typeof(Advapi32.QUERY_SERVICE_CONFIG)) can't predict the required value for cbBufSize, * we'll pretend we care about it by first letting the Windows API modify the pcbBytesNeeded variable and then feed * it back to the API as our cbBufSize in our second QueryServiceConfig() call (even though .NET will allocate the * memory needed for each string in Advapi32.QUERY_SERVICE_CONFIG for us anyway). */ Advapi32.QueryServiceConfig( serviceHandle.DangerousGetHandle(), lpBuffer, 0, out pcbBytesNeeded ); // obtain the actual, desired information if (!Advapi32.QueryServiceConfig( serviceHandle.DangerousGetHandle(), lpBuffer, pcbBytesNeeded, out pcbBytesNeeded )) { throw new Win32Exception(Marshal.GetLastWin32Error()); } return((Advapi32.QUERY_SERVICE_CONFIG)Marshal.PtrToStructure(lpBuffer, typeof(Advapi32.QUERY_SERVICE_CONFIG))); }
public SafeServiceHandle(SafeHandle safeSCHandle, string serviceName, uint desiredAccess) : base(true) { if ((handle = Advapi32.OpenService(safeSCHandle.DangerousGetHandle(), serviceName, desiredAccess)).Equals(IntPtr.Zero)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } }
/// <summary> /// Query the current status of the service /// </summary> /// <returns>Service status process instance</returns> public Advapi32.ServiceStatusProcess QueryServiceStatus() { uint bytesNeeded = 0; //Determine the required buffer size => buffer and bufferSize must be null if (!Advapi32.QueryServiceStatusEx(serviceHandle: this, Advapi32.ScStatusProcessInfo, buffer: IntPtr.Zero, 0, ref bytesNeeded)) { int result = Marshal.GetLastWin32Error(); if (result != Win32ErrorCodes.ERROR_INSUFFICIENT_BUFFER) { throw new Win32Exception(result); } } //Allocate the required buffer size IntPtr bufferPtr = Marshal.AllocHGlobal((int)bytesNeeded); try { if (!Advapi32.QueryServiceStatusEx(serviceHandle: this, Advapi32.ScStatusProcessInfo, buffer: bufferPtr, bufferSize: bytesNeeded, ref bytesNeeded)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } return(Marshal.PtrToStructure <Advapi32.ServiceStatusProcess>(bufferPtr)); } finally { Marshal.FreeHGlobal(bufferPtr); } }
/// <summary> /// Implementation of <see cref="T:Waffle.Windows.AuthProvider.IWindowsAuthProvider.LogonDomainUserEx" />. /// </summary> public IWindowsIdentity LogonDomainUserEx( string username, string domain, string password, Advapi32.LogonType logonType, Advapi32.LogonProvider logonProvider) { IntPtr hToken = IntPtr.Zero; try { if (!Advapi32.LogonUser(username, domain, password, (int)logonType, (int)logonProvider, out hToken)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } return(new WindowsIdentityImpl(new WindowsIdentity(hToken))); } finally { if (hToken != null) { Kernel32.CloseHandle(hToken); hToken = IntPtr.Zero; } } }
/// <summary> /// Start the service with the given arguments /// </summary> /// <param name="arguments"></param> public void Start(string[] arguments) { if (!Advapi32.StartService(serviceHandle: this, numberOfArgs: (uint)arguments.Length, args: arguments)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } }
public UserImpersonation(UserCredentials credentials) { const int logon32ProviderDefault = 0; const int logon32LogonInteractive = 2; const int securityImpersonation = 2; _tokenHandle = IntPtr.Zero; _dupeTokenHandle = IntPtr.Zero; if (!Advapi32.LogonUser(credentials.Username, credentials.Domain, credentials.Password, logon32LogonInteractive, logon32ProviderDefault, out _tokenHandle)) { var win32ErrorNumber = Marshal.GetLastWin32Error(); // REVIEW: maybe ImpersonationException should inherit from win32exception throw new ImpersonationException(win32ErrorNumber, new Win32Exception(win32ErrorNumber).Message, credentials.Username, credentials.Domain); } if (!Advapi32.DuplicateToken(_tokenHandle, securityImpersonation, out _dupeTokenHandle)) { var win32ErrorNumber = Marshal.GetLastWin32Error(); Kernel32.CloseHandle(_tokenHandle); throw new ImpersonationException(win32ErrorNumber, "Unable to duplicate token!", credentials.Username, credentials.Domain); } var newId = new WindowsIdentity(_dupeTokenHandle); _impersonatedUser = newId.Impersonate(); }
/// <summary> /// Allow failure actions on non crash failures. /// The change takes effect the next time the system is started. /// </summary> /// <param name="enable"> /// When <c>true</c>, failure actions will be called even when the service reports that it is stopped but with a return code diffrent from zero. /// When <c>false</c>, failure actions will only be called when the service terminates without reporting an exit code. /// </param> /// <exception cref="Win32Exception"></exception> public void ChangeFailureActionsOnNonCrashFailures(bool enable) { if (QueryServiceStatus().currentState != Advapi32.ServiceCurrentState.Stopped) { throw new ServiceNotStoppedException(); } IntPtr ptr = IntPtr.Zero; //Create the struct Advapi32.ServiceConfigFailureActionsFlag serviceConfigFailureActionsFlag; serviceConfigFailureActionsFlag.failureActionsOnNonCrashFailures = enable; try { // Copy the struct to unmanaged memory ptr = Marshal.AllocHGlobal(Marshal.SizeOf(serviceConfigFailureActionsFlag)); Marshal.StructureToPtr(serviceConfigFailureActionsFlag, ptr, fDeleteOld: false); //Call ChangeServiceConfig2 if (!Advapi32.ChangeServiceConfig2(this, Advapi32.ServiceInfoLevel.FailureActionsFlag, ptr)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } finally { if (ptr != IntPtr.Zero) { Marshal.FreeHGlobal(ptr); } } }
/// <summary> /// Allows you to disable or enable the delayed start of the service /// </summary> /// <param name="enable"> /// When <c>true</c>, the service start delayed. /// When <c>false</c>, the service start normal. /// </param> public void ChangeDelayedStart(bool enable) { if (QueryServiceStatus().currentState != Advapi32.ServiceCurrentState.Stopped) { throw new ServiceNotStoppedException(); } IntPtr ptr = IntPtr.Zero; //Create the struct Advapi32.ServiceConfigDelayedAutoStartInfo serviceDelayedAutoStartInfo; serviceDelayedAutoStartInfo.DelayedAutostart = enable; try { // Copy the struct to unmanaged memory ptr = Marshal.AllocHGlobal(Marshal.SizeOf(serviceDelayedAutoStartInfo)); Marshal.StructureToPtr(serviceDelayedAutoStartInfo, ptr, fDeleteOld: false); //Call ChangeServiceConfig2 if (!Advapi32.ChangeServiceConfig2(this, Advapi32.ServiceInfoLevel.DelayedAutoStartInfo, ptr)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } finally { if (ptr != IntPtr.Zero) { Marshal.FreeHGlobal(ptr); } } }
public static SafeTokenHandle FromThread(IntPtr hThread, AccessTypes desiredAccess = AccessTypes.TokenDuplicate, bool openAsSelf = true) { SafeTokenHandle val; if (!Advapi32.OpenThreadToken(hThread, desiredAccess, openAsSelf, out val)) { if (Marshal.GetLastWin32Error() == ERROR_NO_TOKEN) { SafeTokenHandle pval = FromCurrentProcess(); if (!Advapi32.DuplicateTokenEx(pval, AccessTypes.TokenImpersonate | desiredAccess, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.Impersonation, TokenType.TokenImpersonation, ref val)) { throw new System.ComponentModel.Win32Exception(); } if (!Advapi32.SetThreadToken(IntPtr.Zero, val)) { throw new System.ComponentModel.Win32Exception(); } } else { throw new System.ComponentModel.Win32Exception(); } } return(val); }
public static AccessTokenSessionId FromTokenHandle(AccessTokenHandle handle) { uint tokenInfLength = 0; bool success; IntPtr hToken = handle.GetHandle(); success = Advapi32.GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenSessionId, IntPtr.Zero, tokenInfLength, out tokenInfLength); IntPtr tokenInfo = Marshal.AllocHGlobal(Convert.ToInt32(tokenInfLength)); success = Advapi32.GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenSessionId, tokenInfo, tokenInfLength, out tokenInfLength); Int32 sessionId = -1; if (success) { sessionId = Marshal.ReadInt32(tokenInfo); Marshal.FreeHGlobal(tokenInfo); return(new AccessTokenSessionId(sessionId)); } else { Marshal.FreeHGlobal(tokenInfo); Logger.GetInstance().Error($"Failed to retreive session id information for access token. GetTokenInformation failed with error: {Kernel32.GetLastError()}"); throw new TokenInformationException(); } }
/// <summary> /// Query the current config of the service /// </summary> /// <returns>Service status process instance</returns> public Advapi32.QUERY_SERVICE_CONFIG QueryServiceConfig() { uint bytesNeeded = 0; //Determine the required buffer size => buffer and bufferSize must be null if (!Advapi32.QueryServiceConfig(this, IntPtr.Zero, 0, ref bytesNeeded)) { int result = Marshal.GetLastWin32Error(); if (result != Win32ErrorCodes.ERROR_INSUFFICIENT_BUFFER) { throw new Win32Exception(result); } } //Allocate the required buffer size IntPtr bufferPtr = Marshal.AllocHGlobal((int)bytesNeeded); try { if (!Advapi32.QueryServiceConfig(this, bufferPtr, bytesNeeded, ref bytesNeeded)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } return(Marshal.PtrToStructure <Advapi32.QUERY_SERVICE_CONFIG>(bufferPtr)); } finally { Marshal.FreeHGlobal(bufferPtr); } }
internal static IEnumerable <CREDENTIAL> CredEnumerate() { int count; IntPtr pCredentials; var ret = Advapi32.CredEnumerate(null, 0, out count, out pCredentials); if (ret == false) { string exceptionDetails = string.Format("Win32Exception: {0}", new Win32Exception(Marshal.GetLastWin32Error()).ToString()); Beaprint.NoColorPrint($" [!] Unable to enumerate credentials automatically, error: '{exceptionDetails}'"); Beaprint.NoColorPrint("Please run: "); Beaprint.ColorPrint("cmdkey /list", Beaprint.ansi_color_yellow); return(Enumerable.Empty <CREDENTIAL>()); } var credentials = new IntPtr[count]; for (var n = 0; n < count; n++) { credentials[n] = Marshal.ReadIntPtr(pCredentials, n * Marshal.SizeOf(typeof(IntPtr))); } return(credentials.Select(ptr => (CREDENTIAL)Marshal.PtrToStructure(ptr, typeof(CREDENTIAL)))); }
/// <summary> /// Start the service with the given arguments /// </summary> /// <param name="arguments"></param> public void Start(string[] arguments) { IntPtr[] ptrArgs = new IntPtr[arguments.Length]; try { for (int i = 0; i < ptrArgs.Length; i++) { ptrArgs[i] = Marshal.StringToHGlobalUni(arguments[i]); } GCHandle stringPtrHandle = GCHandle.Alloc(ptrArgs, GCHandleType.Pinned); try { if (!Advapi32.StartService(this, (uint)ptrArgs.Length, stringPtrHandle.AddrOfPinnedObject())) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } finally { if (stringPtrHandle.IsAllocated) { stringPtrHandle.Free(); } } } finally { for (int i = 0; i < ptrArgs.Length; i++) { Marshal.FreeHGlobal(ptrArgs[i]); } } }
public static IReadOnlyList <Credential> EnumerateCrendentials(string?filter) { var result = new List <Credential>(); var ret = Advapi32.CredEnumerate(filter, 0, out var count, out var pCredentials); using (pCredentials) { if (ret && !pCredentials.IsInvalid) { for (var n = 0; n < count; n++) { var credentialPtr = Marshal.ReadIntPtr(pCredentials.DangerousGetHandle(), n * Marshal.SizeOf <IntPtr>()); var credential = Marshal.PtrToStructure <CREDENTIAL>(credentialPtr); result.Add(ReadCredential(credential)); } } else { var lastError = Marshal.GetLastWin32Error(); throw new Win32Exception(lastError); } } return(result); }
/// <summary> /// Query the delayed start flag of the service /// </summary> public bool QueryDelayedStart() { uint bytesNeeded = 0; //Call QueryServiceConfig2 if (!Advapi32.QueryServiceConfig2(this, Advapi32.ServiceInfoLevel.Description, IntPtr.Zero, 0, ref bytesNeeded)) { int result = Marshal.GetLastWin32Error(); if (result != Win32ErrorCodes.ERROR_INSUFFICIENT_BUFFER) { throw new Win32Exception(result); } } //Allocate the required buffer size IntPtr bufferPtr = Marshal.AllocHGlobal((int)bytesNeeded); try { if (!Advapi32.QueryServiceConfig2(this, Advapi32.ServiceInfoLevel.Description, bufferPtr, bytesNeeded, ref bytesNeeded)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } return(Marshal.PtrToStructure <Advapi32.ServiceConfigDelayedAutoStartInfo>(bufferPtr).DelayedAutostart); } finally { Marshal.FreeHGlobal(bufferPtr); } }
public SafeSCManagerHandle(String machineName, String databaseName, uint desiredAccess) : base(true) { if ((handle = Advapi32.OpenSCManager(machineName, databaseName, desiredAccess)).Equals(IntPtr.Zero)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } }
public static AccessTokenHandle FromThreadHandle(TMThreadHandle hThread, params TokenAccess[] desiredAccess) { var defaultAccess = TokenAccess.TOKEN_ALL_ACCESS; uint combinedAccess = (uint)defaultAccess; if (desiredAccess.Length > 0) { combinedAccess = (uint)(new List <TokenAccess>(desiredAccess).Aggregate((x, y) => x | y)); } IntPtr hToken; if (!Advapi32.OpenThreadToken(hThread.Handle, combinedAccess, false, out hToken)) { Logger.GetInstance().Error($"Failed to retrieve handle to processes access token. OpenThreadToken failed with error: {Kernel32.GetLastError()}"); throw new OpenThreadTokenException(); } if (desiredAccess.Length > 0) { return(new AccessTokenHandle(hToken, desiredAccess)); } else { return(new AccessTokenHandle(hToken, defaultAccess)); } }
/// <summary> /// Sets debug privileges for running program. /// </summary> /// <returns>Internal name of a process</returns> public static bool SetDebugPrivileges() { IntPtr hToken; LUID luidSEDebugNameValue; TOKEN_PRIVILEGES tkpPrivileges; if (!Advapi32.OpenProcessToken(Kernel32.GetCurrentProcess(), TokenObject.TOKEN_ADJUST_PRIVILEGES | TokenObject.TOKEN_QUERY, out hToken)) { return(false); } if (!Advapi32.LookupPrivilegeValue(null, SE_DEBUG_NAME, out luidSEDebugNameValue)) { Kernel32.CloseHandle(hToken); return(false); } tkpPrivileges.PrivilegeCount = 1; tkpPrivileges.Luid = luidSEDebugNameValue; tkpPrivileges.Attributes = PrivilegeAttributes.SE_PRIVILEGE_ENABLED; if (!Advapi32.AdjustTokenPrivileges(hToken, false, ref tkpPrivileges, 0, IntPtr.Zero, IntPtr.Zero)) { Kernel32.CloseHandle(hToken); return(false); } return(Kernel32.CloseHandle(hToken)); }
/// <summary> /// Apparently, this cannot be done, and always returns the error /// code 87. /// </summary> /// <param name="logonSid"></param> /// <param name="handle"></param> public static void SetTokenLogonSid(AccessTokenLogonSid logonSid, AccessTokenHandle handle) { TOKEN_GROUPS tokenGroups = new TOKEN_GROUPS(); var ptrs = logonSid.GetLogonSids(); var attributes = logonSid.GetLogonSidAttributes(); tokenGroups.GroupCount = (uint)ptrs.Count; tokenGroups.Groups = new SID_AND_ATTRIBUTES[tokenGroups.GroupCount]; for (int i = 0; i < tokenGroups.GroupCount; i++) { tokenGroups.Groups[i] = new SID_AND_ATTRIBUTES(); tokenGroups.Groups[i].Sid = ptrs[i]; tokenGroups.Groups[i].Attributes = attributes[i]; } var size = Marshal.SizeOf(tokenGroups); var tgPtr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(tokenGroups, tgPtr, true); if (!Advapi32.SetTokenInformation(handle.GetHandle(), TOKEN_INFORMATION_CLASS.TokenLogonSid, tgPtr, size)) { Marshal.FreeHGlobal(tgPtr); Logger.GetInstance().Error($"Failed to set new logon sid for token. SetTokenInformation failed with error: {Kernel32.GetLastError()}"); throw new TokenInformationException(); } Marshal.FreeHGlobal(tgPtr); }
public static IReadOnlyList <Credential> EnumerateCrendentials(string filter) { var result = new List <Credential>(); var ret = Advapi32.CredEnumerate(filter, 0, out int count, out IntPtr pCredentials); try { if (ret) { for (var n = 0; n < count; n++) { var credential = Marshal.ReadIntPtr(pCredentials, n * Marshal.SizeOf <IntPtr>()); result.Add(ReadCredential(Marshal.PtrToStructure <CREDENTIAL>(credential))); } } else { var lastError = Marshal.GetLastWin32Error(); throw new Win32Exception(lastError); } } finally { Advapi32.CredFree(pCredentials); } return(result); }
/// <summary> /// Gets the localized name of the network service account. /// </summary> /// <value> /// The name of the network service account. /// </value> public static string GetNetworkServiceName() { IntPtr pSid = IntPtr.Zero; try { if (Advapi32.ConvertStringSidToSid(NetworkServiceSid, out pSid) == false) { return(string.Empty); } uint cchName = 1024; uint cchDomainName = 1024; StringBuilder lpName = new StringBuilder((int)cchName); StringBuilder lpDomainName = new StringBuilder((int)cchDomainName); int euse = 0; if (Advapi32.LookupAccountSid(null, pSid, lpName, ref cchName, lpDomainName, ref cchDomainName, out euse) == false) { return(string.Empty); } return(lpName.ToString()); } finally { if (pSid != IntPtr.Zero) { Kernel32.LocalFree(pSid); } } }
public static AccessTokenHandle FromProcessHandle(TMProcessHandle process, params TokenAccess[] desiredAccess) { var defaultAccess = TokenAccess.TOKEN_ALL_ACCESS; uint combinedAccess = (uint)defaultAccess; if (desiredAccess.Length > 0) { combinedAccess = (uint)(new List <TokenAccess>(desiredAccess).Aggregate((x, y) => x | y)); } IntPtr tokenHandle; Logger.GetInstance().Debug($"Attemping to open handle to process access token."); if (!Advapi32.OpenProcessToken(process.Handle, combinedAccess, out tokenHandle)) { Logger.GetInstance().Error($"Failed to retrieve handle to processes access token. OpenProcessToken failed with error: {Kernel32.GetLastError()}"); throw new OpenProcessTokenException(); } Logger.GetInstance().Debug($"Successfully opened handle to process access token."); if (desiredAccess.Length > 0) { return(new AccessTokenHandle(tokenHandle, desiredAccess)); } else { return(new AccessTokenHandle(tokenHandle, defaultAccess)); } }
/// <summary> /// Implementation of <see cref="T:Waffle.Windows.AuthProvider.IWindowsAuthProvider.LogonDomainUserEx" />. /// </summary> public IWindowsIdentity LogonDomainUserEx( string username, string domain, string password, Advapi32.LogonType logonType, Advapi32.LogonProvider logonProvider) { IntPtr hToken = IntPtr.Zero; try { if (!Advapi32.LogonUser(username, domain, password, (int)logonType, (int)logonProvider, out hToken)) throw new Win32Exception(Marshal.GetLastWin32Error()); return new WindowsIdentityImpl(new WindowsIdentity(hToken)); } finally { if (hToken != null) { Kernel32.CloseHandle(hToken); hToken = IntPtr.Zero; } } }