Beispiel #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="domain"></param>
        /// <param name="logontype"></param>
        /// <param name="provider"></param>
        /// <returns></returns>
        public Int32 Authenticate(String username, String password, String domain, LogOnType logontype, LogOnProvider provider)
        {
            WindowsIdentity _NewId = null;
            IntPtr          _Token = IntPtr.Zero;

            try
            {
                //logon and store the creds in "token"
                Boolean _Result = LogonUser(username, domain, password, (UInt32)logontype, (UInt32)provider, ref _Token);

                //did the login fail?
                if (!_Result)
                {
                    return(Marshal.GetLastWin32Error());
                }
                else
                {
                    //load the token into a WindowsIdentity
                    _NewId            = new WindowsIdentity(_Token, "LogonUser", WindowsAccountType.Normal, true);
                    _ImpersonatedUser = _NewId.Impersonate();

                    this._isAuthenticated = true;
                    return(0);
                }                //end of if-else
            }
            catch (Exception) { throw; }
            finally
            {
                //clear the token
                if (_Token != IntPtr.Zero)
                {
                    CloseHandle(_Token);
                }
            }
        }                //end of Authenticate
Beispiel #2
0
 internal static extern bool LogonUser(
     char[] username,
     char[]?domain,
     char[] password,
     LogOnType logonType,
     LogOnProviderType logonProvider,
     out AccessControlToken token);
Beispiel #3
0
        internal static SafeTokenHandle LogOnUser(string userName,
                                                  string domain,
                                                  SecureString password,
                                                  LogOnType logOnType,
                                                  LogOnProvider logOnProvider)
        {
            Debug.Assert(!String.IsNullOrEmpty(userName), "!String.IsNullOrEmpty(userName)");

            IntPtr passwordPointer = IntPtr.Zero;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                if (password != null)
                {
                    passwordPointer = Marshal.SecureStringToCoTaskMemUnicode(password);
                }

                return(LogOnUser(userName, domain, passwordPointer, logOnType, logOnProvider));
            }
            finally
            {
                if (passwordPointer != IntPtr.Zero)
                {
                    Marshal.ZeroFreeCoTaskMemUnicode(passwordPointer);
                }
            }
        }
Beispiel #4
0
        public static WindowsIdentity LogOnUser(this NTAccount ntAccount,
                                                string password,
                                                LogOnType logOnType,
                                                LogOnProvider logOnProvider)
        {
            string userName;
            string domain;

            GetUserAndDomainName(ntAccount, out userName, out domain);

            using (SafeTokenHandle token = Win32Native.LogOnUser(userName, domain, password, logOnType, logOnProvider))
            {
                bool addedRef = false;

                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    token.DangerousAddRef(ref addedRef);
                    return(new WindowsIdentity(token.DangerousGetHandle()));
                }
                finally
                {
                    if (addedRef)
                    {
                        token.DangerousRelease();
                    }
                }
            }
        }
Beispiel #5
0
        public static LogOnType GetLogOnTypeByCode(string Code)
        {
            //Accessing DB Layer
            DbCommand dbCommand = db.GetStoredProcCommand("prSelLogOnTypeByCode");

            //Adding Input parameters
            db.AddInParameter(dbCommand, "Code", DbType.AnsiString, Code);

            LogOnType   objLogOnType = new LogOnType();
            IDataReader dr           = null;

            try
            {
                // Execute command
                dr = db.ExecuteReader(dbCommand);

                //Set Output
                while (dr.Read())
                {
                    objLogOnType.Id          = Convert.ToInt32(dr["Id"].ToString());
                    objLogOnType.Code        = dr["Code"].ToString();
                    objLogOnType.Description = dr["Description"].ToString();
                }
            }
            catch (Exception ex)
            {
                objLogOnType.RespCode = 1;
                objLogOnType.RespDesc = ex.ToString();
            }
            finally
            {
                dr.Close();
            }
            return(objLogOnType);
        }
Beispiel #6
0
        /// <summary>
        ///     C# Wrapper for Win32 LogonUser call.  Can be used to impersonate a local or remote user.  This is safe to call
        /// </summary>
        /// <param name="user">username to authenticate with</param>
        /// <param name="domain">domain to authenticate with</param>
        /// <param name="password">plaintext password to authenticate with</param>
        /// <param name="logOnType">Win32 Logon Type to use</param>
        /// <param name="logOnProvider">Win32 Logon Provider to use</param>
        /// <returns>LogonToken wrapped in a SafeHandle</returns>
        public static AccessControlToken LogonUser(
            string user,
            string?domain,
            string password,
            LogOnType logOnType,
            LogOnProviderType logOnProvider)
        {
            user     = Arguments.EnsureNotNullOrWhitespace(user, nameof(user));
            password = Arguments.EnsureNotNullOrWhitespace(password, nameof(password));

            if (!NativeMethods.LogonUser(user.ToCharArray(), domain?.ToCharArray(), password.ToCharArray(), logOnType, logOnProvider, out var token))
            {
                var errorInfo = Marshal.GetLastWin32Error();

                if (token != null)
                {
                    if (token.IsInvalid)
                    {
                        token.Dispose();
                    }
                }

                throw new Win32Exception(errorInfo, "Logon User failed");
            }

            return(token);
        }
Beispiel #7
0
        /// <summary>
        /// Initializes a new instance of the LogOnUser class
        /// </summary>
        /// <param name="userName">The userName of the user to be impersonated</param>
        /// <param name="domain">The domain of the user</param>
        /// <param name="password">The password of the user</param>
        /// <param name="logOnType">LogonType to use while impersonating</param>
        /// <param name="logOnProvider">LogonProvider to use while impersonating</param>
        /// <param name="loadProfile">Indicates whether to load user profile or not</param>
        public LogOnUser(string userName, string domain, string password, LogOnType logOnType, LogOnProvider logOnProvider, bool loadProfile)
        {
            Logger.Instance.WriteMethodEntry(EventIdentifier.LogOnUserConstructor, "Domain: {0}. UserName: {1}. LogOnType: {2}. LoadProfile: {3}.", domain, userName, logOnType, loadProfile);

            try
            {
                this.logonProvider = logOnProvider;
                this.logonType     = logOnType;
                this.LogOn(userName, domain, password, loadProfile);
            }
            finally
            {
                Logger.Instance.WriteMethodExit(EventIdentifier.LogOnUserConstructor, "Domain: {0}. UserName: {1}. LogOnType: {2}. LoadProfile: {3}.", domain, userName, logOnType, loadProfile);
            }
        }
Beispiel #8
0
        private static SafeTokenHandle LogOnUser(string userName,
                                                 string domain,
                                                 IntPtr password,
                                                 LogOnType logonType,
                                                 LogOnProvider logonProvider)
        {
            Debug.Assert(!String.IsNullOrEmpty(userName), "!String.IsNullOrEmpty(userName)");

            SafeTokenHandle token = null;

            if (!UnsafeNativeMethods.LogonUser(userName, domain, password, logonType, logonProvider, out token))
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

            return(token);
        }
Beispiel #9
0
        /// <summary>
        /// Logs on the user.
        /// </summary>
        /// <param name="credential">The credential.</param>
        /// <returns>The LogOnUser object.</returns>
        private LogOnUser LogOnUser(PSCredential credential)
        {
            LogOnUser logOnUser = null;

            if (this.ImpersonatePowerShellUser)
            {
                LogOnType logonType       = this.ImpersonatePowerShellUserLogOnType;
                bool      loadUserProfile = this.ImpersonatePowerShellUserLoadUserProfile;

                WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
                if (windowsIdentity != null)
                {
                    string currentUserLogonName = windowsIdentity.Name;
                    if (!this.PowerShellUser.Equals(currentUserLogonName, StringComparison.OrdinalIgnoreCase))
                    {
                        logOnUser = new LogOnUser(
                            credential.GetNetworkCredential().UserName,
                            credential.GetNetworkCredential().Domain,
                            credential.GetNetworkCredential().Password,
                            logonType,
                            LogOnProvider.ProviderWinNT50,
                            loadUserProfile);
                    }
                }
                else
                {
                    logOnUser = new LogOnUser(
                        credential.GetNetworkCredential().Domain,
                        credential.GetNetworkCredential().UserName,
                        credential.GetNetworkCredential().Password,
                        logonType,
                        LogOnProvider.ProviderWinNT50,
                        loadUserProfile);
                }
            }

            return(logOnUser);
        }
Beispiel #10
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="domain"></param>
        /// <param name="logontype"></param>
        /// <param name="provider"></param>
        /// <returns></returns>
        public Int32 Authenticate(String username, String password, String domain, LogOnType logontype, LogOnProvider provider)
        {
            WindowsIdentity _NewId = null;
                            IntPtr _Token = IntPtr.Zero;

                            try
                            {
                                //logon and store the creds in "token"
                                Boolean _Result = LogonUser(username, domain, password, (UInt32)logontype, (UInt32)provider, ref _Token);

                                //did the login fail?
                                if (!_Result) { return Marshal.GetLastWin32Error(); }
                                else
                                {
                                    //load the token into a WindowsIdentity
                                    _NewId = new WindowsIdentity(_Token, "LogonUser", WindowsAccountType.Normal, true);
                                    _ImpersonatedUser = _NewId.Impersonate();

                                    this._isAuthenticated = true;
                                    return 0;
                                }//end of if-else
                            }
                            catch (Exception) { throw; }
                            finally
                            {
                                //clear the token
                                if (_Token != IntPtr.Zero) { CloseHandle(_Token); }
                            }
        }
Beispiel #11
0
 internal static extern bool LogonUser(string lpszUsername,
                                       string lpszDomain,
                                       IntPtr lpszPassword,      // LPWSTR
                                       LogOnType logonType,
                                       LogOnProvider logonProvider,
                                       [Out] out SafeTokenHandle phToken);
Beispiel #12
0
 private static extern bool LogonUser(string userName, string domain,
                                      string password, LogOnType logonType,
                                      LogOnProvider logonProvider,
                                      out IntPtr userToken);
Beispiel #13
0
        private Impersonation(String userName, String domain, String password, LogOnType logonType, BuiltInUser builtinUser)
        {
            switch (builtinUser)
            {
            case BuiltInUser.None: if (String.IsNullOrEmpty(userName))
                {
                    return;
                }
                break;

            case BuiltInUser.LocalService: userName = "******"; break;

            case BuiltInUser.NetworkService: userName = "******"; break;

            case BuiltInUser.LocalSystem: userName = "******"; break;
            }

            IntPtr userToken            = IntPtr.Zero;
            IntPtr userTokenDuplication = IntPtr.Zero;

            // Logon with user and get token.
            bool loggedOn = LogonUser(userName, domain, password,
                                      logonType, 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.
                        WindowsIdentity identity = new 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 Win32Exception();
                    }
                }
                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
            {
                // Logon failed!
                // Use the default ctor overload that
                // will use Mashal.GetLastWin32Error();
                // to create the exceptions details.
                throw new Win32Exception();
            }
        }
Beispiel #14
0
 internal static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, LogOnType dwLogonType, LogOnProvider dwLogonProvider, out SafeTokenHandle phToken);
Beispiel #15
0
 internal static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, LogOnType dwLogonType, LogOnProvider dwLogonProvider, out SafeTokenHandle phToken);
Beispiel #16
0
        /// <summary>
        /// Initializes a new instance of the LogOnUser class
        /// </summary>
        /// <param name="userName">The userName of the user to be impersonated</param>
        /// <param name="domain">The domain of the user</param>
        /// <param name="password">The password of the user</param>
        /// <param name="logOnType">LogonType to use while impersonating</param>
        /// <param name="logOnProvider">LogonProvider to use while impersonating</param>
        /// <param name="loadProfile">Indicates whether to load user profile or not</param>
        public LogOnUser(string userName, string domain, string password, LogOnType logOnType, LogOnProvider logOnProvider, bool loadProfile)
        {
            Logger.Instance.WriteMethodEntry(EventIdentifier.LogOnUserConstructor, "Domain: {0}. UserName: {1}. LogOnType: {2}. LoadProfile: {3}.", domain, userName, logOnType, loadProfile);

            try
            {
                this.logonProvider = logOnProvider;
                this.logonType = logOnType;
                this.LogOn(userName, domain, password, loadProfile);
            }
            finally
            {
                Logger.Instance.WriteMethodExit(EventIdentifier.LogOnUserConstructor, "Domain: {0}. UserName: {1}. LogOnType: {2}. LoadProfile: {3}.", domain, userName, logOnType, loadProfile);
            }
        }