MacOS: Switch to PersistKeySet on X509Certificate2Collection.Import() causes failure on MacOS (Windows and Linux work fine)
Description
When we switch to PersistKeySet for X509Certificatre2Collection.Import(), see the below error stack.
Note, this looks similar to the below issue, but i thought it was fixed. We are running .NET 6.0.402
Similar issue:
https://github.com/dotnet/runtime/issues/39603
Error stack:
2023-01-09 12:31:49.561128 TID:12 (PRI) (SVC) (ERR) OracleConnectionImpl.Connect() (txnid=n/a) OracleInternal.Network.NetworkException (0x80004005): Network Transport: SSL failure in parsing wallet location
---> Interop+AppleCrypto+AppleCommonCryptoCryptographicException: UNIX[Is a directory]
at Interop.AppleCrypto.X509ImportCertificate(ReadOnlySpan1 bytes, X509ContentType contentType, SafeCreateHandle importPassword, SafeKeychainHandle keychain, Boolean exportable, SafeSecIdentityHandle& identityHandle)
at Interop.AppleCrypto.X509ImportCertificate(ReadOnlySpan1 bytes, X509ContentType contentType, SafePasswordHandle importPassword, SafeKeychainHandle keychain, Boolean exportable, SafeSecIdentityHandle& identityHandle)
at Internal.Cryptography.Pal.AppleCertificatePal.ImportPkcs12NonExportable(AppleCertificatePal cert, SafeSecKeyRefHandle privateKey, SafePasswordHandle password, SafeKeychainHandle keychain)
at Internal.Cryptography.Pal.StorePal.ApplePkcs12CertLoader.MoveTo(X509Certificate2Collection collection)
at System.Security.Cryptography.X509Certificates.X509Certificate2Collection.Import(ReadOnlySpan1 rawData, ReadOnlySpan1 password, X509KeyStorageFlags keyStorageFlags)
at System.Security.Cryptography.X509Certificates.X509Certificate2Collection.Import(Byte[] rawData, String password, X509KeyStorageFlags keyStorageFlags)
Reproduction Steps
Simply provide a byte[] of the loaded pfx/pkcs12 file to import with PersistKeySet set.
Expected behavior
Return a X509Certificate2Collection.
Actual behavior
Exception with error stack specified
Regression?
No response
Known Workarounds
No response
Configuration
No response
Other information
No response
Tagging subscribers to this area: @dotnet/area-system-security, @vcsjones See info in area-owners.md if you want to be subscribed.
Issue Details
Description
When we switch to PersistKeySet for X509Certificatre2Collection.Import(), see the below error stack.
Note, this looks similar to the below issue, but i thought it was fixed. We are running .NET 6.0.402
Similar issue:
https://github.com/dotnet/runtime/issues/39603
Error stack:
2023-01-09 12:31:49.561128 TID:12 (PRI) (SVC) (ERR) OracleConnectionImpl.Connect() (txnid=n/a) OracleInternal.Network.NetworkException (0x80004005): Network Transport: SSL failure in parsing wallet location
---> Interop+AppleCrypto+AppleCommonCryptoCryptographicException: UNIX[Is a directory]
at Interop.AppleCrypto.X509ImportCertificate(ReadOnlySpan1 bytes, X509ContentType contentType, SafeCreateHandle importPassword, SafeKeychainHandle keychain, Boolean exportable, SafeSecIdentityHandle& identityHandle)
at Interop.AppleCrypto.X509ImportCertificate(ReadOnlySpan1 bytes, X509ContentType contentType, SafePasswordHandle importPassword, SafeKeychainHandle keychain, Boolean exportable, SafeSecIdentityHandle& identityHandle)
at Internal.Cryptography.Pal.AppleCertificatePal.ImportPkcs12NonExportable(AppleCertificatePal cert, SafeSecKeyRefHandle privateKey, SafePasswordHandle password, SafeKeychainHandle keychain)
at Internal.Cryptography.Pal.StorePal.ApplePkcs12CertLoader.MoveTo(X509Certificate2Collection collection)
at System.Security.Cryptography.X509Certificates.X509Certificate2Collection.Import(ReadOnlySpan1 rawData, ReadOnlySpan1 password, X509KeyStorageFlags keyStorageFlags)
at System.Security.Cryptography.X509Certificates.X509Certificate2Collection.Import(Byte[] rawData, String password, X509KeyStorageFlags keyStorageFlags)
Reproduction Steps
Simply provide a byte[] of the loaded pfx/pkcs12 file to import with PersistKeySet set.
Expected behavior
Return a X509Certificate2Collection.
Actual behavior
Exception with error stack specified
Regression?
No response
Known Workarounds
No response
Configuration
No response
Other information
No response
| Author: | ScotMac |
|---|---|
| Assignees: | - |
| Labels: |
|
| Milestone: | - |
Thanks for the report. I'm not able to reproduce this with the following code:
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using RSA rsa = RSA.Create(2048);
CertificateRequest req = new("CN=potatos", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
using X509Certificate2 cert = req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now);
byte[] pkcs12 = cert.Export(X509ContentType.Pkcs12, "carrots");
X509Certificate2Collection collection = new();
collection.Import(pkcs12, "carrots", X509KeyStorageFlags.PersistKeySet);
Console.WriteLine(collection.Count); // prints 1
This issue looks slightly different. A few questions:
- Does your issue reproduce consistently, or occasionally?
- Does the above code reproduce the issue for you?
- If "no" to 2, can you produce a sample application that does reproduce the issue?
Sorry if i wasn't fully clear. We went from DefaultKeySet to "DefaultKeySet | PersistKeySet",we had 2 certs in the pfx/pkcs12 (root and user cert).
Going back to the old code w/ the PersistKeySet taken out (just DefaultKeySet) works. However, "DefaultKeyset | PersistKeySet" works find on windows and linux.
Yes, it does reproduce consistently.
Please try the above, if it doesn't reproduce for you, we may need to pass our pfx/pkcs12 file and password to you.
Adapting my example to 2 certificates, I still cannot reproduce the issue.
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
const string password = "carrots";
using RSA rsa1 = RSA.Create(2048);
using RSA rsa2 = RSA.Create(2048);
CertificateRequest req1 = new("CN=potatos", rsa1, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
CertificateRequest req2 = new("CN=potatos", rsa2, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
using X509Certificate2 cert1 = req1.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now);
using X509Certificate2 cert2 = req2.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now);
PbeParameters pbe = new(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 2000);
Pkcs12Builder builder = new();
Pkcs12SafeContents certBag = new();
certBag.AddCertificate(cert1);
certBag.AddCertificate(cert2);
Pkcs12SafeContents keyBag = new();
keyBag.AddShroudedKey(rsa1, password, pbe);
keyBag.AddShroudedKey(rsa2, password, pbe);
builder.AddSafeContentsUnencrypted(certBag);
builder.AddSafeContentsEncrypted(keyBag, "carrots", pbe);
builder.SealWithMac(password, HashAlgorithmName.SHA256, 2000);
byte[] pkcs12 = builder.Encode();
X509Certificate2Collection collection = new();
collection.Import(pkcs12, password, X509KeyStorageFlags.PersistKeySet);
Console.WriteLine(collection.Count); // prints 2
foreach (X509Certificate2 cert in collection)
{
Console.WriteLine(cert.HasPrivateKey);
}
"DefaultKeySet | PersistKeySet"
DefaultKeySet has a value of 0. So DefaultKeySet | PersistKeySet is the same thing as PersistKeySet:
// Prints 'True'
Console.WriteLine(
(X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.DefaultKeySet) ==
X509KeyStorageFlags.PersistKeySet);
if it doesn't reproduce for you, we may need to pass our pfx/pkcs12 file and password to you
Before we get to that, some other questions:
- Does this reproduce on all machines, or just one?
- Does this reproduce with all PKCS12 files, or just the one you are using?
- If you are able to generate a test PFX that reproduces the issue, can you share that? A test PFX is highly preferable to any "real" key.
Are you doing this in an interactive session, or a headless one? (And does it involve anything weird, like su(do)?) Since PersistKeySet writes to the default keychain I wonder if the keychain is in a read-only state and the OS is just surfacing a bad error code...
@vcsjones :
- We have only tried on one machine so far.
- It appears to reproduce w/ all our test pfx/pkcs12 : self-signed root w/ user cert on top of it
- Yes, this is what i mentioned earlier...we may need to transfer one of our p12 files to you
@bartonjs It is just being run via dotnet on the command-line...simple app. Yes, i have seen bad error codes from MacOS in the past.
We have only tried on one machine so far.
It would be helpful to see if you can reproduce it on another machine. We've observed a handful of issues occurring sometimes because the login keychain gets in to a "weird" state.
It is just being run via dotnet on the command-line
Just to be super specific... this is just in a plain terminal? No sudo, not an SSH connection, etc?
Jeremy, is it the case that .NET is using some MacOS Native APIs to do this Collection.Import()? If so, could this be similar to the issue we originally had with Core 3.1, where we need to the WORKAROUND we did for 3.1 to load the p12 into pkcs12info and then export back out in order for the Collection.Import() to be able to parse it?
@vcsjones It is not a sudo. However, i believe they are using a SSH.
So, as Jeremy said, the SSH will put the "keychain" into a READ-ONLY state? I don't really understand that, but is there a way to get around it?
So, as Jeremy said, the SSH will put the "keychain" into a READ-ONLY state? I
macOS sometimes likes to lock the keychain from an SSH session. Does running security unlock-keychain then running the code work?
Our test team updated:
"I’ve tried via VNC session on the same Mac testing VM but still hit the same error. Maybe VNC session has the same problem like SSH.
I also tried it on my Mac desktop and there is no error thrown.
So maybe keychain issue is correct. However customers will also run into the same problem via SSH or VNC. "
Is there any workaround for this, so that SSH or VNC sessions will be able to load the p12 data into persistent storage?
Is there any workaround for this, so that SSH or VNC sessions will be able to load the p12 data into persistent storage?
The only one that I know of was already mentioned by @vcsjones: "Does running security unlock-keychain then running the code work?", but perhaps that got missed as cross-posting.
Through a VNC session you could also try to launch the keychain app and see if it shows the default keychain being in a read-only state and/or has buttons to make it writable.
@ScotMac I'm not certain there is much we can do here - persisting to the keychain requires the keychain be unlocked, and certain remote connections (like SSH) don't unlock the login keychain.
Were you able to confirm if using security unlock-keychain addressed the error during import?
This issue has been marked needs-author-action and may be missing some important information.
This issue has been automatically marked no-recent-activity because it has not had any activity for 14 days. It will be closed if no further activity occurs within 14 more days. Any new comment (by anyone, not necessarily the author) will remove no-recent-activity.
This issue will now be closed since it had been marked no-recent-activity but received no further activity in the past 14 days. It is still possible to reopen or comment on the issue, but please note that the issue will be locked if it remains inactive for another 30 days.