0

I have an executable which calls CryptAcquireContext with CRYPT_NEWKEYSET:

BOOL b_result;
HCRYPTPROV prov;

b_result = CryptAcquireContext(&prov, L"testcontext6", MS_DEF_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET);

if(!b_result) {
    int err = GetLastError();
    fprintf(stderr, "Error acquiring context: %#x\n", err);
    return 1;
}
return 0;

If I run this locally, it works fine. If I run it via WMI as follows, it returns error 0x5 (ERROR_ACCESS_DENIED):

using (var processClass = new ManagementClass(m_scope, new ManagementPath("Win32_Process"), new ObjectGetOptions()))
{
    var inParams = processClass.GetMethodParameters("Create");
    inParams["commandLine"] = @"cmd.exe /c C:\CppTest.exe 2>C:\test.log";
    var outParams = processClass.InvokeMethod("Create", inParams, null);
    return outParams["ProcessId"];
}

It seems that the environment under WMI is somehow more restrictive, which stops the new key container being created. Any suggestions for why this might be, and how to work around it?

richvdh
  • 1,163
  • 11
  • 19
  • Is that local WMI or are you attempting to launch a remote process through WMI? – Remus Rusanu Dec 21 '12 at 14:02
  • I'm launching a remote process. – richvdh Dec 21 '12 at 14:07
  • Does Delegation occur? ('two-hops') – Remus Rusanu Dec 21 '12 at 14:08
  • No, there's only two computers involved. – richvdh Dec 21 '12 at 14:41
  • You'll need to read the MSDN article for the Create() method. Do note the usage of "impersonationLevel" in the code sample. And the explicit warning that starting interactive processes on the target machine is not permitted. Cmd.exe is an interactive process. Consider tinkering with SysInternals' PsExec utility. – Hans Passant Dec 21 '12 at 14:48
  • @HansPassant: thanks. I already have impersonationLevel=Impersonate; and I get the same problem when I run the test program without cmd.exe - I was just doing that for ease of redirecting the error to a file. And yes, this works fine with PsExec. I guess the problem is that CRYPT_NEWKEYSET requires an interactive logon, though. – richvdh Dec 21 '12 at 15:09
  • This actually fails for Process.Start in C# if UseShellExecute is not used. Did you find any workaround? – halivingston Mar 21 '13 at 09:40

1 Answers1

1

The environment under Win32_Process.CreateProcess forbids the use of interactive operations. and it turns out that using CryptAcquireContext to access user-specific (rather than machine-wide) key containers doesn't work in non-interactive environments (see http://social.msdn.microsoft.com/Forums/uk/clr/thread/2033c171-0809-4e14-aa50-1b9287389cb3, for example).

richvdh
  • 1,163
  • 11
  • 19