zblurx / impersonate-rs

Rusty Impersonate
91 stars 7 forks source link

Process spawned finishes with 3221225794 when run from a non-interactive shell #2

Closed snovvcrash closed 1 year ago

snovvcrash commented 1 year ago

Hey @zblurx! Thanks for this awesome reimplementation, it's been very handy for me recently!

However, I've faced the following issue. When I run irs from a non-interactive shell from memory (with Donut), the following output is received:

[2023-06-15T00:01:45Z INFO  irs::utils::impersonate] Impersonate user NIGHTCITY\snovvcrash
[2023-06-15T00:01:45Z ERROR irs] [!] Failed to run impersonate(): Process spawned finish with 3221225794: The operation completed successfully. (os error 0)

I supposed it comes from the CreateProcessWithTokenW lpEnvironment parameter which is not set when the API is invoked as LocalSystem from a semi-interactive shell (correct me if I'm wrong, please):

CreateProcessWithTokenW(
    duplicate_token_handle,
    LOGON_WITH_PROFILE,
    null_mut(),
    cmd.as_mut_ptr() as *mut _ as PWSTR,
    CREATE_NO_WINDOW,
    FALSE as *const c_void,  // <-- RIGHT HERE
    working_dir.as_ptr(),
    &si ,
    &mut pi
)

Also null desktop and window station values within the lpDesktop member of the STARTUPINFOW struct may affect this behavior if I remeber correctly.

I'm not a rusty dev for sure, so I won't embarrass myself trying to suggest a proper PR, but in C# I'd do something like this to resolve the issue:

CreateEnvironmentBlock(out IntPtr lpEnvironment, hToken, false);
STARTUPINFO si = new STARTUPINFO();
si.cb = Marshal.SizeOf(si);
si.lpDesktop = @"WinSta0\Default";
StringBuilder sbSystemDir = new StringBuilder(256);
GetSystemDirectory(sbSystemDir, 256);

CreateProcessWithTokenW(
    hDupToken,
    LOGON_WITH_PROFILE,
    null,
    lpCommandLine,
    CREATE_NO_WINDOW,
    lpEnvironment,
    sbSystemDir.ToString(),
    ref si,
    out PROCESS_INFORMATION _);

Looking forward for your thoughts on this, thanks!

zblurx commented 1 year ago

Thank you very much for this issue and the hint, first you were exactly right and I learned a lot

snovvcrash commented 1 year ago

Thanks for the quick feedback! My pleasure to be helpful 😌