public void Enter() { if (this.IsInContext) { return; } m_Token = new IntPtr(0); try { m_Token = IntPtr.Zero; bool logonSuccessfull = LogonUser( _username, _domain, _password, _type == CredentialsType.Local ? LOGON32_LOGON_INTERACTIVE : LOGON32_LOGON_NEW_CREDENTIALS, _type == CredentialsType.Local ? LOGON32_PROVIDER_DEFAULT : LOGON32_PROVIDER_WINNT50, ref m_Token); if (logonSuccessfull == false) { int error = Marshal.GetLastWin32Error(); throw new ApplicationException(string.Format("Could not impersonate the elevated user. LogonUser returned error code {0}.", error)); } System.Security.Principal.WindowsIdentity identity = new System.Security.Principal.WindowsIdentity(m_Token); _context = identity.Impersonate(); } catch (Exception e) { Console.WriteLine("Could not impersonate the elevated user. It may be invalid credentials."); } }
private void _get_access() { IntPtr _token = new IntPtr(); if (Win32API.LogonUser(_user_name, _domain_name, _password, Win32API.LogonTypes.NewCredentials, Win32API.LogonProviders.Default, out _token)) { _ok = true; Win32API.DuplicateToken(_token, 2, ref _main_token); _win_identity = new System.Security.Principal.WindowsIdentity(_main_token); _win_identity_context = _win_identity.Impersonate(); } else { _ok = false; try { _error = System.Runtime.InteropServices.Marshal.GetLastWin32Error().ToString(); } catch (Exception ex) { } } }
public Impersonation(String username, String domain, String password) { IntPtr userToken = IntPtr.Zero; IntPtr userTokenDuplication = IntPtr.Zero; // Logon with user and get token. bool loggedOn = LogonUser(username, domain, password, LogonType.Interactive, LogonProvider.Default, out userToken); if (loggedOn) { try { // Create a duplication of the usertoken, this is a solution // for the known bug that is published under KB article Q319615. if (DuplicateToken(userToken, 2, ref userTokenDuplication)) { // Create windows identity from the token and impersonate the user. System.Security.Principal.WindowsIdentity identity = new System.Security.Principal.WindowsIdentity(userTokenDuplication); _impersonationContext = identity.Impersonate(); } else { // Token duplication failed! // Use the default ctor overload // that will use Mashal.GetLastWin32Error(); // to create the exceptions details. throw new Exception("Could not copy token"); } GlobalVars.LOGIN_NAME = Environment.UserName.ToString(); } finally { // Close usertoken handle duplication when created. if (!userTokenDuplication.Equals(IntPtr.Zero)) { // Closes the handle of the user. CloseHandle(userTokenDuplication); userTokenDuplication = IntPtr.Zero; } // Close usertoken handle when created. if (!userToken.Equals(IntPtr.Zero)) { // Closes the handle of the user. CloseHandle(userToken); userToken = IntPtr.Zero; } } } else { throw new Exception("Login failed"); //HttpContext.Current.Response.Write("<script>alert('Username or Password is incorrect. Please try again')</script>"); } }
private List <string> GetItems() { System.Security.Principal.WindowsImpersonationContext targetImpersonationContext = null; List <string> list = null; bool res = false; System.Data.SqlClient.SqlConnectionStringBuilder bldr; if (m_serverInfo.windowsAuth) { try { System.Security.Principal.WindowsIdentity wi = Impersonation.GetCurrentIdentity(m_serverInfo.login, m_serverInfo.password); targetImpersonationContext = wi.Impersonate(); } catch (Exception ex) { Idera.SQLsecure.Core.Logger.LogX logX = new Idera.SQLsecure.Core.Logger.LogX("Idera.SQLsecure.UI.Console.Sql.Database"); logX.loggerX.Error("Error Processing Impersonation for retrieving Database objects list (" + m_serverInfo.login + ")", ex); } bldr = Sql.SqlHelper.ConstructConnectionString(m_serverInfo.connectionName, null, null, Utility.Activity.TypeServerOnPremise); } else { bldr = Sql.SqlHelper.ConstructConnectionString(m_serverInfo.connectionName, m_serverInfo.login, m_serverInfo.password, Utility.Activity.TypeServerOnPremise); } switch (m_filterObject.ObjectType) { case RuleObjectType.Database: res = Idera.SQLsecure.UI.Console.Sql.Database.GetTargetDatabases(m_serverInfo.version, m_filterObject.ObjectScope, bldr.ConnectionString, out list); break; case RuleObjectType.Table: res = Idera.SQLsecure.UI.Console.Sql.Database.GetTargetTables(m_serverInfo.version, m_filterObject.ObjectScope, m_databaseFilterObject, bldr.ConnectionString, out list); break; case RuleObjectType.View: res = Idera.SQLsecure.UI.Console.Sql.Database.GetTargetViews(m_serverInfo.version, m_filterObject.ObjectScope, m_databaseFilterObject, bldr.ConnectionString, out list); break; case RuleObjectType.Function: res = Idera.SQLsecure.UI.Console.Sql.Database.GetTargetFunctions(m_serverInfo.version, m_filterObject.ObjectScope, m_databaseFilterObject, bldr.ConnectionString, out list); break; } if (targetImpersonationContext != null) { targetImpersonationContext.Undo(); targetImpersonationContext.Dispose(); targetImpersonationContext = null; } return(res ? list : new List <string>()); }
public static void CopyFile2RemoteFolder(string from, string to, string username, string domain, string password) { IntPtr tokenHandle = new IntPtr(0); int returnValue = LogonUser(username, domain, password, 2, 0, ref tokenHandle); if (returnValue == -1) { throw new Exception("Logon failed."); } System.Security.Principal.WindowsImpersonationContext impersonatedUser = null; System.Security.Principal.WindowsIdentity wid = new System.Security.Principal.WindowsIdentity(tokenHandle); impersonatedUser = wid.Impersonate(); System.IO.File.Copy(from, to, true); impersonatedUser.Undo(); }
private void NTAccess() { IntPtr token = new IntPtr(); IntPtr dupToken = new IntPtr(); //if (WIN32.Win32API.LogonUser("BATCHWEB", "SVIGI-11", "HEXTRADIFERENTE", if (WIN32.Win32API.LogonUser("DOTNETADMIN", "SVWEB02-07", "P@ELL@59", DotNet.Tools.WIN32.Win32API.LogonTypes.NewCredentials, DotNet.Tools.WIN32.Win32API.LogonProviders.Default, out token)) { int ok = WIN32.Win32API.DuplicateToken(token, 2, ref dupToken); } System.Security.Principal.WindowsIdentity id = new System.Security.Principal.WindowsIdentity(dupToken); System.Security.Principal.WindowsImpersonationContext impersonatedUser = id.Impersonate(); impersonatedUser.ToString(); //System.Security.Principal.WindowsPrincipal p = new System.Security.Principal.WindowsPrincipal(id); }
/// <summary> /// 连接网络资源 /// </summary> /// <param name="domain">IP/计算机名</param> /// <param name="userName">用户名</param> /// <param name="password">密码</param> /// <returns></returns> public static bool impersonateValidUser(String domain, String userName, String password) { System.Security.Principal.WindowsIdentity tempWindowsIdentity; IntPtr token = IntPtr.Zero; IntPtr tokenDuplicate = IntPtr.Zero; if (RevertToSelf()) { // 这里使用LOGON32_LOGON_NEW_CREDENTIALS来访问远程资源。 // 如果要(通过模拟用户获得权限)实现服务器程序,访问本地授权数据库可 // 以用LOGON32_LOGON_INTERACTIVE if (LogonUser(userName, domain, password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref token) != 0) { if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) { tempWindowsIdentity = new System.Security.Principal.WindowsIdentity(tokenDuplicate); impersonationContext = tempWindowsIdentity.Impersonate(); if (impersonationContext != null) { System.AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal); System.Security.Principal.IPrincipal pr = System.Threading.Thread.CurrentPrincipal; System.Security.Principal.IIdentity id = pr.Identity; CloseHandle(token); CloseHandle(tokenDuplicate); return(true); } } } } if (token != IntPtr.Zero) { CloseHandle(token); } if (tokenDuplicate != IntPtr.Zero) { CloseHandle(tokenDuplicate); } return(false); }
static void Main(string[] args) { if (!ProcessCommandLine(args)) { while (!System.Console.KeyAvailable) /* do nothing */ } { return; } System.Security.Principal.WindowsIdentity windowsIdentity = new System.Security.Principal.WindowsIdentity(System.Security.Principal.WindowsIdentity.GetCurrent().Token); System.Security.Principal.WindowsImpersonationContext impersonationContext = windowsIdentity.Impersonate(); System.Threading.Thread.CurrentPrincipal = new System.Security.Principal.WindowsPrincipal(windowsIdentity); Mercury.Server.Data.SqlConfiguration enterpriseConfiguration = new Mercury.Server.Data.SqlConfiguration(); enterpriseConfiguration.ServerName = enterpriseServerName; enterpriseConfiguration.DatabaseName = enterpriseDatabaseName; enterpriseConfiguration.TrustedConnection = enterpriseUseTrustedConnection; enterpriseConfiguration.UserName = enterpriseUserName; enterpriseConfiguration.Password = enterprisePassword; try { Mercury.Server.Engine.Processor processor = new Processor(enterpriseServerName, enterpriseDatabaseName, enterpriseUserName, enterprisePassword, environmentDatabaseName); processor.MaximumThreads = processThreadCount; if (processServices) { processor.ProcessSingletons(); processor.ProcessSets(); processor.ProcessAuthorizedServices(); } if (processMetrics) { processor.ProcessMetrics(); } if (processPopulations) { processor.ProcessPopulations(); } } catch (Exception engineException) { Exception currentException = engineException; do { System.Console.WriteLine(currentException.Message); System.Diagnostics.Debug.WriteLine(currentException.Message); currentException = currentException.InnerException; } while (currentException != null); } finally { if (impersonationContext != null) { impersonationContext.Undo(); } } System.Console.WriteLine("Completed."); if (pauseAfterRun) { while (!System.Console.KeyAvailable) /* do nothing */ } { } return; }
/// <summary> /// public constructor /// </summary> /// <param name="upn_uname">UPN user name example : admin@WS01 , where 'WS01' is a domain name </param> /// <param name="password"> password </param> public AutomagicAdmin( string upn_uname, string password ) { try { AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal); System.Security.Principal.WindowsIdentity idnt = new System.Security.Principal.WindowsIdentity(upn_uname, password ); context = idnt.Impersonate(); } catch (Exception) { context = null; } }
// NTRAID#Windows Out Of Band Releases-915506-2005/09/09 // Removed HandleUnexpectedExceptions infrastructure /// <summary> /// Start thread method for asynchronous pipeline execution. /// </summary> private void InvokeThreadProc() { bool incompleteParseException = false; Runspace previousDefaultRunspace = Runspace.DefaultRunspace; try { #if !CORECLR // Impersonation is not supported in CoreCLR. // Used to store old impersonation context if we impersonate. System.Security.Principal.WindowsImpersonationContext oldImpersonationCtxt = null; try { if ((null != InvocationSettings) && (InvocationSettings.FlowImpersonationPolicy)) { // we have a valid identity to impersonate. System.Security.Principal.WindowsIdentity identityToImPersonate = new System.Security.Principal.WindowsIdentity(InvocationSettings.WindowsIdentityToImpersonate.Token); oldImpersonationCtxt = identityToImPersonate.Impersonate(); } #endif // Set up pipeline internal host if it is available. if (InvocationSettings != null && InvocationSettings.Host != null) { InternalHost internalHost = InvocationSettings.Host as InternalHost; if (internalHost != null) // if we are given an internal host, use the external host { LocalRunspace.ExecutionContext.InternalHost.SetHostRef(internalHost.ExternalHost); } else { LocalRunspace.ExecutionContext.InternalHost.SetHostRef(InvocationSettings.Host); } } if (LocalRunspace.ExecutionContext.InternalHost.ExternalHost.ShouldSetThreadUILanguageToZero) { // BUG: 610329. Pipeline execution happens in a new thread. For // Console applications SetThreadUILanguage(0) must be called // inorder for the native MUI loader to load the resources correctly. // ConsoleHost already does this in its entry point..but the same // call is not performed in the Pipeline execution threads causing // cmdlets that load native resources show unreadable messages on // the console. Microsoft.PowerShell.NativeCultureResolver.SetThreadUILanguage(0); } //Put Execution Context In TLS Runspace.DefaultRunspace = this.LocalRunspace; FlowControlException flowControlException = InvokeHelper(); if (flowControlException != null) { // Let pipeline propagate the BreakException. SetPipelineState(Runspaces.PipelineState.Failed, flowControlException); } else { // Invoke finished successfully. Set state to Completed. SetPipelineState(PipelineState.Completed); } #if !CORECLR } finally { // Impersonation is not supported in CoreCLR. // This finally block is needed to handle fxcop CA2124 // If sensitive operations such as impersonation occur in the try block, and an // exception is thrown, the filter can execute before the finally block. For the // impersonation example, this means that the filter would execute as the impersonated user. if (null != oldImpersonationCtxt) { try { oldImpersonationCtxt.Undo(); oldImpersonationCtxt.Dispose(); oldImpersonationCtxt = null; } catch (System.Security.SecurityException) { } } } #endif } catch (PipelineStoppedException ex) { SetPipelineState(PipelineState.Stopped, ex); } catch (RuntimeException ex) { incompleteParseException = ex is IncompleteParseException; SetPipelineState(PipelineState.Failed, ex); SetHadErrors(true); } catch (ScriptCallDepthException ex) { SetPipelineState(PipelineState.Failed, ex); SetHadErrors(true); } catch (System.Security.SecurityException ex) { SetPipelineState(PipelineState.Failed, ex); SetHadErrors(true); } #if !CORECLR // No ThreadAbortException In CoreCLR catch (ThreadAbortException ex) { SetPipelineState(PipelineState.Failed, ex); SetHadErrors(true); } #endif // 1021203-2005/05/09-JonN // HaltCommandException will cause the command // to stop, but not be reported as an error. catch (HaltCommandException) { SetPipelineState(PipelineState.Completed); } finally { // Remove pipeline specific host if it was set. // Win8:464422 Revert the host only if this pipeline invocation changed it // with 464422 a nested pipeline reverts the host, although the nested pipeline did not set it. if ((InvocationSettings != null && InvocationSettings.Host != null) && (LocalRunspace.ExecutionContext.InternalHost.IsHostRefSet)) { LocalRunspace.ExecutionContext.InternalHost.RevertHostRef(); } //Remove Execution Context From TLS Runspace.DefaultRunspace = previousDefaultRunspace; //If incomplete parse exception is hit, we should not add to history. //This is ensure that in case of multiline commands, command is in the //history only once. if (!incompleteParseException) { try { // do not update the history if we are in the debugger and the history is locked, since that may go into a deadlock bool skipIfLocked = LocalRunspace.ExecutionContext.Debugger.InBreakpoint; if (_historyIdForThisPipeline == -1) { AddHistoryEntry(skipIfLocked); } else { UpdateHistoryEntryAddedByAddHistoryCmdlet(skipIfLocked); } } // Updating the history may trigger variable breakpoints; the debugger may throw a TerminateException to // indicate that the user wants to interrupt the variable access. catch (TerminateException) { } } // IsChild makes it possible for LocalPipeline to differentiate // between a true v1 nested pipeline and the "Cmdlets Calling Cmdlets" case. //Close the output stream if it is not closed. if (OutputStream.IsOpen && !IsChild) { try { OutputStream.Close(); } catch (ObjectDisposedException) { } } //Close the error stream if it is not closed. if (ErrorStream.IsOpen && !IsChild) { try { ErrorStream.Close(); } catch (ObjectDisposedException) { } } //Close the input stream if it is not closed. if (InputStream.IsOpen && !IsChild) { try { InputStream.Close(); } catch (ObjectDisposedException) { } } // Clear stream links from ExecutionContext ClearStreams(); //Runspace object maintains a list of pipelines in execution. //Remove this pipeline from the list. This method also calls the //pipeline finished event. LocalRunspace.RemoveFromRunningPipelineList(this); //If async call raise the event here. For sync invoke call, //thread on which invoke is called will raise the event. if (!SyncInvokeCall) { //This should be called after signaling PipelineFinishedEvent and //RemoveFromRunningPipelineList. If it is done before, and in the //Event, Runspace.Close is called which waits for pipeline to close. //We will have deadlock RaisePipelineStateEvents(); } } }
private bool Login() { IntPtr tokenHandle = new IntPtr(0); bool returnValue = LogonUser(UserName, "", Password, 2, 0, ref tokenHandle); if (!returnValue) { if (EnableLog) Log.Write("Login failed", "Login", _FullLogName); return false; } System.Security.Principal.WindowsImpersonationContext impersonatedUser = null; System.Security.Principal.WindowsIdentity wid = new System.Security.Principal.WindowsIdentity(tokenHandle); impersonatedUser = wid.Impersonate(); if (EnableLog) Log.Write("Login successfully", "Login", _FullLogName); return true; }
} // End Function GetProcessInfoByPID public static void Test() { using (System.Security.Principal.WindowsIdentity wi = // new System.Security.Principal.WindowsIdentity(InvalidHandle)) //System.Security.Principal.WindowsIdentity.GetAnonymous()) GetWindowsIdentity(@"domain\username") ) { using (System.Security.Principal.WindowsImpersonationContext context = wi.Impersonate()) { // string n; string d; // string la = GetProcessInfoByPID(System.Diagnostics.Process.GetCurrentProcess().Id, out n, out d); System.Console.WriteLine(IdCache.MyId); string foo = GetProcessUser(System.Diagnostics.Process.GetCurrentProcess()); System.Console.WriteLine(foo); // string bar = GetProcessOwner(System.Diagnostics.Process.GetCurrentProcess().Id); // System.Console.WriteLine(bar); System.Console.WriteLine(wi.Name); System.Console.WriteLine(System.Environment.UserName); System.Security.Principal.WindowsIdentity wai = System.Security.Principal .WindowsIdentity.GetCurrent(true); System.Console.WriteLine(wai.User); } // End Using context } // End Using WindowsIdentity } // End Sub Test
public override void Execute() { try { this.Validate(); string key = base.Args["CompanyName"]; string file = base.Args["NonEncryptedFile"]; string timeout = base.Args["Timeout"]; string formattedString = CommandResources.GetFormattedString(CommandResources.ResourceID.Deploy, new object[] { key, file }); base.WriteLogEntry(LogEntryType.Information, formattedString); // We need to show the identity used to deploy to SSO System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent(); if (null != identity) { WriteLogEntry(LogEntryType.Verbose, string.Format("Current WindowsIdentity: AuthenticationType:{0} - IsAuthenticated:{1} - Name:{2}", identity.AuthenticationType, identity.IsAuthenticated, identity.Name)); using (System.Security.Principal.WindowsImpersonationContext context = identity.Impersonate()) { identity = System.Security.Principal.WindowsIdentity.GetCurrent(); if (null != identity) { WriteLogEntry(LogEntryType.Verbose, string.Format("Impersonated WindowsIdentity: AuthenticationType:{0} - IsAuthenticated:{1} - Name:{2}", identity.AuthenticationType, identity.IsAuthenticated, identity.Name)); } // Deploy the non encrypted SSO XML file. //System.Diagnostics.Debugger.Launch(); string title; DeploySSO deploy = new DeploySSO() { NonEncryptedFile = file, CompanyName = key }; deploy.Overwrite = true; // We always overwrite the current SSO application settings deploy.Log += new DeploySSO.LogHandler(deploy_Log); deploy.Execute(out title); formattedString = CommandResources.GetFormattedString(CommandResources.ResourceID.DeploySuccess, new object[] { title }); base.WriteLogEntry(LogEntryType.Information, formattedString); } } identity = System.Security.Principal.WindowsIdentity.GetCurrent(); if (null != identity) { WriteLogEntry(LogEntryType.Verbose, string.Format("After impersonation WindowsIdentity: AuthenticationType:{0} - IsAuthenticated:{1} - Name:{2}", identity.AuthenticationType, identity.IsAuthenticated, identity.Name)); } base.commandResult = new CommandResult(); } catch (Exception exception2) { base.ShowError(exception2); base.commandResult = new CommandResult(exception2); if ((exception2 is OutOfMemoryException) || (exception2 is StackOverflowException)) { throw; } } }