Skip to content

Occasional "Keyset does not exist" exception when calling .GetRSAPrivateKey on Windows #67752

Closed

Description

@qmfrederik

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

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

Other information

/cc @bartonjs @vcsjones

Activity

  1. ghost added
    untriaged
    on Apr 8, 2022
  2. qmfrederik commented on Apr 8, 2022

    @qmfrederik
    ContributorAuthor

    Forgot to mention that https://github.com/qmfrederik/rsacng/ contains the code and GitHub actions which reproduce the issue.

  3. vcsjones commented on Apr 8, 2022

    @vcsjones
    Member

    I've been able to construct a small console application which can reproduce the issue in GitHub actions

    To help me understand and reproduce: does this only happen in GitHub actions? Can you reproduce it on a local Windows install or VM?

  4. qmfrederik commented on Apr 8, 2022

    @qmfrederik
    ContributorAuthor

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

  5. qmfrederik commented on Apr 8, 2022

    @qmfrederik
    ContributorAuthor

    Update: I've been able to reproduce this on Windows client using the following application:

    using System.Buffers.Binary;
    using System.Security.Cryptography;
    using System.Security.Cryptography.X509Certificates;
    
    while (true)
    {
        var tasks = new List<Task>();
    
        for (int i = 0; i < 0x1000; i++)
        {
            tasks.Add(Task.Run(DoWork));
        }
    
        await Task.WhenAll(tasks);
    
        static void DoWork()
        {
            using (var certificate = new X509Certificate2("certificate.pfx", "quamotion", 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());
    
                    if (!exportPolicyValue.HasFlag(CngExportPolicies.AllowPlaintextExport))
                    {
                        Console.WriteLine("Error: Export policy is missing AllowPlaintextExport");
                    }
    
                    var parameters = cng.ExportParameters(includePrivateParameters: true);
                }
            }
        }
    }

    which generates this output:

    Error: Export policy is missing AllowPlaintextExport
    Error: Export policy is missing AllowPlaintextExport
    Error: Export policy is missing AllowPlaintextExport
    Error: Export policy is missing AllowPlaintextExport
    Error: Export policy is missing AllowPlaintextExport
    Error: Export policy is missing AllowPlaintextExport
    Unhandled exception. Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: The requested operation is not supported.
       at System.Security.Cryptography.CngKey.Export(CngKeyBlobFormat format)
       at System.Security.Cryptography.RSACng.ExportParameters(Boolean includePrivateParameters)
       at Program.<<Main>$>g__DoWork|0_0() in C:\Users\fredcarl\source\repos\rsacng\Program.cs:line 32
       at System.Threading.Tasks.Task.InnerInvoke()
       at System.Threading.Tasks.Task.<>c.<.cctor>b__272_0(Object obj)
       at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
    --- End of stack trace from previous location ---
       at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
    --- End of stack trace from previous location ---
       at Program.<Main>$(String[] args) in C:\Users\fredcarl\source\repos\rsacng\Program.cs:line 14
       at Program.<Main>(String[] args)
    

    which is a slightly different symptom (AllowPlaintextExport missing in the export policy and The requested operation is not supported. error)

  6. vcsjones commented on Apr 8, 2022

    @vcsjones
    Member

    An observation on the PFX, it has the following bag attributes:

    Bag Attributes 
        friendlyName: Quamotion924ce70f-610c-4839-b671-c964a6950da4
        Microsoft CSP Name: Microsoft Enhanced RSA and AES Cryptographic Provider
    

    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.

  7. bartonjs commented on Apr 8, 2022

    @bartonjs
    Member

    Yeah, my immediate reaction was the same as what @vcsjones just identified: That the PFX has the friendlyName attribute on the key.

    Windows PFXImportCertStore has a race condition where opening two PFXes (including "the same PFX") that have identical friendlyName values 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 calling File.Create and dealing with that failing.

  8. qmfrederik commented on Apr 8, 2022

    @qmfrederik
    ContributorAuthor

    @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 AllowPlaintextExport policy is missing in a few iterations?

  9. vcsjones commented on Apr 8, 2022

    @vcsjones
    Member

    Does that also explain why the AllowPlaintextExport policy is missing in a few iterations?

    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.

  10. added
    needs-author-action
    on Apr 9, 2022
  11. ghost removed
    untriaged
    on Apr 9, 2022
  12. ghost closed this as completedon May 8, 2022
  13. ghost locked as resolved and limited conversation to collaborators on Jun 7, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Securityneeds-author-actionno-recent-activity

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions