10

我正在开发一个家长控制应用程序(用 WPF 编写),并希望禁止任何人(包括管理员)杀死我的进程。不久前,我在网上找到了以下代码,它几乎可以完美运行,只是有时它不起作用。

static void SetAcl()
{
    var sd = new RawSecurityDescriptor(ControlFlags.None, new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), null, null, new RawAcl(2, 0));
    sd.SetFlags(ControlFlags.DiscretionaryAclPresent | ControlFlags.DiscretionaryAclDefaulted);
    var rawSd = new byte[sd.BinaryLength];

    sd.GetBinaryForm(rawSd, 0);
    if (!Win32.SetKernelObjectSecurity(Process.GetCurrentProcess().Handle, SecurityInfos.DiscretionaryAcl, rawSd))
        throw new Win32Exception();
}

在 Win7 中,如果应用程序是由登录用户启动的,即使是管理员也无法终止该进程(访问被拒绝)。但是,如果您切换到另一个用户帐户(管理员或标准用户),然后选中“显示所有用户的进程”,那么您可以毫无问题地终止该进程。谁能给我一个提示为什么以及如何解决它?

编辑:
我知道有些人对这个问题感到不安,但这是我的困境。这是我主要为自己使用而编写的家长控制。主要特点是我想监控和限制我的孩子玩游戏(而不是简单地关闭所有游戏)。我可以为孩子们分配一个标准用户帐户,他们无法终止该过程。但是,某些游戏(例如 Mabinogi)需要管理员权限才能玩。所以,我每次都必须输入我的管理员密码,这很烦人。

顺便说一句,我不确定这是否违反 Stackoverflow 的政策,如果您想查看,这是我的应用程序:https ://sites.google.com/site/goppieinc/pc-screen-watcher 。

编辑:
我这篇文章的主要目的是询问是否有人可以给我一个提示,为什么发布的代码并不总是有效 - 例如,如果你显示所有用户的进程。

4

4 回答 4

12

有些评论是对的,你正在玩一个很可能注定没有尽头的游戏。但是,据我所知,将您的进程设置为关键内核进程似乎会给您带来明显的胜利。任何杀死该进程的尝试只会让您的计算机蓝屏。代码是:

/*
Copyright © 2017 Jesse Nicholson  
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/


using System;
using System.Runtime.InteropServices;
using System.Threading;

namespace MyRedactedNamespace
{
    /// <summary>
    /// Class responsible for exposing undocumented functionality making the host process unkillable.
    /// </summary>
    public static class ProcessProtection
    {
        [DllImport("ntdll.dll", SetLastError = true)]
        private static extern void RtlSetProcessIsCritical(UInt32 v1, UInt32 v2, UInt32 v3);

        /// <summary>
        /// Flag for maintaining the state of protection.
        /// </summary>
        private static volatile bool s_isProtected = false;

        /// <summary>
        /// For synchronizing our current state.
        /// </summary>
        private static ReaderWriterLockSlim s_isProtectedLock = new ReaderWriterLockSlim();

        /// <summary>
        /// Gets whether or not the host process is currently protected.
        /// </summary>
        public static bool IsProtected
        {
            get
            {
                try
                {
                    s_isProtectedLock.EnterReadLock();

                    return s_isProtected;
                }
                finally
                {
                    s_isProtectedLock.ExitReadLock();
                }
            }
        }

        /// <summary>
        /// If not alreay protected, will make the host process a system-critical process so it
        /// cannot be terminated without causing a shutdown of the entire system.
        /// </summary>
        public static void Protect()
        {
            try
            {
                s_isProtectedLock.EnterWriteLock();

                if(!s_isProtected)
                {
                    System.Diagnostics.Process.EnterDebugMode();
                    RtlSetProcessIsCritical(1, 0, 0);
                    s_isProtected = true;
                }
            }
            finally
            {
                s_isProtectedLock.ExitWriteLock();
            }
        }

        /// <summary>
        /// If already protected, will remove protection from the host process, so that it will no
        /// longer be a system-critical process and thus will be able to shut down safely.
        /// </summary>
        public static void Unprotect()
        {
            try
            {
                s_isProtectedLock.EnterWriteLock();

                if(s_isProtected)
                {
                    RtlSetProcessIsCritical(0, 0, 0);
                    s_isProtected = false;
                }
            }
            finally
            {
                s_isProtectedLock.ExitWriteLock();
            }
        }
    }
}

这里的想法是您Protect()尽快调用该方法,然后Unprotect()在您自愿关闭应用程序时调用。

对于 WPF 应用程序,您将要挂钩SessionEnding事件,这是您将调用该Unprotect()方法的地方,以防有人注销或关闭计算机。这绝对必须是SessionEnding事件,而不是SystemEvents.SessionEnded事件。很多时候,当SystemEvents.SessionEnded事件被调用时,如果您花费太长时间来释放保护,您的应用程序可能会被强制终止,导致每次重新启动或注销时都会出现蓝屏死机。如果你使用SessionEnding事件,你可以避免这个问题。关于该事件的另一个有趣事实是,您可以在某种程度上对注销或关闭提出异议。此外,您显然希望在事件处理程序Unprotect()内部调用。Application.Exit

在部署此机制之前确保您的应用程序是稳定的,因为如果进程受到保护,崩溃也会导致您的计算机蓝屏。

作为所有攻击您采取这些措施的人的说明,请忽略它们。是否有人可能会使用此代码进行恶意操作并不重要,这是为完全合法的原因停止完全合法的研究的糟糕借口。就我而言,我已将其开发为我自己的应用程序的一部分,因为成年人(管理员)不希望能够通过杀死它来停止我的进程。他们明确地想要这个功能,因为它可以防止他们自己绕过软件的设计目的。

于 2017-02-05T16:54:57.390 回答
1

使 WPF 端只是一个客户端。在这种情况下,“服务器”必须是 Windows 服务。然后将服务设置为自动启动(这最后一部分需要管理员权限)。如果它以网络管理员身份运行,则会获得奖励。

如果服务的进程被杀死,Windows 会立即重新启动它。然后无论用户尝试什么,他们都无法真正停止您的程序逻辑,除非他们拥有管理员权限并自己停止服务。仅使用 WPF GUI 进行配置。

于 2013-06-06T17:42:36.093 回答
0

系统帐户高于管理员(至少在操作系统的情况下)。系统帐户和管理员帐户具有相同的文件权限,但它们具有不同的功能。系统帐户由操作系统和在 Windows 下运行的服务使用。Windows 中有许多服务和进程需要能够在内部登录(例如在 Windows 安装期间)。系统帐户就是为此目的而设计的;它是一个内部帐户,不显示在用户管理器中,不能添加到任何组,也不能为其分配用户权限。

因此,挑战在于如何在安装过程中将您的应用程序权限提升到系统帐户。我不确定如何提升您的流程。但值得阅读后参考 1参考 2。此外,即使我们假设您设法将其添加到系统帐户,在管理您自己的应用程序时,即使您是指数级的超级用户,您仍可能面临更多挑战。

于 2013-06-06T17:54:36.213 回答
0

您无法阻止管理员使用此代码终止您的进程或停止您的服务,但可能会在几周后结束。

//Obtaining the process DACL
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool GetKernelObjectSecurity(IntPtr Handle, int securityInformation, [Out] byte[] pSecurityDescriptor, uint nLength, out uint lpnLengthNeeded);
public static RawSecurityDescriptor GetProcessSecurityDescriptor(IntPtr processHandle)
{
    const int DACL_SECURITY_INFORMATION = 0x00000004;
    byte[] psd = new byte[0];
    uint bufSizeNeeded;
    // Call with 0 size to obtain the actual size needed in bufSizeNeeded
    GetKernelObjectSecurity(processHandle, DACL_SECURITY_INFORMATION, psd, 0, out bufSizeNeeded);
    if (bufSizeNeeded < 0 || bufSizeNeeded > short.MaxValue)
        throw new Win32Exception();
    // Allocate the required bytes and obtain the DACL
    if (!GetKernelObjectSecurity(processHandle, DACL_SECURITY_INFORMATION,
    psd = new byte[bufSizeNeeded], bufSizeNeeded, out bufSizeNeeded))
        throw new Win32Exception();
    // Use the RawSecurityDescriptor class from System.Security.AccessControl to parse the bytes:
    return new RawSecurityDescriptor(psd, 0);
}


//Updating the process DACL
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool SetKernelObjectSecurity(IntPtr Handle, int securityInformation, [In] byte[] pSecurityDescriptor);
public static void SetProcessSecurityDescriptor(IntPtr processHandle, RawSecurityDescriptor dacl)
{
    const int DACL_SECURITY_INFORMATION = 0x00000004;
    byte[] rawsd = new byte[dacl.BinaryLength];
    dacl.GetBinaryForm(rawsd, 0);
    if (!SetKernelObjectSecurity(processHandle, DACL_SECURITY_INFORMATION, rawsd))
        throw new Win32Exception();
}


//Getting the current process
[DllImport("kernel32.dll")]
public static extern IntPtr GetCurrentProcess();


//Process access rights
[Flags]
public enum ProcessAccessRights
{
    PROCESS_CREATE_PROCESS = 0x0080, //  Required to create a process.
    PROCESS_CREATE_THREAD = 0x0002, //  Required to create a thread.
    PROCESS_DUP_HANDLE = 0x0040, // Required to duplicate a handle using DuplicateHandle.
    PROCESS_QUERY_INFORMATION = 0x0400, //  Required to retrieve certain information about a process, such as its token, exit code, and priority class (see OpenProcessToken, GetExitCodeProcess, GetPriorityClass, and IsProcessInJob).
    PROCESS_QUERY_LIMITED_INFORMATION = 0x1000, //  Required to retrieve certain information about a process (see QueryFullProcessImageName). A handle that has the PROCESS_QUERY_INFORMATION access right is automatically granted PROCESS_QUERY_LIMITED_INFORMATION. Windows Server 2003 and Windows XP/2000:  This access right is not supported.
    PROCESS_SET_INFORMATION = 0x0200, //    Required to set certain information about a process, such as its priority class (see SetPriorityClass).
    PROCESS_SET_QUOTA = 0x0100, //  Required to set memory limits using SetProcessWorkingSetSize.
    PROCESS_SUSPEND_RESUME = 0x0800, // Required to suspend or resume a process.
    PROCESS_TERMINATE = 0x0001, //  Required to terminate a process using TerminateProcess.
    PROCESS_VM_OPERATION = 0x0008, //   Required to perform an operation on the address space of a process (see VirtualProtectEx and WriteProcessMemory).
    PROCESS_VM_READ = 0x0010, //    Required to read memory in a process using ReadProcessMemory.
    PROCESS_VM_WRITE = 0x0020, //   Required to write to memory in a process using WriteProcessMemory.
    DELETE = 0x00010000, // Required to delete the object.
    READ_CONTROL = 0x00020000, //   Required to read information in the security descriptor for the object, not including the information in the SACL. To read or write the SACL, you must request the ACCESS_SYSTEM_SECURITY access right. For more information, see SACL Access Right.
    SYNCHRONIZE = 0x00100000, //    The right to use the object for synchronization. This enables a thread to wait until the object is in the signaled state.
    WRITE_DAC = 0x00040000, //  Required to modify the DACL in the security descriptor for the object.
    WRITE_OWNER = 0x00080000, //    Required to change the owner in the security descriptor for the object.
    STANDARD_RIGHTS_REQUIRED = 0x000f0000,
    PROCESS_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFF),//    All possible access rights for a process object.
}

public Form1()
{
        InitializeComponent();

        //Put it all together to prevent users from killing your service or process
        IntPtr hProcess = GetCurrentProcess(); // Get the current process handle
        // Read the DACL
        var dacl = GetProcessSecurityDescriptor(hProcess);
        // Insert the new ACE
        dacl.DiscretionaryAcl.InsertAce(
        0,
        new CommonAce(
        AceFlags.None,
        AceQualifier.AccessDenied,
        (int)ProcessAccessRights.PROCESS_ALL_ACCESS,
        new SecurityIdentifier(WellKnownSidType.WorldSid, null),
        false,
        null)
        );
        // Save the DACL
        SetProcessSecurityDescriptor(hProcess, dacl);
}

参考:如何防止用户杀死你的服务或进程

于 2021-02-17T09:42:18.990 回答