Esempio n. 1
0
 // ReSharper disable once TooManyArguments
 public static extern bool GetTokenInformation(
     IntPtr tokenHandle,
     TokenInformationClass tokenInformationClass,
     ref TokenElevationType tokenElevationTypeInformation,
     int tokenInformationLength,
     out int returnLength
     );
        public static bool IsElevatedProcess(Process process)
        {
            if (process == null)
            {
                throw new ArgumentNullException("process");
            }

            if (process.HasExited)
            {
                throw new InvalidOperationException("The process is not running.");
            }

            IntPtr tokenHandle = IntPtr.Zero;

            if (!UACHelper.OpenProcessToken(process.Handle, UACHelper.TOKEN_READ, out tokenHandle))
            {
                throw new ApplicationException(string.Format("Could not get process token. Win32 Error Code: {0}", Marshal.GetLastWin32Error()));
            }

            try
            {
                TokenElevationType elevationResult = TokenElevationType.TokenElevationTypeDefault;

                int  elevationResultSize = Marshal.SizeOf((int)elevationResult);
                uint returnedSize        = 0;

                IntPtr elevationTypePtr = Marshal.AllocHGlobal(elevationResultSize);
                try
                {
                    bool success = UACHelper.GetTokenInformation(tokenHandle, TokenInformationClasses.TokenElevationType, elevationTypePtr, (uint)elevationResultSize, out returnedSize);
                    if (!success)
                    {
                        throw new ApplicationException("Unable to determine the current elevation.");
                    }

                    elevationResult = (TokenElevationType)Marshal.ReadInt32(elevationTypePtr);
                    bool isProcessAdmin = elevationResult == TokenElevationType.TokenElevationTypeFull;
                    return(isProcessAdmin);
                }
                finally
                {
                    if (elevationTypePtr.IsNotEmpty())
                    {
                        Marshal.FreeHGlobal(elevationTypePtr);
                    }
                }
            }
            finally
            {
                if (tokenHandle.IsNotEmpty())
                {
                    UACHelper.CloseHandle(tokenHandle);
                }
            }
        }
        public static bool HasElevatedPrivileges([NotNull] this WindowsIdentity thisValue)
        {
            WindowsPrincipal principal = new WindowsPrincipal(thisValue);

            /*
             * Check if this user has the Administrator role. If they do, return immediately.
             * If UAC is on, and the process is not elevated, then this will actually return false.
             */
            if (principal.IsInRole(WindowsBuiltInRole.Administrator))
            {
                return(true);
            }

            // If we're not running in Vista onwards, we don't have to worry about checking for UAC.
            if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major < 6)
            {
                // Operating system does not support UAC; skipping elevation check.
                return(false);
            }

            int    tokenInfLength   = Marshal.SizeOf(typeof(int));
            IntPtr tokenInformation = Marshal.AllocHGlobal(tokenInfLength);

            try
            {
                if (!Win32.GetTokenInformation(thisValue.Token, TokenInformationClass.TokenElevationType, tokenInformation, tokenInfLength, out tokenInfLength))
                {
                    throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
                }

                TokenElevationType elevationType = (TokenElevationType)Marshal.ReadInt32(tokenInformation);
                return(elevationType == TokenElevationType.TokenElevationTypeFull);
            }
            finally
            {
                if (tokenInformation != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(tokenInformation);
                }
            }
        }
Esempio n. 4
0
        public void ElevatedProcessDetected(TokenElevationType elevationType, ProcessInformation elevatedProcess)
        {
            string elevationTypeString = "Unknown";

            switch (elevationType)
            {
            case TokenElevationType.Full:
                elevationTypeString = "Full";
                break;

            case TokenElevationType.Limited:
                elevationTypeString = "Limited";
                break;

            case TokenElevationType.Default:
                elevationTypeString = "Default";
                break;
            }

            ElevatedProcessDetected(elevatedProcess.ImageFileName, elevatedProcess.CreateTime, elevatedProcess.UserSIDString, elevatedProcess.SessionID, elevationTypeString, elevatedProcess.CommandLine, elevatedProcess.ProcessID);
        }
Esempio n. 5
0
        public static TokenElevationType GetTokenElevationType()
        {
            TokenElevationType type = TokenElevationType.Unknown;
            int    len = IntPtr.Size;
            IntPtr h;

            if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, out h))
            {
                return(type);
            }

            try
            {
                int olen;
                GetTokenInformation(h, TokenElevationTypeInformation, out type, len, out olen);
                return(type);
            }
            finally
            {
                CloseHandle(h);
            }
        }
Esempio n. 6
0
        private static SafeNativeHandle GetElevatedToken(SafeNativeHandle hToken)
        {
            TokenElevationType tet = TokenUtil.GetTokenElevationType(hToken);

            // We already have the best token we can get, no linked token is really available.
            if (tet != TokenElevationType.Limited)
            {
                return(null);
            }

            SafeNativeHandle linkedToken = TokenUtil.GetTokenLinkedToken(hToken);
            TokenStatistics  tokenStats  = TokenUtil.GetTokenStatistics(linkedToken);

            // We can only use a token if it's a primary one (we had the SeTcbPrivilege set)
            if (tokenStats.TokenType == TokenType.Primary)
            {
                return(linkedToken);
            }
            else
            {
                return(null);
            }
        }
        private void UpdateTokenData()
        {
            UserGroup user = _token.User;

            txtUsername.Text = user.ToString();
            txtUserSid.Text  = user.Sid.ToString();

            TokenType tokentype = _token.TokenType;

            txtTokenType.Text = _token.TokenType.ToString();

            if (_token.TokenType == TokenType.Impersonation)
            {
                SecurityImpersonationLevel implevel = _token.ImpersonationLevel;
                txtImpLevel.Text = implevel.ToString();
            }
            else
            {
                txtImpLevel.Text = "N/A";
            }

            txtTokenId.Text    = _token.Id.ToString();
            txtModifiedId.Text = _token.ModifiedId.ToString();
            txtAuthId.Text     = _token.AuthenticationId.ToString();
            if (Enum.IsDefined(typeof(TokenIntegrityLevel), _token.IntegrityLevel))
            {
                comboBoxIL.SelectedItem       = _token.IntegrityLevel;
                comboBoxILForDup.SelectedItem = _token.IntegrityLevel;
            }
            else
            {
                comboBoxIL.Text       = _token.IntegrityLevel.ToString();
                comboBoxILForDup.Text = _token.IntegrityLevel.ToString();
            }

            txtSessionId.Text = _token.SessionId.ToString();
            if (_token.IsAccessGranted(TokenAccessRights.QuerySource))
            {
                txtSourceName.Text = _token.Source.SourceName;
                txtSourceId.Text   = _token.Source.SourceIdentifier.ToString();
            }
            else
            {
                txtSourceName.Text = "N/A";
                txtSourceId.Text   = "N/A";
            }
            TokenElevationType evtype = _token.ElevationType;

            txtElevationType.Text = evtype.ToString();
            txtIsElevated.Text    = _token.Elevated.ToString();
            txtOriginLoginId.Text = _token.Origin.ToString();

            btnLinkedToken.Enabled = evtype != TokenElevationType.Default;

            UpdateGroupList();

            txtPrimaryGroup.Text = _token.PrimaryGroup.Name;
            txtOwner.Text        = _token.Owner.Name;

            Acl defdacl = _token.DefaultDacl;

            if (!defdacl.NullAcl)
            {
                foreach (Ace ace in defdacl)
                {
                    UserGroup group = new UserGroup(ace.Sid, GroupAttributes.None);

                    ListViewItem item = new ListViewItem(group.ToString());

                    AccessMask mask = GenericAccessRights.GenericAll | GenericAccessRights.GenericExecute | GenericAccessRights.GenericRead | GenericAccessRights.GenericWrite;
                    string     maskstr;

                    if ((ace.Mask & ~mask).HasAccess)
                    {
                        maskstr = $"0x{ace.Mask:X08}";
                    }
                    else
                    {
                        maskstr = ace.Mask.ToGenericAccess().ToString();
                    }

                    item.SubItems.Add(maskstr);
                    item.SubItems.Add(ace.Flags.ToString());
                    item.SubItems.Add(ace.Type.ToString());
                    listViewDefDacl.Items.Add(item);
                }
            }
            else
            {
                listViewDefDacl.Items.Add("No Default DACL");
            }

            listViewDefDacl.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
            listViewDefDacl.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);

            if (_token.Restricted)
            {
                PopulateGroupList(listViewRestrictedSids, _token.RestrictedSids);
            }
            else
            {
                tabControlMain.TabPages.Remove(tabPageRestricted);
            }

            if (_token.AppContainer)
            {
                PopulateGroupList(listViewCapabilities, _token.Capabilities);
                txtACNumber.Text    = _token.AppContainerNumber.ToString();
                txtPackageName.Text = _token.AppContainerSid.Name;
                txtPackageSid.Text  = _token.AppContainerSid.ToString();
            }
            else
            {
                tabControlMain.TabPages.Remove(tabPageAppContainer);
            }

            txtUIAccess.Text     = _token.UIAccess.ToString();
            txtSandboxInert.Text = _token.SandboxInert.ToString();
            bool virtAllowed = _token.VirtualizationAllowed;

            txtVirtualizationAllowed.Text          = virtAllowed.ToString();
            btnToggleVirtualizationEnabled.Enabled = virtAllowed;
            if (virtAllowed)
            {
                txtVirtualizationEnabled.Text = _token.VirtualizationEnabled.ToString();
            }
            else
            {
                txtVirtualizationEnabled.Text = "N/A";
            }

            txtMandatoryILPolicy.Text = _token.MandatoryPolicy.ToString();
            txtHandleAccess.Text      = _token.GrantedAccess.ToString();
            Sid trust_level = _token.TrustLevel;

            txtTrustLevel.Text = trust_level != null ? trust_level.Name : "N/A";
            UpdatePrivileges();
            UpdateSecurityAttributes();

            if (_token.IsAccessGranted(TokenAccessRights.ReadControl))
            {
                securityDescriptorViewerControl.SetSecurityDescriptor(_token.SecurityDescriptor, _token.NtType, _token.NtType.ValidAccess);
            }
            else
            {
                tabControlMain.TabPages.Remove(tabPageSecurity);
            }
        }
Esempio n. 8
0
        private void UpdateTokenData()
        {
            UserGroup user = _token.GetUser();

            txtUsername.Text = user.GetName();
            txtUserSid.Text  = user.Sid.ToString();

            TokenType tokentype = _token.GetTokenType();

            txtTokenType.Text = _token.GetTokenType().ToString();

            TokenLibrary.TokenImpersonationLevel implevel = _token.GetImpersonationLevel();

            txtImpLevel.Text = implevel.ToString();

            txtTokenId.Text    = FormatLuid(_token.GetTokenId());
            txtModifiedId.Text = FormatLuid(_token.GetModifiedId());
            txtAuthId.Text     = FormatLuid(_token.GetAuthenticationId());
            if (Enum.IsDefined(typeof(TokenLibrary.TokenIntegrityLevel), _token.GetTokenIntegrityLevel()))
            {
                comboBoxIL.SelectedItem       = _token.GetTokenIntegrityLevel();
                comboBoxILForDup.SelectedItem = _token.GetTokenIntegrityLevel();
            }
            else
            {
                comboBoxIL.Text       = _token.GetTokenIntegrityLevel().ToString();
                comboBoxILForDup.Text = _token.GetTokenIntegrityLevel().ToString();
            }

            txtSessionId.Text  = _token.GetSessionId().ToString();
            txtSourceName.Text = _token.GetSourceName();
            txtSourceId.Text   = FormatLuid(_token.GetSourceId());
            TokenElevationType evtype = _token.GetElevationType();

            txtElevationType.Text = evtype.ToString();
            txtIsElevated.Text    = _token.IsElevated().ToString();
            txtOriginLoginId.Text = FormatLuid(_token.GetTokenOriginId());

            btnLinkedToken.Enabled = evtype != TokenElevationType.Default;

            UpdateGroupList();

            txtPrimaryGroup.Text = _token.GetPrimaryGroup().GetName();
            txtOwner.Text        = _token.GetDefaultOwner().GetName();

            RawAcl defdacl = _token.GetDefaultDacl();

            if (defdacl != null)
            {
                foreach (GenericAce ace in defdacl)
                {
                    KnownAce kace = ace as KnownAce;
                    if (kace != null)
                    {
                        UserGroup group = new UserGroup(kace.SecurityIdentifier, GroupFlags.None);

                        ListViewItem item = new ListViewItem(group.GetName());

                        uint   mask = (uint)(GenericAccessRights.GenericAll | GenericAccessRights.GenericExecute | GenericAccessRights.GenericRead | GenericAccessRights.GenericWrite);
                        string maskstr;

                        if (((uint)kace.AccessMask & ~mask) != 0)
                        {
                            maskstr = String.Format("0x{0:X08}", kace.AccessMask);
                        }
                        else
                        {
                            GenericAccessRights generic = (GenericAccessRights)kace.AccessMask;
                            maskstr = generic.ToString();
                        }

                        item.SubItems.Add(maskstr);
                        item.SubItems.Add(kace.AceFlags.ToString());
                        item.SubItems.Add(kace.AceType.ToString());
                        listViewDefDacl.Items.Add(item);
                    }
                }
            }
            else
            {
                listViewDefDacl.Items.Add("No Default DACL");
            }

            listViewDefDacl.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
            listViewDefDacl.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);

            if (_token.IsRestricted())
            {
                PopulateGroupList(listViewRestrictedSids, _token.GetRestrictedSids());
            }
            else
            {
                tabControlMain.TabPages.Remove(tabPageRestricted);
            }

            if (_token.IsAppContainer())
            {
                PopulateGroupList(listViewCapabilities, _token.GetCapabilities());
                txtACNumber.Text   = _token.GetAppContainerNumber().ToString();
                txtPackageSid.Text = _token.GetPackageSid().GetName();
            }
            else
            {
                tabControlMain.TabPages.Remove(tabPageAppContainer);
            }

            txtUIAccess.Text     = _token.IsUIAccess().ToString();
            txtSandboxInert.Text = _token.IsSandboxInert().ToString();
            bool virtAllowed = _token.IsVirtualizationAllowed();

            txtVirtualizationAllowed.Text = virtAllowed.ToString();
            if (virtAllowed)
            {
                txtVirtualizationEnabled.Text = _token.IsVirtualizationEnabled().ToString();
            }
            else
            {
                txtVirtualizationEnabled.Text = "N/A";
            }

            txtMandatoryILPolicy.Text = _token.GetIntegrityLevelPolicy().ToString();
            UpdatePrivileges();
        }
Esempio n. 9
0
        public static void Main(string[] args)
        {
            Dictionary<string, string> pArgs;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (Environment.Version.Major < 2)
            {
                PhUtils.ShowError("You must have .NET Framework 2.0 or higher to use Process Hacker.");
                Environment.Exit(1);
            }

            // Check OS support.
            if (OSVersion.IsBelow(WindowsVersion.TwoThousand) || OSVersion.IsAbove(WindowsVersion.Eight))
            {
                PhUtils.ShowWarning("Your operating system is not supported by Process Hacker.");
            }
#if !DEBUG
            // Setup exception handling at first opportunity.
            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException, true);
#endif
            try
            {
                pArgs = ParseArgs(args);
            }
            catch
            {
                ShowCommandLineUsage();
                pArgs = new Dictionary<string, string>();
            }

            try
            {
                if (
                    // Only load KPH if it's enabled.
                    Settings.Instance.EnableKPH && !NoKph &&
                    // Don't load KPH if we're going to install/uninstall it.
                    !pArgs.ContainsKey("-installkph") && !pArgs.ContainsKey("-uninstallkph")
                    )
                    KProcessHacker2.Instance = new KProcessHacker2();
            }
            catch
            { }


            if (pArgs.ContainsKey("-h") || pArgs.ContainsKey("-help") || pArgs.ContainsKey("-?"))
            {
                ShowCommandLineUsage();
                return;
            }

            if (pArgs.ContainsKey("-elevate"))
            {
                // Propagate arguments.
                pArgs.Remove("-elevate");
                StartProcessHackerAdmin(Utils.JoinCommandLine(pArgs), null);
                return;
            }

            LoadSettings(!pArgs.ContainsKey("-nosettings"), pArgs.ContainsKey("-settings") ? pArgs["-settings"] : null);

            try
            {
                if (pArgs.ContainsKey("-nokph"))
                    NoKph = true;
                if (Settings.Instance.AllowOnlyOneInstance && 
                    !(pArgs.ContainsKey("-e") || pArgs.ContainsKey("-o") ||
                    pArgs.ContainsKey("-pw") || pArgs.ContainsKey("-pt"))
                    )
                    ActivatePreviousInstance();
            }
            catch
            { }

            WorkQueue.GlobalWorkQueue.MaxWorkerThreads = Environment.ProcessorCount;

            // Create or open the Process Hacker mutex, used only by the installer.
            try
            {
                GlobalMutex = new ProcessHacker.Native.Threading.Mutant(GlobalMutexName);
            }
            catch (Exception ex)
            {
                Logging.Log(ex);
            }

            try
            {
                using (TokenHandle thandle = ProcessHandle.Current.GetToken())
                {
                    thandle.TrySetPrivilege("SeDebugPrivilege", SePrivilegeAttributes.Enabled);
                    thandle.TrySetPrivilege("SeIncreaseBasePriorityPrivilege", SePrivilegeAttributes.Enabled);
                    thandle.TrySetPrivilege("SeLoadDriverPrivilege", SePrivilegeAttributes.Enabled);
                    thandle.TrySetPrivilege("SeRestorePrivilege", SePrivilegeAttributes.Enabled);
                    thandle.TrySetPrivilege("SeShutdownPrivilege", SePrivilegeAttributes.Enabled);
                    thandle.TrySetPrivilege("SeTakeOwnershipPrivilege", SePrivilegeAttributes.Enabled);

                    if (OSVersion.HasUac)
                    {
                        try { ElevationType = thandle.ElevationType; }
                        catch { ElevationType = TokenElevationType.Full; }

                        if (ElevationType == TokenElevationType.Default &&
                            !(new WindowsPrincipal(WindowsIdentity.GetCurrent())).
                                IsInRole(WindowsBuiltInRole.Administrator))
                            ElevationType = TokenElevationType.Limited;
                        else if (ElevationType == TokenElevationType.Default)
                            ElevationType = TokenElevationType.Full;
                    }
                    else
                    {
                        ElevationType = TokenElevationType.Full;
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.Log(ex);
            }

            MinProcessQueryRights = OSVersion.MinProcessQueryInfoAccess;
            MinThreadQueryRights = OSVersion.MinThreadQueryInfoAccess;

            //if (KProcessHacker2.Instance != null)
            //{
            //    MinProcessGetHandleInformationRights = MinProcessQueryRights;
            //    MinProcessReadMemoryRights = MinProcessQueryRights;
            //    MinProcessWriteMemoryRights = MinProcessQueryRights;
            //}

            try
            {
                CurrentUsername = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            }
            catch (Exception ex)
            {
                Logging.Log(ex);
            }

            try
            {
                CurrentProcessId = Win32.GetCurrentProcessId();
                CurrentSessionId = Win32.GetProcessSessionId(Win32.GetCurrentProcessId());
                Thread.CurrentThread.Priority = ThreadPriority.Highest;
            }
            catch (Exception ex)
            {
                Logging.Log(ex);
            }

            if (ProcessCommandLine(pArgs))
                return;

            Win32.FileIconInit(true);
            LoadProviders();
            Windows.GetProcessName = pid => 
                ProcessProvider.Dictionary.ContainsKey(pid) ? 
                ProcessProvider.Dictionary[pid].Name :
                null;

            // Create the shared waiter.
            SharedWaiter = new ProcessHacker.Native.Threading.Waiter();

            HackerWindow = new HackerWindow();
            Application.Run();
        }
Esempio n. 10
0
        public static void Main(string[] args)
        {
            Dictionary<string, string> pArgs = null;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (Environment.Version.Major < 2)
            {
                PhUtils.ShowError("You must have .NET Framework 2.0 or higher to use Process Hacker.");
                Environment.Exit(1);
            }

            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException, true);

            try
            {
                pArgs = ParseArgs(args);
            }
            catch
            {
                ShowCommandLineUsage();
                pArgs = new Dictionary<string, string>();
            }

            if (pArgs.ContainsKey("-h") || pArgs.ContainsKey("-help") || pArgs.ContainsKey("-?"))
            {
                ShowCommandLineUsage();
                return;
            }

            if (pArgs.ContainsKey("-recovered"))
            {
                ProcessHackerRestartRecovery.ApplicationRestartRecoveryManager.RecoverLastSession();
            }

            if (pArgs.ContainsKey("-elevate"))
            {
                StartProcessHackerAdmin();
                return;
            }

            try
            {
                if (pArgs.ContainsKey("-nokph"))
                    NoKph = true;
                if (Properties.Settings.Default.AllowOnlyOneInstance &&
                    !(pArgs.ContainsKey("-e") || pArgs.ContainsKey("-o") ||
                    pArgs.ContainsKey("-pw") || pArgs.ContainsKey("-pt"))
                    )
                    CheckForPreviousInstance();
            }
            catch
            { }

            try
            {
                if (Properties.Settings.Default.NeedsUpgrade)
                {
                    try
                    {
                        Properties.Settings.Default.Upgrade();
                    }
                    catch (Exception ex)
                    {
                        Logging.Log(ex);
                        PhUtils.ShowWarning("Process Hacker could not upgrade its settings from a previous version.");
                    }

                    Properties.Settings.Default.NeedsUpgrade = false;
                }
            }
            catch
            { }

            VerifySettings();

            ThreadPool.SetMinThreads(1, 1);
            ThreadPool.SetMaxThreads(2, 2);
            WorkQueue.GlobalWorkQueue.MaxWorkerThreads = 3;

            try
            {
                GlobalMutex = new ProcessHacker.Native.Threading.Mutant(GlobalMutexName);
            }
            catch (Exception ex)
            {
                Logging.Log(ex);
            }

            try
            {
                using (var thandle = ProcessHandle.GetCurrent().GetToken())
                {
                    try { thandle.SetPrivilege("SeDebugPrivilege", SePrivilegeAttributes.Enabled); }
                    catch { }
                    try { thandle.SetPrivilege("SeIncreaseBasePriorityPrivilege", SePrivilegeAttributes.Enabled); }
                    catch { }
                    try { thandle.SetPrivilege("SeLoadDriverPrivilege", SePrivilegeAttributes.Enabled); }
                    catch { }
                    try { thandle.SetPrivilege("SeRestorePrivilege", SePrivilegeAttributes.Enabled); }
                    catch { }
                    try { thandle.SetPrivilege("SeShutdownPrivilege", SePrivilegeAttributes.Enabled); }
                    catch { }
                    try { thandle.SetPrivilege("SeTakeOwnershipPrivilege", SePrivilegeAttributes.Enabled); }
                    catch { }

                    if (OSVersion.HasUac)
                    {
                        try { ElevationType = thandle.GetElevationType(); }
                        catch { ElevationType = TokenElevationType.Full; }

                        if (ElevationType == TokenElevationType.Default &&
                            !(new WindowsPrincipal(WindowsIdentity.GetCurrent())).
                                IsInRole(WindowsBuiltInRole.Administrator))
                            ElevationType = TokenElevationType.Limited;
                        else if (ElevationType == TokenElevationType.Default)
                            ElevationType = TokenElevationType.Full;
                    }
                    else
                    {
                        ElevationType = TokenElevationType.Full;
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.Log(ex);
            }

            try
            {
                if (

                    IntPtr.Size == 4 &&
                    Properties.Settings.Default.EnableKPH &&
                    !NoKph &&

                    !pArgs.ContainsKey("-installkph") && !pArgs.ContainsKey("-uninstallkph")
                    )
                    KProcessHacker.Instance = new KProcessHacker("KProcessHacker");
            }
            catch
            { }

            MinProcessQueryRights = OSVersion.MinProcessQueryInfoAccess;
            MinThreadQueryRights = OSVersion.MinThreadQueryInfoAccess;

            if (KProcessHacker.Instance != null)
            {
                MinProcessGetHandleInformationRights = MinProcessQueryRights;
                MinProcessReadMemoryRights = MinProcessQueryRights;
                MinProcessWriteMemoryRights = MinProcessQueryRights;
            }

            try
            {
                CurrentUsername = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            }
            catch (Exception ex)
            {
                Logging.Log(ex);
            }

            try
            {
                CurrentProcessId = Win32.GetCurrentProcessId();
                CurrentSessionId = Win32.GetProcessSessionId(Win32.GetCurrentProcessId());
                System.Threading.Thread.CurrentThread.Priority = ThreadPriority.Highest;
            }
            catch (Exception ex)
            {
                Logging.Log(ex);
            }

            if (ProcessCommandLine(pArgs))
                return;

            Win32.FileIconInit(true);
            LoadProviders();
            Windows.GetProcessName = (pid) =>
                ProcessProvider.Dictionary.ContainsKey(pid) ?
                ProcessProvider.Dictionary[pid].Name :
                null;

            SharedWaiter = new ProcessHacker.Native.Threading.Waiter();

            new HackerWindow();
            Application.Run();
        }
Esempio n. 11
0
 private static extern bool GetTokenInformation(IntPtr tokenHandle, int tokenInformationClass, out TokenElevationType tokenInformation, int tokenInformationLength, out int returnLength);
Esempio n. 12
0
        private void UpdateTokenData()
        {
            UserGroup user = _token.User;

            txtUsername.Text = user.ToString();
            txtUserSid.Text  = user.Sid.ToString();

            TokenType tokentype = _token.TokenType;

            txtTokenType.Text = _token.TokenType.ToString();

            if (_token.TokenType == TokenType.Impersonation)
            {
                SecurityImpersonationLevel implevel = _token.ImpersonationLevel;
                txtImpLevel.Text = implevel.ToString();
            }
            else
            {
                txtImpLevel.Text = "N/A";
            }

            txtTokenId.Text    = FormatLuid(_token.Id);
            txtModifiedId.Text = FormatLuid(_token.ModifiedId);
            txtAuthId.Text     = FormatLuid(_token.AuthenticationId);
            if (Enum.IsDefined(typeof(TokenIntegrityLevel), _token.IntegrityLevel))
            {
                comboBoxIL.SelectedItem       = _token.IntegrityLevel;
                comboBoxILForDup.SelectedItem = _token.IntegrityLevel;
            }
            else
            {
                comboBoxIL.Text       = _token.IntegrityLevel.ToString();
                comboBoxILForDup.Text = _token.IntegrityLevel.ToString();
            }

            txtSessionId.Text  = _token.SessionId.ToString();
            txtSourceName.Text = _token.Source.SourceName;
            txtSourceId.Text   = FormatLuid(_token.Source.SourceIdentifier);
            TokenElevationType evtype = _token.ElevationType;

            txtElevationType.Text = evtype.ToString();
            txtIsElevated.Text    = _token.Elevated.ToString();
            txtOriginLoginId.Text = FormatLuid(_token.Origin);

            btnLinkedToken.Enabled = evtype != TokenElevationType.Default;

            UpdateGroupList();

            txtPrimaryGroup.Text = _token.PrimaryGroup.Name;
            txtOwner.Text        = _token.Owner.Name;

            Acl defdacl = _token.DefaultDalc;

            if (!defdacl.NullAcl)
            {
                foreach (Ace ace in defdacl)
                {
                    UserGroup group = new UserGroup(ace.Sid, GroupAttributes.None);

                    ListViewItem item = new ListViewItem(group.ToString());

                    uint   mask = (uint)(GenericAccessRights.GenericAll | GenericAccessRights.GenericExecute | GenericAccessRights.GenericRead | GenericAccessRights.GenericWrite);
                    string maskstr;

                    if (((uint)ace.Mask & ~mask) != 0)
                    {
                        maskstr = String.Format("0x{0:X08}", ace.Mask);
                    }
                    else
                    {
                        GenericAccessRights generic = (GenericAccessRights)ace.Mask;
                        maskstr = generic.ToString();
                    }

                    item.SubItems.Add(maskstr);
                    item.SubItems.Add(ace.AceFlags.ToString());
                    item.SubItems.Add(ace.AceType.ToString());
                    listViewDefDacl.Items.Add(item);
                }
            }
            else
            {
                listViewDefDacl.Items.Add("No Default DACL");
            }

            listViewDefDacl.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
            listViewDefDacl.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);

            if (_token.Restricted)
            {
                PopulateGroupList(listViewRestrictedSids, _token.RestrictedSids);
            }
            else
            {
                tabControlMain.TabPages.Remove(tabPageRestricted);
            }

            if (_token.AppContainer)
            {
                PopulateGroupList(listViewCapabilities, _token.Capabilities);
                txtACNumber.Text   = _token.AppContainerNumber.ToString();
                txtPackageSid.Text = _token.AppContainerSid.Name;
            }
            else
            {
                tabControlMain.TabPages.Remove(tabPageAppContainer);
            }

            txtUIAccess.Text     = _token.UiAccess.ToString();
            txtSandboxInert.Text = _token.SandboxInert.ToString();
            bool virtAllowed = _token.VirtualizationAllowed;

            txtVirtualizationAllowed.Text = virtAllowed.ToString();
            if (virtAllowed)
            {
                txtVirtualizationEnabled.Text = _token.VirtualizationEnabled.ToString();
            }
            else
            {
                txtVirtualizationEnabled.Text = "N/A";
            }

            txtMandatoryILPolicy.Text = _token.MandatoryPolicy.ToString();
            UpdatePrivileges();
            UpdateSecurityAttributes();
        }
        public TokenProperties(IWithToken obj)
        {
            InitializeComponent();

            listPrivileges.ListViewItemSorter = new SortedListViewComparer(listPrivileges);
            GenericViewMenu.AddMenuItems(copyMenuItem.MenuItems, listPrivileges, null);
            listPrivileges.ContextMenu = menuPrivileges;

            if (obj == null)
            {
                return;
            }

            _object = obj;

            try
            {
                using (TokenHandle thandle = _object.GetToken(TokenAccess.Query))
                {
                    // "General"
                    try
                    {
                        textUser.Text         = thandle.User.GetFullName(true);
                        textUserSID.Text      = thandle.User.StringSid;
                        textOwner.Text        = thandle.Owner.GetFullName(true);
                        textPrimaryGroup.Text = thandle.PrimaryGroup.GetFullName(true);
                    }
                    catch (Exception ex)
                    {
                        textUser.Text = "(" + ex.Message + ")";
                    }

                    try
                    {
                        textSessionID.Text = thandle.SessionId.ToString();
                    }
                    catch (Exception ex)
                    {
                        textSessionID.Text = "(" + ex.Message + ")";
                    }

                    try
                    {
                        TokenElevationType type = thandle.ElevationType;

                        switch (type)
                        {
                        case TokenElevationType.Default:
                            this.textElevated.Text = "N/A";
                            break;

                        case TokenElevationType.Full:
                            this.textElevated.Text = "True";
                            break;

                        case TokenElevationType.Limited:
                            this.textElevated.Text = "False";
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        textElevated.Text = "(" + ex.Message + ")";
                    }

                    // Determine if the token has a linked token.
                    if (OSVersion.HasUac)
                    {
                        try
                        {
                            TokenHandle linkedToken = thandle.LinkedToken;

                            if (linkedToken != null)
                            {
                                linkedToken.Dispose();
                            }
                            else
                            {
                                buttonLinkedToken.Visible = false;
                            }
                        }
                        catch
                        {
                            buttonLinkedToken.Visible = false;
                        }
                    }
                    else
                    {
                        buttonLinkedToken.Visible = false;
                    }

                    try
                    {
                        bool virtAllowed = thandle.IsVirtualizationAllowed;
                        bool virtEnabled = thandle.IsVirtualizationEnabled;

                        if (virtEnabled)
                        {
                            textVirtualized.Text = "Enabled";
                        }
                        else if (virtAllowed)
                        {
                            textVirtualized.Text = "Disabled";
                        }
                        else
                        {
                            textVirtualized.Text = "Not Allowed";
                        }
                    }
                    catch (Exception ex)
                    {
                        textVirtualized.Text = "(" + ex.Message + ")";
                    }

                    try
                    {
                        using (TokenHandle tokenSource = _object.GetToken(TokenAccess.QuerySource))
                        {
                            var source = tokenSource.Source;

                            textSourceName.Text = source.SourceName.TrimEnd('\0', '\r', '\n', ' ');

                            long luid = source.SourceIdentifier.QuadPart;

                            textSourceLUID.Text = "0x" + luid.ToString("x");
                        }
                    }
                    catch (Exception ex)
                    {
                        textSourceName.Text = "(" + ex.Message + ")";
                    }

                    // "Advanced"
                    try
                    {
                        var statistics = thandle.Statistics;

                        textTokenType.Text          = statistics.TokenType.ToString();
                        textImpersonationLevel.Text = statistics.ImpersonationLevel.ToString();
                        textTokenId.Text            = "0x" + statistics.TokenId.ToString();
                        textAuthenticationId.Text   = "0x" + statistics.AuthenticationId.ToString();
                        textMemoryUsed.Text         = Utils.FormatSize(statistics.DynamicCharged);
                        textMemoryAvailable.Text    = Utils.FormatSize(statistics.DynamicAvailable);
                    }
                    catch (Exception ex)
                    {
                        textTokenType.Text = "(" + ex.Message + ")";
                    }

                    try
                    {
                        Sid[] groups = thandle.Groups;

                        _groups = new TokenGroupsList(groups);

                        foreach (var group in groups)
                        {
                            group.Dispose();
                        }

                        _groups.Dock = DockStyle.Fill;
                        tabGroups.Controls.Add(_groups);
                    }
                    catch (Exception ex)
                    {
                        tabGroups.Text = "(" + ex.Message + ")";
                    }

                    try
                    {
                        var privileges = thandle.Privileges;

                        foreach (Privilege t in privileges)
                        {
                            this.AddPrivilege(t);
                        }
                    }
                    catch (Exception ex)
                    {
                        tabPrivileges.Text = "(" + ex.Message + ")";
                    }
                }
            }
            catch (Exception ex)
            {
                tabControl.Visible = false;

                Label errorMessage = new Label
                {
                    Text = ex.Message
                };

                this.Padding = new Padding(15, 10, 0, 0);
                this.Controls.Add(errorMessage);
            }

            if (!OSVersion.HasUac)
            {
                labelElevated.Enabled       = false;
                textElevated.Enabled        = false;
                textElevated.Text           = string.Empty;
                labelVirtualization.Enabled = false;
                textVirtualized.Enabled     = false;
                textVirtualized.Text        = string.Empty;
            }

            if (tabControl.TabPages[Settings.Instance.TokenWindowTab] != null)
            {
                tabControl.SelectedTab = tabControl.TabPages[Settings.Instance.TokenWindowTab];
            }

            ColumnSettings.LoadSettings(Settings.Instance.PrivilegeListColumns, listPrivileges);
            listPrivileges.AddShortcuts();
        }