从 C# 控制台应用程序终止 Windows 进程:如何设置权限?

发布于 2024-08-11 23:34:09 字数 441 浏览 3 评论 0原文

在 ASP.NET Web 应用程序中使用 Process.Kill() 时,我收到带有文本“访问被拒绝”的 Win32Exception。

网上搜索了好几次都告诉我要设置权限。但是我对 Windows XP 用户系统的了解还不够深入,不知道如何开始。

引发异常时,Thread.CurrentPrincipal.Identity 具有以下可见属性:

  1. AuthenticationType = ""
  2. IsAuthenticated = "false"
  3. Name = ""

WindowsIdentity.GetCurrent() 显示我以“NAME\ASPNET”登录,但我认为这不相关。

我需要做什么?我可以以某种方式让线程以某个 Windows 用户身份登录吗?

Using Process.Kill() from an ASP.NET web application, I get a Win32Exception with text "Access is denied".

Searching the web has several times told me to set permissions. However I don't really understand the Windows XP User system well enough to know how to get started.

At the time the exception is thrown, Thread.CurrentPrincipal.Identity has the following visible properties:

  1. AuthenticationType = ""
  2. IsAuthenticated = "false"
  3. Name = ""

WindowsIdentity.GetCurrent() shows me logged in as "NAME\ASPNET" but I don't think that this is relevant.

What do I need to do? Can I somehow get the thread to log in as some Windows user?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦里的微风 2024-08-18 23:34:09

我认为您的方法是正确的,“访问被拒绝”的问题是由于 ASP.NET 进程与 ASPNET 用户一起运行,该用户的权限有限,这就是您收到的错误。您可以做的是为您的 Web 应用程序设置沉浸。您可以通过更改 web.config 或代码来实现。有关模拟的更多信息,您可以阅读此处

web.comfig 非常简单,您需要添加以下内容行进入 web.config 的 system.web 部分,

<identity impersonate="true" userName="domain\user" password="password" />

用户需要在服务器上拥有管理员权限,

如果您想在代码中执行模拟,

...
WindowsImpersonationContext context = ImpersonateUser("domain", "user", "password");
// kill your process
context.Undo();
...

[DllImport("advapi32.dll")]
private static extern bool LogonUser(
    String lpszUsername, String lpszDomain, String lpszPassword,
    int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

[DllImport("advapi32.dll")]
private static extern bool DuplicateToken(
    IntPtr ExistingTokenHandle, int ImpersonationLevel,
    ref IntPtr DuplicateTokenHandle);

[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr hObject);


private enum SecurityImpersonationLevel
{
    SecurityAnonymous,
    SecurityIdentification,
    SecurityImpersonation,
    SecurityDelegation
}

private enum LogonTypes
{
    LOGON32_PROVIDER_DEFAULT=0,
    LOGON32_LOGON_INTERACTIVE=2,
    LOGON32_LOGON_NETWORK=3,
    LOGON32_LOGON_BATCH=4,
    LOGON32_LOGON_SERVICE=5,
    LOGON32_LOGON_UNLOCK=7,
    LOGON32_LOGON_NETWORK_CLEARTEXT=8,
    LOGON32_LOGON_NEW_CREDENTIALS=9
}

public static WindowsImpersonationContext ImpersonateUser(string domain, string username, string password)
{
    WindowsImpersonationContext result = null;
    IntPtr existingTokenHandle = IntPtr.Zero;
    IntPtr duplicateTokenHandle = IntPtr.Zero;

    try
    {
        if (LogonUser(username, domain, password,
            (int)LogonTypes.LOGON32_LOGON_NETWORK_CLEARTEXT, (int)LogonTypes.LOGON32_PROVIDER_DEFAULT,
            ref existingTokenHandle))
        {
            if (DuplicateToken(existingTokenHandle,
                (int)SecurityImpersonationLevel.SecurityImpersonation,
                ref duplicateTokenHandle))
            {
                WindowsIdentity newId = new WindowsIdentity(duplicateTokenHandle);
                result = newId.Impersonate();
            }
        }
    }
    finally
    {
        if (existingTokenHandle != IntPtr.Zero)
            CloseHandle(existingTokenHandle);
        if (duplicateTokenHandle != IntPtr.Zero)
            CloseHandle(duplicateTokenHandle);
    }
    return result;
}

下面是如何执行此操作的示例:希望这有帮助,问候

I think you're on the right way, the problem with "Access denied" is due to ASP.NET process running with ASPNET user which has limited rights and that's what you're getting an error. What you could do is to set up imersnation for your web application. You can it either by changing web.config or in code. More about impersonation you can read here

web.comfig is realtively easy, you need to add a following line into the system.web section of your web.config

<identity impersonate="true" userName="domain\user" password="password" />

user need to have admin rights on the server

if you would like to perform the impersonation in code below is an example of how you could do this:

...
WindowsImpersonationContext context = ImpersonateUser("domain", "user", "password");
// kill your process
context.Undo();
...

[DllImport("advapi32.dll")]
private static extern bool LogonUser(
    String lpszUsername, String lpszDomain, String lpszPassword,
    int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

[DllImport("advapi32.dll")]
private static extern bool DuplicateToken(
    IntPtr ExistingTokenHandle, int ImpersonationLevel,
    ref IntPtr DuplicateTokenHandle);

[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr hObject);


private enum SecurityImpersonationLevel
{
    SecurityAnonymous,
    SecurityIdentification,
    SecurityImpersonation,
    SecurityDelegation
}

private enum LogonTypes
{
    LOGON32_PROVIDER_DEFAULT=0,
    LOGON32_LOGON_INTERACTIVE=2,
    LOGON32_LOGON_NETWORK=3,
    LOGON32_LOGON_BATCH=4,
    LOGON32_LOGON_SERVICE=5,
    LOGON32_LOGON_UNLOCK=7,
    LOGON32_LOGON_NETWORK_CLEARTEXT=8,
    LOGON32_LOGON_NEW_CREDENTIALS=9
}

public static WindowsImpersonationContext ImpersonateUser(string domain, string username, string password)
{
    WindowsImpersonationContext result = null;
    IntPtr existingTokenHandle = IntPtr.Zero;
    IntPtr duplicateTokenHandle = IntPtr.Zero;

    try
    {
        if (LogonUser(username, domain, password,
            (int)LogonTypes.LOGON32_LOGON_NETWORK_CLEARTEXT, (int)LogonTypes.LOGON32_PROVIDER_DEFAULT,
            ref existingTokenHandle))
        {
            if (DuplicateToken(existingTokenHandle,
                (int)SecurityImpersonationLevel.SecurityImpersonation,
                ref duplicateTokenHandle))
            {
                WindowsIdentity newId = new WindowsIdentity(duplicateTokenHandle);
                result = newId.Impersonate();
            }
        }
    }
    finally
    {
        if (existingTokenHandle != IntPtr.Zero)
            CloseHandle(existingTokenHandle);
        if (duplicateTokenHandle != IntPtr.Zero)
            CloseHandle(duplicateTokenHandle);
    }
    return result;
}

hope this helps, regards

关于从前 2024-08-18 23:34:09

您需要以具有足够权限的用户身份运行 C# 应用程序。

如果您不能信任具有此类权限的 ASP AppPool(您不应该),您需要创建一个单独的服务,该服务在具有足够权限的帐户下运行,并在低权限应用程序和较高权限服务之间建立协议,以达到以下目的:杀死一个进程。

不要冒充 AppPool 中的高权限用户。您必须提供其密码,这样您就可以通过一切有效手段,有效地将低特权帐户提升为高特权帐户,以防 AppPool 受到威胁,就像您在高特权下运行 AppPool 一样,并且没有完成任何隔离。

You need to run your C# application as an user with sufficient privileges.

If you cannot trust the ASP AppPool with such privileges (you shouldn't) you need to create a separate service that runs under an account with sufficent privileges and have protocol between the low privileged app and the higher privileged service to communicate with the purpose of killing a process.

Don't impersonate a high privileged user in the AppPool. You must present its password and by this you have effectively elevated the low privileged account to the high privileged one, by all effective means, in case of AppPool compromise, is just as if you run the AppPool under high privilege and did not accomplish any isolation.

一抹淡然 2024-08-18 23:34:09

基于 Serge Gubenko 的答案,这里是模拟和终止进程的代码(在他的答案中他写了“//kill your process”):

using (WindowsImpersonationContext context = ImpersonateUser("domain", "user", "password"))
    {
        Process[] proc = Process.GetProcessesByName("process name");
        if (proc.Length > 0)
            proc[0].Kill();

        context.Undo();
    }

您仍然需要使用他的答案中的其余代码。
请注意,如果您不属于域,只需输入空字符串

Building on Serge Gubenko's answer, Here is the code to impersonate and kill a process (where in his answer he wrote "//kill your process"):

using (WindowsImpersonationContext context = ImpersonateUser("domain", "user", "password"))
    {
        Process[] proc = Process.GetProcessesByName("process name");
        if (proc.Length > 0)
            proc[0].Kill();

        context.Undo();
    }

You still need to use the rest of the code in his answer.
Note that if you are not part of a domain just enter an empty string

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文