Repository navigation
Description
Description
For the last couple of years, we've been seeing flakiness in unit tests which access private keys of certificates. The issue is exclusive to Windows.
Typical symptoms are:
Unhandled exception. Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: Keyset does not exist
at Internal.NativeCrypto.CapiHelper.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
at System.Security.Cryptography.RSACryptoServiceProvider.get_SafeProvHandle()
at System.Security.Cryptography.RSACryptoServiceProvider.get_SafeKeyHandle()
at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 keySize, CspParameters parameters, Boolean useDefaultKeySize)
at System.Security.Cryptography.RSACryptoServiceProvider..ctor(CspParameters parameters)
at Internal.Cryptography.Pal.CertificatePal.<>c.<GetRSAPrivateKey>b__67_0(CspParameters csp)
at Internal.Cryptography.Pal.CertificatePal.GetPrivateKey[T](Func`2 createCsp, Func`2 createCng)
at Internal.Cryptography.Pal.CertificateExtensionsCommon.GetPrivateKey[T](X509Certificate2 certificate, Predicate`1 matchesConstraints)
And, occasionally, the Export Policy of the private key to be missing the AllowPlaintextExport value.
There's an incentive to reduce this flakiness, so I did some further digging.
Reproduction Steps
I've been able to construct a small console application which can reproduce the issue in GitHub actions. Essentially, it runs the following code in a loop, which will eventually fail:
using (var certificate = new X509Certificate2("certificate.pfx", "password", X509KeyStorageFlags.Exportable))
{
var data = certificate.GetRawCertData();
using (var cng = (RSACng)certificate.GetRSAPrivateKey())
{
var exportPolicy = cng.Key.GetProperty("Export Policy", CngPropertyOptions.None);
var exportPolicyValue = (CngExportPolicies)BinaryPrimitives.ReadInt32LittleEndian(exportPolicy.GetValue());
Console.WriteLine($"Export policy: {exportPolicyValue}");
if(!exportPolicyValue.HasFlag(CngExportPolicies.AllowPlaintextExport))
{
Console.WriteLine("Error: Export policy is missing AllowPlaintextExport");
}
var parameters = cng.ExportParameters(includePrivateParameters: true);
}
}Expected behavior
This program should never crash.
Actual behavior
- Sometimes, the
AllowPlaintextExportexport policy is missing (e.g. https://github.com/qmfrederik/rsacng/runs/5884649535?check_suite_focus=true#step:4:3260) - Often, the program crashes with
WindowsCryptographicException: Keyset does not exist(e.g. https://github.com/qmfrederik/rsacng/runs/5884688366?check_suite_focus=true#step:4:4124)
Regression?
This is probably not a regression, but it's worth noting that the issue does not reproduce on macOS or Linux (due to a different crypto implementation)
Known Workarounds
None
Configuration
.NET 6.0.201 on x64 Windows Server
Activity
qmfrederik commentedon Apr 8, 2022
Forgot to mention that https://github.com/qmfrederik/rsacng/ contains the code and GitHub actions which reproduce the issue.
vcsjones commentedon Apr 8, 2022
To help me understand and reproduce: does this only happen in GitHub actions? Can you reproduce it on a local Windows install or VM?
qmfrederik commentedon Apr 8, 2022
It's not specific to GitHub actions; I've seen it fail with Azure DevOps and GitLab pipelines as well. I just created the GitHub workflow to "provide public evidence", if you want ;-)
I haven't been able to reproduce this on a Windows client; failures were always on a Windows server (in a CI context). Not sure if this is because something is different on Windows Server, because the CI machines have lower specs (VMs with a few CPUs), were running under stress, or something else.
Like I said, I've literally been chasing this for a few years now and was quite happy to have a fairly simple repro scenario :-).
qmfrederik commentedon Apr 8, 2022
Update: I've been able to reproduce this on Windows client using the following application:
which generates this output:
which is a slightly different symptom (
AllowPlaintextExportmissing in the export policy andThe requested operation is not supported.error)vcsjones commentedon Apr 8, 2022
An observation on the PFX, it has the following bag attributes:
Since the RSA key has CSP Identifier, I think this is a thread race issue. Every time the PFX is imported, it imports the RSA key with a container ID Quamotion924ce70f-610c-4839-b671-c964a6950da4. Then one thread is done, it deletes it. But another thread may have been using the key at that time, and it gets deleted out from underneath of it.
@qmfrederik does it reproduce for you if you strip the P12 of the CSP / FriendlyName attributes? I did that here (I just re-ran the cert and key through OpenSSL) and can no longer reproduce the issue.
bartonjs commentedon Apr 8, 2022
Yeah, my immediate reaction was the same as what @vcsjones just identified: That the PFX has the
friendlyNameattribute on the key.Windows PFXImportCertStore has a race condition where opening two PFXes (including "the same PFX") that have identical
friendlyNamevalues in parallel may result in the two objects becoming inter-linked, and deleting one deletes the key out from under the other."parallel" here is determined by the filesystem, so it's across all processes (and if you happen to have done interesting thing with remounts and SMB/CIFS/AFS/whatever then "on all computers that are trying to write to that drive concurrently"). It boils down to using
if (File.Exists(...))instead of just callingFile.Createand dealing with that failing.qmfrederik commentedon Apr 8, 2022
@vcsjones I'll give that a try and let you know. I did ran the tests without the multi-threading and cannot reproduce it if I just open the certificate sequentially, so that seems to confirm your analysis. That's also why we've seen these issues in CI, presumably because they are slower/under higher load so there's more multi-threading.
Does that also explain why the
AllowPlaintextExportpolicy is missing in a few iterations?vcsjones commentedon Apr 8, 2022
Probably. It's likely that one thread was reading that property at the same time the key was re-imported but before the export property was set.