runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Different behavior of X509Certificate2 target net461 and netcoreapp2.1

Open kevinlo opened this issue 7 years ago • 15 comments

I ask the question at AspNetCore and I am asked to submit issue here.

I have a console app like this

        static void Main(string[] args)
        {
            string certificateFileName = args[0];
            string password = args[1];
            var cert = new X509Certificate2(certificateFileName, password, X509KeyStorageFlags.DefaultKeySet);

            string uniqueKeyContainerName = "";
            var privateKey = cert.PrivateKey as RSACryptoServiceProvider;
            if (privateKey != null)
            {
                uniqueKeyContainerName = privateKey.CspKeyContainerInfo.UniqueKeyContainerName;
                Console.WriteLine($@"Created C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys\{uniqueKeyContainerName}");
            }

            cert.Reset();
        }

When the app is target net461, the MachineKey file is clean up even without calling cert.Reset. However, when target netcoreapp2.1, the file is not deleted unless it calls the Reset.

Why is the behavior different?

Moreover, When target to net461, the PrivateKey is RSACryptoServiceProvider and it can use the following codes to get the MachineKey file name.

var privateKey = cert.PrivateKey as RSACryptoServiceProvider;
string uniqueKeyContainerName = privateKey.CspKeyContainerInfo.UniqueKeyContainerName;

When target netcoreapp2.1, the cert.PrivateKey is RSACng. I can't find a way to get that containerName from RSACng. Can anyone tell me how the file name can be found from RSACng?

kevinlo avatar Jan 15 '19 22:01 kevinlo

@bartonjs

davidsh avatar Jan 16 '19 00:01 davidsh

When the app is target net461, the MachineKey file is clean up even without calling cert.Reset. However, when target netcoreapp2.1, the file is not deleted unless it calls the Reset.

The difference is that .NET Core does not run pending finalizers after main exits. If you add "GC.Collect();GC.WaitForPendingFinalizers();" at the end of Main, or put the cert object in a using statement you should see the file be reliably removed.

When target netcoreapp2.1, the cert.PrivateKey is RSACng.

My standard comment at this point: Don't use cert.PrivateKey; use cert.GetRSAPrivateKey(). :smile:

I can't find a way to get that containerName from RSACng

Caring about the container name is pretty unusual. But, if you really want to, you can get it via properties under ((RSACng)rsa).Key (which is, of course, a dangerous cast, but more compact in a comment).

bartonjs avatar Jan 16 '19 01:01 bartonjs

@bartonjs Thanks for you reply.

The main purpose is to clean up the MachineKey file when it is not used anymore.

Firstly, does the Reset work differently if the certificate is created with DefaultKeySet or MachineKeySet?

When I create the cert with MachineKeySet, I find that calling Reset sometime delete the machinekey file and sometimes does not. Is it related to the finalizers too? How can I make sure calling Reset will always delete it? Should I use File.Exists and File.Delete after Reset to make sure the file is deleted (that's why I want to find out the file name).

var cert = new X509Certificate2(certificateFileName, password, X509KeyStorageFlags.MachineKeySet);

Secondly, I want to get the file name so I can log it. In case our application is killed or crashed unexpectedly and the Reset is not called, we still have the log file to check back the file name so we can delete it manually or write some script to parse the file to clean it up. Is ((RSACng)rsa).Key the right way to put in codes to get the file name? If not as you already say that is dangerous cast, what is the right way to find the name?

Last question is, if DefaultKeySet is used and the app is run under ApplicationPoolIdentity in IIS, where is the MachineKey file created? Currently, my app using DefaultKeySet has some problem to start up in IIS when the ApplicationPoolIdentity is used. If I change the pool identity to a specific user, it runs properly. I am still investigating it and see if you can give some hints about what's wrong.

kevinlo avatar Jan 16 '19 02:01 kevinlo

Firstly, does the Reset work differently if the certificate is created with DefaultKeySet or MachineKeySet?

Nope. PersistKeySet is different, but MachineKeySet isn't.

Is it related to the finalizers too?

If there's an active hold (such as from an outstanding P/Invoke) on the key the delete will be postponed until it is released; but otherwise calling Reset or Dispose should be fairly deterministic on file erasing.

Should I use File.Exists and File.Delete after Reset to make sure the file is deleted (that's why I want to find out the file name).

I wouldn't recommend it; but I also wouldn't tell you no?

Is ((RSACng)rsa).Key the right way to put in codes to get the file name? If not as you already say that is dangerous cast, what is the right way to find the name?

I meant you should use an as instead of a hard cast. cert.GetRSAPrivateKey() can return any of

  • RSACryptoServiceProvider (Windows)
  • RSACng (Windows)
  • RSAOpenSsl (Linux)
  • RSA (a derived type you can't talk about) (macOS)

You'll need to handle the dynamism appropriately.

if DefaultKeySet is used and the app is run under ApplicationPoolIdentity in IIS, where is the MachineKey file created?

I don't know. https://docs.microsoft.com/en-us/windows/desktop/seccng/key-storage-and-retrieval doesn't mention that (and it's for CNG-stored keys; yours is probably a CAPI-stored key via CNG, which is a different set of locations). The paths are controlled by Windows, not .NET... .NET doesn't ever touch the files (when we delete them, we delete the key object, which Windows happens to have written to disk, and then they delete the file).

bartonjs avatar Jan 16 '19 03:01 bartonjs

@bartonjs I just try the cert.GetRSAPrivateKey(). I get the RSACng whose Key is CngKey. I check the properties of CngKey, I cannot find the property that has string matching the filename. CngKey has a KeyName property, but it is different from the file name.

Could you please tell which property can get the file name?

kevinlo avatar Jan 16 '19 05:01 kevinlo

For the DefaultKeySet using ApplicationPoolIdentity problem I have, it is solved by setting the "Load User Profile" to true in the application pool Advanced Settings. If PersistKeySet is set, the MachineKey file will be created in the c:\users<Pool name>\AppData\Roaming\Microsoft\Crypto\RSA<sid>

kevinlo avatar Jan 16 '19 05:01 kevinlo

Theoretically it should be the UniqueKeyName property, based on https://docs.microsoft.com/en-us/windows/desktop/SecCNG/key-storage-property-identifiers#NCRYPT_UNIQUE_NAME_PROPERTY; but on my computer for a wrapped CAPI key the UniqueKeyName property is throwing an exception saying the property is not defined. If it throws for you as well, you might not be able to get it.

If PersistKeySet is set,

If PersistKeySet is set then .NET doesn't cause the key file to be deleted; you presumably don't want that. It should not have any impact on where the file is saved, since PersistKeySet is a .NET option, not a Windows option.

bartonjs avatar Jan 16 '19 05:01 bartonjs

I get the Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException:'The requested operation is not supported' when accessing the UniqueKeyName property. Do you know why it throws exception or which team I should ask about it? I still hope I can find a way to get the file name.

At first I thought I need to set the PersistKeySet to have the file created. I just try setting DefaultKeySet only, it still creates the machinekey file and the file will be deleted by the Reset call at the ApplicationStopping event when the pool is stopped. The Reset call won't delete the file if the PersistKeySet is used. That may be the reason I feel Reset sometimes can delete the file, sometimes can't. I might have set the PersistKeySet in some cases. It has nothing to do with DefaultKeySet or MachineKeySet. Thanks for your clarification.

kevinlo avatar Jan 16 '19 06:01 kevinlo

@bartonjs One last question to you. For my application, it loads a .pfx file to create the X509Certificate2 when it is started up for the Data Protection and we don't need the machinekey saved in drive. Is the X509KeyStorageFlags.EphemeralKeySet the right flag for this purpose?

kevinlo avatar Jan 16 '19 18:01 kevinlo

Do you know why it throws exception or which team I should ask about it?

The exception seems to be present on Windows 7, but not on Windows Server 2012 R2 or Windows 10; so I think this was just a Windows bug which has subsequently been fixed. I don't know there's much you can do about it aside from upgrade your OS.

Is the X509KeyStorageFlags.EphemeralKeySet the right flag for this purpose?

Yep. Well, maybe. I'd say try using EphemeralKeySet, and if everything works then it does, and you're happy. There are some things which don't work right on EphemeralKeySet-based keys... (if you run into any them please find/file an issue) and so you might find that it won't work for you. Plus, you can't currently use the flag on macOS due to how Apple stores/loads/processes certificates.

bartonjs avatar Jan 16 '19 21:01 bartonjs

You are right. My dev machine is Win7. Just test the app on Win2012 R2 and the UniqueName shows the file name.

I get what I need to know. Thanks for your help. I can close this issue.

kevinlo avatar Jan 16 '19 23:01 kevinlo

@bartonjs. I am sorry that I need to ask you again.

I try deleting the MachineKey file right after the X509Certificate2 is created:

            _certificate = new X509Certificate2(certificateFileName, certificatePassword, X509KeyStorageFlags.MachineKeySet);
            if (_certificate != null)
            {
                RSA rsa = _certificate.GetRSAPrivateKey();
                RSACng rsaCng = rsa as RSACng;
                if (rsaCng != null)
                {
                    try
                    {
                        _certificateMachineKeyFileName = rsaCng.Key.UniqueName;
                        string fileName = $@"C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys\{_certificateMachineKeyFileName}";
                        try
                        {
                            File.Delete(fileName);
                        }
                        catch (Exception ex)
                        {
                            _logger.LogWarning($"Cannot delete the MachineKey file {fileName} with exception : {ex.Message}");
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning($"Cannot get the UniqueName for certificate {certificateFileName} with exception : {ex.Message}");
                    }
                }
            }

At first, I thought it works, but I find out I have the certificate in the Personal store. After I delete the certificate in the personal store and run the program again, I get this exception:

fail: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[24]
      An exception occurred while processing the key element '<key id="1fd27d8e-e2b3-4d25-8e8a-cbc9e9b40c6a" version="1" />'.
System.Security.Cryptography.CryptographicException: Keyset does not exist

   at System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
   at System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle)
   at System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()
   at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize)
   at System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()
   at System.Security.Cryptography.X509Certificates.RSACertificateExtensions.GetRSAPrivateKey(X509Certificate2 certificate)
   at Microsoft.AspNetCore.DataProtection.XmlEncryption.EncryptedXmlDecryptor.EncryptedXmlWithCertificateKeys.GetKeyFromCert(EncryptedKey encryptedKey, KeyInfoX509Data keyInfo)
   at Microsoft.AspNetCore.DataProtection.XmlEncryption.EncryptedXmlDecryptor.EncryptedXmlWithCertificateKeys.DecryptEncryptedKey(EncryptedKey encryptedKey)
   at System.Security.Cryptography.Xml.EncryptedXml.GetDecryptionKey(EncryptedData encryptedData, String symmetricAlgorithmUri)
   at System.Security.Cryptography.Xml.EncryptedXml.DecryptDocument()
   at Microsoft.AspNetCore.DataProtection.XmlEncryption.EncryptedXmlDecryptor.Decrypt(XElement encryptedElement)
   at Microsoft.AspNetCore.DataProtection.XmlEncryption.XmlEncryptionExtensions.DecryptElement(XElement element, IActivator activator)
   at Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager.Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.IInternalXmlKeyManager.DeserializeDescriptorFromKeyElement(XElement keyElement)
warn: Microsoft.AspNetCore.DataProtection.KeyManagement.DefaultKeyResolver[12]
      Key {1fd27d8e-e2b3-4d25-8e8a-cbc9e9b40c6a} is ineligible to be the default key because its CreateEncryptor method failed.
System.Security.Cryptography.CryptographicException: Keyset does not exist

After I remove that File.Delete line, it works fine.

At first, I think X509Certificate2 will load everything from the .pfx file. But it seems it still need the MachineKey file OR it needs the certificate from the store.

What is that MachineKey file? Does it contain the private key? We want to clean up that file after it is used. The Reset will remove it, but in case the application crash or not quitted properly, the Reset won't be called and it will be left orphaned.

Any suggestion what I should do? Thanks.

kevinlo avatar Jan 25 '19 17:01 kevinlo

@bartonjs, do you think you can answer my question above? If not, where is the right place to ask?

kevinlo avatar Jan 30 '19 17:01 kevinlo

What is that MachineKey file? Does it contain the private key?

Yes.

At first, I think X509Certificate2 will load everything from the .pfx file. But it seems it still need the MachineKey file OR it needs the certificate from the store.

Keys don't live in the cert store, they always live in the key directories; if you added the cert to the store and deleted the keyfile manually then the cert store version would also fail to open the private key.

Any suggestion what I should do? Thanks.

My recommendation is to just always use certificates in a using statement and let the system handle the files. There's no way (other than EphemeralKeySet) to have the file not be on disk but things still work.

bartonjs avatar Feb 02 '19 00:02 bartonjs

@bartonjs Thanks for your explanation. The certificate is needed for the data protection and is needed for life time of the application. These application processes are sometimes killed by their parent process and don't have the Reset called properly. A workaround for us may be to have that parent process to get the file name from the child processes and delete those MachineKeys file when it detects those child processes don't exist.

kevinlo avatar Feb 02 '19 00:02 kevinlo