public ImpersonationContext(TokenHandle token) { if (!Win32.ImpersonateLoggedOnUser(token)) { Win32.Throw(); } }
protected override void OnStart(string[] args) { // okay, the 'args' here are ONLY for when the service is started via the Properties dialog in services.msc try { using (TokenHandle my_token = TokenUtil.OpenProcessToken(Process.GetCurrentProcess(), TokenAccess.TOKEN_ADJUST_PRIVILEGES | TokenAccess.TOKEN_DUPLICATE)) { PrivilegeState[] privs = new PrivilegeState[] { new PrivilegeState(TokenPrivileges.SE_TCB_NAME, true) }; if (!my_token.AdjustPrivileges(privs)) { throw new Win32Exception(); } // open the token of the process that lives in the session we want Process proc = Process.GetProcessById(this.Pid); TokenHandle proc_token = TokenUtil.OpenProcessToken(proc.Handle, TokenAccess.TOKEN_READ); // create a primary token TokenHandle new_token = TokenUtil.DuplicateTokenEx(my_token, TokenAccess.TOKEN_ALL_ACCESS, SECURITY_IMPERSONATION_LEVEL.SecurityDelegation, TOKEN_TYPE.TokenPrimary); // override the session under which it's going to be created new_token.SessionId = proc_token.SessionId; string cmd_exe = Environment.GetEnvironmentVariable("COMSPEC"); STARTUPINFO sui = new STARTUPINFO(); sui.cb = Marshal.SizeOf(typeof(STARTUPINFO)); PROCESS_INFORMATION procinfo; bool result = Advapi32.CreateProcessAsUser( new_token, cmd_exe, cmd_exe, IntPtr.Zero, // default process attributes IntPtr.Zero, // default thread attributes false, CreateProcessFlags.CREATE_NEW_CONSOLE | CreateProcessFlags.CREATE_NEW_PROCESS_GROUP | CreateProcessFlags.CREATE_DEFAULT_ERROR_MODE | CreateProcessFlags.CREATE_BREAKAWAY_FROM_JOB | CreateProcessFlags.CREATE_PRESERVE_CODE_AUTHZ_LEVEL | CreateProcessFlags.CREATE_UNICODE_ENVIRONMENT, IntPtr.Zero, // inherit environment null, // inherit current directory ref sui, out procinfo); if (!result) { throw new Win32Exception(); } } } catch { this.ExitCode = 1; } finally { EventWaitHandle ewh = EventWaitHandle.OpenExisting(EventName); ewh.Set(); } ThreadPool.QueueUserWorkItem(DoStop); }
public static TokenHandle MakeTokenHandle(string subjectSeed, int i) { var subjectId = subjectSeed + i % 2; TokenHandle tokenHandle = new TokenHandle { Key = Guid.NewGuid().ToString(), ClientId = "CLIENTID:" + i, Claims = new List <ClaimTypeRecord>() { new ClaimTypeRecord() { Type = Constants.ClaimTypes.Subject, Value = subjectId, ValueType = "ValueType:" + i } }, CreationTime = DateTimeOffset.UtcNow, Issuer = "ISSUER:" + i, Lifetime = 5, Type = "Type:" + i, SubjectId = subjectId }; return(tokenHandle); }
public static bool ValidateUser(string username, SecureString password) { if (string.IsNullOrWhiteSpace(username)) { throw new ArgumentNullException(nameof(username)); } if (password == null) { throw new ArgumentNullException(nameof(password)); } try { using (TokenHandle tokenHandle = TokenHandle.GetTokenFromLogon(username, password, Advapi32.LogonType.Interactive)) { return(!tokenHandle.IsInvalid); } } catch (Win32Exception) { return(false); } }
private Privilege(TokenHandle tokenHandle, string name, bool hasLuid, Luid luid, SePrivilegeAttributes attributes) : base(tokenHandle != null) { _tokenHandle = tokenHandle; if (_tokenHandle != null) { _tokenHandle.Reference(); } _name = name; _attributes = attributes; if (!hasLuid) { if (_name == null) { throw new ArgumentException("You must specify either a LUID or a name."); } _luid = LsaPolicyHandle.LookupPolicyHandle.LookupPrivilegeValue(_name); } else { _luid = luid; } }
private void RefreshProcesses() { Dictionary <int, SystemProcess> processes = Windows.GetProcesses(); listProcesses.BeginUpdate(); listProcesses.Items.Clear(); var generic_process = imageList.Images["generic_process"]; imageList.Images.Clear(); imageList.Images.Add("generic_process", generic_process); foreach (var process in processes.Values) { string userName = string.Empty; string fileName = null; try { using (ProcessHandle phandle = new ProcessHandle(process.Process.ProcessId, OSVersion.MinProcessQueryInfoAccess)) { using (TokenHandle thandle = phandle.GetToken(TokenAccess.Query)) using (Sid sid = thandle.User) userName = sid.GetFullName(true); fileName = phandle.ImageFileName; } } catch { } ListViewItem item = new ListViewItem(new string[] { process.Process.ProcessId == 0 ? "System Idle Process" : process.Name, process.Process.ProcessId.ToString(), userName }); if (!string.IsNullOrEmpty(fileName)) { Icon fileIcon = FileUtils.GetFileIcon(fileName); if (fileIcon != null) { imageList.Images.Add(process.Process.ProcessId.ToString(), fileIcon); item.ImageKey = process.Process.ProcessId.ToString(); } } if (string.IsNullOrEmpty(item.ImageKey)) { item.ImageKey = "generic_process"; } listProcesses.Items.Add(item); } listProcesses.EndUpdate(); }
public async Task <IActionResult> StudentLogin(LoginInformation loginInformation) { // find 1 account with matching username in Account var ac = await _context.Account.SingleOrDefaultAsync(a => a.Username == loginInformation.Username); if (ac != null) { var isCorrectClient = ac.Id.StartsWith("STU"); if (isCorrectClient) { // check matching password if (ac.Password == PasswordHandle.GetInstance().EncryptPassword(loginInformation.Password, ac.Salt)) { // check if account is deactivated if (ac.Status != AccountStatus.Deactive) { // check if account is logged in elsewhere var cr = await _context.Credential.SingleOrDefaultAsync(c => c.OwnerId == ac.Id); var accessToken = TokenHandle.GetInstance().GenerateToken(); if (cr != null) // if account has logged in { cr.AccessToken = accessToken; // update token _context.Credential.Update(cr); await _context.SaveChangesAsync(); return(Ok(accessToken)); } // create new credential with AccountId var firstCredential = new Credential { OwnerId = ac.Id, AccessToken = accessToken }; // save token _context.Credential.Add(firstCredential); await _context.SaveChangesAsync(); return(Ok(accessToken)); } return(Forbid("Your account is deactivated. Contact managers for more information.")); } Response.StatusCode = (int)HttpStatusCode.Forbidden; return(new JsonResult(new ResponseError("UserName or Password is incorrect", (int)HttpStatusCode.Forbidden))); } Response.StatusCode = (int)HttpStatusCode.Forbidden; return(new JsonResult(new ResponseError("Client is Wrong", (int)HttpStatusCode.Forbidden))); } Response.StatusCode = (int)HttpStatusCode.Forbidden; return(new JsonResult(new ResponseError("UserName or Password is incorrect", (int)HttpStatusCode.Forbidden))); }
public void KphAssignImpersonationToken(ThreadHandle threadHandle, TokenHandle tokenHandle) { byte *inData = stackalloc byte[8]; *(int *)inData = threadHandle; *(int *)(inData + 4) = tokenHandle; _fileHandle.IoControl(CtlCode(Control.KphAssignImpersonationToken), inData, 8, null, 0); }
public static extern bool DuplicateTokenEx ( TokenHandle existingTokenHandle, uint desiredAccess, IntPtr threadAttributes, int tokenType, int impersonationLevel, ref TokenHandle duplicateTokenHandle );
public static extern bool LogonUser ( string username, string domain, IntPtr password, LogonType dwLogonType, LogonProvider dwLogonProvider, out TokenHandle logonToken );
private void buttonLinkedToken_Click(object sender, EventArgs e) { using (TokenHandle thandle = _object.GetToken(TokenAccess.Query)) { TokenWithLinkedToken token = new TokenWithLinkedToken(thandle); TokenWindow window = new TokenWindow(token); window.ShowDialog(); } }
public static ProcessInformation CreateWithToken(TokenHandle tokenHandle, ProcessLogonFlags logonFlags, string applicationName, string commandLine, ProcessCreationFlags creationFlags, EnvironmentBlockHandle environment, string currentDirectory, ProcessStartInfo startupInfo) { ProcessInformationOut processInformation; if (!NativeMethods.CreateProcessWithTokenW(tokenHandle, logonFlags, applicationName, commandLine, creationFlags, environment, currentDirectory, startupInfo, out processInformation) || processInformation.ProcessHandle == IntPtr.Zero || processInformation.ThreadHandle == IntPtr.Zero) { ErrorHelper.ThrowCustomWin32Exception(); } return(new ProcessInformation(processInformation.ProcessHandle, processInformation.ProcessId, processInformation.ThreadHandle, processInformation.ThreadId)); }
public static EnvironmentBlockHandle Create(TokenHandle token, bool inherit) { EnvironmentBlockHandle environmentBlockHandle; if (!NativeMethods.CreateEnvironmentBlock(out environmentBlockHandle, token, inherit)) { ErrorHelper.ThrowCustomWin32Exception(); } return(environmentBlockHandle); }
public void ProcessRequest(HttpContext context) { System.Collections.Generic.Dictionary <string, string> content = ContentParser.FromURL(context); // Start handling TokenHandle handler = new TokenHandle(content, "prop"); TokenHandleResult result = handler.HandleResult; context.Response.ContentType = "application/json"; context.Response.Write(result.ToString()); context.Response.StatusCode = Convert.ToInt32(result.StatusCode); }
public static EnvironmentBlockHandle Create(TokenHandle token, IDictionary <string, string> extraEnvironmentVariables) { using (var environment = Create(token, false)) { var current = environment.GetEnvironmentVariables(); foreach (var extraEnvironmentVariable in extraEnvironmentVariables) { current[extraEnvironmentVariable.Key] = extraEnvironmentVariable.Value; } return(Create(current)); } }
public static extern bool CreateProcessAsUser ( TokenHandle logonToken, string applicationName, StringBuilder commandLineArgs, Kernel32.Kernel32.SecurityAttributes processAttributes, Kernel32.Kernel32.SecurityAttributes threadAttributes, bool inheritHandles, Kernel32.Kernel32.CreationFlags creationFlags, IntPtr lpEnvironment, string currentDirectory, ref Kernel32.Kernel32.StartupInfo startupInfo, out Kernel32.Kernel32.ProcessInformation processInformation );
public static void Main(string[] args) { using (var windowsIdentity = WindowsIdentity.GetCurrent()) { using (var token = new TokenHandle(windowsIdentity)) { var groups = token.GetGroupsTokenInformation(TokenInformationClass.TokenLogonSid); SecurityIdentifier securityIdentifier = groups.Single().SecurityIdentifier; Console.WriteLine("Is Account: {0}", securityIdentifier.IsAccountSid()); Console.WriteLine("SID: {0}", securityIdentifier); Console.WriteLine("ProfilePath: {0}", token.GetUserProfileDirectory().FullName); } } }
public static ProcessInformation CreateAsUser(TokenHandle tokenHandle, string applicationName, string commandLine, bool inheritHandles, ProcessCreationFlags creationFlags, EnvironmentBlockHandle environmentHandle, string currentDirectory, ProcessStartInfo startInfo, ProcessSecurity processSecurity = null, ThreadSecurity threadSecurity = null) { using (var processSecurityAttributes = processSecurity == null ? new SecurityAttributes() : new SecurityAttributes(processSecurity)) { using (var threadSecurityAttributes = threadSecurity == null ? new SecurityAttributes() : new SecurityAttributes(threadSecurity)) { ProcessInformationOut processInformation; if (!NativeMethods.CreateProcessAsUser(tokenHandle, applicationName, commandLine, processSecurityAttributes, threadSecurityAttributes, inheritHandles, creationFlags, environmentHandle ?? new EnvironmentBlockHandle(), currentDirectory, startInfo, out processInformation) || processInformation.ProcessHandle == IntPtr.Zero || processInformation.ThreadHandle == IntPtr.Zero) { ErrorHelper.ThrowCustomWin32Exception(); } return(new ProcessInformation(processInformation.ProcessHandle, processInformation.ProcessId, processInformation.ThreadHandle, processInformation.ThreadId)); } } }
public static Token ToToken3(this TokenHandle tokenHandle, IClientStore store) { var token = new Token(tokenHandle.Type) { Audience = tokenHandle.Audience, Claims = tokenHandle.Claims.ToClaims(), Client = store.FindClientByIdAsync(tokenHandle.ClientId).Result, CreationTime = tokenHandle.CreationTime, Issuer = tokenHandle.Issuer, Lifetime = tokenHandle.Lifetime, Type = tokenHandle.Type, Version = tokenHandle.Version }; return(token); }
public static string GetIntegrity(this TokenHandle tokenHandle, out int integrityLevel) { var groups = tokenHandle.Groups; string integrity = null; integrityLevel = 0; foreach (Sid t in groups) { if ((t.Attributes & SidAttributes.IntegrityEnabled) != 0) { integrity = t.GetFullName(false).Replace(" Mandatory Level", string.Empty); switch (integrity) { case "Untrusted": integrityLevel = 0; break; case "Low": integrityLevel = 1; break; case "Medium": integrityLevel = 2; break; case "High": integrityLevel = 3; break; case "System": integrityLevel = 4; break; case "Installer": integrityLevel = 5; break; } } t.Dispose(); } return(integrity); }
/// <summary> /// Checks whether the security descriptor grants a set of access rights to a client. /// </summary> /// <param name="tokenHandle">A handle to a token which represents the client.</param> /// <param name="desiredAccess">The access rights requested by the client.</param> /// <param name="genericMapping">A structure which defines how generic access rights are to be mapped.</param> /// <param name="grantedAccess">A variable which receives the granted access rights.</param> /// <returns>Success if access was granted, otherwise another NT status value.</returns> public NtStatus CheckAccess(TokenHandle tokenHandle, int desiredAccess, GenericMapping genericMapping, out int grantedAccess) { NtStatus accessStatus; int privilegeSetLength = 0; Win32.NtAccessCheck( this, tokenHandle, desiredAccess, ref genericMapping, IntPtr.Zero, ref privilegeSetLength, out grantedAccess, out accessStatus ).ThrowIf(); return(accessStatus); }
public static string GetIntegrity(this TokenHandle tokenHandle, out int integrityLevel) { var groups = tokenHandle.GetGroups(); string integrity = null; integrityLevel = 0; for (int i = 0; i < groups.Length; i++) { if ((groups[i].Attributes & SidAttributes.IntegrityEnabled) != 0) { integrity = groups[i].GetFullName(false).Replace(" Mandatory Level", ""); if (integrity == "Untrusted") { integrityLevel = 0; } else if (integrity == "Low") { integrityLevel = 1; } else if (integrity == "Medium") { integrityLevel = 2; } else if (integrity == "High") { integrityLevel = 3; } else if (integrity == "System") { integrityLevel = 4; } else if (integrity == "Installer") { integrityLevel = 5; } } groups[i].Dispose(); } return(integrity); }
public static bool Impersonate(string userName, string domain, string password, TokenImpersonationLevel impersonationLevel) { lock (_syncRoot) { var threadID = Thread.CurrentThread.ManagedThreadId; if (IsCurrentlyImpersonated) { Revert(); } var newUserToken = new TokenHandle(); var luRet = NativeMethods.LogonUser(userName, domain, password, NativeMethods.LOGON32_LOGON_INTERACTIVE, NativeMethods.LOGON32_PROVIDER_DEFAULT, ref newUserToken); if (luRet == false) { newUserToken.Close(); return(false); } var duplicatedUserToken = new TokenHandle(); var dtRet = NativeMethods.DuplicateToken(newUserToken, (Int32)impersonationLevel, ref duplicatedUserToken); if (dtRet == false) { duplicatedUserToken.Close(); newUserToken.Close(); return(false); } try { var newIdentity = new WindowsIdentity(duplicatedUserToken.DangerousGetHandle()); var impersonationContext = newIdentity.Impersonate(); _impersonationPerThreadID.Add(threadID, new TransferBag(newUserToken, duplicatedUserToken, impersonationContext)); return(true); } finally { duplicatedUserToken.Close(); newUserToken.Close(); } } }
/// <summary> /// Checks whether the security descriptor grants a set of access rights to a client. /// </summary> /// <param name="tokenHandle">A handle to a token which represents the client.</param> /// <param name="desiredAccess">The access rights requested by the client.</param> /// <param name="genericMapping">A structure which defines how generic access rights are to be mapped.</param> /// <param name="grantedAccess">A variable which receives the granted access rights.</param> /// <returns>Success if access was granted, otherwise another NT status value.</returns> public NtStatus CheckAccess(TokenHandle tokenHandle, int desiredAccess, GenericMapping genericMapping, out int grantedAccess) { NtStatus status; NtStatus accessStatus; int privilegeSetLength = 0; if ((status = Win32.NtAccessCheck( this, tokenHandle, desiredAccess, ref genericMapping, IntPtr.Zero, ref privilegeSetLength, out grantedAccess, out accessStatus )) >= NtStatus.Error) { Win32.Throw(status); } return(accessStatus); }
private Privilege(TokenHandle tokenHandle, string name, bool hasLuid, Luid luid, SePrivilegeAttributes attributes) : base(tokenHandle != null) { _tokenHandle = tokenHandle; if (_tokenHandle != null) _tokenHandle.Reference(); _name = name; _attributes = attributes; if (!hasLuid) { if (_name == null) throw new ArgumentException("You must specify either a LUID or a name."); _luid = LsaPolicyHandle.LookupPolicyHandle.LookupPrivilegeValue(_name); } else { _luid = luid; } }
public ImpersonationContext(TokenHandle token) { if (!Win32.ImpersonateLoggedOnUser(token)) Win32.Throw(); }
public void Remove(TokenHandle tokenHandle) { this.SetState(tokenHandle, SePrivilegeAttributes.Removed); }
protected Token(TokenHandle position) { Position = position; }
public QuotedStringToken(string content, TokenHandle position) : base(position) { Content = content; }
public EmptyLineToken(TokenHandle position) : base(position) { }
public Privilege(TokenHandle tokenHandle, Luid luid, SePrivilegeAttributes attributes) : this(tokenHandle, null, true, luid, attributes) { }
public Privilege(TokenHandle tokenHandle, string name, SePrivilegeAttributes attributes) : this(tokenHandle, name, false, Luid.Empty, attributes) { }
private void SetState(TokenHandle tokenHandle, SePrivilegeAttributes attributes) { _attributes = attributes; _tokenHandle.SetPrivilege(_luid, _attributes); }
/// <summary> /// Checks whether the security descriptor grants a set of access rights to a client. /// </summary> /// <param name="tokenHandle">A handle to a token which represents the client.</param> /// <param name="desiredAccess">The access rights requested by the client.</param> /// <param name="genericMapping">A structure which defines how generic access rights are to be mapped.</param> /// <param name="grantedAccess">A variable which receives the granted access rights.</param> /// <returns>Success if access was granted, otherwise another NT status value.</returns> public NtStatus CheckAccess(TokenHandle tokenHandle, int desiredAccess, GenericMapping genericMapping, out int grantedAccess) { NtStatus accessStatus; int privilegeSetLength = 0; Win32.NtAccessCheck( this, tokenHandle, desiredAccess, ref genericMapping, IntPtr.Zero, ref privilegeSetLength, out grantedAccess, out accessStatus ).ThrowIf(); return accessStatus; }
public Privilege(TokenHandle tokenHandle, Luid luid) : this(tokenHandle, luid, 0) { }
public void KphAssignImpersonationToken(ThreadHandle threadHandle, TokenHandle tokenHandle) { byte* inData = stackalloc byte[8]; *(int*)inData = threadHandle; *(int*)(inData + 4) = tokenHandle; _fileHandle.IoControl(CtlCode(Control.KphAssignImpersonationToken), inData, 8, null, 0); }
public Privilege(TokenHandle tokenHandle, string name) : this(tokenHandle, name, 0) { }
public void Enable(TokenHandle tokenHandle) { this.SetState(tokenHandle, SePrivilegeAttributes.Enabled); }
public NtStatus CheckAccess(TokenHandle tokenHandle, int desiredAccess, GenericMapping genericMapping, out int grantedAccess) { NtStatus status; NtStatus accessStatus; int privilegeSetLength = 0; if ((status = Win32.NtAccessCheck( this, tokenHandle, desiredAccess, ref genericMapping, IntPtr.Zero, ref privilegeSetLength, out grantedAccess, out accessStatus )) >= NtStatus.Error) Win32.ThrowLastError(status); return accessStatus; }
public CommentToken(string type, string content, TokenHandle position) : base(position) { Type = type; Content = content; }
public DirectiveToken(string directive, TokenHandle position) : base(position) { Directive = directive; }
public EnvironmentBlock(TokenHandle tokenHandle) { if (!Win32.CreateEnvironmentBlock(out _environment, tokenHandle, false)) Win32.Throw(); }
public TokenWithLinkedToken(TokenHandle token) { _token = token; }