gpt4 book ai didi

c# - .Net Core 模拟无法与 Process.Start 一起使用

转载 作者:行者123 更新时间:2023-12-01 22:44:54 25 4
gpt4 key购买 nike

在 .Net Core 下使用模拟时,我似乎无法以其他用户身份启动进程。我在 Linqpad 中以 User1 身份运行此脚本,并尝试以 User2 身份启动程序。起初,模拟似乎有效(当前用户的 Console.Writeline()RunImpersonated() 方法中从 User1 正确更改为 User2)。但是,该进程始终以 User1 身份运行。

这是我为验证 RunImpersonated() 是否有效而进行的众多测试之一(这最初源于试图模拟当前用户的 ASP.Net Core 应用程序中的问题)。这是我能找到的最简单的可重现示例。

[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, out SafeAccessTokenHandle phToken);

void Main()
{
string domainName = "myDomain";
string userName = "User2";
string passWord = "User2Password";

const int LOGON32_PROVIDER_DEFAULT = 0;
//This parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;

// Call LogonUser to obtain a handle to an access token.
SafeAccessTokenHandle safeAccessTokenHandle;
bool returnValue = LogonUser(userName, domainName, passWord,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
out safeAccessTokenHandle);

if (false == returnValue)
{
int ret = Marshal.GetLastWin32Error();
Console.WriteLine("LogonUser failed with error code : {0}", ret);
throw new System.ComponentModel.Win32Exception(ret);
}

Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
// Check the identity.
Console.WriteLine("Before impersonation: " + WindowsIdentity.GetCurrent().Name);

// Note: if you want to run as unimpersonated, pass
// 'SafeAccessTokenHandle.InvalidHandle' instead of variable 'safeAccessTokenHandle'
WindowsIdentity.RunImpersonated(
safeAccessTokenHandle,
// User action
() =>
{
// Check the identity.
Console.WriteLine("During impersonation: " + WindowsIdentity.GetCurrent().Name);
Directory.GetFiles(@"C:\TMP\").Dump();
var pi = new ProcessStartInfo
{
WorkingDirectory = @"C:\TMP\",
FileName = @"C:\TMP\TestUser.exe"
};
var proc = Process.Start(pi);
proc.WaitForExit();
}
);

// Check the identity again.
Console.WriteLine("After impersonation: " + WindowsIdentity.GetCurrent().Name);
}

最佳答案

如果您不指定用户名和密码,Process.Start 将使用调用进程的 token ,而不是模拟 token 。

调查source code Process.Start:

If the calling process is impersonating another user, the new process uses the token for the calling process, not the impersonation token. To run the new process in the security context of the user represented by the impersonation token, use the CreateProcessAsUser or CreateProcessWithLogonW function.

如果不传递用户名和密码,进程始终在原始进程所有者的安全上下文中运行。如果您想在另一个用户的上下文中运行该进程:

关于c# - .Net Core 模拟无法与 Process.Start 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59307181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com