/// <summary>
        /// Gets the security descriptor of a kernel object.
        /// </summary>
        /// <param name="handle">A handle to a kernel object.</param>
        /// <param name="securityInformation">The information to retrieve.</param>
        /// <returns>A security descriptor.</returns>
        public static SecurityDescriptor GetSecurity(IntPtr handle, SecurityInformation securityInformation)
        {
            using (MemoryAlloc data = new MemoryAlloc(0x100))
            {
                int retLength;

                NtStatus status = Win32.NtQuerySecurityObject(
                    handle,
                    securityInformation,
                    data,
                    data.Size,
                    out retLength
                    );

                if (status == NtStatus.BufferTooSmall)
                {
                    data.ResizeNew(retLength);

                    Win32.NtQuerySecurityObject(
                        handle,
                        securityInformation,
                        data,
                        data.Size,
                        out retLength
                        ).ThrowIf();
                }

                status.ThrowIf();

                return(new SecurityDescriptor(data));
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Enumerates the modules loaded by the kernel.
        /// </summary>
        /// <param name="enumCallback">A callback for the enumeration.</param>
        public static void EnumKernelModules(EnumKernelModulesDelegate enumCallback)
        {
            int retLength;

            if (_kernelModulesBuffer == null)
            {
                _kernelModulesBuffer = new MemoryAlloc(0x1000);
            }

            NtStatus status = Win32.NtQuerySystemInformation(
                SystemInformationClass.SystemModuleInformation,
                _kernelModulesBuffer,
                _kernelModulesBuffer.Size,
                out retLength
                );

            if (status == NtStatus.InfoLengthMismatch)
            {
                _kernelModulesBuffer.ResizeNew(retLength);

                status = Win32.NtQuerySystemInformation(
                    SystemInformationClass.SystemModuleInformation,
                    _kernelModulesBuffer,
                    _kernelModulesBuffer.Size,
                    out retLength
                    );
            }

            status.ThrowIf();

            RtlProcessModules modules = _kernelModulesBuffer.ReadStruct <RtlProcessModules>();

            for (int i = 0; i < modules.NumberOfModules; i++)
            {
                var module     = _kernelModulesBuffer.ReadStruct <RtlProcessModuleInformation>(RtlProcessModules.ModulesOffset, RtlProcessModuleInformation.SizeOf, i);
                var moduleInfo = new Debugging.ModuleInformation(module);

                if (!enumCallback(new KernelModule(
                                      moduleInfo.BaseAddress,
                                      moduleInfo.Size,
                                      moduleInfo.Flags,
                                      moduleInfo.BaseName,
                                      FileUtils.GetFileName(moduleInfo.FileName)
                                      )))
                {
                    break;
                }
            }
        }
Ejemplo n.º 3
0
        public bool Listen()
        {
            int returnLength;

            NtStatus status = this.FsControl(FsCtlListen, IntPtr.Zero, 0, IntPtr.Zero, 0, out returnLength);

            if (status == NtStatus.PipeConnected)
            {
                return(true);
            }

            status.ThrowIf();

            return(false);
        }
        public string GetVariable(string name)
        {
            UnicodeString nameStr = new UnicodeString(name);

            try
            {
                using (MemoryAlloc data = new MemoryAlloc(100))
                {
                    UnicodeString valueStr = new UnicodeString
                    {
                        Buffer        = data,
                        MaximumLength = (ushort)data.Size
                    };

                    NtStatus status = Win32.RtlQueryEnvironmentVariable_U(
                        this,
                        ref nameStr,
                        ref valueStr
                        );

                    if (status == NtStatus.BufferTooSmall)
                    {
                        // Resize and try again (+2 for the null terminator).
                        data.ResizeNew(valueStr.Length + 2);
                        valueStr.Buffer        = data;
                        valueStr.MaximumLength = (ushort)(valueStr.Length + 2);

                        status = Win32.RtlQueryEnvironmentVariable_U(
                            this,
                            ref nameStr,
                            ref valueStr
                            );
                    }

                    status.ThrowIf();

                    return(valueStr.Text);
                }
            }
            finally
            {
                nameStr.Dispose();
            }
        }
        /// <summary>
        /// Creates a copy of the security descriptor in self-relative form.
        /// </summary>
        /// <returns>A new self-relative security descriptor.</returns>
        public SecurityDescriptor ToSelfRelative()
        {
            using (MemoryAlloc data = new MemoryAlloc(Win32.SecurityDescriptorMinLength))
            {
                int retLength = data.Size;

                NtStatus status = Win32.RtlMakeSelfRelativeSD(this, data, ref retLength);

                if (status == NtStatus.BufferTooSmall)
                {
                    data.ResizeNew(retLength);
                    status = Win32.RtlMakeSelfRelativeSD(this, data, ref retLength);
                }

                status.ThrowIf();

                return(new SecurityDescriptor(data));
            }
        }
Ejemplo n.º 6
0
        public static bool Wait(string name, long timeout, bool relative)
        {
            using (FileHandle npfsHandle = new FileHandle(
                       Win32.NamedPipePath + "\\",
                       FileShareMode.ReadWrite,
                       FileCreateOptions.SynchronousIoNonAlert,
                       FileAccess.ReadAttributes | (FileAccess)StandardRights.Synchronize
                       ))
            {
                using (MemoryAlloc data = new MemoryAlloc(FilePipeWaitForBuffer.NameOffset + name.Length * 2))
                {
                    FilePipeWaitForBuffer info = new FilePipeWaitForBuffer
                    {
                        Timeout          = timeout,
                        TimeoutSpecified = true,
                        NameLength       = name.Length * 2
                    };

                    data.WriteStruct(info);
                    data.WriteUnicodeString(FilePipeWaitForBuffer.NameOffset, name);

                    int returnLength;

                    NtStatus status = npfsHandle.FsControl(FsCtlWait, data, data.Size, IntPtr.Zero, 0, out returnLength);

                    if (status == NtStatus.IoTimeout)
                    {
                        return(false);
                    }

                    status.ThrowIf();

                    return(true);
                }
            }
        }
Ejemplo n.º 7
0
        public static unsafe string GetVistaFileName(int pid)
        {
            using (MemoryAlloc buffer = new MemoryAlloc(0x100))
            {
                SystemProcessImageNameInformation info;

                info.ProcessId               = pid;
                info.ImageName.Length        = 0;
                info.ImageName.MaximumLength = 0x100;
                info.ImageName.Buffer        = buffer;

                NtStatus status = Win32.NtQuerySystemInformation(
                    SystemInformationClass.SystemProcessImageName,
                    &info,
                    SystemProcessImageNameInformation.SizeOf,
                    null
                    );

                if (status == NtStatus.InfoLengthMismatch)
                {
                    // Our buffer was too small. The required buffer length is stored in MaximumLength.
                    buffer.ResizeNew(info.ImageName.MaximumLength);

                    status = Win32.NtQuerySystemInformation(
                        SystemInformationClass.SystemProcessImageName,
                        &info,
                        SystemProcessImageNameInformation.SizeOf,
                        null
                        );
                }

                status.ThrowIf();

                return(GetFileName(info.ImageName.Text));
            }
        }
Ejemplo n.º 8
0
        private void unloadMenuItem_Click(object sender, EventArgs e)
        {
            if (!PhUtils.ShowConfirmMessage(
                    "Unload",
                    _pid != 4 ? "the selected module" : "the selected driver",
                    _pid != 4 ?
                    "Unloading a module may cause the process to crash." :
                    "Unloading a driver may cause system instability.",
                    true
                    ))
            {
                return;
            }

            if (_pid == 4)
            {
                try
                {
                    var    moduleItem  = (ModuleItem)listModules.SelectedItems[0].Tag;
                    string serviceName = null;

                    // Try to find the name of the service key for the driver by
                    // looping through the objects in the Driver directory and
                    // opening each one.
                    using (var dhandle = new DirectoryHandle("\\Driver", DirectoryAccess.Query))
                    {
                        foreach (var obj in dhandle.GetObjects())
                        {
                            try
                            {
                                using (var driverHandle = new DriverHandle("\\Driver\\" + obj.Name))
                                {
                                    if (driverHandle.GetBasicInformation().DriverStart == moduleItem.BaseAddress)
                                    {
                                        serviceName = driverHandle.GetServiceKeyName();
                                        break;
                                    }
                                }
                            }
                            catch
                            { }
                        }
                    }

                    // If we didn't find the service name, use the driver base name.
                    if (serviceName == null)
                    {
                        if (moduleItem.Name.ToLower().EndsWith(".sys"))
                        {
                            serviceName = moduleItem.Name.Remove(moduleItem.Name.Length - 4, 4);
                        }
                        else
                        {
                            serviceName = moduleItem.Name;
                        }
                    }

                    RegistryKey servicesKey =
                        Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Services", true);
                    bool        serviceKeyCreated;
                    RegistryKey serviceKey;

                    // Check if the service key exists so that we don't delete it
                    // later if it does.
                    if (Array.Exists <string>(servicesKey.GetSubKeyNames(),
                                              (keyName) => (string.Compare(keyName, serviceName, true) == 0)))
                    {
                        serviceKeyCreated = false;
                    }
                    else
                    {
                        serviceKeyCreated = true;
                        // Create the service key.
                        serviceKey = servicesKey.CreateSubKey(serviceName);

                        serviceKey.SetValue("ErrorControl", 1, RegistryValueKind.DWord);
                        serviceKey.SetValue("ImagePath", "\\??\\" + moduleItem.FileName, RegistryValueKind.ExpandString);
                        serviceKey.SetValue("Start", 1, RegistryValueKind.DWord);
                        serviceKey.SetValue("Type", 1, RegistryValueKind.DWord);
                        serviceKey.Close();
                        servicesKey.Flush();
                    }

                    try
                    {
                        Windows.UnloadDriver(serviceName);
                    }
                    finally
                    {
                        if (serviceKeyCreated)
                        {
                            servicesKey.DeleteSubKeyTree(serviceName);
                        }

                        servicesKey.Close();
                    }

                    listModules.SelectedItems.Clear();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Unable to unload the driver. Make sure Process Hacker " +
                                    "is running with administrative privileges. Error:\n\n" +
                                    ex.Message, "Process Hacker", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                try
                {
                    using (ProcessHandle phandle = new ProcessHandle(_pid,
                                                                     Program.MinProcessQueryRights | ProcessAccess.VmOperation |
                                                                     ProcessAccess.VmRead | ProcessAccess.VmWrite | ProcessAccess.CreateThread))
                    {
                        IntPtr baseAddress = ((ModuleItem)listModules.SelectedItems[0].Tag).BaseAddress;

                        phandle.SetModuleReferenceCount(baseAddress, 1);

                        ThreadHandle thread;

                        if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista))
                        {
                            // Use RtlCreateUserThread to bypass session boundaries. Since
                            // LdrUnloadDll is a native function we don't need to notify CSR.
                            thread = phandle.CreateThread(
                                Loader.GetProcedure("ntdll.dll", "LdrUnloadDll"),
                                baseAddress
                                );
                        }
                        else
                        {
                            // On XP it seems we need to notify CSR...
                            thread = phandle.CreateThreadWin32(
                                Loader.GetProcedure("kernel32.dll", "FreeLibrary"),
                                baseAddress
                                );
                        }

                        thread.Wait(1000 * Win32.TimeMsTo100Ns);

                        NtStatus exitStatus = thread.GetExitStatus();

                        if (exitStatus == NtStatus.DllNotFound)
                        {
                            if (IntPtr.Size == 8)
                            {
                                PhUtils.ShowError("Unable to find the module to unload. This may be caused " +
                                                  "by an attempt to unload a mapped file or a 32-bit module.");
                            }
                            else
                            {
                                PhUtils.ShowError("Unable to find the module to unload. This may be caused " +
                                                  "by an attempt to unload a mapped file.");
                            }
                        }
                        else
                        {
                            exitStatus.ThrowIf();
                        }

                        thread.Dispose();
                    }

                    listModules.SelectedItems.Clear();
                }
                catch (Exception ex)
                {
                    PhUtils.ShowException("Unable to unload the module", ex);
                }
            }
        }