我一直在尝试使用CreateProcessAsUser
Windows API 的功能在特定用户的上下文中创建一个新进程,但似乎遇到了一个相当讨厌的安全问题......
在我进一步解释之前,这是我当前用于启动新进程的代码(控制台进程 - 具体来说是 PowerShell,尽管它不重要)。
private void StartProcess()
{
bool retValue;
// Create startup info for new console process.
var startupInfo = new STARTUPINFO();
startupInfo.cb = Marshal.SizeOf(startupInfo);
startupInfo.dwFlags = StartFlags.STARTF_USESHOWWINDOW;
startupInfo.wShowWindow = _consoleVisible ? WindowShowStyle.Show : WindowShowStyle.Hide;
startupInfo.lpTitle = this.ConsoleTitle ?? "Console";
var procAttrs = new SECURITY_ATTRIBUTES();
var threadAttrs = new SECURITY_ATTRIBUTES();
procAttrs.nLength = Marshal.SizeOf(procAttrs);
threadAttrs.nLength = Marshal.SizeOf(threadAttrs);
// Log on user temporarily in order to start console process in its security context.
var hUserToken = IntPtr.Zero;
var hUserTokenDuplicate = IntPtr.Zero;
var pEnvironmentBlock = IntPtr.Zero;
var pNewEnvironmentBlock = IntPtr.Zero;
if (!WinApi.LogonUser("UserName", null, "Password",
LogonType.Interactive, LogonProvider.Default, out hUserToken))
throw new Win32Exception(Marshal.GetLastWin32Error(), "Error logging on user.");
var duplicateTokenAttrs = new SECURITY_ATTRIBUTES();
duplicateTokenAttrs.nLength = Marshal.SizeOf(duplicateTokenAttrs);
if (!WinApi.DuplicateTokenEx(hUserToken, 0, ref duplicateTokenAttrs,
SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary,
out hUserTokenDuplicate))
throw new Win32Exception(Marshal.GetLastWin32Error(), "Error duplicating user token.");
try
{
// Get block of environment vars for logged on user.
if (!WinApi.CreateEnvironmentBlock(out pEnvironmentBlock, hUserToken, false))
throw new Win32Exception(Marshal.GetLastWin32Error(),
"Error getting block of environment variables for user.");
// Read block as array of strings, one per variable.
var envVars = ReadEnvironmentVariables(pEnvironmentBlock);
// Append custom environment variables to list.
foreach (var var in this.EnvironmentVariables)
envVars.Add(var.Key + "=" + var.Value);
// Recreate environment block from array of variables.
var newEnvironmentBlock = string.Join("\0", envVars.ToArray()) + "\0";
pNewEnvironmentBlock = Marshal.StringToHGlobalUni(newEnvironmentBlock);
// Start new console process.
retValue = WinApi.CreateProcessAsUser(hUserTokenDuplicate, null, this.CommandLine,
ref procAttrs, ref threadAttrs, false, CreationFlags.CREATE_NEW_CONSOLE |
CreationFlags.CREATE_SUSPENDED | CreationFlags.CREATE_UNICODE_ENVIRONMENT,
pNewEnvironmentBlock, null, ref startupInfo, out _processInfo);
if (!retValue) throw new Win32Exception(Marshal.GetLastWin32Error(),
"Unable to create new console process.");
}
catch
{
// Catch any exception thrown here so as to prevent any malicious program operating
// within the security context of the logged in user.
// Clean up.
if (hUserToken != IntPtr.Zero)
{
WinApi.CloseHandle(hUserToken);
hUserToken = IntPtr.Zero;
}
if (hUserTokenDuplicate != IntPtr.Zero)
{
WinApi.CloseHandle(hUserTokenDuplicate);
hUserTokenDuplicate = IntPtr.Zero;
}
if (pEnvironmentBlock != IntPtr.Zero)
{
WinApi.DestroyEnvironmentBlock(pEnvironmentBlock);
pEnvironmentBlock = IntPtr.Zero;
}
if (pNewEnvironmentBlock != IntPtr.Zero)
{
Marshal.FreeHGlobal(pNewEnvironmentBlock);
pNewEnvironmentBlock = IntPtr.Zero;
}
throw;
}
finally
{
// Clean up.
if (hUserToken != IntPtr.Zero)
WinApi.CloseHandle(hUserToken);
if (hUserTokenDuplicate != IntPtr.Zero)
WinApi.CloseHandle(hUserTokenDuplicate);
if (pEnvironmentBlock != IntPtr.Zero)
WinApi.DestroyEnvironmentBlock(pEnvironmentBlock);
if (pNewEnvironmentBlock != IntPtr.Zero)
Marshal.FreeHGlobal(pNewEnvironmentBlock);
}
_process = Process.GetProcessById(_processInfo.dwProcessId);
}
为了这里的问题,忽略处理环境变量的代码(我已经独立测试了该部分,它似乎工作。)
现在,我得到的错误如下(在调用之后的行中抛出CreateProcessAsUSer
):
“客户端未持有所需的权限”(错误代码 1314)
(错误消息是通过从 Win32Exception 构造函数中删除 message 参数发现的。诚然,我这里的错误处理代码可能不是最好的,但这有点无关紧要。但是,如果您愿意,欢迎您对此发表评论。 ) 对于这种情况下这种模糊错误的原因,我真的很困惑。MSDN 文档和各种论坛帖子只给了我这么多建议,尤其是考虑到此类错误的原因似乎多种多样,我不知道我需要修改哪段代码。也许这只是我需要更改的一个参数,但我可能会做出错误/不足的 WinAPI 调用,就我所知。让我非常困惑的是,以前版本的代码使用了普通的CreateProcess
函数(除用户令牌参数外等效)工作得非常好。据我了解,只需要调用 Logon 用户函数来接收适当的令牌句柄,然后复制它,以便它可以传递给CreateProcessAsUser
.
非常欢迎对代码修改和解释提出任何建议。
笔记
我主要指的是 MSDN 文档(以及用于 C# 函数/strut/enum 声明的PInvoke.net )。特别是以下页面似乎在备注部分中有很多信息,其中一些可能很重要并且我无法理解:
编辑
我刚刚尝试了 Mitch 的建议,但不幸的是,旧的错误刚刚被一个新的错误所取代:“系统找不到指定的文件。” (错误代码 2)
之前的调用CreateProcessAsUser
已替换为以下内容:
retValue = WinApi.CreateProcessWithTokenW(hUserToken, LogonFlags.WithProfile, null,
this.CommandLine, CreationFlags.CREATE_NEW_CONSOLE |
CreationFlags.CREATE_SUSPENDED | CreationFlags.CREATE_UNICODE_ENVIRONMENT,
pNewEnvironmentBlock, null, ref startupInfo, out _processInfo);
请注意,正如 MSDN 文档所暗示的那样,此代码不再使用重复的令牌,而是使用原始令牌。
这是使用CreateProcessWithLogonW
. 这次的错误是“登录失败:未知用户名或密码错误”(错误代码1326)
retValue = WinApi.CreateProcessWithLogonW("Alex", null, "password",
LogonFlags.WithProfile, null, this.CommandLine,
CreationFlags.CREATE_NEW_CONSOLE | CreationFlags.CREATE_SUSPENDED |
CreationFlags.CREATE_UNICODE_ENVIRONMENT, pNewEnvironmentBlock,
null, ref startupInfo, out _processInfo);
我还尝试以 UPN 格式(“Alex@Alex-PC”)指定用户名并将域作为第二个参数独立传递,但都无济于事(相同的错误)。