Пример #1
0
 public void Impersonate()
 {
     //create identity
     WindowsIdentity newId = new WindowsIdentity(this.tokenHandle);
     //start impersonating
     this.impersonatedUser = newId.Impersonate();
 }
Пример #2
0
 public void Impersonate(string domainName, string userName, string password){
     //try
     {
         // Use the unmanaged LogonUser function to get the user token for
         // the specified user, domain, and password.
         const int LOGON32_PROVIDER_DEFAULT = 0;
         // Passing this parameter causes LogonUser to create a primary token.
         const int LOGON32_LOGON_INTERACTIVE = 2;
         tokenHandle = IntPtr.Zero;
         // ---- Step - 1
         // Call LogonUser to obtain a handle to an access token.
         bool returnValue = LogonUser(
                                 userName,
                                 domainName,
                                 password,
                                 LOGON32_LOGON_INTERACTIVE,
                                 LOGON32_PROVIDER_DEFAULT,
                                 ref tokenHandle); // tokenHandle - new security token
         if (false == returnValue){
             int ret = Marshal.GetLastWin32Error();
             throw new System.ComponentModel.Win32Exception(ret);
         }
         // ---- Step - 2
         WindowsIdentity newId = new WindowsIdentity(tokenHandle);
         // ---- Step - 3
         {
             impersonatedUser = newId.Impersonate();
         }
     }
 }
Пример #3
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            try
            {
                IntPtr hToken = IntPtr.Zero;
                IntPtr hTokenDuplicate = IntPtr.Zero;

                if (NativeMethods.LogonUser(txtUsername.Text, txtDomain.Text, txtPassword.Text, (uint)NativeMethods.LogonType.LOGON32_LOGON_INTERACTIVE, (uint)NativeMethods.LogonProvider.LOGON32_PROVIDER_DEFAULT, out hToken))
                {
                    if (NativeMethods.DuplicateToken(hToken, 2, ref hTokenDuplicate))
                    {
                        WindowsIdentity windowsIdentity = new WindowsIdentity(hTokenDuplicate);
                        using (WindowsImpersonationContext impersonationContext = windowsIdentity.Impersonate())
                        {
                            System.Diagnostics.Debug.WriteLine(WindowsIdentity.GetCurrent().Name);

                            MessageBox.Show(this, string.Format("Ready to execute program {0} as {1}\\{2}...", txtProgram.Text, txtDomain.Text, txtUsername.Text), "Diagnostic", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            impersonationContext.Undo();
                        }
                    }
                }
                else
                {
                    MessageBox.Show(this, string.Format("Authentication failed for {0}\\{1}.", txtDomain.Text, txtUsername.Text), "Diagnostic", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }

                if (hToken != IntPtr.Zero) NativeMethods.CloseHandle(hToken);
                if (hTokenDuplicate != IntPtr.Zero) NativeMethods.CloseHandle(hTokenDuplicate);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, string.Format("An error occurred: {0}", ex), "Diagnostic", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Пример #4
0
        public bool ImpersonateValidUser(String userName, String domain, String password)
        {
            System.Security.Principal.WindowsIdentity tempWindowsIdentity;
            IntPtr token          = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            if (RevertToSelf())
            {
                if (LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, 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)
                        {
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return(true);
                        }
                    }
                }
            }
            if (token != IntPtr.Zero)
            {
                CloseHandle(token);
            }
            if (tokenDuplicate != IntPtr.Zero)
            {
                CloseHandle(tokenDuplicate);
            }
            _Token = token;
            return(false);
        }
        public void Enter()
        {
            if (this.IsInContext)
            {
                return;
            }

            this.token = new IntPtr(0);
            try
            {
                this.token = IntPtr.Zero;
                bool logonSuccessfull = NativeMethods.LogonUser(
                   this.username,
                   this.domain,
                   this.password,
                   Logon32LogonInteractive,
                   Logon32ProviderDefault,
                   ref this.token);
                if (logonSuccessfull == false)
                {
                    int error = Marshal.GetLastWin32Error();
                    throw new Win32Exception(error);
                }

                var identity = new WindowsIdentity(this.token);
                this.context = identity.Impersonate();
            }
            catch
            {
                // Catch exceptions here
            }
        }
Пример #6
0
 /// <summary>
 ///   Constructor. Starts the impersonation with the given credentials. Please note that the account that instantiates the Impersonator class needs to have the 'Act as part of operating system' privilege set.
 /// </summary>
 /// <param name="userName"> The name of the user to act as. </param>
 /// <param name="domainName"> The domain name of the user to act as. </param>
 /// <param name="password"> The password of the user to act as. </param>
 public WindowsImpersonatedIdentity(string userName, string domainName, string password)
 {
     var token = IntPtr.Zero;
     var tokenDuplicate = IntPtr.Zero;
     try {
         if (string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(domainName) && string.IsNullOrEmpty(password)) {
             identity = WindowsIdentity.GetCurrent();
         } else {
             if (LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0) {
                 if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) {
                     identity = new WindowsIdentity(tokenDuplicate);
                     impersonationContext = identity.Impersonate();
                 } else {
                     throw new Win32Exception(Marshal.GetLastWin32Error());
                 }
             } else {
                 throw new Win32Exception(Marshal.GetLastWin32Error());
             }
         }
     } finally {
         if (token != IntPtr.Zero) {
             CloseHandle(token);
         }
         if (tokenDuplicate != IntPtr.Zero) {
             CloseHandle(tokenDuplicate);
         }
     }
 }
Пример #7
0
 //Public Sub PerformImpersonatedTask(ByVal username As String, ByVal domain As String, ByVal password As String, ByVal logonType As Integer, ByVal logonProvider As Integer, ByVal methodToPerform As Action)
 public void PerformImpersonatedTask(string username, string domain, string password, int logonType, int logonProvider, Action methodToPerform)
 {
     IntPtr token = IntPtr.Zero;
     if (RevertToSelf())
     {
         if (LogonUser(username, domain, password, logonType, logonProvider, ref token) != 0)
         {
             dynamic identity = new WindowsIdentity(token);
             dynamic impersonationContext = identity.Impersonate();
             if (impersonationContext != null)
             {
                 methodToPerform.Invoke();
                 impersonationContext.Undo();
             }
             // do logging
         }
         else
         {
         }
     }
     if (token != IntPtr.Zero)
     {
         CloseHandle(token);
     }
 }
Пример #8
0
        /// <summary>
        /// 사용자를 가장합니다.
        /// </summary>
        /// <param name="userName">사용자 이름 입니다.</param>
        /// <param name="domain">도메인 이름 입니다.</param>
        /// <param name="password">암호 입니다.</param>
        /// /// <exception cref="SecurityException">가장이 실패할 경우 <c>SecurityException</c>를 던집니다.</exception>
        public void Impersonate(string userName, string domain, string password)
        {
            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            if (RevertToSelf())
            {
                if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                    LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                {
                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {
                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        impersonationContext = tempWindowsIdentity.Impersonate();
                        if (impersonationContext != null)
                        {
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return;
                        }
                    }
                }
            }

            if (token != IntPtr.Zero) CloseHandle(token);
            if (tokenDuplicate != IntPtr.Zero) CloseHandle(tokenDuplicate);

            throw new SecurityException("사용자를 가장하는데 실패했습니다.");
        }
Пример #9
0
        public bool Impersonate(string userName, string domain, string password)
        {
            var token = IntPtr.Zero;
            var tokenDuplicate = IntPtr.Zero;

            if(RevertToSelf())
            {
                if(LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out token))
                {
                    if(DuplicateToken(token, 2, out tokenDuplicate) != 0)
                    {
                        var tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        _impersonationContext = tempWindowsIdentity.Impersonate();
                        if(_impersonationContext != null)
                        {
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return true;
                        }
                    }
                }
            }
            if(token != IntPtr.Zero)
            {
                CloseHandle(token);
            }
            if(tokenDuplicate != IntPtr.Zero)
            {
                CloseHandle(tokenDuplicate);
            }
            return false;
        }
Пример #10
0
        public PerformanceCounterRetriever(string server, string domain, string user, string password)
        {
            if (string.IsNullOrWhiteSpace(server))
                throw new ArgumentException($"Null/blank {nameof(server)} specified");
            if (string.IsNullOrWhiteSpace(domain))
                throw new ArgumentException($"Null/blank {nameof(domain)} specified");
            if (string.IsNullOrWhiteSpace(user))
                throw new ArgumentException($"Null/blank {nameof(user)} specified");
            if (password == null)
                throw new ArgumentNullException(nameof(password));

            try
            {
                var userHandle = new IntPtr(0);
                var logonSuccess = LogonUser(user, domain, password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, ref userHandle);
                if (!logonSuccess)
                    throw new Exception("LogonUser failed");
                _identity = new WindowsIdentity(userHandle);
                _context = _identity.Impersonate();
                _server = server;
                _disposed = false;
            }
            finally
            {
                Dispose();
            }
        }
 public void Enter()
 {
     if (this.IsInContext) return;
     m_Token = new IntPtr(0);
     try
     {
         m_Token = IntPtr.Zero;
         bool logonSuccessfull = LogonUser(
            m_Username,
            m_Domain,
            m_Password,
            LOGON32_LOGON_INTERACTIVE,
            LOGON32_PROVIDER_DEFAULT,
            ref m_Token);
         if (logonSuccessfull == false)
         {
             int error = Marshal.GetLastWin32Error();
             throw new Win32Exception(error);
         }
         WindowsIdentity identity = new WindowsIdentity(m_Token);
         m_Context = identity.Impersonate();
     }
     catch (Exception exception)
     {
         // Catch exceptions here
     }
 }
Пример #12
0
        //public void Page_Load(Object s, EventArgs e)
        //{
        //    if (impersonateValidUser("username", "domain", "password"))
        //    {
        //        //Insert your code that runs under the security context of a specific user here.
        //        undoImpersonation();
        //    }
        //    else
        //    {
        //        //Your impersonation failed. Therefore, include a fail-safe mechanism here.
        //    }
        //}

        /// <summary>
        /// 模擬使用者
        /// </summary>
        /// <param name="userName">使用者名稱</param>
        /// <param name="domain">網域名稱</param>
        /// <param name="password">密碼</param>
        /// <returns>True:模擬成功;False:模擬失敗</returns>
        public static bool impersonateValidUser(String userName, 
                                                String domain, 
                                                String password
                                                )
        {
            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            if (RevertToSelf())
            {
                if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                    LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                {
                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {
                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        impersonationContext = tempWindowsIdentity.Impersonate();
                        if (impersonationContext != null)
                        {
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return true;
                        }
                    }
                }
            }
            if (token != IntPtr.Zero)
                CloseHandle(token);
            if (tokenDuplicate != IntPtr.Zero)
                CloseHandle(tokenDuplicate);
            return false;
        }
Пример #13
0
        public void Impersonate(string domainName, string userName, string password)
        {
            try
            {
                const int logon32ProviderDefault = 0;
                const int logon32LogonInteractive = 2;
                TokenHandle = IntPtr.Zero;
                var returnValue = LogonUser(
                                    userName,
                                    domainName,
                                    password,
                                    logon32LogonInteractive,
                                    logon32ProviderDefault,
                                    ref TokenHandle);

                if (false == returnValue)
                {
                    int ret = Marshal.GetLastWin32Error();
                    Console.WriteLine("LogonUser call failed with error code : " + ret);
                    throw new System.ComponentModel.Win32Exception(ret);
                }
                NewId = new WindowsIdentity(TokenHandle);
                ImpersonatedUser = NewId.Impersonate();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occurred. " + ex.Message);
            }
        }
        /// <summary>
        /// 模擬特定使用者帳號
        /// 
        /// reference : http://www.dotblogs.com.tw/puma/archive/2009/02/24/7281.aspx
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns>表示模擬作業前的 Windows 使用者</returns>
        /// <remarks>
        /// Response.Write("CurrentUserName: "******"localhost", "Administrator", "AccountPass");
        /// Response.Write("CurrentUserName: "******"CurrentUserName: " + WindowsIdentity.GetCurrent().Name);
        /// </remarks>
        public WindowsImpersonationContext Impersonate(string domain, string userName, string password)
        {
            WindowsImpersonationContext impersonationContext = null;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            try
            {
                if (RevertToSelf())
                {
                    if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                        LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                    {
                        if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                        {
                            WindowsIdentity tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                            impersonationContext = tempWindowsIdentity.Impersonate();
                        }
                    }
                }
            }
            catch
            {
                ;
            }
            finally
            {
                if (token != IntPtr.Zero)
                    CloseHandle(token);
                if (tokenDuplicate != IntPtr.Zero)
                    CloseHandle(tokenDuplicate);
            }

            return impersonationContext;
        }
Пример #15
0
        /// <summary>
        /// removes the old home folder directory and contents.
        /// </summary>
        /// <param name="strSource">source location of old home folder to remove</param>
        public void DeleteHomeDirectory(string strSource)
        {
            IntPtr admin_token = default(IntPtr);
            WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
            WindowsIdentity wid_admin = null;
            WindowsImpersonationContext wic = null;
            if (LogonUser(Form1._AdminUser, Form1._Domain, Form1._Password, 9, 0, ref admin_token) != 0)
            {
                wid_admin = new WindowsIdentity(admin_token);
                wic = wid_admin.Impersonate();

                try
                {
                    Directory.Delete(strSource, true);
                    Form1.myForm.cbMoveHome.Checked = true;
                    Form1.myForm._Notes.AppendLine();
                    Form1.myForm._Notes.Append("<br>Home folder moved to backup location.<br>");
                }
                catch (Exception ex)
                {
                    Form1.myForm.lblMessage.Text = ex.Message;
                    Form1.myForm.cbMoveHome.Checked = false;
                    Form1.myForm._Notes.AppendLine();
                    Form1.myForm._Notes.Append("<br><b>Error in home folder move process.</b><br>" + ex.Message + "<br>");
                }
            }
        }
Пример #16
0
        public void Impersonate()
        {
            // Create the new Identity from the token
            WindowsIdentity impersonatedID = new WindowsIdentity(this._tokenHandle);

            // Start impersonating as the new ID
            this._impersonatedUser = impersonatedID.Impersonate();
        }
Пример #17
0
 /// <summary>
 /// Starts the impersonation.
 /// </summary>
 public void Impersonate()
 {
     // Create Identity.
     WindowsIdentity newId = new WindowsIdentity(this.tokenHandle);
     
     // Start impersonating.
     this.impersonatedUser = newId.Impersonate();
 }
Пример #18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Impersonation"/> class.
        /// </summary>
        /// <param name="windowsId">The Windows ID.</param>
        /// <exception cref="ArgumentNullException" />
        public Impersonation(WindowsIdentity windowsId)
        {
            if (windowsId == null)
            {
                throw new ArgumentNullException("windowsId");
            }

            this.windowsImpersonationContext = windowsId.Impersonate();
        }
Пример #19
0
        static public WindowsImpersonationContext ImpersinateUser(string sUsername, string sDomain, string sPassword, Log log)
        {

            IntPtr pExistingTokenHandle = new IntPtr(0);
            IntPtr pDuplicateTokenHandle = new IntPtr(0);
            pExistingTokenHandle = IntPtr.Zero;
            pDuplicateTokenHandle = IntPtr.Zero;
            try
            {
                //const int LOGON32_PROVIDER_DEFAULT = 0;
                const int LOGON32_PROVIDER_NT = 3;

                //const int LOGON32_LOGON_INTERACTIVE = 2;
                const int LOGON32_LOGON_NEW_CREDENTIAL = 9;
                bool bImpersonated = LogonUser(sUsername, sDomain, sPassword, LOGON32_LOGON_NEW_CREDENTIAL, LOGON32_PROVIDER_NT, ref pExistingTokenHandle);

                if (false == bImpersonated)
                {
                    int nErrorCode = Marshal.GetLastWin32Error();
                    log.write(LogType.Info, 0, "LogOn", "LogTest", "Log On failed with error code" + nErrorCode);
                    return null;
                }
                log.write(LogType.Info, 0, "LogOn", "LogTest", "Before impersomation" + WindowsIdentity.GetCurrent().Name);
                bool bRetVal = DuplicateToken(pExistingTokenHandle, (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, ref pDuplicateTokenHandle);
                if (false == bRetVal)
                {
                    int nErrorCode = Marshal.GetLastWin32Error();
                    CloseHandle(pExistingTokenHandle);
                    log.write(LogType.Info, 0, "LogOn", "LogTest", "DuplocateToken() failed with error code" + nErrorCode);
                    return null;
                }
                else
                {
                    WindowsIdentity newId = new WindowsIdentity(pDuplicateTokenHandle);
                    WindowsImpersonationContext impersonatedUser = newId.Impersonate();
                    log.write(LogType.Info, 0, "LogOn", "LogSuccess", "After impersonation:" + WindowsIdentity.GetCurrent().Name);
                    return impersonatedUser;
                }

            }
            catch (Exception ex)
            {
                log.write(LogType.Info, 0, "LogOn", "LogFaile", "Logon Fail:" + ex.Message);
            }
            finally
            {
                if (pExistingTokenHandle != IntPtr.Zero)
                    CloseHandle(pExistingTokenHandle);
                if (pDuplicateTokenHandle != IntPtr.Zero)
                    CloseHandle(pDuplicateTokenHandle);
            }

            return null;


        }
        public bool ImpersonateValidUser(String userName, String domain, String password)
        {
            if (!Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["isImpersonate"]))
            {
                return true;
            }

            bool isImpersonated = false;
            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            try
            {
                if (RevertToSelf())
                {
                    if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                    {
                        if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                        {
                            tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                            _impersonationContext = tempWindowsIdentity.Impersonate();
                            if (_impersonationContext != null)
                            {
                                CloseHandle(token);
                                CloseHandle(tokenDuplicate);

                                isImpersonated = true;
                                return isImpersonated;
                            }
                        }
                    }
                    else
                    {
                        //TODO - log on error
                        //int ret = Marshal.GetLastWin32Error();
                        //Console.WriteLine("LogonUser failed with error code : {0}", ret);
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorCode = Marshal.GetLastWin32Error();
                this.Exception = ex;
            }
            finally
            {
                if (token != IntPtr.Zero)
                    CloseHandle(token);
                if (tokenDuplicate != IntPtr.Zero)
                    CloseHandle(tokenDuplicate);
            }
            return isImpersonated;
        }
Пример #21
0
        public ImpersonateUser(string userAndDomanName, string password)
        {
            string userName = string.Empty;
            string domainName = string.Empty;

            if (userAndDomanName.Contains("\\") == true)
            {
                domainName = userAndDomanName.Split('\\')[0];
                userName = userAndDomanName.Split('\\')[1];
            }
            else
            {
                userName = userAndDomanName;
            }

            // Use the unmanaged LogonUser function to get the user token for
            // the specified user, domain, and password.
            // To impersonate a user on this machine, use the local machine
            // name for the domain name.
            const int LOGON32_PROVIDER_DEFAULT = 0;
            // Passing this parameter causes LogonUser to create a primary
            // token.
            const int LOGON32_LOGON_INTERACTIVE = 2;
            _tokenHandle = IntPtr.Zero;
            // Call  LogonUser to obtain a handle to an access token.
            bool returnValue = LogonUser(
                userName,
                domainName,
                password,
                LOGON32_LOGON_INTERACTIVE,
                LOGON32_PROVIDER_DEFAULT,
                ref _tokenHandle);

            if (false == returnValue)
            {
                int ret = Marshal.GetLastWin32Error();
                throw new System.ComponentModel.Win32Exception(ret);
            }

            _duplicateTokenHandle = IntPtr.Zero;
            returnValue = DuplicateToken(_tokenHandle,
            (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
                ref _duplicateTokenHandle);

            if (false == returnValue)
            {
                int ret = Marshal.GetLastWin32Error();
                throw new System.ComponentModel.Win32Exception(ret);
            }

            WindowsIdentity newId = new WindowsIdentity(_duplicateTokenHandle);
            _impersonatedUser = newId.Impersonate();
            _isImpersonating = true;
        }
Пример #22
0
        private static WindowsImpersonationContext ImpersonateUser(string sUsername, string sDomain, string sPassword)
        {
            // initialize tokens
            IntPtr pExistingTokenHandle = IntPtr.Zero;
            IntPtr pDuplicateTokenHandle = IntPtr.Zero;

            // if domain name was blank, assume local machine
            if (sDomain == "")
                sDomain = Environment.MachineName;

            try
            {
                const int LOGON32_PROVIDER_DEFAULT = 0;
                const int LOGON32_LOGON_INTERACTIVE = 2;
                bool bImpersonated = LogonUser(sUsername, sDomain, sPassword,
                    LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);

                // did impersonation fail?
                if (false == bImpersonated)
                {
                    int nErrorCode = Marshal.GetLastWin32Error();
                    throw new ApplicationException("LogonUser() failed with error code: " + nErrorCode + "\r\n");
                }

                bool bRetVal = DuplicateToken(pExistingTokenHandle, (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, ref pDuplicateTokenHandle);

                // did DuplicateToken fail?
                if (false == bRetVal)
                {
                    int nErrorCode = Marshal.GetLastWin32Error();
                    CloseHandle(pExistingTokenHandle); // close existing handle
                    throw new ApplicationException("DuplicateToken() failed with error code: " + nErrorCode + "\r\n");


                }
                else
                {
                    // create new identity using new primary token
                    WindowsIdentity newId = new WindowsIdentity(pDuplicateTokenHandle);
                    WindowsImpersonationContext impersonatedUser = newId.Impersonate();

                    return impersonatedUser;
                }

            }
            finally
            {
                // close handle(s)
                if (pExistingTokenHandle != IntPtr.Zero)
                    CloseHandle(pExistingTokenHandle);
                if (pDuplicateTokenHandle != IntPtr.Zero)
                    CloseHandle(pDuplicateTokenHandle);
            }
        }
Пример #23
0
        /// <summary>
        /// Does the actual impersonation.
        /// </summary>
        /// <param name="userName">The name of the user to act as.</param>
        /// <param name="domainName">The domain name of the user to act as.</param>
        /// <param name="password">The password of the user to act as.</param>
        public void ImpersonateValidUser(string userName, string domain, string encryptedPassword)
        {
            IEncryptor encryptor = new RijndaelEncryptor();
            string password = encryptor.Decrypt(encryptedPassword);
            WindowsIdentity tempWindowsIdentity = null;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            try
            {
                if (RevertToSelf())
                {
                    if (LogonUser(
                    userName,
                    domain,
                    password,
                    LOGON_TYPE_NEW_CREDENTIALS,
                    LOGON32_PROVIDER_DEFAULT,
                    ref token) != 0)
                    {
                        if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                        {
                            tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                            impersonationContext = tempWindowsIdentity.Impersonate();
                        }
                        else
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }
                    }
                    else
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                else
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            finally
            {
                if (token != IntPtr.Zero)
                {
                    CloseHandle(token);
                }
                if (tokenDuplicate != IntPtr.Zero)
                {
                    CloseHandle(tokenDuplicate);
                }
            }
        }
        public Impersonation(string domain, string username, string password)
        {
            var ok = LogonUser(username, domain, password,
                            LOGON32_LOGON_BATCH, 0, out this._handle);
            if (!ok)
            {
                var errorCode = Marshal.GetLastWin32Error();
                throw new ApplicationException(string.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode));
            }

            WindowsIdentity ident = new WindowsIdentity(this._handle.DangerousGetHandle());
            this._context = ident.Impersonate();
        }
 /// <summary>
 /// 开始身份角色模拟。
 /// </summary>
 /// <returns></returns>
 public bool BeginImpersonate()
 {
     bool bLogined = LogonUser(this.imperUsername, this.imperDomain, this.imperPassword, 2, 0, ref this.adminToken);
     if (!bLogined)
         return false;
     bool bDuped = DuplicateToken(this.adminToken, 2, ref this.dupeToken);
     if (!bDuped)
         return false;
     WindowsIdentity fakeid = new WindowsIdentity(this.dupeToken);
     this.imperContext = fakeid.Impersonate();
     this.closed = false;
     return true;
 }
Пример #26
0
        public bool DownLoad(Server server)
        {
            DeployUtil.CleanTransferFolder();

            if (!string.IsNullOrEmpty(server.UserName))
            {
                AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
                WindowsIdentity idnt = new WindowsIdentity(server.UserName, server.Password);
                WindowsImpersonationContext context = idnt.Impersonate();
            }
            File.Copy(server.Uri, DeployUtil.TransferFolder, true);
            return true;
        }
Пример #27
0
        /// <summary>
        /// This method will be called before an opration to login.
        /// </summary>
        /// <param name="Username"></param>
        /// <param name="password"></param>
        /// <param name="domain"></param>
        /// <returns></returns>
        private static WindowsImpersonationContext Login(string Username, string password, string domain)
        {
            IntPtr tokenHandle = new IntPtr(0);
            bool   ret         = LogonUser(Username, domain, password, 9, 0, ref tokenHandle);


            if (!ret)
            {
                throw new Exception("Logon at networkshare failed.");
            }

            System.Security.Principal.WindowsIdentity wid = new System.Security.Principal.WindowsIdentity(tokenHandle);
            return(wid.Impersonate());
        }
        public bool ImpersonateValidUser(String userName, String domain, String password)
        {
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            if (LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                LOGON32_PROVIDER_DEFAULT, ref token) == 0) return false;

            if (DuplicateToken(token, 2, ref tokenDuplicate) == 0) return false;

            var tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
            impersonationContext = tempWindowsIdentity.Impersonate();

            return impersonationContext != null;
        }
 public NetworkImpersonationContext(string domain, string userName, string password)
 {
     if (!LogonUser(userName, domain, password, 9, 0, out _token))
         throw new Win32Exception();
     _identity = new WindowsIdentity(_token);
     try
     {
         _impersonationContext = _identity.Impersonate();
     }
     catch
     {
         _identity.Dispose();
         throw;
     }
 }
Пример #30
0
 public bool Deploy(Project project)
 {
     foreach (var serverId in project.DeployServers)
     {
         var server = Dal.GetServerById(serverId);
         if (!string.IsNullOrEmpty(server.UserName))
         {
             AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
             WindowsIdentity idnt = new WindowsIdentity(server.UserName, server.Password);
             WindowsImpersonationContext context = idnt.Impersonate();
         }
         File.Copy(DeployUtil.TransferFolder, server.Uri, true);
     }
     //TODO config files
     return true;
 }
        private static void RunWebClientWicExample()
        {
            /* some articles said that HttpClient could not pass over the credentials because of async operations, these were some "experiments" using the older WebClient.  Stick with HttpClient if you can */
            System.Security.Principal.WindowsIdentity ident = System.Security.Principal.WindowsIdentity.GetCurrent();
            WindowsImpersonationContext wic = ident.Impersonate();

            try
            {
                WebClient webClient = new WebClient();
                webClient.UseDefaultCredentials = true;
                string serviceUrl = WebApiExampleUrl;
                string json       = webClient.DownloadString(serviceUrl);
                IEnumerable <Product> returnItems = JsonConvert.DeserializeObject <IEnumerable <Product> >(json);
                ShowProducts(returnItems);
            }
            finally
            {
                wic.Undo();
            }
        }
        // Revert to previous impersonation (the only public method)
        /// <include file='doc\WindowsImpersonationContext.uex' path='docs/doc[@for="WindowsImpersonationContext.Undo"]/*' />
        public void Undo()
        {
            if (m_userToken == ZeroHandle)
            {
                if (!_RevertToSelf())
                {
                    throw new SecurityException(Environment.GetResourceString("Argument_RevertSystem"));
                }
            }
            else
            {
                lock (this)
                {
                    if (!_SetThreadToken(m_userToken))
                    {
                        // We need to assert ControlPrincipal because WindowsIdentity.GetCurrent()
                        // requires it.

                        new SecurityPermission(SecurityPermissionFlag.ControlPrincipal).Assert();

                        WindowsIdentity userId    = new WindowsIdentity(m_userToken);
                        WindowsIdentity currentId = WindowsIdentity.GetCurrent();

                        if (!_RevertToSelf())
                        {
                            throw new SecurityException(Environment.GetResourceString("Argument_ImpersonateUser"));
                        }

                        WindowsIdentity newCurrentId = WindowsIdentity.GetCurrent();

                        if (!newCurrentId.Name.Equals(userId.Name))
                        {
                            currentId.Impersonate();
                            throw new SecurityException(Environment.GetResourceString("Argument_ImpersonateUser"));
                        }
                    }
                }
            }
        }
Пример #33
0
        /// <summary>
        /// Impersonates the given user.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="domain">The domain.</param>
        /// <param name="password">The password.</param>
        /// <returns></returns>
        private bool ImpersonateUser(string domain, string userName, SecureString password)
        {
            WindowsIdentity tempWindowsIdentity;
            IntPtr          token          = IntPtr.Zero;
            IntPtr          tokenDuplicate = IntPtr.Zero;

            if (NativeMethods.RevertToSelf())
            {
                IntPtr passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(password);
                if (NativeMethods.LogonUser(userName, domain, passwordPtr, (int)LogonType.LOGON32_LOGON_NETWORK, (int)LogonProvider.LOGON32_PROVIDER_DEFAULT, ref token))
                {
                    if (NativeMethods.DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {
                        tempWindowsIdentity   = new WindowsIdentity(tokenDuplicate);
                        _impersonationContext = tempWindowsIdentity.Impersonate();
                        if (_impersonationContext != null)
                        {
                            _userName = userName;

                            Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr);
                            NativeMethods.CloseHandle(token);
                            NativeMethods.CloseHandle(tokenDuplicate);
                            return(true);
                        }
                    }
                }
                Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr);
            }
            if (token != IntPtr.Zero)
            {
                NativeMethods.CloseHandle(token);
            }
            if (tokenDuplicate != IntPtr.Zero)
            {
                NativeMethods.CloseHandle(tokenDuplicate);
            }
            return(false);
        }
Пример #34
0
        void submitButton_Click(object sender, EventArgs e)
        {
            byte[]     contents            = null;
            string     fullDirPath         = string.Empty;
            string     fullFilePath        = string.Empty;
            bool       overWrite           = false;
            string     xmlMetadataFilePath = String.Empty;
            string     destinationUrl      = String.Empty;
            Hashtable  metadata            = null;
            bool       shouldReturn        = false;
            SPListItem fileItem            = null;


            System.Security.Principal.WindowsIdentity currentIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();

            try
            {
                if (IsValidFile())
                {
                    FileUpload uploadControl = (FileUpload)this.FindControl(UploadFileID);
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        //DownloadFile
                        string parentPath = Path.Combine(Path.GetTempPath(), "LRUpload");
//                           string parentPath = Path.Combine(Environment.CurrentDirectory, "LRUpload");
                        //The directory that will hold the zip file and the extracted files
                        //The directory is named by the filename
                        fullDirPath = Path.Combine(parentPath, Path.GetFileNameWithoutExtension(uploadControl.FileName));
                        //the full zip file path
                        fullFilePath = Path.Combine(fullDirPath, Path.GetFileName(uploadControl.FileName));


                        //Get requried permissions for the temp directory
                        FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.AllAccess, parentPath);
                        perm.Assert();

                        //Create the directory and save the file
                        Directory.CreateDirectory(fullDirPath);
                        uploadControl.PostedFile.SaveAs(fullFilePath);



                        //Unzip
                        try
                        {
                            Compression.Unzip(new FileInfo(fullFilePath), new DirectoryInfo(fullDirPath));
                        }
                        catch (CompressionException)
                        {
                            ShowMessage(LoadResource("InvalidFile"));
                            shouldReturn = true;
                            return;
                        }
                        //Look for the file

                        try
                        {
                            xmlMetadataFilePath = GetXmlMetadataFile(fullDirPath);
                        }

                        catch (FileNotFoundException)
                        {
                            Directory.Delete(fullDirPath, true);
                            ShowMessage(LoadResource("InvalidPackage"));
                            shouldReturn = true;
                            return;
                        }


                        destinationUrl = Path.GetFileName(fullFilePath);
                        //destinationUrl = SourceDocumentLibrary.TrimEnd('/') + "/" + Path.GetFileName(fullFilePath);

                        overWrite = ((CheckBox)this.FindControl(CheckOverrideID)).Checked;
                        //Check if existing files exist
                        if (!overWrite)
                        {
                            if (FileExistsInDocumentLibrary(destinationUrl))
                            {
                                Directory.Delete(fullDirPath, true);
                                ShowMessage(LoadResource("FileAlreadyExists"));
                                shouldReturn = true;
                                return;
                            }
                        }
                        //Read the file contents
                        contents = ReadFileContents(fullFilePath);
                        //Populate file metadata
                        metadata = PopulateMetadata(GetContentTypeByID(GetSelectedContentType()), xmlMetadataFilePath);
                    });

                    if (!shouldReturn)
                    {
                        //Re-impersonate the current user
                        currentIdentity.Impersonate();
                        fileItem = UploadFile(contents, destinationUrl, overWrite).Item;
                        UpdateDocLibItem(fileItem, metadata);
                    }
                    else
                    {
                        return;
                    }

                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        Directory.Delete(fullDirPath, true);
                    });

                    ShowMessage(LoadResource("FileUploaded"));
                }
            }
            catch (Exception ex)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    if (Directory.Exists(fullDirPath))
                    {
                        Directory.Delete(fullDirPath, true);
                    }
                });
                ShowError(ex);
            }
        }
Пример #35
-1
        public WindowsImpersonationContext SetImpersonatedUser(string userName, string domainName, string password)
        {
            WindowsImpersonationContext impersonatedUser = null;
            const int LOGON32_PROVIDER_DEFAULT = 0;
            ////This parameter causes LogonUser to create a primary token.
            const int LOGON32_LOGON_INTERACTIVE = 2;

            try
            {
                SafeTokenHandle safeTokenHandle;
                //// Call LogonUser to obtain a handle to an access token.
                bool returnValue = LogonUser(userName, domainName, password,LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,out safeTokenHandle);

                using (safeTokenHandle)
                {
                    //// Check the identity.
                    Console.WriteLine("Before impersonation: "
                        + WindowsIdentity.GetCurrent().Name);
                    //// Use the token handle returned by LogonUser.
                    WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
                    impersonatedUser = newId.Impersonate();
                }

                return impersonatedUser;
            }
            catch (Exception ex)
            {
                logger.Error(string.Format("SetImpersonatedUser - {0}", ex.Message));
                return impersonatedUser;
            }
        }
Пример #36
-1
        //private static readonly byte[] _genericIv = ConvertEx.FromBase16String("C9DCF37AED8574A1441FD82DB743765C");

        /// <summary>
        /// Impersonates the windows user.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="domain">The domain.</param>
        /// <param name="password">The password.</param>
        /// <returns></returns>
        public static WindowsImpersonationContext ImpersonateWindowsUser(string userName, string domain, string password)
        {
            var token = IntPtr.Zero;
            var tokenDuplicate = IntPtr.Zero;
            try
            {
                if (CoreExtensions.RevertToSelf())
                    if (CoreExtensions.LogonUserA(userName, domain, password, CoreExtensions.LOGON32_LOGON_INTERACTIVE, CoreExtensions.LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                        if (CoreExtensions.DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                        {
                            var tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                            var impersonationContext = tempWindowsIdentity.Impersonate();
                            if (impersonationContext != null)
                            {
                                CoreExtensions.CloseHandle(token);
                                CoreExtensions.CloseHandle(tokenDuplicate);
                                return impersonationContext;
                            }
                        }
            }
            finally
            {
                if (token != IntPtr.Zero)
                    CoreExtensions.CloseHandle(token);
                if (tokenDuplicate != IntPtr.Zero)
                    CoreExtensions.CloseHandle(tokenDuplicate);
            }
            throw new Exception("Unable to login.");
        }