Why can I get an Access Denied error when creating an X509Certificate2 object?

We have several unit tests in which PFX certificates are embedded. These certificates are read at run time and converted to X509Certificate2 objects. Unfortunately, when starting as an unprivileged user, we get Access Denied exceptions:

 using (var s = EmbeddedResourceUtilities.GetEmbeddedResourceAsStream(typeThatContainsEmbeddedResource, certFileName)) { if (s == null) { throw new ApplicationException(String.Format("Embedded certificate {0} for type {1} not found.", certFileName, typeThatContainsEmbeddedResource.FullName)); } try { var bytes = new byte[s.Length]; s.Read(bytes, 0, (int)s.Length); return new X509Certificate2(bytes); } catch (Exception ex) { throw new ApplicationException(String.Format("Error loading embedded certificate {0} for type {1}.", certFileName, typeThatContainsEmbeddedResource.FullName), ex); } } 

Here's the exception:

System.Security.Cryptography.CryptographicException: Access denied.
at System.Security.Cryptography.CryptographicException.ThrowCryptographicException (Int32 hr)
in System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromBlob (Byte [] rawData, password IntPtr, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle & pCertCtx)
in System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob (Byte [] rawData, object password, X509KeyStorageFlags keyStorageFlags)
in System.Security.Cryptography.X509Certificates.X509Certificate2..ctor (Byte [] rawData)

I tried modifying the constructor to use an empty password and explicit set flags, but this does not fix it:

 // this doesn't work, either return new X509Certificate2(bytes, String.Empty, X509KeyStorageFlags.MachineKeySet); 

I read elsewhere that I should give my unprivileged users increased permissions in the MachineKeys directory, but I do not want to do this, as this will allow the production code to assume that these permissions are available in this directory outside the test environment.

Is there a way to allow an unprivileged user to load X509Certificate from a file?

+4
source share
1 answer

This is my best guess about what is happening.

The X509Certificate2 constructor creates temporary public / private key objects in the Machine Keys directory (I guess, through the local Windows Security Center). Because our unprivileged user does not have access to these keys or the Machine Keys directory, the tests fail.

Our solution was to update our environment setup scripts to install these test certificates in advance, grant them unprivileged user rights, and rewrite tests to download certificates from the appropriate certificate store.

+4
source

All Articles