示例#1
0
 public static extern Boolean LogonUser(
     String lpszUserName,
     String lpszDomain,
     String lpszPassword,
     LogonType dwLogonType,
     LogonProvider dwLogonProvider,
     out SafeFileHandle phToken);
 private static extern bool LogonUser(
     string username,
     string domain,
     string password,
     LogonType logonType,
     LogonProvider logonProvider,
     out SafeTokenHandle token);
        /// <summary>
        /// This ROP logs on to a private mailbox or public folder. 
        /// </summary>
        /// <param name="logonType">This type specifies ongoing action on the private mailbox or public folder.</param>
        /// <param name="logonResponse">The response of this ROP.</param>
        /// <param name="userDN">This string specifies which mailbox to log on to.</param>
        /// <param name="needVerify">Whether need to verify the response.</param>
        /// <returns>The handle of logon object.</returns>
        private uint RopLogon(LogonType logonType, out RopLogonResponse logonResponse, string userDN, bool needVerify)
        {
            this.rawDataValue = null;
            this.responseValue = null;
            this.responseSOHsValue = null;
            userDN += "\0";
            uint insideObjHandle = 0;

            RopLogonRequest logonRequest = new RopLogonRequest()
            {
                RopId = (byte)RopId.RopLogon,
                LogonId = LogonId,
                OutputHandleIndex = (byte)HandleIndex.FirstIndex,
                StoreState = (uint)StoreState.None,

                // Set parameters for public folder logon type.
                LogonFlags = logonType == LogonType.PublicFolder ? (byte)LogonFlags.PublicFolder : (byte)LogonFlags.Private,
                OpenFlags = logonType == LogonType.PublicFolder ? (uint)(OpenFlags.UsePerMDBReplipMapping | OpenFlags.Public) : (uint)OpenFlags.UsePerMDBReplipMapping,

                // Set EssdnSize to 0, which specifies the size of the ESSDN field.
                EssdnSize = logonType == LogonType.PublicFolder ? (ushort)0 : (ushort)Encoding.ASCII.GetByteCount(userDN),
                Essdn = logonType == LogonType.PublicFolder ? null : Encoding.ASCII.GetBytes(userDN),
            };

            this.responseSOHsValue = this.ProcessSingleRop(logonRequest, insideObjHandle, ref this.responseValue, ref this.rawDataValue, RopResponseType.SuccessResponse);
            logonResponse = (RopLogonResponse)this.responseValue;
            if (needVerify)
            {
                this.Site.Assert.AreEqual((uint)RopResponseType.SuccessResponse, logonResponse.ReturnValue, string.Format("Logon Failed! Error: 0x{0:X8}", logonResponse.ReturnValue));
            }

            return this.responseSOHsValue[0][logonResponse.OutputHandleIndex];
        }
        private Impersonation(string domain, string username, string password, LogonType logonType)
        {
            IntPtr handle;
            var ok = NativeMethods.LogonUser(username, domain, password, (int)logonType, 0, out handle);
            if (!ok)
            {
                var errorCode = Marshal.GetLastWin32Error();
                throw new ApplicationException(string.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode));
            }

            var profileInfo = new ProfileInfo();
            profileInfo.dwSize = Marshal.SizeOf(profileInfo);
            profileInfo.lpUserName = username;
            profileInfo.dwFlags = 1;

            ok = NativeMethods.LoadUserProfile(handle, ref profileInfo);
            if (ok == false)
            {
                var errorCode = Marshal.GetLastWin32Error();
                throw new ApplicationException(string.Format("Could not load profile. Error code {0}.", errorCode));
            }
            NativeMethods.UnloadUserProfile(handle, profileInfo.hProfile);

            _handle = new SafeTokenHandle(handle);
            _context = WindowsIdentity.Impersonate(_handle.DangerousGetHandle());
        }
示例#5
0
 internal static extern int LogonUser(
     string lpszUsername,
     string lpszDomain,
     string lpszPassword,
     LogonType dwLogonType,
     ProviderType dwLogonProvider,
     out IntPtr phToken);
示例#6
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            
 );
示例#7
0
        /// <summary>
        /// Perform Windows Logon returning an authentication token.
        /// </summary>
        /// <param name="username">Full username as DOMAIN\USERNAME, .\USERNAME or [email protected].</param>
        /// <param name="password">Password to logon with.</param>
        /// <param name="logonType">Type of logon to use.</param>
        /// <returns>An authentication token.</returns>
        public static IntPtr LogonUser(string username, string password, LogonType logonType)
        {
            IntPtr token = IntPtr.Zero;

            if (!LogonUser(username, null, password, logonType, LogonProvider.LOGON32_PROVIDER_DEFAULT, ref token))
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());

            return token;
        }
示例#8
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();
        }
        private Impersonation(string domain, string username, string password, LogonType logonType)
        {
            IntPtr handle;
            var ok = NativeMethods.LogonUser(username, domain, password, (int)logonType, 0, out handle);
            if (!ok)
            {
                var errorCode = Marshal.GetLastWin32Error();
                throw new ApplicationException(string.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode));
            }

            _handle = new SafeTokenHandle(handle);
            _context = WindowsIdentity.Impersonate(_handle.DangerousGetHandle());
        }
示例#10
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();
        }
示例#11
0
        private Impersonation(string domain, string username, SecureString password, LogonType logonType)
        {
            IntPtr token;
            IntPtr passPtr = Marshal.SecureStringToGlobalAllocUnicode(password);

            bool success;
            try
            {
                success = NativeMethods.LogonUser(username, domain, passPtr, (int)logonType, 0, out token);
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(passPtr);
            }

            CompleteImpersonation(success, token, out _handle, out _context);
        }
        /// <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));
            }
        }
示例#13
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);
 }
示例#14
0
        /// <summary>
        /// Logon a user with the specified credentials.
        /// </summary>
        /// <param name="credentials">Credentials for logon. See <see cref="NetworkCredential"/>.</param>
        /// <param name="logontype">See <see cref="LogonType"/>.</param>
        /// <returns>The <see cref="WindowsIdentity"/> of the logged on account.</returns>
        /// <permission cref="SecurityPermission">Demand for <see cref="SecurityPermissionFlag.ControlPrincipal"/> permission flag.</permission>
        /// <exception cref="ArgumentException">Unable to logon</exception>
        public static WindowsIdentity LogonUser(NetworkCredential credentials, LogonType logontype)
        {
            // Parameter validation
            if (credentials == null)
            {
                throw new ArgumentException("credentials");
            }

            // Demand permissions
            new SecurityPermission(SecurityPermissionFlag.ControlPrincipal).Demand();
            // Assert permissions
            _assertedPermissions.Assert();

            // initialize tokens
            IntPtr pExistingTokenHandle  = IntPtr.Zero;
            IntPtr pDuplicateTokenHandle = IntPtr.Zero;

            string domain = credentials.Domain;

            if (domain == null || domain.Length == 0)
            {
                domain = Environment.MachineName;
            }

            bool returnValue = false;

            try
            {
                returnValue = Win32Native.LogonUser(credentials.UserName,
                                                    domain,
                                                    credentials.Password,
                                                    (int)logontype,
                                                    Win32Native.LOGON32_PROVIDER_DEFAULT,
                                                    ref pExistingTokenHandle);

                if (returnValue && pExistingTokenHandle != IntPtr.Zero)
                {
                    returnValue = Win32Native.DuplicateToken(pExistingTokenHandle, (int)Win32Native.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, ref pDuplicateTokenHandle);
                    // did DuplicateToken fail?
                    if (returnValue)
                    {
                        // create new identity using new primary token
                        return(new WindowsIdentity(pDuplicateTokenHandle, "NTLM", WindowsAccountType.Normal, true));
                    }
                    else
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                else
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            catch (Win32Exception wex)
            {
                //Add detailed description
                throw new ArgumentException(Resource.ResourceManager[Resource.MessageKey.LogonUserException,
                                                                     domain,
                                                                     credentials.UserName,
                                                                     logontype.ToString(),
                                                                     Environment.NewLine,
                                                                     wex.Message,
                                                                     Environment.MachineName,
                                                                     WindowsIdentity.GetCurrent().Name]);
            }
            finally
            {
                // close handles
                if (pExistingTokenHandle != IntPtr.Zero)
                {
                    Win32Native.CloseHandle(pExistingTokenHandle);
                }
                if (pDuplicateTokenHandle != IntPtr.Zero)
                {
                    Win32Native.CloseHandle(pDuplicateTokenHandle);
                }
                // Revert permission (Not strictly necessary but a good practice indeed.)
                System.Security.CodeAccessPermission.RevertAssert();
            }
        }
示例#15
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);
   }
 }
 public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, LogonType dwLogonType, LogonProvider dwLogonProvider, out SafeTokenHandle phToken);
示例#17
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;
            }

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

            // Logon with user and get token.
            bool loggedOn = NativeMethod.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 (NativeMethod.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.
                        NativeMethod.CloseHandle(userTokenDuplication);
                        userTokenDuplication = IntPtr.Zero;
                    }

                    // Close usertoken handle when created.
                    if (!userToken.Equals(IntPtr.Zero))
                    {
                        // Closes the handle of the user.
                        NativeMethod.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();
            //}
        }
        /// <summary>
        /// Initialize the test environment.
        /// </summary>
        /// <param name="site">TestSite is used to initialization.</param>
        /// <param name="logonType">This type specifies ongoing action on the mailbox or public folder.</param>
        private void InitHandle(ITestSite site, LogonType logonType)
        {
            this.Initialize(site);
            bool isConnected = this.RpcConnect(logonType);
            this.Site.Assert.IsTrue(isConnected, "Rpc connect method should be executed successfully.");

            // Log on to the specific folder.
            RopLogonResponse logonRes;
            this.cprptLogonHandle = this.logonHandle = this.RopLogon(logonType, out logonRes, Common.GetConfigurationPropertyValue("UserEssdn", site), true);
            this.folderIds = logonRes.FolderIds;
        }
示例#19
0
 private static extern bool LogonUser(string username, string domain, [In] IntPtr password, LogonType logonType, LogonProvider logonProvider, out IntPtr token);
示例#20
0
 public static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword, LogonType dwLogonType, LogonProvider dwLogonProvider, ref IntPtr phToken);
示例#21
0
        public static void Main(Dictionary <string, string> pArgs)
        {
            args = pArgs;

            EnablePrivilege("SeAssignPrimaryTokenPrivilege");
            EnablePrivilege("SeBackupPrivilege");
            EnablePrivilege("SeRestorePrivilege");

            try
            {
                bool bad = false;

                if (!args.ContainsKey("-w"))
                {
                    if (!args.ContainsKey("-c") && !args.ContainsKey("-f"))
                    {
                        bad = true;
                    }

                    if (args.ContainsKey("-c") && args.ContainsKey("-f"))
                    {
                        bad = true;
                    }

                    if (!args.ContainsKey("-u") && !args.ContainsKey("-P"))
                    {
                        bad = true;
                    }

                    if (args.ContainsKey("-u") && args.ContainsKey("-P"))
                    {
                        bad = true;
                    }
                }

                if (args.ContainsKey("-v") || args.ContainsKey("-h"))
                {
                    bad = true;
                }

                if (bad)
                {
                    PrintUsage();
                    Exit();
                }
            }
            catch
            {
                PrintUsage();
                Exit();
            }

            if (args.ContainsKey("-w"))
            {
                try
                {
                    SetDesktopWinStaAccess();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Warning: Could not set desktop and window station access: " + ex.Message);
                }
            }

            TokenHandle token    = null;
            string      domain   = null;
            string      username = "";

            if (args.ContainsKey("-u"))
            {
                string user = args["-u"];

                if (user.Contains("\\"))
                {
                    domain   = user.Split('\\')[0];
                    username = user.Split('\\')[1];
                }
                else if (user.Contains("@"))
                {
                    username = user.Split('@')[0];
                    domain   = user.Split('@')[1];
                }
                else
                {
                    username = user;
                }

                LogonType type = LogonType.Interactive;

                if (args.ContainsKey("-t"))
                {
                    try
                    {
                        type = (LogonType)Enum.Parse(typeof(LogonType), args["-t"], true);
                    }
                    catch
                    {
                        Console.WriteLine("Error: Invalid logon type.");
                        Exit(-1);
                    }
                }

                try
                {
                    token = TokenHandle.Logon(
                        username,
                        domain,
                        args.ContainsKey("-p") ? args["-p"] : "",
                        type,
                        LogonProvider.Default
                        );
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: Could not logon as user: "******"-P"))
                    {
                        pid = int.Parse(args["-P"]);
                    }
                }
                catch
                {
                    Console.WriteLine("Error: Invalid PID.");
                }

                try
                {
                    using (var phandle = new ProcessHandle(pid, OSVersion.MinProcessQueryInfoAccess))
                    {
                        try
                        {
                            token = phandle.GetToken(TokenAccess.All);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error: Could not open process token: " + ex.Message);
                            Exit(Marshal.GetLastWin32Error());
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: Could not open process: " + ex.Message);
                    Exit(Marshal.GetLastWin32Error());
                }

                // Need to duplicate the token if we're going to set the session ID.
                if (args.ContainsKey("-s"))
                {
                    try
                    {
                        TokenHandle dupToken;

                        dupToken = token.Duplicate(
                            TokenAccess.All,
                            SecurityImpersonationLevel.SecurityImpersonation,
                            TokenType.Primary
                            );
                        token.Dispose();
                        token = dupToken;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error: Could not duplicate own token: " + ex.Message);
                        Exit(Marshal.GetLastWin32Error());
                    }
                }
            }

            if (args.ContainsKey("-s"))
            {
                int sessionId = int.Parse(args["-s"]);

                try
                {
                    token.SetSessionId(sessionId);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: Could not set token session ID: " + ex.Message);
                }
            }

            if (args.ContainsKey("-c") || args.ContainsKey("-f"))
            {
                if (!args.ContainsKey("-e"))
                {
                    EnvironmentBlock environment;
                    StartupInfo      startupInfo = new StartupInfo();
                    ProcessHandle    processHandle;
                    ThreadHandle     threadHandle;
                    ClientId         clientId;

                    environment         = new EnvironmentBlock(token);
                    startupInfo.Desktop = "WinSta0\\Default";

                    try
                    {
                        processHandle = ProcessHandle.CreateWin32(
                            token,
                            args.ContainsKey("-f") ? args["-f"] : null,
                            args.ContainsKey("-c") ? args["-c"] : null,
                            false,
                            ProcessCreationFlags.CreateUnicodeEnvironment,
                            environment,
                            args.ContainsKey("-d") ? args["-d"] : null,
                            startupInfo,
                            out clientId,
                            out threadHandle
                            );
                        processHandle.Dispose();
                        threadHandle.Dispose();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error: Could not create process: " + ex.Message);
                        Exit(Marshal.GetLastWin32Error());
                    }
                    finally
                    {
                        environment.Destroy();
                    }
                }
            }

            token.Dispose();

            Exit();
        }
示例#22
0
 /// <summary>
 /// Impersonates the account.
 /// </summary>
 /// <param name="userName">Name of the user.</param>
 /// <param name="password">The password.</param>
 /// <param name="logonType">Type of the logon.</param>
 /// <returns></returns>
 public static WindowsImpersonationContext ImpersonateAccount(string userName, string password, LogonType logonType)
 {
     return(ImpersonateAccount(userName, ".", password, logonType, LogonProvider.LOGON32_PROVIDER_DEFAULT));
 }
示例#23
0
        /// <summary>
        /// Determines whether this instance [can account logon] the specified LPSZ username.
        /// </summary>
        /// <param name="lpszUsername">The LPSZ username.</param>
        /// <param name="lpszDomain">The LPSZ domain.</param>
        /// <param name="lpszPassword">The LPSZ password.</param>
        /// <param name="lType">Type of the l.</param>
        /// <param name="lProvider">The l provider.</param>
        /// <param name="lastError">The last error.</param>
        /// <returns></returns>
        public static bool CanAccountLogon(string lpszUsername, string lpszDomain, string lpszPassword, LogonType lType, LogonProvider lProvider, out int lastError)
        {
            var hToken = IntPtr.Zero;

            try
            {
                var rValue = LogonUser(lpszUsername, lpszDomain, lpszPassword, lType, lProvider, out hToken);
                if (!rValue)
                {
                    lastError = Marshal.GetLastWin32Error();
                }
                else
                {
                    lastError = 0;
                }

                return(rValue);
            }
            finally
            {
                if (hToken != IntPtr.Zero)
                {
                    Kernel.CloseHandle(hToken);
                    hToken = IntPtr.Zero;
                }
            }
        }
示例#24
0
        /// <summary>
        /// Impersonates the account.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="domain">The domain.</param>
        /// <param name="password">The password.</param>
        /// <param name="logonType">Type of the logon.</param>
        /// <param name="logonProvider">The logon provider.</param>
        /// <returns></returns>
        /// <exception cref="System.Security.SecurityException"></exception>
        public static WindowsImpersonationContext ImpersonateAccount(string userName, string domain, string password, LogonType logonType, LogonProvider logonProvider)
        {
            WindowsIdentity tempWindowsIdentity;
            var             token          = IntPtr.Zero;
            var             tokenDuplicate = IntPtr.Zero;

            if (RevertToSelf())
            {
                if (LogonUser(userName, domain, password, logonType, logonProvider, out token))
                {
                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {
                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        var impersonationContext = tempWindowsIdentity.Impersonate();
                        if (impersonationContext != null)
                        {
                            var lpProfile = new Userenv.PROFILEINFO();
                            lpProfile.dwSize     = Marshal.SizeOf(lpProfile);
                            lpProfile.lpUserName = userName;
                            lpProfile.dwFlags    = 1;
                            Userenv.LoadUserProfile(tokenDuplicate, ref lpProfile);

                            Kernel.CloseHandle(token);
                            Kernel.CloseHandle(tokenDuplicate);

                            token          = IntPtr.Zero;
                            tokenDuplicate = IntPtr.Zero;

                            return(impersonationContext);
                        }
                    }
                }
                else
                {
                    throw new SecurityException(string.Format(@"Unable to impersonate user: {0}\{1}", domain, userName));
                }
            }

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

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

            return(null);
        }
        /// <summary>
        /// Logon onto the Exchange server.
        /// </summary>
        /// <param name="logonType">Specify the logon folder type: PublicFolder, MailBox.</param>
        /// <param name="userDN">Identifies the mailbox to logon.</param>
        /// <param name="objHandle">The server object handle.</param>
        /// <returns>The Logon ROP response.</returns>
        private RopLogonResponse ROPLogon(LogonType logonType, string userDN, out uint objHandle)
        {
            RopLogonRequest logonRequest;
            this.inobjHandle = 0;
            logonRequest.RopId = 0xFE;
            logonRequest.LogonId = 0x0;
            logonRequest.OutputHandleIndex = 0x0;
            logonRequest.StoreState = 0;
            string fullUserDNString = userDN + StringNullTerminator;

            if (LogonType.PublicFolder == logonType)
            {
                logonRequest.LogonFlags = 0x00; // Logon to public folders
                logonRequest.OpenFlags = 0x01000002; // Logon to public folders
                logonRequest.EssdnSize = 0;
                logonRequest.Essdn = null;
            }
            else
            {
                logonRequest.LogonFlags = 0x01; // Logon to a private mailbox
                logonRequest.OpenFlags = 0x01000000;

                logonRequest.EssdnSize = (ushort)Encoding.ASCII.GetByteCount(fullUserDNString);
                logonRequest.Essdn = Encoding.ASCII.GetBytes(fullUserDNString);
            }

            this.responseSOHs = this.DoRopCall(logonRequest, this.inobjHandle, ref this.response, ref this.rawData);
            RopLogonResponse logonResponse = (RopLogonResponse)this.response;

            Site.Assert.AreEqual<uint>(UINT32SUCCESS, logonResponse.ReturnValue, "0 indicates RopLogon operates successfully.");
            objHandle = this.responseSOHs[0][logonResponse.OutputHandleIndex];

            return logonResponse;
        }
示例#26
0
            ///// <summary>
            ///// Impersonates the specified user account.
            ///// </summary>
            //public void Impersonate(string domainName, string userName, string password)
            //{
            //    Impersonate(domainName, userName, password, LogonType.Interactive, LogonProvider.Default);
            //}

            /// <summary>
            /// Impersonates the specified user account.
            /// </summary>
            public void Impersonate(string domainName, string userName, string password, LogonType logonType = LogonType.Interactive, LogonProvider logonProvider = LogonProvider.Default)
            {
                UndoImpersonation();

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

                    // do logon & impersonate
                    if (Win32Sec.LogonUser(userName, domainName, password, (int)logonType, (int)logonProvider, ref logonToken))
                    {
                        if (Win32Sec.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)
                        Win32Sec.CloseHandle(logonToken);

                    if (logonTokenDuplicate != IntPtr.Zero)
                        Win32Sec.CloseHandle(logonTokenDuplicate);
                }
            }
        /// <summary>
        /// Connect to the server for RPC calling.
        /// </summary>
        /// <param name="logonType">The logon type.</param>
        /// <returns>Result of connecting.</returns>
        private bool RpcConnect(LogonType logonType)
        {
            ConnectionType connectionType = ConnectionType.PrivateMailboxServer;
            if (logonType == LogonType.PublicFolder)
            {
                connectionType = ConnectionType.PublicFolderServer;
            }

            bool retValue1 = this.oxcropsClient.Connect(
                    Common.GetConfigurationPropertyValue("SutComputerName", this.Site),
                    connectionType,
                    Common.GetConfigurationPropertyValue("UserEssdn", this.Site),
                    Common.GetConfigurationPropertyValue("Domain", this.Site),
                    Common.GetConfigurationPropertyValue("UserName", this.Site),
                    Common.GetConfigurationPropertyValue("Password", this.Site));

            bool retValue2 = this.oxcropsClientSession2.Connect(
                    Common.GetConfigurationPropertyValue("SutComputerName", this.Site),
                    connectionType,
                    Common.GetConfigurationPropertyValue("UserEssdn", this.Site),
                    Common.GetConfigurationPropertyValue("Domain", this.Site),
                    Common.GetConfigurationPropertyValue("UserName", this.Site),
                    Common.GetConfigurationPropertyValue("Password", this.Site));

            return retValue1 && retValue2;
        }
 internal SafeAccessTokenHandle Impersonate(LogonType logonType)
 {
     return(Impersonate(logonType, LogonProvider.Default));
 }
示例#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);

            // 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);
               }
        }
 public static extern bool LogonUser([In] string lpszUserName, [In] string lpszDomain, [In] string lpszPassword, [In] LogonType dwLogonType, [In] LogonProvider dwLogonProvider, out SafeCloseHandle phToken);
示例#31
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;
 }
示例#32
0
 public SystemLogonSession(
     string authenticationPackage,
     string dnsDomainName,
     string logonDomain,
     Luid logonId,
     string logonServer,
     DateTime logonTime,
     LogonType logonType,
     int session,
     Sid sid,
     string upn,
     string userName
     )
 {
     this.AuthenticationPackage = authenticationPackage;
     this.DnsDomainName = dnsDomainName;
     this.LogonDomain = logonDomain;
     this.LogonId = logonId;
     this.LogonServer = logonServer;
     this.LogonTime = logonTime;
     this.LogonType = logonType;
     this.Session = session;
     this.Sid = sid;
     this.Upn = upn;
     this.UserName = userName;
 }
示例#33
0
        private static bool LogonUser(string username, string domain, SecureString password, LogonType logonType, LogonProvider logonProvider, out IntPtr token)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            IntPtr plainpassword = IntPtr.Zero;

            try
            {
                plainpassword = Marshal.SecureStringToGlobalAllocUnicode(password);
                return(LogonUser(username, domain, plainpassword, logonType, logonProvider, out token));
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(plainpassword);
            }
        }
示例#34
0
 /// <summary>
 /// Initialises a new instance of the <see cref="UserFactAttribute"/> class.
 /// </summary>
 /// <param name="userSecretsId">Id used to retrieve user credentials for test impersonation</param>
 /// <param name="logonType">Logon method to use</param>
 /// <param name="displayNameOnTest">Append username to test</param>
 public UserFactAttribute(string userSecretsId, LogonType logonType = Default.Logon, bool displayNameOnTest = Default.DisplayName)
 => UserContext = new UserContextSettings(userSecretsId, logonType, displayNameOnTest);
示例#35
0
 private static extern bool LogonUser(string username, string domain,
                                           string password, LogonType logonType,
                                           LogonProvider logonProvider,
                                           out IntPtr userToken);
        /// <summary>
        /// This method is used to log on to a private mailbox or public folder and will be called before other ROPs
        /// </summary>
        /// <param name="logonType">The logon type.</param>
        /// <param name="userDN">The user Essdn to be used to logon a specific mailbox</param>
        /// <param name="objHandle">The Object handle.</param>
        /// <returns>The logon response.</returns>
        protected RopLogonResponse Logon(LogonType logonType, string userDN, out uint objHandle)
        {
            RopLogonRequest logonRequest;

            logonRequest.RopId = (byte)RopId.RopLogon;
            logonRequest.LogonId = LogonId;

            // Set OutputHandleIndex to 0x0, which specifies the location in the Server object handle table
            // where the handle for the output Server object will be stored.
            logonRequest.OutputHandleIndex = OutputHandleIndex0;
            logonRequest.StoreState = (uint)StoreState.None;

            if (LogonType.PublicFolder == logonType)
            {
                // Set other parameters for logon type of PublicFolder.
                logonRequest.LogonFlags = (byte)LogonFlags.PublicFolder;
                logonRequest.OpenFlags = (uint)OpenFlags.UsePerMDBReplipMapping + (uint)OpenFlags.Public;

                // Set EssdnSize to 0, which specifies the size of the Essdn field.
                logonRequest.EssdnSize = 0;

                // Initialize the Essdn to null.
                logonRequest.Essdn = null;
            }
            else
            {
                // Set other parameters for logon type of Mailbox (private mailbox).
                logonRequest.LogonFlags = (byte)LogonFlags.Private;
                logonRequest.OpenFlags = (uint)OpenFlags.UsePerMDBReplipMapping;

                // Set EssdnSize to the byte count of user DN, which specifies the size of the Essdn field.
                logonRequest.EssdnSize = (ushort)Encoding.ASCII.GetByteCount(userDN);

                // Set Essdn to the content of user DN, which specifies it will log on to the mail box of user represented by the user DN.
                logonRequest.Essdn = Encoding.ASCII.GetBytes(userDN);
            }

            // Send the RopLogon request and get the response.
            this.responseSOHs = this.cropsAdapter.ProcessSingleRop(
                logonRequest,
                this.inputObjHandle,
                ref this.response,
                ref this.rawData,
                RopResponseType.SuccessResponse);
            RopLogonResponse logonResponse = (RopLogonResponse)this.response;

            Site.Assert.AreEqual<uint>(
                    TestSuiteBase.SuccessReturnValue,
                    logonResponse.ReturnValue,
                    "If ROP succeeds, the ReturnValue of its response is 0 (success)");

            objHandle = this.responseSOHs[0][logonResponse.OutputHandleIndex];
            return logonResponse;
        }
示例#37
0
 public Impersonator(string userName, string domainName, string password, LogonType logonType,
                     LogonProvider logonProvider)
 {
     Impersonate(userName, domainName, password, logonType, logonProvider);
 }
 /// <summary>Constructs a terminal logon request object.</summary>
 /// <param name="LogonType">The logon type to perform.</param>
 public PINPADLogonRequest(LogonType LogonType) : base(true, typeof(PINPADLogonResponse))
 {
     this.LogonType = LogonType;
 }
示例#39
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;
      }
    }
        public static WindowsImpersonationContext Impersonate(this PrincipalContext principalContext, string username, string password, LogonType logonType)
        {
            if (username == null)
            {
                throw new ArgumentNullException(nameof(username));
            }

            if (password == null)
            {
                throw new ArgumentNullException(nameof(password));
            }

            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentException("The parameter cannot be empty", nameof(username));
            }

            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentException("The parameter cannot be empty", nameof(password));
            }

            SafeTokenHandle handle = null;

            try
            {
                if (!UnsafeNative.LogonUser(username, principalContext.Name, password, (int)logonType, 3 /* LOGON32_PROVIDER_WINNT50 */, out handle))
                {
                    throw new PrincipalOperationException("Could not impersonate the user.", Marshal.GetLastWin32Error());
                }

                var identity = WindowsIdentity.Impersonate(handle.DangerousGetHandle());
                return(identity);
            }
            catch
            {
                throw;
            }
            finally
            {
                handle?.Dispose();
            }
        }
示例#41
0
 private static extern bool LogonUser(String lpszUsername, String lpszDomain, IntPtr lpszPassword, LogonType dwLogonType, LogonProvider dwLogonProvider, out SafeTokenHandle phToken);
示例#42
0
 private bool Logon(String sDomain, String sUser, String sPassword, out IntPtr token, LogonType type)
 {
     token = IntPtr.Zero;
     try
     {
         var succees = Win32Sec.LogonUser(sUser, sDomain, sPassword, (int)type, (int)LogonProvider.Default, ref token);
         // did impersonation fail?
         if (!succees)
         {
             throw new Win32Exception(Marshal.GetLastWin32Error());
             //int nErrorCode = Marshal.GetLastWin32Error();
             //throw new UnauthorizedAccessException("LogonUser() failed with error code: " + nErrorCode);
         }
         return true;
     }
     catch (Exception e)
     {
         Trace.WriteLine("SECURITY ERROR: " + e.Message);
         Trace.TraceError(e.ToString());
     }
     return false;
 }
示例#43
0
 /// <summary>
 /// Impersonates a specific user account to get a safe access token handle.
 /// </summary>
 /// <param name="userCredentials">The credentials of the user account to impersonate.</param>
 /// <param name="logonType">The logon type used when impersonating the user account.</param>
 /// <returns>The safe access token handle.</returns>
 public SafeAccessTokenHandle Impersonate(UserCredentials userCredentials, LogonType logonType)
 {
     return(userCredentials.Impersonate(logonType));
 }
 /// <summary>
 /// Log in windows authentication using impersonation
 /// </summary>
 public static ImpersonationHelper LogonUser(string domain, string username, string password, LogonType logonType = LogonType.Interactive)
 {
     return(new ImpersonationHelper(domain, username, password, logonType));
 }
示例#45
0
 public static extern bool LogonUser(string username, string domain, string password, LogonType dwLogonType, LogonProvider dwLogonProvider, out IntPtr phToken);
示例#46
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 NetworkConnection(string NetworkLocation, string userName, string domainName, string password, LogonType logonType, LogonProvider logonProvider)
 {
     Impersonate(NetworkLocation, userName, domainName, password, logonType, logonProvider);
 }
示例#47
0
 private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, LogonType dwLogonType, LogonProvider dwLogonProvider, out IntPtr phToken);
示例#48
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>
        private void Impersonate(string NetworkLocation, string userName, string domainName, string password, LogonType logonType, LogonProvider logonProvider)
        {
            try
            {
                UndoImpersonation();

                /*
                 * if (userName.Contains("\\") || userName.Contains("/"))
                 * {
                 * string[] tokens = userName.Split(new char[] { '\\', '/' });
                 * if (tokens.Length != 2) throw new Exception("Expected user name to contain at most one / or \\ character.  User name: " + userName);
                 * if (domainName.Trim().Length != 0) throw new Exception("Cannot specify a / or \\ in user name when domain is also given.  User name: " + userName + "  Domain: " + domainName);
                 * domainName = tokens[0];
                 * userName = tokens[1];
                 * }
                 */

                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(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
                        {
                            ThrowSpecificException();
                        }
                    }
                    else
                    {
                        ThrowSpecificException();
                    }
                }
                finally
                {
                    if (logonToken != IntPtr.Zero)
                    {
                        Win32NativeMethods.CloseHandle(logonToken);
                    }

                    if (logonTokenDuplicate != IntPtr.Zero)
                    {
                        Win32NativeMethods.CloseHandle(logonTokenDuplicate);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new IOException("Unable to access path:\n" + NetworkLocation + "\nAs username: "******"\nOn domain: " + domainName + "\nError: " + ex.ToString());
            }
        }
示例#49
0
 /// <summary>
 /// Initialises a new instance of the <see cref="UserFactAttribute"/> class.
 /// </summary>
 /// <param name="username">Username to use for test impersonation</param>
 /// <param name="password">Password to use for test impersonation</param>
 /// <param name="domain">Domain that user belongs to</param>
 /// <param name="logonType">Logon method to use</param>
 /// <param name="displayNameOnTest">Append username to test</param>
 public UserFactAttribute(string username, string password, string domain, LogonType logonType = Default.Logon, bool displayNameOnTest = Default.DisplayName)
 => UserContext = new UserContextSettings(username, password, domain, logonType, displayNameOnTest);
示例#50
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);
 }
示例#51
0
 public static extern bool LogonUser(string username, string domain, string password, LogonType dwLogonType, LogonProvider dwLogonProvider, out IntPtr phToken);
示例#52
0
 public static Result CreateProcessAsUser(string username, string password, LogonFlags logonFlags, LogonType logonType,
                                          string lpApplicationName, string lpCommandLine, string lpCurrentDirectory, IDictionary environment,
                                          string stdin)
 {
     byte[] stdinBytes;
     if (String.IsNullOrEmpty(stdin))
     {
         stdinBytes = new byte[0];
     }
     else
     {
         if (!stdin.EndsWith(Environment.NewLine))
         {
             stdin += Environment.NewLine;
         }
         stdinBytes = new UTF8Encoding(false).GetBytes(stdin);
     }
     return(CreateProcessAsUser(username, password, logonFlags, logonType, lpApplicationName, lpCommandLine,
                                lpCurrentDirectory, environment, stdinBytes));
 }
示例#53
0
        public static SafeTokenHandle LogonUser(string userName, string domain, string password, LogonType logonType, LogonProvider logonProvider)
        {
            IntPtr token;

            if (!LogonUser(userName, domain, password, (int)logonType, (int)logonProvider, out token))
            {
                WindowsApi.NativeMethods.ReportWin32Exception();
            }

            return(new SafeTokenHandle(token));
        }
示例#54
0
        /// <summary>
        /// Creates a process as another user account. This method will attempt to run as another user with the
        /// highest possible permissions available. The main privilege required is the SeDebugPrivilege, without
        /// this privilege you can only run as a local or domain user if the username and password is specified.
        /// </summary>
        /// <param name="username">The username of the runas user</param>
        /// <param name="password">The password of the runas user</param>
        /// <param name="logonFlags">LogonFlags to control how to logon a user when the password is specified</param>
        /// <param name="logonType">Controls what type of logon is used, this only applies when the password is specified</param>
        /// <param name="lpApplicationName">The name of the executable or batch file to executable</param>
        /// <param name="lpCommandLine">The command line to execute, typically this includes lpApplication as the first argument</param>
        /// <param name="lpCurrentDirectory">The full path to the current directory for the process, null will have the same cwd as the calling process</param>
        /// <param name="environment">A dictionary of key/value pairs to define the new process environment</param>
        /// <param name="stdin">Bytes sent to the stdin pipe</param>
        /// <returns>Ansible.Process.Result object that contains the command output and return code</returns>
        public static Result CreateProcessAsUser(string username, string password, LogonFlags logonFlags, LogonType logonType,
                                                 string lpApplicationName, string lpCommandLine, string lpCurrentDirectory, IDictionary environment, byte[] stdin)
        {
            // While we use STARTUPINFOEX having EXTENDED_STARTUPINFO_PRESENT causes a parameter validation error
            Process.NativeHelpers.ProcessCreationFlags creationFlags = Process.NativeHelpers.ProcessCreationFlags.CREATE_UNICODE_ENVIRONMENT;
            Process.NativeHelpers.PROCESS_INFORMATION  pi            = new Process.NativeHelpers.PROCESS_INFORMATION();
            Process.NativeHelpers.STARTUPINFOEX        si            = new Process.NativeHelpers.STARTUPINFOEX();
            si.startupInfo.dwFlags = Process.NativeHelpers.StartupInfoFlags.USESTDHANDLES;

            SafeFileHandle stdoutRead, stdoutWrite, stderrRead, stderrWrite, stdinRead, stdinWrite;

            ProcessUtil.CreateStdioPipes(si, out stdoutRead, out stdoutWrite, out stderrRead, out stderrWrite,
                                         out stdinRead, out stdinWrite);
            FileStream stdinStream = new FileStream(stdinWrite, FileAccess.Write);

            // $null from PowerShell ends up as an empty string, we need to convert back as an empty string doesn't
            // make sense for these parameters
            if (lpApplicationName == "")
            {
                lpApplicationName = null;
            }

            if (lpCurrentDirectory == "")
            {
                lpCurrentDirectory = null;
            }

            // A user may have 2 tokens, 1 limited and 1 elevated. GetUserTokens will return both token to ensure
            // we don't close one of the pairs while the process is still running. If the process tries to retrieve
            // one of the pairs and the token handle is closed then it will fail with ERROR_NO_SUCH_LOGON_SESSION.
            List <SafeNativeHandle> userTokens = GetUserTokens(username, password, logonType);

            try
            {
                using (Process.SafeMemoryBuffer lpEnvironment = ProcessUtil.CreateEnvironmentPointer(environment))
                {
                    bool          launchSuccess = false;
                    StringBuilder commandLine   = new StringBuilder(lpCommandLine);
                    foreach (SafeNativeHandle token in userTokens)
                    {
                        // GetUserTokens could return null if an elevated token could not be retrieved.
                        if (token == null)
                        {
                            continue;
                        }

                        if (NativeMethods.CreateProcessWithTokenW(token, logonFlags, lpApplicationName,
                                                                  commandLine, creationFlags, lpEnvironment, lpCurrentDirectory, si, out pi))
                        {
                            launchSuccess = true;
                            break;
                        }
                    }

                    if (!launchSuccess)
                    {
                        throw new Process.Win32Exception("CreateProcessWithTokenW() failed");
                    }
                }
                return(ProcessUtil.WaitProcess(stdoutRead, stdoutWrite, stderrRead, stderrWrite, stdinStream, stdin,
                                               pi.hProcess));
            }
            finally
            {
                userTokens.Where(t => t != null).ToList().ForEach(t => t.Dispose());
            }
        }
示例#55
0
 public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, LogonType dwLogonType, LogonProvider dwLogonProvider, ref IntPtr phToken);
示例#56
0
        private static List <SafeNativeHandle> GetUserTokens(string username, string password, LogonType logonType)
        {
            List <SafeNativeHandle> userTokens = new List <SafeNativeHandle>();

            SafeNativeHandle systemToken  = null;
            bool             impersonated = false;
            string           becomeSid    = username;

            if (logonType != LogonType.NewCredentials)
            {
                // If prefixed with .\, we are becoming a local account, strip the prefix
                if (username.StartsWith(".\\"))
                {
                    username = username.Substring(2);
                }

                NTAccount account = new NTAccount(username);
                becomeSid = ((SecurityIdentifier)account.Translate(typeof(SecurityIdentifier))).Value;

                // Grant access to the current Windows Station and Desktop to the become user
                GrantAccessToWindowStationAndDesktop(account);

                // Try and impersonate a SYSTEM token, we need a SYSTEM token to either become a well known service
                // account or have administrative rights on the become access token.
                // If we ultimately are becoming the SYSTEM account we want the token with the most privileges available.
                // https://github.com/ansible/ansible/issues/71453
                bool mostPrivileges = becomeSid == "S-1-5-18";
                systemToken = GetPrimaryTokenForUser(new SecurityIdentifier("S-1-5-18"),
                                                     new List <string>()
                {
                    "SeTcbPrivilege"
                }, mostPrivileges);
                if (systemToken != null)
                {
                    try
                    {
                        TokenUtil.ImpersonateToken(systemToken);
                        impersonated = true;
                    }
                    catch (Process.Win32Exception) { }  // We tried, just rely on current user's permissions.
                }
            }

            // We require impersonation if becoming a service sid or becoming a user without a password
            if (!impersonated && (SERVICE_SIDS.Contains(becomeSid) || String.IsNullOrEmpty(password)))
            {
                throw new Exception("Failed to get token for NT AUTHORITY\\SYSTEM required for become as a service account or an account without a password");
            }

            try
            {
                if (becomeSid == "S-1-5-18")
                {
                    userTokens.Add(systemToken);
                }
                // Cannot use String.IsEmptyOrNull() as an empty string is an account that doesn't have a pass.
                // We only use S4U if no password was defined or it was null
                else if (!SERVICE_SIDS.Contains(becomeSid) && password == null && logonType != LogonType.NewCredentials)
                {
                    // If no password was specified, try and duplicate an existing token for that user or use S4U to
                    // generate one without network credentials
                    SecurityIdentifier sid         = new SecurityIdentifier(becomeSid);
                    SafeNativeHandle   becomeToken = GetPrimaryTokenForUser(sid);
                    if (becomeToken != null)
                    {
                        userTokens.Add(GetElevatedToken(becomeToken));
                        userTokens.Add(becomeToken);
                    }
                    else
                    {
                        becomeToken = GetS4UTokenForUser(sid, logonType);
                        userTokens.Add(null);
                        userTokens.Add(becomeToken);
                    }
                }
                else
                {
                    string domain = null;
                    switch (becomeSid)
                    {
                    case "S-1-5-19":
                        logonType = LogonType.Service;
                        domain    = "NT AUTHORITY";
                        username  = "******";
                        break;

                    case "S-1-5-20":
                        logonType = LogonType.Service;
                        domain    = "NT AUTHORITY";
                        username  = "******";
                        break;

                    default:
                        // Trying to become a local or domain account
                        if (username.Contains(@"\"))
                        {
                            string[] userSplit = username.Split(new char[1] {
                                '\\'
                            }, 2);
                            domain   = userSplit[0];
                            username = userSplit[1];
                        }
                        else if (!username.Contains("@"))
                        {
                            domain = ".";
                        }
                        break;
                    }

                    SafeNativeHandle hToken = TokenUtil.LogonUser(username, domain, password, logonType,
                                                                  LogonProvider.Default);

                    // Get the elevated token for a local/domain accounts only
                    if (!SERVICE_SIDS.Contains(becomeSid))
                    {
                        userTokens.Add(GetElevatedToken(hToken));
                    }
                    userTokens.Add(hToken);
                }
            }
            finally
            {
                if (impersonated)
                {
                    TokenUtil.RevertToSelf();
                }
            }

            return(userTokens);
        }
示例#57
0
 internal static extern bool LogonUser(
     string userName,
     string domain,
     string password,
     LogonType logonType,
     LogonProvider logonProvider,
     out IntPtr token);
示例#58
0
        private static SafeNativeHandle GetS4UTokenForUser(SecurityIdentifier sid, LogonType logonType)
        {
            NTAccount becomeAccount = (NTAccount)sid.Translate(typeof(NTAccount));

            string[] userSplit = becomeAccount.Value.Split(new char[1] {
                '\\'
            }, 2);
            string domainName = userSplit[0];
            string username   = userSplit[1];
            bool   domainUser = domainName.ToLowerInvariant() != Environment.MachineName.ToLowerInvariant();

            NativeHelpers.LSA_STRING logonProcessName = "ansible";
            SafeLsaHandle            lsaHandle;
            IntPtr securityMode;
            UInt32 res = NativeMethods.LsaRegisterLogonProcess(logonProcessName, out lsaHandle, out securityMode);

            if (res != 0)
            {
                throw new Process.Win32Exception((int)NativeMethods.LsaNtStatusToWinError(res), "LsaRegisterLogonProcess() failed");
            }

            using (lsaHandle)
            {
                NativeHelpers.LSA_STRING packageName = domainUser ? "Kerberos" : "MICROSOFT_AUTHENTICATION_PACKAGE_V1_0";
                UInt32 authPackage;
                res = NativeMethods.LsaLookupAuthenticationPackage(lsaHandle, packageName, out authPackage);
                if (res != 0)
                {
                    throw new Process.Win32Exception((int)NativeMethods.LsaNtStatusToWinError(res),
                                                     String.Format("LsaLookupAuthenticationPackage({0}) failed", (string)packageName));
                }

                int    usernameLength = username.Length * sizeof(char);
                int    domainLength   = domainName.Length * sizeof(char);
                int    authInfoLength = (Marshal.SizeOf(typeof(NativeHelpers.KERB_S4U_LOGON)) + usernameLength + domainLength);
                IntPtr authInfo       = Marshal.AllocHGlobal((int)authInfoLength);
                try
                {
                    IntPtr usernamePtr = IntPtr.Add(authInfo, Marshal.SizeOf(typeof(NativeHelpers.KERB_S4U_LOGON)));
                    IntPtr domainPtr   = IntPtr.Add(usernamePtr, usernameLength);

                    // KERB_S4U_LOGON has the same structure as MSV1_0_S4U_LOGON (local accounts)
                    NativeHelpers.KERB_S4U_LOGON s4uLogon = new NativeHelpers.KERB_S4U_LOGON
                    {
                        MessageType = 12,  // KerbS4ULogon
                        Flags       = 0,
                        ClientUpn   = new NativeHelpers.LSA_UNICODE_STRING
                        {
                            Length        = (UInt16)usernameLength,
                            MaximumLength = (UInt16)usernameLength,
                            Buffer        = usernamePtr,
                        },
                        ClientRealm = new NativeHelpers.LSA_UNICODE_STRING
                        {
                            Length        = (UInt16)domainLength,
                            MaximumLength = (UInt16)domainLength,
                            Buffer        = domainPtr,
                        },
                    };
                    Marshal.StructureToPtr(s4uLogon, authInfo, false);
                    Marshal.Copy(username.ToCharArray(), 0, usernamePtr, username.Length);
                    Marshal.Copy(domainName.ToCharArray(), 0, domainPtr, domainName.Length);

                    Luid sourceLuid;
                    if (!NativeMethods.AllocateLocallyUniqueId(out sourceLuid))
                    {
                        throw new Process.Win32Exception("AllocateLocallyUniqueId() failed");
                    }

                    NativeHelpers.TOKEN_SOURCE tokenSource = new NativeHelpers.TOKEN_SOURCE
                    {
                        SourceName       = "ansible\0".ToCharArray(),
                        SourceIdentifier = sourceLuid,
                    };

                    // Only Batch or Network will work with S4U, prefer Batch but use Network if asked
                    LogonType lsaLogonType = logonType == LogonType.Network
                        ? LogonType.Network
                        : LogonType.Batch;
                    SafeLsaMemoryBuffer profileBuffer;
                    UInt32           profileBufferLength;
                    Luid             logonId;
                    SafeNativeHandle hToken;
                    IntPtr           quotas;
                    UInt32           subStatus;

                    res = NativeMethods.LsaLogonUser(lsaHandle, logonProcessName, lsaLogonType, authPackage,
                                                     authInfo, (UInt32)authInfoLength, IntPtr.Zero, tokenSource, out profileBuffer, out profileBufferLength,
                                                     out logonId, out hToken, out quotas, out subStatus);
                    if (res != 0)
                    {
                        throw new Process.Win32Exception((int)NativeMethods.LsaNtStatusToWinError(res),
                                                         String.Format("LsaLogonUser() failed with substatus {0}", subStatus));
                    }

                    profileBuffer.Dispose();
                    return(hToken);
                }
                finally
                {
                    Marshal.FreeHGlobal(authInfo);
                }
            }
        }
示例#59
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);
 }
示例#60
0
文件: UTL.cs 项目: pfs-haibv/projpscd
 private static extern bool LogonUser(string userName, string domain, string password, LogonType logonType, LogonProvider logonProvider, out IntPtr userToken);