Why does CryptAcquireContext return ERROR_ACCESS_DENIED when called from a process started via WMI?

StackOverflow https://stackoverflow.com/questions/13991337

  •  11-12-2021
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top