更改运行进程所有者C#

时间:2015-08-13 23:10:24

标签: c# windows process

是否可以更改已启动的流程的所有者,最好在必要时使用C#/PInvoke

看起来好像SetSecurityInfo允许我这样做,但每次调用该函数都会返回错误code 1307

  

ERROR_INVALID_OWNER

1307 (0x51B)

This security ID may not be assigned as the owner of this object.

我不确定为什么我收到这个,因为原始帐户和新所有者都是管理员帐户。 UAC已禁用。

我的谷歌冒险让我相信我需要SetPrivileges,但这似乎没有任何改变。下面是我到目前为止尝试的代码:

SecurityIdentifier userSid = getUserSid("Test");

Process proc = Process.GetCurrentProcess();
IntPtr procHandle = proc.Handle;

byte[] bytes = new byte[userSid.BinaryLength];
userSid.GetBinaryForm(bytes, 0);

GCHandle pinnedArray = GCHandle.Alloc(bytes, GCHandleType.Pinned);
IntPtr pointer = pinnedArray.AddrOfPinnedObject();

SetPrivilege("SeTakeOwnershipPrivilege");
SetPrivilege("SeRestorePrivilege");

uint result = SetSecurityInfo(procHandle, SE_OBJECT_TYPE.SE_KERNEL_OBJECT, SECURITY_INFORMATION.Owner, pointer, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);

pinnedArray.Free();

getUserSid():

private SecurityIdentifier getUserSid(string userName)
{
    // set up machine context
    PrincipalContext ctx = new PrincipalContext(ContextType.Machine);

    // find a user
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "Test");

    if (user != null)
    {
        return user.Sid;
    }
    return null;
}

SetPrivilege():

private static void SetPrivilege(string privilege)
{
    int i1 = 0;
    var luid = new LUID();
    var token_PRIVILEGES = new TOKEN_PRIVILEGES();
    int i2 = OpenProcessToken(GetCurrentProcess(), 40, ref i1);
    if (i2 == 0)
        throw new Exception("OpenProcessToken For Privilege <" + privilege + "> Failed");
    i2 = LookupPrivilegeValue(null, privilege, ref luid);
    if (i2 == 0)
        throw new Exception("LookupPrivilegeValue For Privilege <" + privilege + "> Failed");
    token_PRIVILEGES.PrivilegeCount = 1;
    token_PRIVILEGES.Attributes = 2;
    token_PRIVILEGES.Luid = luid;
    i2 = AdjustTokenPrivileges(i1, 0, ref token_PRIVILEGES, 1024, 0, 0);
    if (i2 == 0)
        throw new Exception("AdjustTokenPrivileges For Privilege <" + privilege + "> Failed");
}

我已经验证在调试期间使用的SID是预期的。我也试过handle.MainWindowHandle,但实际上导致了错误代码6(窗口句柄无效)。我对pinnedArray代码不太确定。它似乎按预期工作。

0 个答案:

没有答案