runtime: Android: Installed X509 certificates can't be used with SSL authentication

Description

On Android when using the SocketsHttpHandler with X509 Client certificates to PKI authenticate with a server, you can only use certificates with a private key coming from a file. When using the more correct and secure way of only using certificates installed in the keychain authentication fails, because the SocketsHttpHandler wants direct access to the private key instead of using the Java APIs to authenticate.

Reproduction Steps

Reproduction steps are a little tricky since they require a server that requires PKI authentication, and a certificate installed on the users device. I’m going to assume you have this here.

           Uri uri = new Uri("https://mypkiserver/index.html");
            var handler = new SocketsHttpHandler();
            var tcs = new TaskCompletionSource<X509Certificate2>();
            Android.Security.KeyChain.ChoosePrivateKeyAlias(Platform.CurrentActivity!, response: new KeyChainAliasCallback(tcs),
                new String[] { Android.Security.Keystore.KeyProperties.KeyAlgorithmRsa, "DSA" }, // List of acceptable key types. null for any
                null,                        // issuer, null for any
                null,                        // host name of server requesting the cert, null if unavailable
                -1,                          // port of server requesting the cert, -1 if unavailable
                "");
            certificate = await tcs.Task;
            if (certificate != null)
                handler.SslOptions.ClientCertificates = new X509Certificate2Collection(certificate); 

            using var client = new HttpClient(handler);
            var response = await client.GetAsync(infoUri); //will usually throw if certificate can't be used
            response = response.EnsureSuccessStatusCode();

KeyChainAliasCallback.cs responsible for letting the user pick an installed certificate:

    public class KeyChainAliasCallback : Java.Lang.Object, Android.Security.IKeyChainAliasCallback
    {
        private readonly TaskCompletionSource<X509Certificate2?> _tcs;
        public KeyChainAliasCallback(TaskCompletionSource<X509Certificate2?> tcs)
        {
            _tcs = tcs;
        }

        void Android.Security.IKeyChainAliasCallback.Alias(string? alias)
        {
            if (alias != null)
            {
                var certificateChain = Android.Security.KeyChain.GetCertificateChain(Platform.CurrentActivity!, alias!);
                if (certificateChain != null && certificateChain.Length > 0)
                {
                    X509Certificate2 certificate = new(certificateChain[0].Handle);
                    _tcs.TrySetResult(certificate);
                }
            }
            _tcs.TrySetResult(null);
        }
    }

Expected behavior

Certificates used from the keychain where the private key isn’t directly accessible will work.

Actual behavior

Fails to authenticate.

Regression?

No response

Known Workarounds

None

Configuration

No response

Other information

Related issue: https://github.com/dotnet/runtime/issues/45741#issuecomment-1823987611

This is a blocker for larger enterprises since they can’t use their secured services with the level of security they require. Using file-based certificates in-app with the full exportable private key just isn’t acceptable to them.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 14
  • Comments: 21 (13 by maintainers)

Most upvoted comments

@dotMorten yes, that should be straightforward IMO. We can check if it is a java object reference and check the type of the java object using JNI.

I’ve looked into the Apple platforms APIs and I noticed that the X509Certificate2(IntPtr) constructor allows passing a handle of an SecCertificate object or of an SecIdentity. It might not be a bad idea to do something similar on Android and allow passing in not only a handle of java.security.cert.X509Certificate, but also of java.security.KeyStore.PrivateKeyEntry.

This approach wouldn’t require any changes to the public APIs and the internal implementation of AndroidCertificatePal and pal_sslstream.c shouldn’t be too complicated. I’m just not sure where we keep documentation of these platform specific details (it certainly isn’t in the X509Certificate2(IntPtr) docs) if we even have such place.

The usage would look like this:

var privateKey = Android.Security.KeyChain.GetPrivateKey(Platform.CurrentActivity!, alias);
var certificateChain = Android.Security.KeyChain.GetCertificateChain(Platform.CurrentActivity!, alias);
var privateKeyEntry = new Java.Security.KeyStore.PrivateKeyEntry(privateKey, certificateChain);

var certificate = new X509Certificate2(privateKeyEntry.Handle);
handler.SslOptions.ClientCertificates = new X509Certificate2Collection(certificate);

It isn’t about getting private key. Private key is in the device. It is about getting SslStream to use it trough native API so we could use certificate stored in the device as X509Certificate2 from X509Store for HttpClient.

do you have any insight?

Unfortunately, I am not particularly familiar with the Android Keychain APIs. There were certainly cases where I had a use case on iOS / Android to convert a native object (SecIdentityRef/SecCertificateRef for iOS, java.security.cert.X509Certificate for Android) into X509Certificate2 and back. I certainly feel it would be warrantied to provide extension methods into the Android/iOS SDKs to do such conversion (without going through export and reimport). iOS is rather straightforward when it comes to the mapping but I vaguely remember that the backing implementation of X509Certificate2 actually mapped to more than one Java object (feel free to correct me) and it gets tricky.

The alias mapping sound like something that could be mapped to X509Store(string storeName) constructor. Not sure if that’s the best way though. Maybe using the primary store and some store.Certificates.Find(...) overload would be a better idea.

I’ll try to sleep on it and perhaps I will come up with a better answer.

I’m not quite getting the argument for providing these extensions - sure they are helpful to avoid writing the code in the issue details, but at the end of the day we can still create the X502Certificate2 from what KeyChain.ChoosePrivateKeyAlias returns.

So to do this on Windows, you need to install the System.Windows.Extensions NuGet package and use the X509Certificate2UI class that will show a Windows dialog (similar to KeyChain.ChoosePrivateKeyAlias) and it will give you a certificate with a non-exportable private key back.

I wonder if we should add a similar public API to xamarin-android and corresponding internal APIs to the Android PAL to work with certificates via aliases in the runtime (I don’t think we want to create and maintain System.Android.Extensions NuGet). I think we would need something like:

// xamarin/xamarin-android
public static class X509Certificate2Factory
{
    public static X509Certificate2 CreateFromAlias(Android.Content.Context context, string alias) { ... }
}

// dotnet/runtime
internal partial class AndroidCertificatePal
{
    internal static X509Certificate2 FromAlias(IntPtr context, string alias) { ... }
}

Unfortunately, unlike System.Windows.Extensions, xamari-android can’t see the internals directly, but I don’t think that would be a major problem.

The AndroidMessageHandler has a number of limitations that makes it really inconvenient to use, like weird pre-authenticate issues, frequent crashes in the send request when it suddenly decides to close the socket, and based on an old Java implementation.

Yes, I understand why you would prefer SocketsHttpHandler over the native one.

I would expect the certificate handling sits all the way down at the socket level which is also using the java apis, so I would expect to be able to use the installed certificates: …

You’re right, there’s no reason why we couldn’t implement it in the Java/JNI code. The problem I see at the moment is that there isn’t a good way to pass the alias all the way down to pal_sslstream.c through existing .NET APIs. I’m currently looking into ways which we could extend the implementation without introducing a new (platform specific) API.