Пример #1
0
        private void QueryValues()
        {
            if (_allow_query)
            {
                _allow_query = false;
                NtToken.EnableDebugPrivilege();
                using (var obj = NtGeneric.DuplicateFrom(ProcessId,
                                                         new IntPtr(Handle), 0, DuplicateObjectOptions.SameAccess, false)) {
                    if (!obj.IsSuccess)
                    {
                        return;
                    }

                    NtType = obj.Result.NtType;
                    if (!_force_file_query && obj.Result.NtTypeName == "File")
                    {
                        using (var file = obj.Result.ToTypedObject() as NtFile) {
                            var device_type = file?.DeviceType ?? FileDeviceType.UNKNOWN;
                            switch (device_type)
                            {
                            case FileDeviceType.DISK:
                            case FileDeviceType.CD_ROM:
                                break;

                            default:
                                return;
                            }
                        }
                    }
                    _handle_valid = true;
                    _name         = GetName(obj.Result);
                    _sd           = GetSecurityDescriptor(obj.Result);
                }
            }
        }
        public static IEnumerable <COMProcessEntry> GetProcesses(IEnumerable <Process> procs, string dbghelp_path, string symbol_path, IProgress <Tuple <string, int> > progress)
        {
            List <COMProcessEntry> ret = new List <COMProcessEntry>();

            NtToken.EnableDebugPrivilege();
            int total_count   = procs.Count();
            int current_count = 0;

            foreach (Process p in procs)
            {
                try
                {
                    if (progress != null)
                    {
                        progress.Report(new Tuple <string, int>(String.Format("Parsing process {0}", p.ProcessName),
                                                                100 * current_count++ / total_count));
                    }
                    COMProcessEntry proc = COMProcessParser.ParseProcess(p.Id,
                                                                         dbghelp_path, symbol_path);
                    if (proc != null)
                    {
                        ret.Add(proc);
                    }
                }
                catch (Win32Exception)
                {
                }
                finally
                {
                    p.Close();
                }
            }

            return(ret);
        }
        internal override void RunAccessCheck(IEnumerable <TokenEntry> tokens)
        {
            AccessMask access_rights        = _process_type.MapGenericRights(AccessRights);
            AccessMask thread_access_rights = _thread_type.MapGenericRights(ThreadAccessRights);

            if (!NtToken.EnableDebugPrivilege())
            {
                WriteWarning("Current process doesn't have SeDebugPrivilege, results may be inaccurate");
            }

            if (CheckProcess())
            {
                using (var procs = NtProcess.GetProcesses(ProcessAccessRights.MaximumAllowed, false).ToDisposableList())
                {
                    DoAccessCheck(tokens, procs.Where(p => ShowDeadProcesses || !p.IsDeleting), access_rights, thread_access_rights);
                }
            }
            else
            {
                using (var threads = NtThread.GetThreads(ThreadAccessRights.MaximumAllowed, true).ToDisposableList())
                {
                    foreach (var thread in threads)
                    {
                        DoAccessCheck(tokens, ProcessDetails.FromThread(thread), thread, thread_access_rights);
                    }
                }
            }
        }
Пример #4
0
        public void UpdateProcessList(ProcessAccessRights desired_access, bool require_token)
        {
            NtToken.EnableDebugPrivilege();
            ClearListView();
            using (var ps = NtProcess.GetProcesses(ProcessAccessRights.QueryLimitedInformation | desired_access, true).ToDisposableList())
            {
                foreach (var p in ps.OrderBy(p => p.ProcessId))
                {
                    using (var result = NtToken.OpenProcessToken(p, TokenAccessRights.MaximumAllowed, false))
                    {
                        if (!result.IsSuccess && require_token)
                        {
                            continue;
                        }

                        ListViewItem item = listViewProcesses.Items.Add(p.ProcessId.ToString());
                        item.SubItems.Add(p.Name);
                        if (result.IsSuccess)
                        {
                            NtToken token = result.Result;
                            item.SubItems.Add(p.User.Name);
                            item.SubItems.Add(token.IntegrityLevel.ToString());
                        }
                        item.Tag = _processes.AddResource(p.Duplicate());
                    }
                }
            }
            listViewProcesses.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
            listViewProcesses.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            listViewProcesses.ListViewItemSorter = new ListItemComparer(0);
        }
        private protected override void RunAccessCheck(IEnumerable <TokenEntry> tokens)
        {
            if (!NtToken.EnableDebugPrivilege())
            {
                WriteWarning("Current process doesn't have SeDebugPrivilege, results may be inaccurate");
            }

            NtType     type               = NtType.GetTypeByType <NtToken>();
            AccessMask access_rights      = type.MapGenericRights(AccessRights);
            int        current_session_id = NtProcess.Current.SessionId;

            using (var procs = NtProcess.GetProcesses(ProcessAccessRights.QueryInformation | ProcessAccessRights.ReadControl, false).ToDisposableList())
            {
                IEnumerable <NtProcess> proc_enum = procs;
                if (CurrentSession)
                {
                    proc_enum = proc_enum.Where(p => CheckSession(p, current_session_id));
                }
                foreach (var proc in proc_enum.Where(p => ShowDeadProcesses || !p.IsDeleting))
                {
                    using (var result = NtToken.OpenProcessToken(proc, TokenAccessRights.ReadControl | TokenAccessRights.Query, false))
                    {
                        if (!result.IsSuccess)
                        {
                            WriteWarning($"Couldn't open token for Process {proc.Name} PID: {proc.ProcessId} Status: {result.Status}");
                            continue;
                        }

                        NtToken primary_token = result.Result;
                        var     sd_result     = primary_token.GetSecurityDescriptor(SecurityInformation.AllBasic, false);
                        if (!sd_result.IsSuccess)
                        {
                            WriteWarning($"Couldn't get token's Security Descriptor for Process {proc.Name} PID: {proc.ProcessId} Status: {sd_result.Status}");
                            continue;
                        }

                        var    sd              = sd_result.Result;
                        string process_name    = proc.Name;
                        string process_cmdline = proc.CommandLine;
                        string image_path      = proc.FullPath;
                        int    process_id      = proc.ProcessId;

                        foreach (var token in tokens)
                        {
                            if (proc.GetMaximumAccess(token.Token).HasFlag(ProcessAccessRights.QueryLimitedInformation))
                            {
                                AccessMask granted_access = NtSecurity.GetMaximumAccess(sd, token.Token, type.GenericMapping);
                                if (IsAccessGranted(granted_access, access_rights))
                                {
                                    WriteObject(new TokenAccessCheckResult(primary_token, proc,
                                                                           granted_access, sd, token.Information));
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Overridden process record method.
        /// </summary>
        protected override void ProcessRecord()
        {
            HashSet <TokenEntry> tokens = new HashSet <TokenEntry>(new TokenEntryComparer());

            try
            {
                bool explicit_tokens = false;
                NtToken.EnableDebugPrivilege();

                if (Token != null)
                {
                    foreach (NtToken token in Token)
                    {
                        AddTokenEntry(tokens, new TokenEntry(token));
                    }
                    explicit_tokens = true;
                }

                if (ProcessId != null)
                {
                    GetTokensFromPids(tokens, ProcessId);
                    explicit_tokens = true;
                }

                if (GetTokensFromArguments(tokens, ProcessName, ProcessCommandLine))
                {
                    explicit_tokens = true;
                }

                if (Process != null)
                {
                    foreach (NtProcess process in Process)
                    {
                        AddTokenEntryFromProcess(tokens, process);
                    }
                    explicit_tokens = true;
                }

                if (tokens.Count == 0)
                {
                    if (explicit_tokens)
                    {
                        return;
                    }

                    AddTokenEntryFromProcess(tokens, NtProcess.Current);
                }

                RunAccessCheck(tokens);
            }
            finally
            {
                foreach (TokenEntry token in tokens)
                {
                    token.Dispose();
                }
            }
        }
Пример #7
0
 static void Main()
 {
     CoInitializeSecurity(IntPtr.Zero, -1, IntPtr.Zero, IntPtr.Zero, AuthnLevel.RPC_C_AUTHN_LEVEL_DEFAULT,
                          ImpLevel.RPC_C_IMP_LEVEL_IMPERSONATE, IntPtr.Zero, EOLE_AUTHENTICATION_CAPABILITIES.EOAC_DYNAMIC_CLOAKING, IntPtr.Zero);
     NtToken.EnableDebugPrivilege();
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new MainForm());
 }
        private void btnRefreshHandles_Click(object sender, EventArgs e)
        {
            ClearList(listViewHandles);
            int current_pid = Process.GetCurrentProcess().Id;

            NtToken.EnableDebugPrivilege();
            List <ListViewItem> items = new List <ListViewItem>();

            foreach (var group in NtSystemInfo.GetHandles()
                     .Where(h => h.ProcessId != current_pid && h.ObjectType.Equals("token", StringComparison.OrdinalIgnoreCase))
                     .GroupBy(h => h.ProcessId))
            {
                using (var proc = NtProcess.Open(group.Key, ProcessAccessRights.DupHandle | ProcessAccessRights.QueryLimitedInformation, false))
                {
                    if (!proc.IsSuccess)
                    {
                        continue;
                    }

                    foreach (NtHandle handle in group)
                    {
                        using (var token_result = NtToken.DuplicateFrom(proc.Result, new IntPtr(handle.Handle),
                                                                        TokenAccessRights.Query | TokenAccessRights.QuerySource, DuplicateObjectOptions.None, false))
                        {
                            if (!token_result.IsSuccess)
                            {
                                continue;
                            }
                            NtToken      token = token_result.Result;
                            ListViewItem item  = new ListViewItem(handle.ProcessId.ToString());
                            item.SubItems.Add(proc.Result.Name);
                            item.SubItems.Add($"0x{handle.Handle:X}");
                            item.SubItems.Add(token.User.ToString());
                            item.SubItems.Add(token.IntegrityLevel.ToString());
                            string restricted = token.Restricted.ToString();
                            if (token.WriteRestricted)
                            {
                                restricted = "Write";
                            }
                            item.SubItems.Add(restricted);
                            item.SubItems.Add(token.AppContainer.ToString());
                            item.SubItems.Add(token.TokenType.ToString());
                            item.SubItems.Add(token.ImpersonationLevel.ToString());
                            item.Tag = token.Duplicate();
                            items.Add(item);
                        }
                    }
                }
            }
            listViewHandles.Items.AddRange(items.ToArray());
            ResizeColumns(listViewHandles);
        }
        private void btnRefreshHandles_Click(object sender, EventArgs e)
        {
            ClearList(listViewHandles);
            int current_pid = Process.GetCurrentProcess().Id;

            NtToken.EnableDebugPrivilege();
            List <ListViewItem> items = new List <ListViewItem>();

            foreach (var group in NtSystemInfo.GetHandles()
                     .Where(h => h.ProcessId != current_pid && h.ObjectType.Equals("token", StringComparison.OrdinalIgnoreCase))
                     .GroupBy(h => h.ProcessId))
            {
                try
                {
                    using (NtProcess proc = NtProcess.Open(group.Key, ProcessAccessRights.DupHandle | ProcessAccessRights.QueryLimitedInformation))
                    {
                        foreach (NtHandle handle in group)
                        {
                            try
                            {
                                using (NtToken token = NtToken.DuplicateFrom(proc, new IntPtr(handle.Handle),
                                                                             TokenAccessRights.Query | TokenAccessRights.QuerySource))
                                {
                                    ListViewItem item = new ListViewItem(handle.ProcessId.ToString());
                                    item.SubItems.Add(proc.Name);
                                    item.SubItems.Add(String.Format("0x{0:X}", handle.Handle));
                                    item.SubItems.Add(token.User.ToString());
                                    item.SubItems.Add(token.IntegrityLevel.ToString());
                                    item.SubItems.Add(token.Restricted.ToString());
                                    item.SubItems.Add(token.AppContainer.ToString());
                                    item.SubItems.Add(token.TokenType.ToString());
                                    item.SubItems.Add(token.ImpersonationLevel.ToString());
                                    item.Tag = token.Duplicate();
                                    items.Add(item);
                                }
                            }
                            catch (NtException)
                            {
                            }
                        }
                    }
                }
                catch (NtException)
                {
                }
            }
            listViewHandles.Items.AddRange(items.ToArray());
            ResizeColumns(listViewHandles);
        }
        /// <summary>
        /// Disable dynamic code policy on another process.
        /// </summary>
        public void DisableDynamicCodePolicy()
        {
            if (!NtToken.EnableDebugPrivilege())
            {
                throw new InvalidOperationException("Must have Debug privilege to disable code policy");
            }

            MitigationPolicy p = new MitigationPolicy();

            p.Policy = ProcessMitigationPolicy.ProcessDynamicCodePolicy;

            using (var buffer = p.ToBuffer())
            {
                NtSystemCalls.NtSetInformationProcess(Handle, ProcessInfoClass.ProcessMitigationPolicy, buffer, buffer.Length).ToNtException();
            }
        }
Пример #11
0
        /// <summary>
        /// Get handle into the current process
        /// </summary>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The handle to the object</returns>
        public NtResult <NtObject> GetObject(bool throw_on_error)
        {
            NtToken.EnableDebugPrivilege();
            using (var result = NtGeneric.DuplicateFrom(ProcessId, new IntPtr(Handle), 0,
                                                        DuplicateObjectOptions.SameAccess | DuplicateObjectOptions.SameAttributes, throw_on_error)) {
                if (!result.IsSuccess)
                {
                    return(result.Cast <NtObject>());
                }

                NtGeneric generic = result.Result;

                // Ensure that we get the actual type from the handle.
                NtType = generic.NtType;
                return(generic.ToTypedObject(throw_on_error).Cast <NtObject>());
            }
        }
        public SelectSecurityCheckForm(bool process_security)
        {
            InitializeComponent();
            _process_security = process_security;
            _tokens           = new DisposableList <NtToken>();
            Disposed         += SelectSecurityCheckForm_Disposed;
            string username = String.Format(@"{0}\{1}", Environment.UserDomainName, Environment.UserName);

            textBoxPrincipal.Text = username;
            NtToken.EnableDebugPrivilege();

            using (var ps = NtProcess.GetProcesses(ProcessAccessRights.QueryLimitedInformation, true).ToDisposableList())
            {
                foreach (var p in ps.OrderBy(p => p.ProcessId))
                {
                    var result = NtToken.OpenProcessToken(p, TokenAccessRights.MaximumAllowed, false);
                    if (result.IsSuccess)
                    {
                        NtToken token = result.Result;
                        _tokens.Add(token);
                        ListViewItem item = listViewProcesses.Items.Add(p.ProcessId.ToString());
                        item.SubItems.Add(p.Name);
                        item.SubItems.Add(p.User.Name);
                        item.SubItems.Add(token.IntegrityLevel.ToString());
                        item.Tag = token;
                    }
                }
            }
            listViewProcesses.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
            listViewProcesses.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            listViewProcesses.ListViewItemSorter = new ListItemComparer(0);

            foreach (object value in Enum.GetValues(typeof(TokenIntegrityLevel)))
            {
                comboBoxIL.Items.Add(value);
            }
            comboBoxIL.SelectedItem = TokenIntegrityLevel.Low;
            if (process_security)
            {
                textBoxPrincipal.Enabled       = false;
                checkBoxLocalLaunch.Enabled    = false;
                checkBoxRemoteLaunch.Enabled   = false;
                checkBoxLocalActivate.Enabled  = false;
                checkBoxRemoteActivate.Enabled = false;
            }
        }
 /// <summary>
 /// Get handle into the current process
 /// </summary>
 /// <returns>The handle to the object</returns>
 public NtObject GetObject()
 {
     NtToken.EnableDebugPrivilege();
     try
     {
         using (NtGeneric generic = NtGeneric.DuplicateFrom(ProcessId, new IntPtr(Handle)))
         {
             // Ensure that we get the actual type from the handle.
             NtType = generic.NtType;
             return(generic.ToTypedObject());
         }
     }
     catch
     {
     }
     return(null);
 }
Пример #14
0
 /// <summary>
 /// Create a kernel dump for current system.
 /// </summary>
 /// <param name="path">The path to the output file.</param>
 /// <param name="flags">Flags</param>
 /// <param name="page_flags">Page flags</param>
 public static void CreateKernelDump(string path, SystemDebugKernelDumpControlFlags flags, SystemDebugKernelDumpPageControlFlags page_flags)
 {
     NtToken.EnableDebugPrivilege();
     using (NtFile file = NtFile.Create(path, FileAccessRights.Synchronize | FileAccessRights.GenericWrite | FileAccessRights.GenericRead,
                                        FileShareMode.Read, FileOpenOptions.SynchronousIoNonAlert | FileOpenOptions.WriteThrough | FileOpenOptions.NoIntermediateBuffering, FileDisposition.OverwriteIf,
                                        null))
     {
         using (var buffer = new SystemDebugKernelDumpConfig()
         {
             FileHandle = file.Handle.DangerousGetHandle(),
             Flags = flags,
             PageFlags = page_flags
         }.ToBuffer())
         {
             NtSystemCalls.NtSystemDebugControl(SystemDebugCommand.SysDbgGetLiveKernelDump, buffer, buffer.Length,
                                                SafeHGlobalBuffer.Null, 0, out int ret_length).ToNtException();
         }
     }
 }
        /// <summary>
        /// Overridden process record method.
        /// </summary>
        protected override void ProcessRecord()
        {
            HashSet <TokenEntry> tokens = new HashSet <TokenEntry>(new TokenEntryComparer());

            try
            {
                NtToken.EnableDebugPrivilege();

                if (Tokens != null)
                {
                    foreach (NtToken token in Tokens)
                    {
                        AddTokenEntry(tokens, new TokenEntry(token));
                    }
                }
                if (ProcessIds != null)
                {
                    GetTokensFromPids(tokens, ProcessIds);
                }
                GetTokensFromArguments(tokens, ProcessNames, ProcessCommandLines);
                if (Processes != null)
                {
                    foreach (NtProcess process in Processes)
                    {
                        AddTokenEntryFromProcess(tokens, process);
                    }
                }
                if (tokens.Count == 0)
                {
                    AddTokenEntryFromProcess(tokens, NtProcess.Current);
                }

                RunAccessCheck(tokens);
            }
            finally
            {
                foreach (TokenEntry token in tokens)
                {
                    token.Dispose();
                }
            }
        }
        private void QueryValues()
        {
            if (_allow_query)
            {
                _allow_query = false;
                NtToken.EnableDebugPrivilege();
                using (var obj = NtGeneric.DuplicateFrom(ProcessId,
                                                         new IntPtr(Handle), 0, DuplicateObjectOptions.SameAccess, false))
                {
                    if (!obj.IsSuccess)
                    {
                        return;
                    }

                    NtType = obj.Result.NtType;
                    _name  = GetName(obj.Result);
                    _sd    = GetSecurityDescriptor(obj.Result);
                }
            }
        }
Пример #17
0
 private void QueryValues()
 {
     if (_allow_query)
     {
         _allow_query = false;
         try
         {
             NtToken.EnableDebugPrivilege();
             using (NtGeneric obj = NtGeneric.DuplicateFrom(ProcessId, new IntPtr(Handle)))
             {
                 // Ensure we get the real type, in case it changed _or_ it was wrong to begin with.
                 ObjectType = obj.NtTypeName;
                 _name      = GetName(obj);
                 _sd        = GetSecurityDescriptor(obj);
             }
         }
         catch (NtException)
         {
         }
     }
 }
Пример #18
0
        static void Main(string[] args)
        {
            CoInitializeSecurity(IntPtr.Zero, -1, IntPtr.Zero, IntPtr.Zero, AuthnLevel.RPC_C_AUTHN_LEVEL_DEFAULT,
                                 ImpLevel.RPC_C_IMP_LEVEL_IMPERSONATE, IntPtr.Zero, EOLE_AUTHENTICATION_CAPABILITIES.EOAC_DYNAMIC_CLOAKING, IntPtr.Zero);
            NtToken.EnableDebugPrivilege();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Form main_form;

            if (args.Length > 0)
            {
                main_form = GetFormFromArgs(args);
                if (main_form == null)
                {
                    Environment.Exit(1);
                }
            }
            else
            {
                main_form = new MainForm();
            }
            Application.Run(main_form);
        }
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            NtToken.EnableDebugPrivilege();

            try
            {
                if (args.Length == 0)
                {
                    Application.Run(new MainForm());
                }
                else
                {
                    if (args.Length < 3)
                    {
                        var handle = new SafeKernelObjectHandle(new IntPtr(int.Parse(args[0])), true);

                        using (var section = NtSection.FromHandle(handle))
                        {
                            bool read_only = args.Length > 1 ? args[1].Equals("--readonly") : !section.IsAccessGranted(SectionAccessRights.MapWrite);
                            using (var map = read_only ? section.MapRead() : section.MapReadWrite())
                            {
                                using (SectionEditorForm frm = new SectionEditorForm(map, GetName(section, map), read_only))
                                {
                                    Application.Run(frm);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
 private static NtToken GetSystemToken()
 {
     NtToken.EnableDebugPrivilege();
     using (var ps = NtProcess.GetProcesses(ProcessAccessRights.QueryLimitedInformation).ToDisposableList())
     {
         Sid local_system = KnownSids.LocalSystem;
         foreach (var p in ps)
         {
             using (var result = NtToken.OpenProcessToken(p, TokenAccessRights.Query | TokenAccessRights.Duplicate, false))
             {
                 if (!result.IsSuccess)
                 {
                     continue;
                 }
                 var token = result.Result;
                 if (token.User.Sid == local_system &&
                     !token.Filtered &&
                     token.GetPrivilege(TokenPrivilegeValue.SeTcbPrivilege) != null &&
                     token.IntegrityLevel == TokenIntegrityLevel.System)
                 {
                     using (var imp_token = token.DuplicateToken(SecurityImpersonationLevel.Impersonation))
                     {
                         if (imp_token.SetPrivilege(TokenPrivilegeValue.SeTcbPrivilege, PrivilegeAttributes.Enabled))
                         {
                             using (imp_token.Impersonate())
                             {
                                 return(LogonUtils.Logon("SYSTEM", "NT AUTHORITY", null,
                                                         SecurityLogonType.Service, Logon32Provider.Default, false).GetResultOrDefault());
                             }
                         }
                     }
                 }
             }
         }
     }
     return(null);
 }
Пример #21
0
        static void Main(string[] args)
        {
            bool verbose = false;

            if (args.Length > 0 && args[0] == "-verbose")
            {
                verbose = true;
            }
            try
            {
                if (!NtToken.EnableDebugPrivilege())
                {
                    Console.WriteLine("WARNING: Can't enable debug privilege. Some zombies may not be found. Run as admin for full results.");
                }
                var zombies = GetZombieObjectAddress();
                Console.WriteLine("{0} total zombie processes.", zombies.Values.Count(h => !h.IsThread));
                Console.WriteLine("{0} total zombie threads.", zombies.Values.Count(h => h.IsThread));
                if (zombies.Count == 0)
                {
                    Console.WriteLine("No zombies found. Maybe all software is working correctly, but I doubt it. " +
                                      "More likely the zombie counting process failed for some reason. Please try again.");
                }
                // Create a list to store the pids of process that hold zombies, a list of zombie handles,
                // a count of the zombies. The count is first for sorting.
                List <Tuple <int, int, List <ZombieHandle> > > count_and_pid = new List <Tuple <int, int, List <ZombieHandle> > >();
                foreach (var group in NtSystemInfo.GetHandles(-1, false).GroupBy(h => h.ProcessId))
                {
                    var total = group.Where(h => zombies.ContainsKey(h.Object)).Select(h => zombies[h.Object]).ToList();
                    int count = total.Select(h => h.ProcessId).Distinct().Count();

                    if (count > 0)
                    {
                        count_and_pid.Add(Tuple.Create(count, group.Key, total));
                    }
                }

                // Print the processes holding handles to zombies, sorted by zombie count.
                count_and_pid.Sort();
                count_and_pid.Reverse();
                foreach (var buggy_process in count_and_pid)
                {
                    int count_by = buggy_process.Item1;
                    int pid      = buggy_process.Item2;
                    var total    = buggy_process.Item3;
                    Console.WriteLine("    {0} {1} held by {2}({3})", count_by, ZombiePluralized(count_by), GetProcessName(pid, verbose), pid);
                    var names = total.GroupBy(h => h.ProcessPath, StringComparer.CurrentCultureIgnoreCase);
                    var zombies_from_process = new List <Tuple <int, string, int, int> >();
                    foreach (var name in names)
                    {
                        int slash_index = name.Key.LastIndexOf('\\');
                        if (verbose)
                        {
                            slash_index = -1;
                        }
                        string process_name   = name.Key.Substring(slash_index + 1);
                        int    process_count  = name.Count(h => !h.IsThread);
                        int    thread_count   = name.Count(h => h.IsThread);
                        int    unique_process = name.Select(h => h.ProcessId).Distinct().Count();
                        zombies_from_process.Add(Tuple.Create(unique_process, process_name, process_count, thread_count));
                    }

                    // Print the processes being held as zombies, sorted by count.
                    zombies_from_process.Sort();
                    zombies_from_process.Reverse();
                    foreach (var zombie_process in zombies_from_process)
                    {
                        int    total_count   = zombie_process.Item1;
                        string process_name  = zombie_process.Item2;
                        int    process_count = zombie_process.Item3;
                        int    thread_count  = zombie_process.Item4;

                        Console.WriteLine("        {0} {1} of {2} - process handle count: {3} - thread handle count: {4}", total_count,
                                          ZombiePluralized(total_count), process_name, process_count, thread_count);
                    }
                }
                if (!verbose)
                {
                    Console.WriteLine("Pass -verbose to get full zombie names.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            int[] pids = new int[3];
            if (GetConsoleProcessList(pids, 3) == 1)
            {
                Console.Write("Press any key to continue");
                Console.ReadKey();
            }
        }
Пример #22
0
        static void Main(string[] args)
        {
            Win32Process new_process = null;

            try
            {
                CreateProcessFlags flags = CreateProcessFlags.None;
                bool parent_process      = false;
                bool set_il            = false;
                TokenIntegrityLevel il = 0;
                bool show_help         = false;

                OptionSet opts = new OptionSet()
                {
                    { "p", "Use parent technique to create the new process", v => parent_process = v != null },
                    { "j", "Try and break away from the current process job", v => flags |= v != null ? CreateProcessFlags.BreakawayFromJob : 0 },
                    { "c", "Create a new console for the process", v => flags |= v != null ? CreateProcessFlags.NewConsole : 0 },
                    { "s", "Create the process suspended", v => flags |= v != null ? CreateProcessFlags.Suspended : 0 },
                    { "i|il=", "Set the process IL level", v => {
                          il = ParseIL(v); set_il = true;
                      } },
                    { "h|help", "show this message and exit", v => show_help = v != null },
                };

                int pid;

                List <string> commands = opts.Parse(args);
                if (show_help || commands.Count < 2)
                {
                    ShowHelp(opts);
                }

                if (!int.TryParse(commands[0], out pid))
                {
                    throw new ArgumentException("Couldn't parse PID value");
                }

                if (!NtToken.EnableDebugPrivilege())
                {
                    Console.WriteLine("WARNING: Couldn't enable Debug privilege");
                }

                using (NtProcess process = NtProcess.Open(pid, ProcessAccessRights.MaximumAllowed))
                {
                    if (parent_process)
                    {
                        new_process = Win32Process.CreateProcess(process, null, commands[1], set_il ? flags | CreateProcessFlags.Suspended : flags, null);
                        if (set_il)
                        {
                            using (NtToken token = new_process.Process.OpenToken())
                            {
                                token.SetIntegrityLevel(il);
                            }
                            if ((flags & CreateProcessFlags.Suspended) == 0)
                            {
                                new_process.Thread.Resume();
                            }
                        }
                    }
                    else
                    {
                        using (NtToken token = process.OpenToken())
                        {
                            using (NtToken target_token = token.DuplicateToken(TokenType.Primary, SecurityImpersonationLevel.Anonymous, TokenAccessRights.MaximumAllowed))
                            {
                                if (set_il)
                                {
                                    target_token.SetIntegrityLevel(il);
                                }

                                new_process = Win32Process.CreateProcessAsUser(target_token, null, commands[1], flags, null);
                            }
                        }
                    }

                    using (new_process)
                    {
                        Console.WriteLine("Created Process: PID: {0}, SID {1}", new_process.Pid, new_process.Process.SessionId);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: {0}", ex.Message);
                if (new_process != null && new_process.Process != null)
                {
                    try
                    {
                        new_process.Process.Terminate(NtStatus.STATUS_WAIT_1);
                    }
                    catch
                    {
                    }
                }
            }
        }
Пример #23
0
        static void Main(string[] args)
        {
            bool verbose = false;

            if (args.Length > 0 && args[0] == "-verbose")
            {
                verbose = true;
            }
            try
            {
                if (!NtToken.EnableDebugPrivilege())
                {
                    Console.WriteLine("WARNING: Can't enable debug privilege. Some zombies may not be found. Run as admin for full results.");
                }
                var zombies = GetZombieProcessObjectAddress();

                var flattenList = zombies.Values.ToList();
                var q           = from x in flattenList
                                  group x by x into g
                                  let count = g.Count()
                                              orderby count descending
                                              select new { Value = g.Key, Count = count };

                Dictionary <string, int> orphaned = q.ToDictionary(x => x.Value, x => x.Count);
                Console.Write("{0} total zombie processes.", zombies.Count);

                if (zombies.Count == 0)
                {
                    Console.WriteLine("No zombies found. Maybe all software is working correctly, but I doubt it. " +
                                      "More likely the zombie counting process failed for some reason. Please try again.");
                }
                // Create a list to store the pids of process that hold zombies, a list of zombie handles,
                // a count of the zombies. The count is first for sorting.
                List <Tuple <int, int, HandleList> > count_and_pid = new List <Tuple <int, int, HandleList> >();
                foreach (var group in NtSystemInfo.GetHandles(-1, false).GroupBy(h => h.ProcessId))
                {
                    var total = group.Where(h => zombies.ContainsKey(h.Object));
                    int count = total.Count();

                    if (count > 0)
                    {
                        count_and_pid.Add(new Tuple <int, int, HandleList>(count, group.Key, total));
                    }
                }

                // Print the processes holding handles to zombies, sorted by zombie count.
                count_and_pid.Sort();
                count_and_pid.Reverse();

                int total_count_zombies = 0;

                foreach (Tuple <int, int, HandleList> buggy_process in count_and_pid)
                {
                    total_count_zombies += buggy_process.Item1;
                }
                int total_count_orphans = zombies.Count - total_count_zombies;
                Console.WriteLine(" ({0} {1} and {2} {3})", total_count_zombies, ZombiePluralized(total_count_zombies), total_count_orphans, OrphanPluralized(total_count_orphans));

                foreach (Tuple <int, int, HandleList> buggy_process in count_and_pid)
                {
                    int        count_by = buggy_process.Item1;
                    int        pid      = buggy_process.Item2;
                    HandleList total    = buggy_process.Item3;
                    Console.WriteLine("    {0} {1} held by {2}({3})", count_by, ZombiePluralized(count_by), GetProcessName(pid, verbose), pid);
                    var names = total.GroupBy(h => zombies[h.Object], StringComparer.CurrentCultureIgnoreCase);
                    List <Tuple <int, string> > zombies_from_process = new List <Tuple <int, string> >();
                    foreach (var name in names)
                    {
                        int slash_index = name.Key.LastIndexOf('\\');
                        if (verbose)
                        {
                            slash_index = -1;
                        }
                        string process_name = name.Key.Substring(slash_index + 1);
                        zombies_from_process.Add(new Tuple <int, string>(name.Count(), process_name));
                        if (orphaned.ContainsKey(name.Key))
                        {
                            orphaned[name.Key] = orphaned[name.Key] - name.Count();
                        }
                    }

                    // Print the processes being held as zombies, sorted by count.
                    zombies_from_process.Sort();
                    zombies_from_process.Reverse();
                    foreach (var zombie_process in zombies_from_process)
                    {
                        int    count_of     = zombie_process.Item1;
                        string process_name = zombie_process.Item2;
                        Console.WriteLine("        {0} {1} of {2}", count_of, ZombiePluralized(count_of), process_name);
                    }
                }

                Console.WriteLine("    {0} {1}", total_count_orphans, OrphanPluralized(total_count_orphans));
                foreach (var item in orphaned)
                {
                    int slash_index = item.Key.LastIndexOf('\\');
                    if (verbose)
                    {
                        slash_index = -1;
                    }
                    string process_name = item.Key.Substring(slash_index + 1);
                    if (item.Value != 0)
                    {
                        Console.WriteLine("        {0} {1} of {2}", item.Value, OrphanPluralized(item.Value), process_name);
                    }
                }
                if (!verbose)
                {
                    Console.WriteLine("Pass -verbose to get full zombie names.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            int[] pids = new int[3];
            if (GetConsoleProcessList(pids, 3) == 1)
            {
                Console.Write("Press any key to continue");
                Console.ReadKey();
            }
        }
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            NtToken.EnableDebugPrivilege();

            try
            {
                if (args.Length == 0)
                {
                    Application.Run(new MainForm());
                }
                else
                {
                    int    handle      = -1;
                    string text        = String.Empty;
                    bool   read_only   = false;
                    bool   delete_file = false;
                    string filename    = string.Empty;

                    OptionSet opts = new OptionSet()
                    {
                        { "handle=", "Specify an inherited handle to view.",
                          v => handle = int.Parse(v) },
                        { "readonly", "Specify view section readonly", v => read_only = v != null },
                        { "file=", "Specify a file to view", v => filename = v },
                        { "delete", "Delete file after viewing", v => delete_file = v != null },
                    };

                    opts.Parse(args);

                    if (handle > 0)
                    {
                        using (var section = NtSection.FromHandle(new SafeKernelObjectHandle(new IntPtr(handle), true)))
                        {
                            read_only = read_only || !section.IsAccessGranted(SectionAccessRights.MapWrite);
                            using (var map = read_only ? section.MapRead() : section.MapReadWrite())
                            {
                                using (SectionEditorForm frm = new SectionEditorForm(map, GetName(section, map), read_only))
                                {
                                    Application.Run(frm);
                                }
                            }
                        }
                    }
                    else if (File.Exists(filename))
                    {
                        try
                        {
                            using (var file = NtFile.Open(NtFileUtils.DosFileNameToNt(filename), null,
                                                          FileAccessRights.ReadData, FileShareMode.Read | FileShareMode.Delete, FileOpenOptions.NonDirectoryFile))
                            {
                                using (NtSection section = NtSection.CreateReadOnlyDataSection(file))
                                {
                                    using (var map = section.MapRead())
                                    {
                                        using (SectionEditorForm frm = new SectionEditorForm(map, filename, true, file.Length))
                                        {
                                            Application.Run(frm);
                                        }
                                    }
                                }
                            }
                        }
                        finally
                        {
                            if (delete_file)
                            {
                                File.Delete(filename);
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("Invalid command line arguments");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        static void Main(string[] args)
        {
            bool             show_help          = false;
            HashSet <string> mitigation_filter  = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
            HashSet <string> process_filter     = new HashSet <string>(StringComparer.CurrentCultureIgnoreCase);
            HashSet <int>    pid_filter         = new HashSet <int>();
            HashSet <string> cmdline_filter     = new HashSet <string>();
            bool             all_mitigations    = false;
            bool             print_command_line = false;
            OptionSet        p = new OptionSet()
            {
                { "t|type=", "A filter for processes with a specific mitigation to display", v => mitigation_filter.Add(v.Trim()) },
                { "f|filter=", "A filter for the path of a process to display", v => process_filter.Add(v.Trim()) },
                { "p|pid=", "A filter for a specific PID to display", v => pid_filter.Add(int.Parse(v)) },
                { "c|cmd=", "A filter for the command line of a process to display", v => cmdline_filter.Add(v.Trim().ToLower()) },
                { "a|all", "Show all process mitigations", v => all_mitigations = v != null },
                { "l|cmdline", "Print the command line of the process", v => print_command_line = v != null },
                { "h|help", "show this message and exit",
                  v => show_help = v != null },
            };

            foreach (PropertyInfo prop in typeof(NtProcessMitigations).GetProperties())
            {
                _props.Add(prop.Name.ToLower(), prop);
            }

            try
            {
                p.Parse(args);

                if (show_help)
                {
                    ShowHelp(p);
                }
                else
                {
                    NtToken.EnableDebugPrivilege();
                    IEnumerable <NtProcess> procs = NtProcess.GetProcesses(ProcessAccessRights.QueryInformation);

                    if (cmdline_filter.Count > 0)
                    {
                        procs = procs.Where(e => ContainsString(GetCommandLine(e).ToLower(), cmdline_filter));
                    }

                    if (pid_filter.Count > 0)
                    {
                        procs = procs.Where(e => pid_filter.Contains(e.ProcessId));
                    }

                    if (process_filter.Count > 0)
                    {
                        procs = procs.Where(e => ContainsString(e.GetImageFilePath(false).ToLower(), process_filter));
                    }

                    if (mitigation_filter.Count > 0)
                    {
                        procs = procs.Where(e => HasPropertySet(e.Mitigations, mitigation_filter));
                    }

                    foreach (NtProcess entry in procs)
                    {
                        DumpProcessEntry(entry, mitigation_filter, all_mitigations, print_command_line);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Пример #26
0
        static void Main(string[] args)
        {
            bool verbose = false;

            if (args.Length > 0 && args[0] == "-verbose")
            {
                verbose = true;
            }
            try
            {
                if (!NtToken.EnableDebugPrivilege())
                {
                    Console.WriteLine("WARNING: Can't enable debug privilege. Some process names may be missing.");
                }
                var zombies = GetZombieProcessObjectAddress();
                Console.WriteLine("{0} total zombie processes.", zombies.Count);
                if (zombies.Count == 0)
                {
                    Console.WriteLine("No zombies found. Maybe all software is working correctly, but I doubt it. " +
                                      "More likely the zombie counting process failed for some reason. Please try again.");
                }
                // Create a list to store the pids of process that hold zombies, a list of zombie handles,
                // a count of the zombies. The count is first for sorting.
                List <Tuple <int, int, HandleList> > count_and_pid = new List <Tuple <int, int, HandleList> >();
                foreach (var group in NtSystemInfo.GetHandles(-1, false).GroupBy(h => h.ProcessId))
                {
                    var total = group.Where(h => zombies.ContainsKey(h.Object));
                    int count = total.Count();

                    if (count > 0)
                    {
                        count_and_pid.Add(new Tuple <int, int, HandleList>(count, group.Key, total));
                    }
                }

                // Print the processes holding handles to zombies, sorted by zombie count.
                count_and_pid.Sort();
                count_and_pid.Reverse();
                foreach (Tuple <int, int, HandleList> buggy_process in count_and_pid)
                {
                    int        count_by = buggy_process.Item1;
                    int        pid      = buggy_process.Item2;
                    HandleList total    = buggy_process.Item3;
                    Console.WriteLine("    {0} {1} held by {2}({3})", count_by, ZombiePluralized(count_by), GetProcessName(pid, verbose), pid);
                    var names = total.GroupBy(h => zombies[h.Object], StringComparer.CurrentCultureIgnoreCase);
                    List <Tuple <int, string> > zombies_from_process = new List <Tuple <int, string> >();
                    foreach (var name in names)
                    {
                        int slash_index = name.Key.LastIndexOf('\\');
                        if (verbose)
                        {
                            slash_index = -1;
                        }
                        string process_name = name.Key.Substring(slash_index + 1);
                        zombies_from_process.Add(new Tuple <int, string>(name.Count(), process_name));
                    }

                    // Print the processes being held as zombies, sorted by count.
                    zombies_from_process.Sort();
                    zombies_from_process.Reverse();
                    foreach (var zombie_process in zombies_from_process)
                    {
                        int    count_of     = zombie_process.Item1;
                        string process_name = zombie_process.Item2;
                        Console.WriteLine("        {0} {1} of {2}", count_of, ZombiePluralized(count_of), process_name);
                    }
                }
                if (!verbose)
                {
                    Console.WriteLine("Pass -verbose to get full zombie names.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Пример #27
0
        static void Main(string[] args)
        {
            try
            {
                int  pid        = NtProcess.Current.ProcessId;
                bool show_help  = false;
                bool print_sddl = false;

                OptionSet opts = new OptionSet()
                {
                    { "p|pid=", "Specify a PID of a process for access check.", v => pid = int.Parse(v.Trim()) },
                    { "sddl", "Print SDDL security descriptor.", v => print_sddl = v != null },
                    { "h|help", "show this message and exit",
                      v => show_help = v != null },
                };

                HashSet <int> pids = new HashSet <int>(opts.Parse(args).Select(a => int.Parse(a)));
                if (show_help)
                {
                    ShowHelp(opts);
                    return;
                }

                Dictionary <string, string> ports = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

                NtToken.EnableDebugPrivilege();
                using (NtToken token = NtToken.OpenProcessToken(pid))
                {
                    IEnumerable <NtHandle> handles         = NtSystemInfo.GetHandles(-1, false);
                    HashSet <ulong>        checked_objects = new HashSet <ulong>();

                    if (pids.Count > 0)
                    {
                        handles = handles.Where(h => pids.Contains(h.ProcessId));
                    }

                    handles = handles.Where(h => h.ObjectType.Equals("ALPC Port", StringComparison.OrdinalIgnoreCase));
                    Dictionary <int, NtProcess> pid_to_process = new Dictionary <int, NtProcess>();
                    foreach (NtHandle handle in handles.Where(h => h.GrantedAccess.IsAccessGranted(GenericAccessRights.ReadControl)))
                    {
                        if (!pid_to_process.ContainsKey(handle.ProcessId))
                        {
                            var result = NtProcess.Open(handle.ProcessId,
                                                        ProcessAccessRights.QueryLimitedInformation | ProcessAccessRights.DupHandle, false);
                            pid_to_process[handle.ProcessId] = result.IsSuccess ? result.Result : null;
                        }

                        NtProcess proc = pid_to_process[handle.ProcessId];
                        if (proc == null)
                        {
                            continue;
                        }

                        try
                        {
                            using (NtAlpc obj = NtAlpc.DuplicateFrom(proc, new IntPtr(handle.Handle)))
                            {
                                string name = obj.FullPath;
                                // We only care about named ALPC ports.
                                if (String.IsNullOrEmpty(name))
                                {
                                    continue;
                                }

                                if (ports.ContainsKey(name))
                                {
                                    continue;
                                }

                                SecurityDescriptor sd             = obj.SecurityDescriptor;
                                AccessMask         granted_access = NtSecurity.GetAllowedAccess(sd, token, AlpcAccessRights.Connect, obj.NtType.GenericMapping);
                                if (granted_access.IsEmpty)
                                {
                                    continue;
                                }
                                ports.Add(name, sd.ToSddl());
                            }
                        }
                        catch (NtException)
                        {
                        }
                    }
                }
                foreach (var pair in ports.OrderBy(p => p.Key))
                {
                    Console.WriteLine(pair.Key);
                    if (print_sddl)
                    {
                        Console.WriteLine("SDDL: {0}", pair.Value);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
            }
        }