static CheckResult CheckDevice(string name, bool writable, EaBuffer ea_buffer)
        {
            CheckResult result = new CheckResult(name, NtStatus.STATUS_INVALID_PARAMETER, FileDeviceType.UNKNOWN);

            try
            {
                using (var imp = NtToken.Impersonate(_pid,
                                                     _identify_only ? SecurityImpersonationLevel.Identification : SecurityImpersonationLevel.Impersonation))
                {
                    FileAccessRights access_mask = FileAccessRights.GenericRead;
                    if (writable)
                    {
                        access_mask |= FileAccessRights.GenericWrite;
                    }

                    FileOpenOptions opts = _open_as_dir ? FileOpenOptions.DirectoryFile : FileOpenOptions.NonDirectoryFile;
                    using (NtFile file = NtFile.Create(name, null, access_mask, NtApiDotNet.FileAttributes.Normal,
                                                       FileShareMode.All, opts, FileDisposition.Open, ea_buffer))
                    {
                        result = new CheckResult(name, NtStatus.STATUS_SUCCESS, file.DeviceType);
                    }
                }
            }
            catch (NtException ex)
            {
                result = new CheckResult(name, ex.Status, FileDeviceType.UNKNOWN);
            }

            return(result);
        }
Ejemplo n.º 2
0
        private void btnCreateProcess_Click(object sender, EventArgs e)
        {
            try
            {
                if (checkBoxUseWmi.Checked)
                {
                    _token.SetDefaultDacl(new Acl(IntPtr.Zero, false));
                    using (var imp = _token.Impersonate())
                    {
                        using (var managementClass = new ManagementClass(@"\\.\root\cimv2",
                                                                         "Win32_Process",
                                                                         new ObjectGetOptions()))
                        {
                            var inputParams = managementClass.GetMethodParameters("Create");

                            inputParams["CommandLine"] = txtCommandLine.Text;
                            var outParams = managementClass.InvokeMethod("Create",
                                                                         inputParams,
                                                                         new InvokeMethodOptions());
                            System.Diagnostics.Trace.WriteLine(outParams["ReturnValue"].ToString());
                        }
                    }
                }
                else
                {
                    using (var token = TokenUtils.CreateProcessForToken(txtCommandLine.Text, _token, checkBoxMakeInteractive.Checked))
                    {
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 3
0
        static bool CheckDevice(string name, bool writable)
        {
            bool success = false;

            try
            {
                using (var imp = NtToken.Impersonate(_pid,
                                                     _identify_only ? SecurityImpersonationLevel.Identification : SecurityImpersonationLevel.Impersonation))
                {
                    FileAccessRights access_mask = FileAccessRights.GenericRead;
                    if (writable)
                    {
                        access_mask |= FileAccessRights.GenericWrite;
                    }

                    FileOpenOptions opts = _open_as_dir ? FileOpenOptions.DirectoryFile : FileOpenOptions.NonDirectoryFile;
                    using (NtFile file = NtFile.Open(name, null, access_mask, FileShareMode.All, opts))
                    {
                        success = true;
                    }
                }
            }
            catch (Win32Exception ex)
            {
                // Ignore access denied and invalid function (indicates there's no IRP_MJ_CREATE handler)
                PrintError(name, ex);
            }
            catch (NtException ex)
            {
                PrintError(name, ex.AsWin32Exception());
            }

            return(success);
        }
        static void ConnectTest(int pid, IPEndPoint ep)
        {
            using (var imp = NtToken.Impersonate(pid, SecurityImpersonationLevel.Impersonation))
            {
                TcpClient client = new TcpClient();
                client.Connect(ep);
                client.Close();

                Console.WriteLine("** Opened Connection **");
            }
        }
        static void ListenTest(int pid, IPEndPoint ep)
        {
            using (var imp = NtToken.Impersonate(pid, SecurityImpersonationLevel.Impersonation))
            {
                TcpListener listener = new TcpListener(ep);

                listener.Start();

                Console.WriteLine("Make a connection to {0}", ep);

                listener.AcceptTcpClient();

                Console.WriteLine("** Accepted Connection **");
            }
        }
        private void btnCreate_Click(object sender, EventArgs e)
        {
            try
            {
                using (NtToken token = _token.DuplicateToken(TokenType.Impersonation,
                                                             SecurityImpersonationLevel.Impersonation, TokenAccessRights.MaximumAllowed))
                {
                    using (var imp = token.Impersonate())
                    {
                        File.WriteAllText(txtFilePath.Text, txtFileContents.Text);
                    }

                    MessageBox.Show(this, "Success", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void btnImpersonate_Click(object sender, EventArgs e)
        {
            SecurityImpersonationLevel implevel = SecurityImpersonationLevel.Impersonation;

            try
            {
                if (_token.TokenType == TokenType.Impersonation)
                {
                    implevel = _token.ImpersonationLevel;
                }

                using (NtToken token = _token.DuplicateToken(TokenType.Impersonation, implevel, TokenAccessRights.MaximumAllowed))
                {
                    TokenIntegrityLevel il = GetILFromComboBox(comboBoxILForDup);
                    if (il != token.IntegrityLevel)
                    {
                        token.SetIntegrityLevel(il);
                    }

                    NtToken imptoken = null;
                    using (var imp = token.Impersonate())
                    {
                        imptoken = NtThread.Current.OpenToken();
                    }
                    if (imptoken != null)
                    {
                        OpenForm(imptoken, "Impersonation", false);
                    }
                    else
                    {
                        MessageBox.Show(this, "Couldn't open thread token", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 8
0
        private void GetInterfacesInternal(NtToken token)
        {
            IntPtr punk         = IntPtr.Zero;
            IntPtr pfactory     = IntPtr.Zero;
            Guid   IID_IUnknown = COMInterfaceEntry.IID_IUnknown;
            CLSCTX clsctx       = _clsctx;

            if (token != null)
            {
                clsctx |= CLSCTX.ENABLE_CLOAKING;
            }

            using (var imp = token?.Impersonate())
            {
                int hr = 0;
                if (_winrt_component)
                {
                    hr = COMUtilities.RoGetActivationFactory(_activatable_classid, ref IID_IUnknown, out pfactory);
                }
                else
                {
                    hr = COMUtilities.CoGetClassObject(ref _clsid, clsctx, null, ref IID_IUnknown, out pfactory);
                }
                // If we can't get class object, no chance we'll get object.
                if (hr != 0)
                {
                    throw new Win32Exception(hr);
                }

                if (_winrt_component)
                {
                    hr = COMUtilities.RoActivateInstance(_activatable_classid, out punk);
                }
                else
                {
                    hr = COMUtilities.CoCreateInstance(ref _clsid, IntPtr.Zero, clsctx,
                                                       ref IID_IUnknown, out punk);
                }
                if (hr != 0)
                {
                    punk = IntPtr.Zero;
                }

                try
                {
                    Dictionary <IntPtr, string> module_names = new Dictionary <IntPtr, string>();
                    QueryInterface(punk, COMInterfaceEntry.IID_IMarshal, module_names, _interfaces);
                    QueryInterface(pfactory, COMInterfaceEntry.IID_IMarshal, module_names, _factory_interfaces);
                    QueryInterface(punk, COMInterfaceEntry.IID_IPSFactoryBuffer, module_names, _interfaces);
                    QueryInterface(pfactory, COMInterfaceEntry.IID_IPSFactoryBuffer, module_names, _factory_interfaces);

                    var actctx = ActivationContext.FromProcess();
                    if (actctx != null)
                    {
                        foreach (var intf in actctx.ComInterfaces)
                        {
                            QueryInterface(punk, intf.Iid, module_names, _interfaces);
                            QueryInterface(pfactory, intf.Iid, module_names, _factory_interfaces);
                        }
                    }

                    using (RegistryKey interface_key = Registry.ClassesRoot.OpenSubKey("Interface"))
                    {
                        foreach (string iid_string in interface_key.GetSubKeyNames())
                        {
                            if (Guid.TryParse(iid_string, out Guid iid))
                            {
                                QueryInterface(punk, iid, module_names, _interfaces);
                                QueryInterface(pfactory, iid, module_names, _factory_interfaces);
                            }
                        }
                    }

                    QueryInspectableInterfaces(punk, module_names, _interfaces);
                    QueryInspectableInterfaces(pfactory, module_names, _factory_interfaces);
                }
                finally
                {
                    if (pfactory != IntPtr.Zero)
                    {
                        Marshal.Release(pfactory);
                    }

                    if (punk != IntPtr.Zero)
                    {
                        Marshal.Release(punk);
                    }
                }
            }
        }
Ejemplo n.º 9
0
        static void Main(string[] args)
        {
            bool show_help = false;

            _pid = Process.GetCurrentProcess().Id;

            try
            {
                OptionSet opts = new OptionSet()
                {
                    { "p|pid=", "Specify a PID of a process to impersonate when checking", v => _pid = int.Parse(v.Trim()) },
                    { "n", "Specifes the list of arguments represents names instead of pids", v => _named_process = v != null },
                    { "i", "Use an indentify level token when impersonating", v => _identify_only = v != null },
                    { "t", "Dump accessible threads for process", v => _dump_threads = v != null },
                    { "k", "Dump tokens for accessible objects", v => _dump_token = v != null },
                    { "a", "Start with all accessible threads instead of processes", v => _dump_threads = _all_threads = v != null },
                    { "sddl", "Dump SDDL strings for objects", v => _print_sddl = v != null },
                    { "h|help", "show this message and exit",
                      v => show_help = v != null },
                };

                List <string> pids = opts.Parse(args).Select(s => s.ToLower()).ToList();

                if (show_help)
                {
                    ShowHelp(opts);
                }
                else
                {
                    IEnumerable <ProcessEntry> processes = new ProcessEntry[0];

                    if (_all_threads)
                    {
                        NtThread[] all_threads = null;

                        using (var imp = NtToken.Impersonate(_pid,
                                                             _identify_only ? SecurityImpersonationLevel.Identification : SecurityImpersonationLevel.Impersonation))
                        {
                            if (pids.Count > 0)
                            {
                                List <NtThread> ths = new List <NtThread>();
                                foreach (string pid_name in pids)
                                {
                                    try
                                    {
                                        ths.Add(NtThread.Open(int.Parse(pid_name), ThreadAccessRights.MaximumAllowed));
                                    }
                                    catch (NtException ex)
                                    {
                                        Console.WriteLine("Error opening tid {0} - {1}", pid_name, ex.Message);
                                    }
                                }

                                all_threads = ths.ToArray();
                            }
                            else
                            {
                                all_threads = NtThread.GetThreads(ThreadAccessRights.MaximumAllowed).ToArray();
                            }

                            List <ProcessEntry> procs = new List <ProcessEntry>();

                            foreach (var group in all_threads.GroupBy(t => t.ProcessId))
                            {
                                ProcessEntry entry   = null;
                                NtThread[]   threads = group.ToArray();
                                try
                                {
                                    entry = new ProcessEntry(NtProcess.Open(group.Key, ProcessAccessRights.MaximumAllowed), threads);
                                }
                                catch (NtException)
                                {
                                    entry = new ProcessEntry(group.Key, threads);
                                }
                                procs.Add(entry);
                            }
                            processes = procs;
                        }
                    }
                    else
                    {
                        if (pids.Count > 0 && !_named_process)
                        {
                            List <ProcessEntry> procs = new List <ProcessEntry>();
                            using (var imp = NtToken.Impersonate(_pid,
                                                                 _identify_only ? SecurityImpersonationLevel.Identification : SecurityImpersonationLevel.Impersonation))
                            {
                                foreach (string pid_name in pids)
                                {
                                    try
                                    {
                                        procs.Add(new ProcessEntry(NtProcess.Open(int.Parse(pid_name), ProcessAccessRights.MaximumAllowed)));
                                    }
                                    catch (NtException ex)
                                    {
                                        Console.WriteLine("Error opening pid {0} - {1}", pid_name, ex.Message);
                                    }
                                }
                            }

                            processes = procs;
                        }
                        else
                        {
                            try
                            {
                                using (var imp = NtToken.Impersonate(_pid,
                                                                     _identify_only ? SecurityImpersonationLevel.Identification : SecurityImpersonationLevel.Impersonation))
                                {
                                    processes = NtProcess.GetProcesses(ProcessAccessRights.MaximumAllowed).Select(h => new ProcessEntry(h));
                                }

                                if (_named_process && pids.Count > 0)
                                {
                                    processes = processes.Where(p => pids.Contains(p.Name.ToLower()));
                                }
                            }
                            catch (NtException ex)
                            {
                                Console.WriteLine(ex);
                            }
                        }
                    }

                    List <ProcessEntry> ps = processes.ToList();

                    ps.Sort((a, b) => a.Pid - b.Pid);

                    processes = ps;

                    foreach (ProcessEntry process in processes)
                    {
                        Console.WriteLine("{0}: {1} {2}", process.Pid, process.Name, process.GetGrantedAccessString());
                        if (_print_sddl && process.Handle.IsAccessGranted(ProcessAccessRights.ReadControl))
                        {
                            Console.WriteLine("SDDL: {0}", process.Handle.GetSddl());
                        }

                        if (_dump_token && process.Token != null)
                        {
                            Console.WriteLine("User: {0}", process.Token.User);
                            if (_print_sddl && process.Token.IsAccessGranted(TokenAccessRights.ReadControl))
                            {
                                Console.WriteLine("Token SDDL: {0}", process.Token.GetSddl());
                            }
                        }

                        if (_dump_threads)
                        {
                            foreach (ThreadEntry thread in process.Threads)
                            {
                                Console.WriteLine("-- Thread {0}: {1}", thread.Tid, thread.Handle.GetGrantedAccessString());
                                if (_print_sddl && thread.Handle.IsAccessGranted(ThreadAccessRights.ReadControl))
                                {
                                    Console.WriteLine("---- SDDL: {0}", thread.Handle.GetSddl());
                                }

                                if (_dump_token && thread.Token != null)
                                {
                                    Console.WriteLine("---- Impersonating {0}", thread.Token.User);
                                    if (_print_sddl && thread.Token.IsAccessGranted(TokenAccessRights.ReadControl))
                                    {
                                        Console.WriteLine("---- Token SDDL: {0}", thread.Token.GetSddl());
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }