Redmon Run As User does not load user environment variables

I am trying to use Redmon http://www.winimage.com/misc/redmon/ to send print jobs to a C # user application. Redmon “launches” (in fact, the print spooler) as SYSTEM, but has the ability to run as a user so that your application runs under the user who printed the job. The problem is that it does not load the user environment. Therefore, calling functions such as Path.GetTempPath () point to \ windows \ temp instead of the user. Also, when trying to start Outlook 2007+ through MAPI calls (to add attachments), it reports form errors due to, in my opinion, the location of the temp folder.

Is there a way to "reload" the profile, or at least get your environments within the Impersonated application? The only ideas I have had so far is to rebuild vars directly from the registry, but I want to avoid this as it is hacking (avoiding implementation details and all that). Or make a stub program that Redmon calls and then properly runs the user application as a user with a full profile.

Any other items or tricks?

+3
source share
1 answer

EnvironmentBlock, . :

#, :

[DllImport("userenv.dll", SetLastError = true)]
private static extern bool CreateEnvironmentBlock(ref IntPtr lpEnvironment, IntPtr hToken, bool bInherit); 

[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, ref IntPtr TokenHandle); 
private const uint TOKEN_QUERY = 0x0008; 

[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcess();

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

private static void ReloadEnviroVars()
{
  IntPtr hToken = IntPtr.Zero;
  IntPtr envBlock = IntPtr.Zero;

  //Load this user environment variables
  OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, ref hToken);
  bool retVal = CreateEnvironmentBlock(ref envBlock, hToken, false);

  //Extract each environment variable from the envroblock and add it to
  // our running program environment vars
  int offset = 0;
  while (true) {
    //EnviroBlock is an array of null-terminated unicode strings
    IntPtr ptr = new IntPtr(envBlock.ToInt64() + offset);
    string Enviro = Marshal.PtrToStringUni(ptr);
    offset += Encoding.Unicode.GetByteCount(Enviro) + 2;
    if (string.IsNullOrEmpty(Enviro))
      break;
    string EnviroKey = Enviro.Substring(0, Enviro.IndexOf("="));
    string EnviroValue = Enviro.Substring(Enviro.IndexOf("=") + 1,  Enviro.Length - 1 - Enviro.IndexOf("="));
    Environment.SetEnvironmentVariable(EnviroKey, EnviroValue);
  }

  CloseHandle(hToken);
}
+7

Source: https://habr.com/ru/post/1746492/


All Articles