如何防止应用程序在任务管理器中被杀?

时间:2013-06-06 17:36:10

标签: c# wpf acl taskmanager

我正在开发一个家长控制应用程序(用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 个答案:

答案 0 :(得分:7)

有些评论是正确的,你正在玩一款可能注定永无止境的游戏。但是,从我所知道的,将您的流程设置为关键内核流程似乎可以为您带来明显的胜利。任何杀死该过程的企图都会使您的计算机失灵。代码是:

/*
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事件时,如果您花费太长时间来释放保护,则可以强制终止您的应用程序,每次重新启动或注销时都会导致BSOD。如果您使用SessionEnding事件,则可以避免此问题。关于该事件的另一个有趣的事实是,您在某种程度上能够对注销或关闭提出异议。此外,您显然希望在Unprotect()事件处理程序中调用Application.Exit

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

作为所有攻击你采取这些措施的人的说明,请忽略它们。如果有人可能使用这些代码来做恶意的事情并不重要,这对于完全合法的事业来说是完全合法的研究是一个糟糕的借口。在我的情况下,我已将此作为我自己的应用程序的一部分开发,因为成人(管理员)不希望能够通过杀死它来阻止我的过程。他们明确地希望这个功能,因为它会阻止自己绕过软件的设计目的。

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

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

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

答案 3 :(得分: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);
}
<块引用>

参考:How to prevent users from killing your service or process