Пример #1
0
        private static void AdjustToken()
        {
            using (Process process = Process.GetCurrentProcess())
            {
                SafeTokenHandle hToken = SafeTokenHandle.InvalidHandle;

                try
                {
                    if (!NativeMethods.OpenProcessToken(process.Handle, TokenAccessLevels.AdjustPrivileges, ref hToken))
                    {
                        throw PscxException.LastWin32Exception();
                    }

                    TokenPrivilegeCollection privileges = new TokenPrivilegeCollection();

                    privileges.Enable(TokenPrivilege.Backup);
                    privileges.Enable(TokenPrivilege.Restore);

                    Utils.AdjustTokenPrivileges(hToken, privileges);
                }
                finally
                {
                    hToken.Dispose();
                }
            }
        }
Пример #2
0
        public virtual bool IsInRole(SecurityIdentifier sid)
        {
            if (sid == null)
            {
                throw new ArgumentNullException("sid");
            }
            if (this.m_identity.TokenHandle.IsInvalid)
            {
                return(false);
            }
            SafeTokenHandle invalidHandle = SafeTokenHandle.InvalidHandle;

            if ((this.m_identity.ImpersonationLevel == TokenImpersonationLevel.None) && !Win32Native.DuplicateTokenEx(this.m_identity.TokenHandle, (uint)8, IntPtr.Zero, (uint)2, (uint)2, ref invalidHandle))
            {
                throw new SecurityException(Win32Native.GetMessage(Marshal.GetLastWin32Error()));
            }
            bool isMember = false;

            if (!Win32Native.CheckTokenMembership((this.m_identity.ImpersonationLevel != TokenImpersonationLevel.None) ? this.m_identity.TokenHandle : invalidHandle, sid.BinaryForm, ref isMember))
            {
                throw new SecurityException(Win32Native.GetMessage(Marshal.GetLastWin32Error()));
            }
            invalidHandle.Dispose();
            return(isMember);
        }
Пример #3
0
        public static bool Validate(string domainName, string userName, string passwd)
        {
            SafeTokenHandle safeTokenHandle = null;

            const int LOGON32_PROVIDER_DEFAULT = 0;
            //This parameter causes LogonUser to create a primary token.
            const int LOGON32_LOGON_INTERACTIVE = 2;

            // Call LogonUser to obtain a handle to an access token.
            try
            {
                bool returnValue = LogonUser(userName, domainName, passwd,
                                             LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                                             out safeTokenHandle);
                //if(!returnValue)
                //{
                //    throw new Exception(new Win32Exception(Marshal.GetLastWin32Error()).Message);
                //}
                return(returnValue);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                safeTokenHandle?.Dispose();
            }
        }
Пример #4
0
        public void Dispose()
        {
#if NETSTANDARD || NETCOREAPP
            NativeMethods.RevertToSelf();
#else
            impersonationContext?.Undo();
#endif
            token?.Dispose();
            identity?.Dispose();
        }
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (m_safeTokenHandle != null && !m_safeTokenHandle.IsClosed)
         {
             Undo();
             m_safeTokenHandle.Dispose();
         }
     }
 }
Пример #6
0
 public void Dispose()
 {
     if (identity != null)
     {
         identity.Dispose();
         identity = null;
     }
     if (token != null)
     {
         token.Dispose();
         token = null;
     }
 }
        public void stop()
        {
            if (winIC != null)
            {
                winIC.Undo();
                winIC.Dispose();
                winIC = null;
            }

            if (safeTokenHandle != null)
            {
                safeTokenHandle.Dispose();
                safeTokenHandle = null;
            }
        }
Пример #8
0
        /// <summary>
        /// Internal implementation of <see cref="IDisposable" /> interface.
        /// </summary>
        /// <param name="disposing">indicates that method called from public Dispose method</param>
        private void Dispose(bool disposing)
        {
            if (IsDisposed)
            {
                return;
            }

            if (disposing)
            {
                _processHandle.Dispose();

                Process.Dispose();
            }

            IsDisposed = true;
        }
Пример #9
0
        private static void SetPrivilege(string privilegeName, int attrib)
        {
            SafeTokenHandle hToken = null;

            Interop.Advapi32.LUID debugValue = new Interop.Advapi32.LUID();

            // this is only a "pseudo handle" to the current process - no need to close it later
            SafeProcessHandle processHandle = Interop.Kernel32.GetCurrentProcess();

            // get the process token so we can adjust the privilege on it.  We DO need to
            // close the token when we're done with it.
            if (!Interop.Advapi32.OpenProcessToken(processHandle, Interop.Kernel32.HandleOptions.TOKEN_ADJUST_PRIVILEGES, out hToken))
            {
                throw new Win32Exception();
            }

            try
            {
                if (!Interop.Advapi32.LookupPrivilegeValue(null, privilegeName, out debugValue))
                {
                    throw new Win32Exception();
                }

                Interop.Advapi32.TokenPrivileges tkp = new Interop.Advapi32.TokenPrivileges();
                tkp.Luid       = debugValue;
                tkp.Attributes = attrib;

                Interop.Advapi32.AdjustTokenPrivileges(hToken, false, tkp, 0, IntPtr.Zero, IntPtr.Zero);

                // AdjustTokenPrivileges can return true even if it failed to
                // set the privilege, so we need to use GetLastError
                if (Marshal.GetLastWin32Error() != Interop.Errors.ERROR_SUCCESS)
                {
                    throw new Win32Exception();
                }
            }
            finally
            {
#if FEATURE_TRACESWITCH
                Debug.WriteLineIf(_processTracing.TraceVerbose, "Process - CloseHandle(processToken)");
#endif
                if (hToken != null)
                {
                    hToken.Dispose();
                }
            }
        }
Пример #10
0
        /// <summary>
        ///     Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing">
        ///     <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only
        ///     unmanaged resources.
        /// </param>
        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_ImpersonationContext != null)
                {
                    _ImpersonationContext.Undo();
                    _ImpersonationContext = null;
                }

                if (_SafeDuplicateTokenHandle != null)
                {
                    _SafeDuplicateTokenHandle.Dispose();
                    _SafeDuplicateTokenHandle = null;
                }
            }
        }
Пример #11
0
        private static unsafe void SetPrivilege(string privilegeName, int attrib)
        {
            // this is only a "pseudo handle" to the current process - no need to close it later
            SafeProcessHandle processHandle = Interop.Kernel32.GetCurrentProcess();

            SafeTokenHandle hToken = null;

            try
            {
                // get the process token so we can adjust the privilege on it.  We DO need to
                // close the token when we're done with it.
                if (!Interop.Advapi32.OpenProcessToken(processHandle, Interop.Kernel32.HandleOptions.TOKEN_ADJUST_PRIVILEGES, out hToken))
                {
                    throw new Win32Exception();
                }

                if (!Interop.Advapi32.LookupPrivilegeValue(null, privilegeName, out Interop.Advapi32.LUID luid))
                {
                    throw new Win32Exception();
                }

                Interop.Advapi32.TOKEN_PRIVILEGE tp;
                tp.PrivilegeCount        = 1;
                tp.Privileges.Luid       = luid;
                tp.Privileges.Attributes = (uint)attrib;

                Interop.Advapi32.AdjustTokenPrivileges(hToken, false, &tp, 0, null, null);

                // AdjustTokenPrivileges can return true even if it failed to
                // set the privilege, so we need to use GetLastError
                if (Marshal.GetLastWin32Error() != Interop.Errors.ERROR_SUCCESS)
                {
                    throw new Win32Exception();
                }
            }
            finally
            {
                if (hToken != null)
                {
                    hToken.Dispose();
                }
            }
        }
        // -----------------------------
        // ---- PAL layer ends here ----
        // -----------------------------

        static unsafe ProcessManager()
        {
            // In order to query information (OpenProcess) on some protected processes
            // like csrss, we need SeDebugPrivilege privilege.
            // After removing the dependency on Performance Counter, we don't have a chance
            // to run the code in CLR performance counter to ask for this privilege.
            // So we will try to get the privilege here.
            // We could fail if the user account doesn't have right to do this, but that's fair.

            Interop.Advapi32.LUID luid = new Interop.Advapi32.LUID();
            if (!Interop.Advapi32.LookupPrivilegeValue(null, Interop.Advapi32.SeDebugPrivilege, out luid))
            {
                return;
            }

            SafeTokenHandle tokenHandle = null;

            try
            {
                if (!Interop.Advapi32.OpenProcessToken(
                        Interop.Kernel32.GetCurrentProcess(),
                        Interop.Kernel32.HandleOptions.TOKEN_ADJUST_PRIVILEGES,
                        out tokenHandle))
                {
                    return;
                }

                Interop.Advapi32.TOKEN_PRIVILEGE tp;
                tp.PrivilegeCount        = 1;
                tp.Privileges.Luid       = luid;
                tp.Privileges.Attributes = Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_ENABLED;

                // AdjustTokenPrivileges can return true even if it didn't succeed (when ERROR_NOT_ALL_ASSIGNED is returned).
                Interop.Advapi32.AdjustTokenPrivileges(tokenHandle, false, &tp, 0, null, null);
            }
            finally
            {
                if (tokenHandle != null)
                {
                    tokenHandle.Dispose();
                }
            }
        }
Пример #13
0
        public virtual bool IsInRole(SecurityIdentifier sid)
        {
            if (sid == null)
            {
                throw new ArgumentNullException("sid");
            }
            Contract.EndContractBlock();

            // special case the anonymous identity.
            if (m_identity.TokenHandle.IsInvalid)
            {
                return(false);
            }

            // CheckTokenMembership expects an impersonation token
            SafeTokenHandle token = SafeTokenHandle.InvalidHandle;

            if (m_identity.ImpersonationLevel == TokenImpersonationLevel.None)
            {
                if (!Win32Native.DuplicateTokenEx(m_identity.TokenHandle,
                                                  (uint)TokenAccessLevels.Query,
                                                  IntPtr.Zero,
                                                  (uint)TokenImpersonationLevel.Identification,
                                                  (uint)TokenType.TokenImpersonation,
                                                  ref token))
                {
                    throw new SecurityException(Win32Native.GetMessage(Marshal.GetLastWin32Error()));
                }
            }

            bool isMember = false;

            // CheckTokenMembership will check if the SID is both present and enabled in the access token.
            if (!Win32Native.CheckTokenMembership((m_identity.ImpersonationLevel != TokenImpersonationLevel.None ? m_identity.TokenHandle : token),
                                                  sid.BinaryForm,
                                                  ref isMember))
            {
                throw new SecurityException(Win32Native.GetMessage(Marshal.GetLastWin32Error()));
            }

            token.Dispose();
            return(isMember);
        }
Пример #14
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);
            }
        }
Пример #15
0
 public void Dispose()
 {
     context?.Dispose();
     handle?.Dispose();
 }
Пример #16
0
 public void Dispose() => tokenHandle.Dispose();
Пример #17
0
        public Collection<PSObject> RunPowerShell(Dictionary<string, object> arguments, LoginViewModel clientId)
        {
            // Start with identity assigned by IIS Application Pool
            var poolIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();

            // TODO: remove, this is for initial testing
            //scriptPath = Path.Combine(DT2.Properties.Settings.Default.PowerShellScriptsFolder, "TestScript.ps1");
            Command command = new Command(scriptPath);

            if (arguments != null)
            {
                foreach (var argument in arguments)
                {
                    command.Parameters.Add(argument.Key, argument.Value);
                }
            }
            if (debug)
            {
                command.Parameters.Add("debug");
            }
            command.Parameters.Add("log", logger);

            // add the ndc context
            string ndcContext = log4net.NDC.Pop();
            log4net.NDC.Push(ndcContext);
            command.Parameters.Add("ndcContext", ndcContext);

            try
            {
                logger.Debug("Application Pool identity is " + poolIdentity.Name + ", but we will impersonate " +
                             clientId.UserName);

                if (System.Security.SecurityContext.IsWindowsIdentityFlowSuppressed())
                {
                    logger.Error("PowerShell calls will fail, because IsWindowsIdentityFlowSuppressed true");
                }

                // A RunSpace defines the operating system environment, which references HKCU\Environment
                // We create it now before impersonating an identity that might not have HKCU\Environment access
                // TODO: it may be possible to improve performance by using a RunSpacePool
                using (PowerShell powerShell = PowerShell.Create())
                {
                    Runspace runspace = RunspaceFactory.CreateRunspace();
                    runspace.Open();
                    powerShell.Runspace = runspace;
                    Collection<PSObject> results;

                    IntPtr handle;
                    SafeTokenHandle _handle;
                    /// Test:  generate primary login token
                    /// LOGON32_PROVIDER_DEFAULT = 0
                    /// 
                    logger.Debug("LogonUser call for " + clientId.UserNameNoDomain);
                    bool logonSuccess = NativeMethods.LogonUser(clientId.UserNameNoDomain, clientId.DomainName,
                        clientId.Password,
                        (int) LogonType.Interactive, 0, out handle);
                    _handle = new SafeTokenHandle(handle);

                    if (!logonSuccess)
                    {
                        string errMsg = "LogonUser() for " + clientId.UserName +
                                        "failed - no handle for user credentials:" +
                                        Marshal.GetLastWin32Error();
                        throw new Win32Exception(errMsg);
                    }


                    // When 'using' block ends, the thread reverts back to previous Windows identity,
                    // because under the hood WindowsImpersonationContext.Undo() is called by Dispose()
                    try
                    {
                        using (
                            WindowsImpersonationContext wic = WindowsIdentity.Impersonate(_handle.DangerousGetHandle()))
                        {
                            // WindowsIdentity will have changed to match clientId
                            var clientIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();
                            logger.Debug("Application Pool identity is now " + clientIdentity.Name);

                            powerShell.Commands.AddCommand(command);
                            logger.Debug("Calling " + scriptPath);
                            results = powerShell.Invoke();
                        }
                    }
                    // Back to the original identity
                    finally
                    {
                        // dispose of the LogonUser handle
                        _handle.Dispose();
                        // clean up RunSpace used by the PowerShell object
                        runspace.Close();
                        runspace.Dispose();
                    }

                    // The order is important here. Debug messages are flushed to the log *before* checking for errors
                    // so the debug traces leading up to an error are not lost 
                    Collection<PSObject> filteredResults = new Collection<PSObject>();
                    foreach (PSObject result in results)
                    {
                        string output = result.BaseObject as string;
                        if ((output != null) && output.StartsWith(DebugPrefix))
                        {
                            if (debug)
                            {
                                logger.Info(output.Substring(DebugPrefix.Length));
                            }
                        }
                        else
                        {
                            filteredResults.Add(result);
                        }
                    }
                    foreach (DebugRecord r in powerShell.Streams.Debug)
                    {
                        logger.Info(r.Message);
                    }
                    logger.Debug("Examining powershell error records");
                    foreach (ErrorRecord r in powerShell.Streams.Error)
                    {
                        // If the exception doesn't match a "to be ignored" exception, then throw it
                        if (IgnoreExceptions.SingleOrDefault(i =>
                            i.Equals(r.Exception.GetType().FullName, StringComparison.InvariantCultureIgnoreCase)) ==
                            null)
                        {
                            logger.Error("Powershell reported exception:" + r.ErrorDetails);
                            throw r.Exception;
                        }
                    }
                    return filteredResults;
                }
            }
            catch (Exception e)
            {
                logger.Error(e);
                logger.Error(e.Message);
                logger.Error(e.StackTrace);
                throw;
            }
        }