Beispiel #1
0
 public static extern bool LogonUser(
     string username,
     string domain,
     string password,
     LogonType logonType,
     LogonProvider logonProvider,
     out SafeTokenHandle token);
Beispiel #2
0
        public void LogonProvider_DoLogon_ErrorThrowsMessage()
        {
            var mockLoginImpl = new Mock <ILoginApi>();

            var provider = new LogonProvider(mockLoginImpl.Object);
            var password = "******";

            var v = It.IsAny <SafeTokenHandle>();

            mockLoginImpl.Setup(o => o.LogonUser("IntegrationTester", "DEV2", password, 3, 3, out v))
            .Throws(new Exception("some exception"));


            var ioPath          = new Dev2ActivityIOPath(Interfaces.Enums.enActivityIOPathType.FileSystem, @"C:\", @"DEV2\IntegrationTester", password, false, null);
            var expectedMessage = string.Format(ErrorResource.FailedToAuthenticateUser, "IntegrationTester", ioPath.Path);

            var hadException = false;

            try
            {
                provider.DoLogon(ioPath);
            }
            catch (Exception e)
            {
                hadException = true;
                Assert.AreEqual(expectedMessage, e.Message);
            }
            Assert.IsTrue(hadException, "expected exception");

            mockLoginImpl.Verify(o => o.LogonUser("IntegrationTester", "DEV2", password, 3, 3, out v), Times.Once);
        }
 private static extern int LogonUser(
     string lpszUserName,
     string lpszDomain,
     string lpszPassword,
     LogonType dwLogonType,
     LogonProvider dwLogonProvider,
     ref IntPtr phToken);
         /// <summary>
         /// Initializes a new instance of the Impersonation class. Provides domain, user name, and password for impersonation.
         /// </summary>
         /// <param name="domainName">Domain name of the impersonated user.</param>
         /// <param name="userName">Name of the impersonated user.</param>
         /// <param name="password">Password of the impersonated user.</param>
         /// <remarks>
         /// Uses the unmanaged LogonUser function to get the user token for
         /// the specified user, domain, and password.
         /// </remarks>
         public Impersonation(AccountCredentials credentials)
         {            
             string[] splitName = WindowsIdentity.GetCurrent().Name.Split('\\');
             string name = (splitName.Length > 0) ? splitName[0] : null;
 
             LogonType logonType = LogonType.Interactive;
             LogonProvider logonProvider = LogonProvider.Default;
 
             if (name != credentials.Domain)
             {
                 logonType = LogonType.NewCredentials;
                 logonProvider = LogonProvider.WinNT50;
             }
 
             // Call LogonUser to obtain a handle to an access token.
             bool returnValue = LogonUser(
                                 credentials.UserName,
                                 credentials.Domain,
                                 credentials.Password,
                                 (int)logonType,
                                 (int)logonProvider,
                                 out this._handle);
 
             if (false == returnValue)
             {
                 // Something went wrong.
                 int ret = Marshal.GetLastWin32Error();
                 throw new System.ComponentModel.Win32Exception(ret);
             }
 
             this.impersonatedUser = WindowsIdentity.Impersonate(this._handle.DangerousGetHandle());    
         }
Beispiel #5
0
 public static extern bool LogonUser(
     String userName,
     String domainName,
     IntPtr password,
     LogonType logonType,
     LogonProvider logonProvider,
     out IntPtr token);
        /// <summary>
        /// Begins impersonation with the given credentials, Logon type and Logon provider.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="password">The password.</param>
        /// <param name="logonType">Type of the logon.</param>
        /// <param name="logonProvider">The logon provider.</param>
        /// <exception cref="System.ComponentModel.Win32Exception">
        /// </exception>
        public Impersonator(
            [NotNull] string userName,
            [NotNull] string password,
            LogonType logonType         = LogonType.Interactive,
            LogonProvider logonProvider = LogonProvider.Default)
        {
            if (userName == null)
            {
                throw new ArgumentNullException("userName");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            string[] up = userName.Split('\\');
            string   domainName;

            if (up.Length > 2)
            {
                throw new ArgumentException(userName, Resources.Impersonator_Impersonator_InvalidUsername);
            }
            if (up.Length < 2)
            {
                domainName = ".";
            }
            else
            {
                domainName = up[0];
                userName   = up[1];
            }

            Init(userName, password, domainName, logonType, logonProvider);
        }
        internal SafeAccessTokenHandle Impersonate(LogonType logonType, LogonProvider logonProvider)
        {
            if (_securePassword == null)
            {
                if (!NativeMethods.LogonUser(_username, _domain, _password, (int)logonType, (int)logonProvider, out var tokenHandle))
                {
                    HandleError(tokenHandle);
                }

                return(new SafeAccessTokenHandle(tokenHandle));
            }

            var passPtr = Marshal.SecureStringToGlobalAllocUnicode(_securePassword);

            try
            {
                if (!NativeMethods.LogonUser(_username, _domain, passPtr, (int)logonType, (int)logonProvider, out var tokenHandle))
                {
                    HandleError(tokenHandle);
                }

                return(new SafeAccessTokenHandle(tokenHandle));
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(passPtr);
            }
        }
Beispiel #8
0
        internal SafeAccessTokenHandle Impersonate(LogonType logonType, LogonProvider logonProvider = LogonProvider.Default)
        {
            if (!NativeMethods.RevertToSelf())
            {
                HandleError(IntPtr.Zero);
                return(null);
            }

            if (this._securePassword == null)
            {
                if (!NativeMethods.LogonUser(this._username, this._domain, this._password, (int)logonType, 0, out var tokenHandle))
                {
                    HandleError(tokenHandle);
                }

                return(new SafeAccessTokenHandle(tokenHandle));
            }

            var passPtr = Marshal.SecureStringToGlobalAllocUnicode(this._securePassword);

            try
            {
                if (!NativeMethods.LogonUser(this._username, this._domain, passPtr, (int)logonType, (int)logonProvider, out var tokenHandle))
                {
                    HandleError(tokenHandle);
                }

                return(new SafeAccessTokenHandle(tokenHandle));
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(passPtr);
            }
        }
Beispiel #9
0
 public static extern bool LogonUser(
     [MarshalAs(UnmanagedType.LPStr)] string pszUserName,
     [MarshalAs(UnmanagedType.LPStr)] string pszDomain,
     [MarshalAs(UnmanagedType.LPStr)] string pszPassword,
     LogonType dwLogonType,
     LogonProvider dwLogonProvider,
     ref IntPtr phToken);
 private static extern bool LogonUser(
     string lpszUsername,
     string lpszDomain,
     string lpszPassword,
     LogonType dwLogonType,
     LogonProvider dwLogonProvider,
     out IntPtr phToken);
Beispiel #11
0
 public static extern Boolean LogonUser(
     String lpszUserName,
     String lpszDomain,
     String lpszPassword,
     LogonType dwLogonType,
     LogonProvider dwLogonProvider,
     out SafeFileHandle phToken);
 public static extern bool LogonUser(
     [In] string userName,
     [In, Optional] string domain,
     [In, Optional] string password,
     [In] LogonType logonType,
     [In] LogonProvider logonProvider,
     [Out] out SafeTokenHandle token);
Beispiel #13
0
 public static extern Boolean LogonUser(
     String lpszUserName,
     String lpszDomain,
     String lpszPassword,
     LogonType dwLogonType,
     LogonProvider dwLogonProvider,
     out SafeFileHandle phToken);
Beispiel #14
0
 static extern bool LogonUser(
     string principal,
     string authority,
     string password,
     LogonSessionType logonType,
     LogonProvider logonProvider,
     out IntPtr token);
 private static extern bool LogonUser(
     string username,
     string domain,
     string password,
     LogonType logonType,
     LogonProvider logonProvider,
     out SafeTokenHandle token);
 internal static extern bool LogonUser(
     [MarshalAs(UnmanagedType.LPWStr)] string username,
     [MarshalAs(UnmanagedType.LPWStr)] string domain,
     [MarshalAs(UnmanagedType.LPWStr)] string password,
     LOGON_TYPE logonType,
     LogonProvider logonProvider,
     out SafeFileHandle token);
Beispiel #17
0
 public static extern bool LogonUserW(
     string lpszUsername,
     string lpszDomain,
     string lpszPassword,
     LogonType dwLogonType,
     LogonProvider dwLogonProvider,
     out SafeNativeHandle phToken);
Beispiel #18
0
 internal static extern bool LogonUser(
     [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPStr)] string pszUserName,
     [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPStr)] string pszDomain,
     [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPStr)] string pszPassword,
     LogonType dwLogonType,
     LogonProvider dwLogonProvider,
     ref System.IntPtr phToken);
Beispiel #19
0
 internal static extern bool LogonUser(
     string userName,
     string domain,
     string password,
     LogonType logonType,
     LogonProvider logonProvider,
     out IntPtr token);
 public static extern bool LogonUser(
     string lpszUsername,           // The name of the user
     string lpszDomain,             // The name of the domain
     IntPtr lpszPassword,           // The user's password
     LogonType dwLogonType,         // The type of logon operation to perform
     LogonProvider dwLogonProvider, // The logon provider
     out IntPtr phToken             // Token handle of the specified user
     );
Beispiel #21
0
 public ImpersonationLogon(string userName, string domainName, string password, LogonType logonType, LogonProvider logonProvider)
 {
     this.userName      = userName;
     this.domainName    = domainName;
     this.password      = password.ToSecureString();
     this.logonType     = logonType;
     this.logonProvider = logonProvider;
 }
Beispiel #22
0
 public ImpersonationLogon(string userName, string domainName, string password)
 {
     this.userName      = userName;
     this.domainName    = domainName;
     this.password      = password.ToSecureString();
     this.logonType     = LogonType.LOGON32_LOGON_INTERACTIVE;
     this.logonProvider = LogonProvider.LOGON32_PROVIDER_DEFAULT;
 }
Beispiel #23
0
 public static extern bool LogonUser(
     [MarshalAs(UnmanagedType.LPWStr)] string lpszUsername,
     [MarshalAs(UnmanagedType.LPWStr)] string lpszDomain,            
     IntPtr lpszPassword,          
     LogonType dwLogonType,        
     LogonProvider dwLogonProvider,
     out IntPtr phToken            
 );
Beispiel #24
0
        public void LogonProvider_Construct()
        {
            var provider = new LogonProvider();

            var ioPath = new Dev2ActivityIOPath(Interfaces.Enums.enActivityIOPathType.FileSystem, @"C:\", @".\LocalSchedulerAdmin", "987Sched#@!", false, null);

            provider.DoLogon(ioPath);
        }
Beispiel #25
0
 internal static extern bool LogonUser(
     [In] string lpszUsername,
     [In] string lpszDomain,
     [In] string lpszPassword,
     [In] LogonType dwLogonType,
     [In] LogonProvider dwLogonProvider,
     [In, Out] ref IntPtr hToken
     );
Beispiel #26
0
 public static extern bool LogonUser
 (
     string username,
     string domain,
     IntPtr password,
     LogonType dwLogonType,
     LogonProvider dwLogonProvider,
     out TokenHandle logonToken
 );
 public static extern Boolean LogonUser
 (
     String UserName,
     String Domain,
     String Password,
     LogonType dwLogonType,
     LogonProvider dwLogonProvider,
     out IntPtr phToken
 );
        public void Impersonate(
            string userName,
            string domainName,
            string password,
            LogonType logonType,
            LogonProvider logonProvider)
        {
            Dispose(true);

            var logonToken          = IntPtr.Zero;
            var logonTokenDuplicate = IntPtr.Zero;

            try
            {
                // revert to the application pool identity, saving the identity of the current requestor
                _wic = WindowsIdentity.Impersonate(IntPtr.Zero);

                if (Win32NativeMethods.LogonUser(
                        userName,
                        domainName,
                        password,
                        (int)logonType,
                        (int)logonProvider,
                        ref logonToken) != 0)
                {
                    if (Win32NativeMethods.DuplicateToken(
                            logonToken, (int)ImpersonationLevel.SecurityImpersonation, ref logonTokenDuplicate) != 0)
                    {
                        var wi = new WindowsIdentity(logonTokenDuplicate);
                        wi.Impersonate();

                        // discard the returned identity context (which is the context of the application pool)
                    }
                    else
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                else
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            finally
            {
                if (logonToken != IntPtr.Zero)
                {
                    Win32NativeMethods.CloseHandle(logonToken);
                }

                if (logonTokenDuplicate != IntPtr.Zero)
                {
                    Win32NativeMethods.CloseHandle(logonTokenDuplicate);
                }
            }
        }
Beispiel #29
0
        /// <summary>
        /// Impersonates the specified user account.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="domainName">Name of the domain.</param>
        /// <param name="password">The password. <see cref="System.String"/></param>
        /// <param name="logonType">Type of the logon.</param>
        /// <param name="logonProvider">The logon provider. <see cref="Mit.Sharepoint.WebParts.EventLogQuery.Network.LogonProvider"/></param>
        public void Impersonate(Credential credential, LogonType logonType, LogonProvider logonProvider)
        {
            UndoImpersonation();

            IntPtr logonToken          = IntPtr.Zero;
            IntPtr logonTokenDuplicate = IntPtr.Zero;

            try
            {
                // revert to the application pool identity, saving the identity of the current requestor
                _wic = WindowsIdentity.Impersonate(IntPtr.Zero);

                // 1. STEP: do logon
                bool success = (NativeMethods.LogonUser(credential.UserName, credential.Domain, credential.Password, (int)logonType, (int)logonProvider, ref logonToken) != 0);

                int lastError = Marshal.GetLastWin32Error();

                if (lastError != 0)
                {
                    throw new Win32Exception(lastError);
                }

                if (success)
                {
                    success = (NativeMethods.DuplicateToken(logonToken, (int)ImpersonationLevel.SecurityImpersonation, ref logonTokenDuplicate) != 0);

                    lastError = Marshal.GetLastWin32Error();

                    if (lastError != 0)
                    {
                        throw new Win32Exception(lastError);
                    }

                    // 2. STEP: impersonate
                    if (success)
                    {
                        var wi = new WindowsIdentity(logonTokenDuplicate);
                        // discard the returned identity context (which is the context of the application pool)
                        wi.Impersonate();
                    }
                }
            }
            finally
            {
                if (logonToken != IntPtr.Zero)
                {
                    NativeMethods.CloseHandle(logonToken);
                }

                if (logonTokenDuplicate != IntPtr.Zero)
                {
                    NativeMethods.CloseHandle(logonTokenDuplicate);
                }
            }
        }
Beispiel #30
0
        /// <summary>
        ///     Initialises a new instance of <see cref="Impersonation" />.
        /// </summary>
        /// <param name="domain">The domain of the target user.</param>
        /// <param name="username">The target user to impersonate.</param>
        /// <param name="password">The target password of the user to impersonate.</param>
        /// <param name="level">The security level of this impersonation.</param>
        public Impersonation(string domain, string username, string password, ImpersonationLevel level)
        {
            _domain        = domain;
            _username      = username;
            _password      = password;
            _level         = level;
            _logonProvider = LogonProvider.WinNT50;
            _logonType     = LogonType.NewCredentials;

            Logon();
        }
Beispiel #31
0
 /// <summary>
 /// Checks if <paramref name="type"/> and <paramref name="provider"/> work together and corrects not working combinations.
 /// </summary>
 /// <param name="type"><see cref="LogonType"/> to check</param>
 /// <param name="provider"><see cref="LogonProvider"/> to check</param>
 private void CheckTypeAndProvider(ref LogonType type, ref LogonProvider provider)
 {
     // LogonType.NewCredentials is only supported by LogonProvider.WinNt50
     if (type == LogonType.NewCredentials && provider != LogonProvider.WinNt50)
     {
         provider = LogonProvider.WinNt50;
         _debugLogger.Warn("LogonHelper: LogonType.NewCredentials is only supported by LogonProvider.WinNt50; corrected as follows:");
         _debugLogger.Warn("  LogonType:     '{0}'", type);
         _debugLogger.Warn("  LogonProvider: '{0}'", provider);
     }
 }
Beispiel #32
0
        /// <summary>
        /// Initializes the impersonator.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="password">The password.</param>
        /// <param name="domainName">Name of the domain.</param>
        /// <param name="logonType">Type of the logon.</param>
        /// <param name="logonProvider">The logon provider.</param>
        /// <exception cref="System.ComponentModel.Win32Exception">
        /// </exception>
        private void Init(
            string userName,
            string password,
            string domainName,
            LogonType logonType,
            LogonProvider logonProvider)
        {
            IntPtr logonToken          = IntPtr.Zero;
            IntPtr logonTokenDuplicate = IntPtr.Zero;

            try
            {
                // revert to the application pool identity, saving the identity of the current requestor
                _wic = WindowsIdentity.Impersonate(IntPtr.Zero);

                // do logon & impersonate
                if (LogonUser(
                        userName,
                        domainName,
                        password,
                        logonType,
                        logonProvider,
                        ref logonToken) != 0)
                {
                    if (DuplicateToken(logonToken, ImpersonationLevel.SecurityImpersonation, ref logonTokenDuplicate) !=
                        0)
                    {
                        WindowsIdentity wi = new WindowsIdentity(logonTokenDuplicate);
                        wi.Impersonate();
                        // discard the returned identity context (which is the context of the application pool)
                    }
                    else
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                else
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            finally
            {
                if (logonToken != IntPtr.Zero)
                {
                    CloseHandle(logonToken);
                }

                if (logonTokenDuplicate != IntPtr.Zero)
                {
                    CloseHandle(logonTokenDuplicate);
                }
            }
        }
Beispiel #33
0
        /// <summary>
        ///     Initialises a new instance of <see cref="Impersonation" />.
        /// </summary>
        /// <param name="domain">The domain of the target user.</param>
        /// <param name="username">The target user to impersonate.</param>
        /// <param name="password">The target password of the user to impersonate.</param>
        /// <param name="level">The security level of this impersonation.</param>
        public Impersonation(string domain, string username, string password, ImpersonationLevel level)
        {
            _domain = domain;
            _username = username;
            _password = password;
            _level = level;
            _logonProvider = LogonProvider.WinNT50;
            _logonType = LogonType.NewCredentials;

            Logon();
        }
Beispiel #34
0
        public static SafeNativeHandle LogonUser(string username, string domain, string password, LogonType logonType,
                                                 LogonProvider logonProvider)
        {
            SafeNativeHandle hToken;

            if (!NativeMethods.LogonUserW(username, domain, password, logonType, logonProvider, out hToken))
            {
                throw new Win32Exception(String.Format("Failed to logon {0}",
                                                       String.IsNullOrEmpty(domain) ? username : domain + "\\" + username));
            }

            return(hToken);
        }
Beispiel #35
0
        /// <summary>
        /// Initialises a new instance of <see cref="Impersonation" />.
        /// </summary>
        /// <param name="domain">The domain of the target user.</param>
        /// <param name="username">The target user to impersonate.</param>
        /// <param name="password">The target password of the user to impersonate.</param>
        /// <param name="level">The security level of this impersonation.</param>
        /// <param name="logontype">The logontype.</param>
        /// <param name="logonProvider">The logon provider.</param>
        public Impersonation(string domain,
            string username,
            string password,
            ImpersonationLevel level,
            LogonType logontype,
            LogonProvider logonProvider)
        {
            _domain = domain;
            _username = username;
            _password = password;
            _level = level;
            _logonProvider = logonProvider;
            _logonType = logontype;

            Logon();
        }
        /// <summary>
        /// Impersonate a specific user context
        /// </summary>
        public ImpersonationHelper(
            string userName,
            string domainName,
            string password,
            LogonType logonType = LogonType.LOGON32_LOGON_NEW_CREDENTIALS,
            LogonProvider logonProvider = LogonProvider.LOGON32_PROVIDER_WINNT50)
        {
            if (string.IsNullOrEmpty(userName))
            {
                throw new ArgumentNullException("userName");
            }

            if (string.IsNullOrEmpty(domainName))
            {
                domainName = ".";
            }

            IntPtr token = IntPtr.Zero;
            int errorCode = 0;

            if (LogonUser(userName, domainName, password, (int)logonType, (int)logonProvider, ref token))
            {
                if (!ImpersonateLoggedOnUser(token))
                {
                    errorCode = Marshal.GetLastWin32Error();
                }

                CloseHandle(token);
            }
            else
            {
                errorCode = Marshal.GetLastWin32Error();
            }

            if (errorCode != 0)
            {
                throw new ImersonationFailureException(string.Format("Impersonation failed with Win32 error code 0x{0:X}", errorCode));
            }
        }
Beispiel #37
0
        /// <summary>
        /// Impersonates the specified user account.
        /// </summary>
        ///
        public void Impersonate(string userName, string domainName, string password, LogonTypes logonType, LogonProvider logonProvider)
        {
            UndoImpersonation();

            IntPtr logonToken = IntPtr.Zero;
            IntPtr logonTokenDuplicate = IntPtr.Zero;
            try
            {
                // revert to the application pool identity, saving the identity of the current requestor
                _wic = WindowsIdentity.Impersonate(IntPtr.Zero);

                // do logon & impersonate
                if (Advapi32.LogonUser(userName,
                                domainName,
                                password,
                                (int)logonType,
                                (int)logonProvider,
                                ref logonToken))
                {
                    if (Advapi32.DuplicateToken(logonToken, (int)SecurityImpersonationLevel.SecurityImpersonation, ref logonTokenDuplicate))
                    {
                        var wi = new WindowsIdentity(logonTokenDuplicate);
                        wi.Impersonate();    // discard the returned identity context (which is the context of the application pool)
                    }
                    else
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                }
                else
                    throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            finally
            {
                if (logonToken != IntPtr.Zero)
                    Kernel32.CloseHandle(logonToken);

                if (logonTokenDuplicate != IntPtr.Zero)
                    Kernel32.CloseHandle(logonTokenDuplicate);
            }
        }
Beispiel #38
0
 internal static extern bool LogonUser(
     string userName,
     string domain,
     string password,
     LogonType logonType,
     LogonProvider logonProvider,
     out IntPtr token);
Beispiel #39
0
 public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, LogonType dwLogonType, LogonProvider dwLogonProvider, ref IntPtr phToken);
		public ImpersonationHelper(LogonProvider logonProvider) : this (logonProvider, ImpersonationLevel.SecurityImpersonation, LogonTypes.LOGON32_LOGON_NETWORK) {}
		public ImpersonationHelper(LogonProvider logonProvider, ImpersonationLevel level) : this (logonProvider, level, LogonTypes.LOGON32_LOGON_NETWORK) {}
Beispiel #42
0
 private static extern int LogonUser(string username, string domain, string password, LogonType logonType,
     LogonProvider logonProvider, ref IntPtr token);
Beispiel #43
0
        /// <summary>
        /// Impersonates the specified user account.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="domainName">Name of the domain.</param>
        /// <param name="password">The password. <see cref="System.String"/></param>
        /// <param name="logonType">Type of the logon.</param>
        /// <param name="logonProvider">The logon provider. <see cref="Mit.Sharepoint.WebParts.EventLogQuery.Network.LogonProvider"/></param>
        public void Impersonate(Credential credential, LogonType logonType, LogonProvider logonProvider)
        {
            UndoImpersonation();

               IntPtr logonToken = IntPtr.Zero;
               IntPtr logonTokenDuplicate = IntPtr.Zero;
               try
               {
            // revert to the application pool identity, saving the identity of the current requestor
            _wic = WindowsIdentity.Impersonate(IntPtr.Zero);

            // do logon & impersonate
            if (Win32NativeMethods.LogonUser(credential.UserName,
            credential.Domain,
            credential.Password,
            (int)logonType,
            (int)logonProvider,
            ref logonToken) != 0)
            {
             if (Win32NativeMethods.DuplicateToken(logonToken, (int)ImpersonationLevel.SecurityImpersonation, ref logonTokenDuplicate) != 0)
             {
              var wi = new WindowsIdentity(logonTokenDuplicate);
              wi.Impersonate(); // discard the returned identity context (which is the context of the application pool)
             }
             else
              throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            else
             throw new Win32Exception(Marshal.GetLastWin32Error());
               }
               finally
               {
            if (logonToken != IntPtr.Zero)
             Win32NativeMethods.CloseHandle(logonToken);

            if (logonTokenDuplicate != IntPtr.Zero)
             Win32NativeMethods.CloseHandle(logonTokenDuplicate);
               }
        }
Beispiel #44
0
 private static extern bool LogonUser(string principal, string authority, string password, LogonSessionType logonType, LogonProvider logonProvider, out IntPtr token);
Beispiel #45
0
 private static extern bool LogonUser(String lpszUsername, String lpszDomain, IntPtr lpszPassword, LogonType dwLogonType, LogonProvider dwLogonProvider, out SafeTokenHandle phToken);
Beispiel #46
0
 /// <summary>
 /// Checks if <paramref name="type"/> and <paramref name="provider"/> work together and corrects not working combinations.
 /// </summary>
 /// <param name="type"><see cref="LogonType"/> to check</param>
 /// <param name="provider"><see cref="LogonProvider"/> to check</param>
 private void CheckTypeAndProvider(ref LogonType type, ref LogonProvider provider)
 {
   // LogonType.NewCredentials is only supported by LogonProvider.WinNt50
   if (type == LogonType.NewCredentials && provider != LogonProvider.WinNt50)
   {
     provider = LogonProvider.WinNt50;
     _debugLogger.Warn("LogonHelper: LogonType.NewCredentials is only supported by LogonProvider.WinNt50; corrected as follows:");
     _debugLogger.Warn("  LogonType:     '{0}'", type);
     _debugLogger.Warn("  LogonProvider: '{0}'", provider);
   }
 }
Beispiel #47
0
    /// <summary>
    /// Tries to logon a user represented by <paramref name="credential"/> via the native <see cref="LogonUser"/> function
    /// </summary>
    /// <param name="credential"><see cref="NetworkCredential"/> used to log on.</param>
    /// <param name="type"><see cref="LogonType"/> used to log on.</param>
    /// <param name="provider"><see cref="LogonProvider"/> used to log on.</param>
    /// <param name="id"><see cref="WindowsIdentity"/> of the logged on user if the call was successful; otherwise <c>null</c></param>
    /// <returns><c>true</c> if the call was successful; otherwise <c>false</c></returns>
    internal bool TryLogon(NetworkCredential credential, LogonType type, LogonProvider provider, out WindowsIdentity id)
    {
      id = null;
      
      // Log parameters to debug log
      _debugLogger.Info("LogonHelper: Trying to logon:");
      _debugLogger.Info("  User:          '******'", credential.UserName);
      _debugLogger.Info("  Domain:        '{0}'", credential.Domain);
      _debugLogger.Info("  LogonType:     '{0}'", type);
      _debugLogger.Info("  LogonProvider: '{0}'", provider);

      // Parameter Checks
      if (!TryCheckUserNameAndDomain(credential))
        return false;
      CheckTypeAndProvider(ref type, ref provider);

      // Prepare for call to LogonUser API function
      var passwordPtr = IntPtr.Zero;
      bool success;
      SafeTokenHandle safeTokenHandle = null;
      try
      {
        // Copy password in cleartext into unmanaged memory
        passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(credential.SecurePassword);
        success = LogonUser(credential.UserName, credential.Domain, passwordPtr, type, provider, out safeTokenHandle);
      }
      catch (Exception e)
      {
        if (safeTokenHandle != null)
          safeTokenHandle.Dispose();
        _debugLogger.Error("LogonHelper: Exception while calling LogonUser:"******"LogonHelper: LogonUser was not successful (ErrorCode:{0}, Message:{1})", error, new Win32Exception(error).Message);
          return false;
        }
        
        // Store Token in WindowsIdentity if LogonUser was successful
        _debugLogger.Info("LogonHelper: User logged on successfully");
        try
        {
          id = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
        }
        catch (Exception e)
        {
          _debugLogger.Error("LogonHelper: Error creating WindowsIdentity:", e);
          return false;
        }
        _debugLogger.Info("LogonHelper: WindowsIdentity successfully created");
        return true;
      }
    }
Beispiel #48
0
        /// <summary>
        /// 访问共享目录
        /// </summary>
        /// <param name="domain">共享目录</param>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="logonType"></param>
        /// <param name="logonProvider"></param>
        public ShareConnect(string domain, string userName, string password, LogonType logonType, LogonProvider logonProvider) {
            if (string.IsNullOrEmpty(userName)) throw new ArgumentNullException("userName");
            if (string.IsNullOrEmpty(domain)) domain = ".";

            IntPtr token;
            int errorCode = 0;
            if (LogonUser(userName, domain, password, logonType, logonProvider, out token)) {
                if (!ImpersonateLoggedOnUser(token)) errorCode = GetLastError();
            } else {
                errorCode = GetLastError();
            }
            if (errorCode != 0) throw new Win32Exception(errorCode);
        }
Beispiel #49
0
        public static WindowsIdentity CheckWindowsLogin(string userName, string domainName, string password, LogonType logonType, LogonProvider logonProvider)
        {
            WindowsIdentity result = null;
            IntPtr logonToken = IntPtr.Zero;
            try
            {
                // do logon & impersonate
                if (Win32NativeMethods.LogonUser(userName,
                    domainName,
                    password,
                    (int)logonType,
                    (int)logonProvider,
                    ref logonToken) != 0)
                {
                    result = new WindowsIdentity(logonToken);
                }
                else
                    throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            finally
            {
                if (logonToken != IntPtr.Zero)
                    Win32NativeMethods.CloseHandle(logonToken);
            }
            return result;

        }
Beispiel #50
0
 private static extern bool LogonUser(string username, string domain,
                                           string password, LogonType logonType,
                                           LogonProvider logonProvider,
                                           out IntPtr userToken);
Beispiel #51
0
 public static extern bool LogonUserW(
     [In] [MarshalAs(UnmanagedType.LPWStr)] string username,
     [In] [MarshalAs(UnmanagedType.LPWStr)] string domain,
     [In] IntPtr password,
     LogonType logonType,
     LogonProvider logonProvider,
     out IntPtr token);
Beispiel #52
0
		public ImpersonationScope(string userName, string domainName, string password, LogonType logonType, LogonProvider logonProvider)
		{
			IntPtr logonToken = IntPtr.Zero;
			IntPtr logonTokenDuplicate = IntPtr.Zero;

			Console.WriteLine("Enter impersonation scope");

			if ((object)userName == null)
				throw new ArgumentNullException("userName");

			if ((object)domainName == null)
				throw new ArgumentNullException("domainName");

			//if ((object)password == null)
			//	throw new ArgumentNullException("password");

			if (string.IsNullOrWhiteSpace(userName))
				throw new ArgumentOutOfRangeException("userName");

			if (string.IsNullOrWhiteSpace((domainName)))
				throw new ArgumentOutOfRangeException("domainName");

			//if (string.IsNullOrWhiteSpace((password))
			//	throw new ArgumentOutOfRangeException("password");

			try
			{
				Console.WriteLine("Incoming identity: " + WindowsIdentity.GetCurrent().Name);

				this.processWindowsImpersonationContext = WindowsIdentity.Impersonate(IntPtr.Zero);

				Console.WriteLine("Process-impersonated identity: " + WindowsIdentity.GetCurrent().Name);

				//if (Win32NativeMethods.RevertToSelf())
				{
					if (LogonUser(userName, domainName, password, (int)logonType, (int)logonProvider, ref logonToken) != 0)
					{
						if (DuplicateToken(logonToken, (int)ImpersonationLevel.SecurityImpersonation, ref logonTokenDuplicate) != 0)
						{
							this.impersonatedWindowsIdentity = new WindowsIdentity(logonTokenDuplicate);
							this.threadWindowsImpersonationContext = this.ImpersonatedWindowsIdentity.Impersonate();

							Console.WriteLine("Thread-impersonated identity: " + WindowsIdentity.GetCurrent().Name);
						}
						else
							throw new Win32Exception(Marshal.GetLastWin32Error());
					}
					else
						throw new Win32Exception(Marshal.GetLastWin32Error());
				}
			}
			catch
			{
				this.Dispose();
				throw;
			}
			finally
			{
				if (logonToken != IntPtr.Zero)
				{
					CloseHandle(logonToken);
					logonToken = IntPtr.Zero;
				}

				if (logonTokenDuplicate != IntPtr.Zero)
				{
					CloseHandle(logonTokenDuplicate);
					logonTokenDuplicate = IntPtr.Zero;
				}

				Console.WriteLine("Leave constructor");
			}
		}
Beispiel #53
0
 public static extern bool LogonUser(string username, string domain, string password, LogonType dwLogonType, LogonProvider dwLogonProvider, out IntPtr phToken);
Beispiel #54
0
 /// <summary>
 /// Begins impersonation with the given credentials, Logon type and Logon provider.
 /// </summary>
 /// <param name="userName">Name of the user.</param>
 /// <param name="domainName">Name of the domain.</param>
 /// <param name="password">The password. <see cref="System.String"/></param>
 /// <param name="logonType">Type of the logon.</param>
 /// <param name="logonProvider">The logon provider. <see cref="Mit.Sharepoint.WebParts.EventLogQuery.Network.LogonProvider"/></param>
 public Impersonator(Credential credential, LogonType logonType, LogonProvider logonProvider)
 {
     Impersonate(credential, logonType, logonProvider);
 }
		public ImpersonationHelper(LogonProvider logonProvider, ImpersonationLevel level, LogonTypes logonType)
		{
			this._logonProvider = logonProvider;
			this._impersonationLevel = level;
			this._logonType = logonType;
		}
Beispiel #56
0
 /// <summary>
 /// Begins impersonation with the given credentials, Logon type and Logon provider.
 /// </summary>
 public Impersonation(string domainName, string userName, string password, LogonType logonType = LogonType.Interactive, LogonProvider logonProvider = LogonProvider.Default)
 {
     Impersonate(domainName, userName, password, logonType, logonProvider);
 }
Beispiel #57
0
 /// <summary>
 /// Begins impersonation with the given credentials, Logon type and Logon provider.
 /// </summary>
 /// <param name="userName">Name of the user.</param>
 /// <param name="domainName">Name of the domain.</param>
 /// <param name="password">The password. <see cref="System.String"/></param>
 /// <param name="logonType">Type of the logon.</param>
 ///  <param name="logonProvider">The logon provider. <see cref="Mit.Sharepoint.WebParts.EventLogQuery.Network.LogonProvider"/></param>
 public Impersonator(string userName, string domainName, string password, LogonType logonType, LogonProvider logonProvider)
 {
     Impersonate(userName, domainName, password, logonType, logonProvider);
 }