Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Android] Allow using installed certificates for client authentication in SslStream #103337

Merged
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,17 @@ ref MemoryMarshal.GetReference(pkcs8PrivateKey),
certificates.Length);
}

[LibraryImport(Interop.Libraries.AndroidCryptoNative, EntryPoint = "AndroidCryptoNative_SSLStreamCreateWithKeyStorePrivateKeyEntry")]
private static partial SafeSslHandle SSLStreamCreateWithKeyStorePrivateKeyEntry(
IntPtr sslStreamProxyHandle,
IntPtr keyStorePrivateKeyEntryHandle);
internal static SafeSslHandle SSLStreamCreateWithKeyStorePrivateKeyEntry(
SslStream.JavaProxy sslStreamProxy,
IntPtr keyStorePrivateKeyEntryHandle)
{
return SSLStreamCreateWithKeyStorePrivateKeyEntry(sslStreamProxy.Handle, keyStorePrivateKeyEntryHandle);
}

[LibraryImport(Interop.Libraries.AndroidCryptoNative, EntryPoint = "AndroidCryptoNative_RegisterRemoteCertificateValidationCallback")]
internal static unsafe partial void RegisterRemoteCertificateValidationCallback(
delegate* unmanaged<IntPtr, bool> verifyRemoteCertificate);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,18 @@ internal static byte[] X509Encode(SafeX509Handle x)

return encoded;
}
[LibraryImport(Libraries.AndroidCryptoNative, EntryPoint = "AndroidCryptoNative_X509IsKeyStorePrivateKeyEntry")]
[return: MarshalAs(UnmanagedType.U1)]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@simonrozsival the native code returns int32_t here so we should change this to UnmanagedType.Bool (4 bytes), or change the native code to use a C bool which is 1 byte. We seem to be using both variants in the Android crypto imports...

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At least in the Linux and MacOS Desktop PALs, we try to use int32_t and not a C bool since there is no guarantee by the C standard that it is exactly one byte.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh, thanks for pointing that out!

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

internal static partial bool IsKeyStorePrivateKeyEntry(IntPtr handle);
[LibraryImport(Libraries.AndroidCryptoNative, EntryPoint = "AndroidCryptoNative_X509GetCertificateForPrivateKeyEntry")]
private static partial IntPtr GetPrivateKeyEntryCertificate(IntPtr privatKeyEntryHandle);
internal static SafeX509Handle GetPrivateKeyEntryCertificate(SafeHandle privatKeyEntryHandle)
{
var certificateHandle = new SafeX509Handle();
var certificatePtr = GetPrivateKeyEntryCertificate(privatKeyEntryHandle.DangerousGetHandle());
vcsjones marked this conversation as resolved.
Show resolved Hide resolved
Marshal.InitHandle(certificateHandle, Interop.JObjectLifetime.NewGlobalReference(certificatePtr));
return certificateHandle;
}

[LibraryImport(Libraries.AndroidCryptoNative, EntryPoint = "AndroidCryptoNative_X509DecodeCollection")]
private static partial int X509DecodeCollection(ref byte buf, int bufLen, IntPtr[]? ptrs, ref int handlesLen);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,12 @@ internal static unsafe partial bool X509StoreRemoveCertificate(
SafeX509StoreHandle store,
SafeX509Handle cert,
string hashString);

[LibraryImport(Libraries.AndroidCryptoNative, EntryPoint = "AndroidCryptoNative_X509StoreGetPrivateKeyEntry", StringMarshalling = StringMarshalling.Utf8)]
internal static partial IntPtr X509StoreGetPrivateKeyEntry(IntPtr store, string hashString);
[LibraryImport(Libraries.AndroidCryptoNative, EntryPoint = "AndroidCryptoNative_X509StoreDeleteEntry", StringMarshalling = StringMarshalling.Utf8)]
[return: MarshalAs(UnmanagedType.Bool)]
simonrozsival marked this conversation as resolved.
Show resolved Hide resolved
internal static partial bool X509StoreDeleteEntry(IntPtr store, string hashString);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,5 +208,45 @@ await LoopbackServer.CreateServerAsync(async server =>
}, new LoopbackServer.Options { UseSsl = true });
}
}

[Fact]
[PlatformSpecific(TestPlatforms.Android)]
public async Task Android_GetCertificateFromKeyStoreViaAlias()
{
var options = new LoopbackServer.Options { UseSsl = true };

var (store, alias) = AndroidKeyStoreHelper.AddCertificate(Configuration.Certificates.GetClientCertificate());
simonrozsival marked this conversation as resolved.
Show resolved Hide resolved
vcsjones marked this conversation as resolved.
Show resolved Hide resolved
try
{
var clientCertificate = AndroidKeyStoreHelper.GetCertificateViaAlias(store, alias);
simonrozsival marked this conversation as resolved.
Show resolved Hide resolved
Assert.True(clientCertificate.HasPrivateKey);


await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using HttpClient client = CreateHttpClientWithCert(clientCertificate);

await TestHelper.WhenAllCompletedOrAnyFailed(
client.GetStringAsync(url),
server.AcceptConnectionAsync(async connection =>
{
SslStream sslStream = Assert.IsType<SslStream>(connection.Stream);

_output.WriteLine(
"Client cert: {0}",
new X509Certificate2(sslStream.RemoteCertificate.Export(X509ContentType.Cert)).GetNameInfo(X509NameType.SimpleName, false));

Assert.Equal(clientCertificate.GetCertHashString(), sslStream.RemoteCertificate.GetCertHashString());

await connection.ReadRequestHeaderAndSendResponseAsync(additionalHeaders: "Connection: close\r\n");
}));
}, options);
}
finally
{
Assert.True(AndroidKeyStoreHelper.DeleteAlias(store, alias));
store.Dispose();
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@

simonrozsival marked this conversation as resolved.
Show resolved Hide resolved
using System.Security.Cryptography.X509Certificates;

namespace System
{
public static partial class AndroidKeyStoreHelper
{
public static (X509Store, string) AddCertificate(X509Certificate2 cert)
{
// Add the certificate to the Android keystore via X509Store
// the alias is the certificate hash string (sha256)
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
string alias = cert.GetCertHashString(System.Security.Cryptography.HashAlgorithmName.SHA256);
return (store, alias);
}

public static X509Certificate2 GetCertificateViaAlias(X509Store store, string alias)
{
var privateKeyEntry = Interop.AndroidCrypto.X509StoreGetPrivateKeyEntry(store.StoreHandle, alias);
return new X509Certificate2(privateKeyEntry);
}

public static bool DeleteAlias(X509Store store, string alias)
{
return Interop.AndroidCrypto.X509StoreDeleteEntry(store.StoreHandle, alias);
}
}
}
9 changes: 9 additions & 0 deletions src/libraries/Common/tests/TestUtilities/TestUtilities.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
Condition="'$(EnableAggressiveTrimming)' == 'true'" />

<Compile Include="System\AdminHelpers.cs" />
<Compile Include="System\AndroidKeyStoreHelper.cs" />
<Compile Include="System\AssertExtensions.cs" />
<Compile Include="System\IO\StreamExtensions.cs" />
<Compile Include="System\IO\PathGenerator.cs" />
Expand Down Expand Up @@ -100,8 +101,16 @@
<ItemGroup>
<Compile Include="$(CommonPath)Interop\Android\Interop.Libraries.cs"
Link="Common\Interop\Android\Interop.Libraries.cs" />
<Compile Include="$(CommonPath)Interop\Android\Interop.JObjectLifetime.cs"
Link="Common\Interop\Android\Interop.JObjectLifetime.cs" />
<Compile Include="$(CommonPath)Interop\Android\System.Security.Cryptography.Native.Android\Interop.Ssl.ProtocolSupport.cs"
Link="Common\Interop\Android\System.Security.Cryptography.Native.Android\Interop.Ssl.ProtocolSupport.cs" />
<Compile Include="$(CommonPath)Interop\Android\System.Security.Cryptography.Native.Android\Interop.X509.cs"
Link="Common\Interop\Android\System.Security.Cryptography.Native.Android\Interop.X509.cs" />
<Compile Include="$(CommonPath)Interop\Android\System.Security.Cryptography.Native.Android\Interop.X509Store.cs"
Link="Common\Interop\Android\System.Security.Cryptography.Native.Android\Interop.X509Store.cs" />
<Compile Include="$(CommonPath)Interop\Android\System.Security.Cryptography.Native.Android\SafeKeyHandle.cs"
Link="Common\Interop\Android\System.Security.Cryptography.Native.Android\SafeKeyHandle.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.DotNet.XUnitExtensions" Version="$(MicrosoftDotNetXUnitExtensionsVersion)" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,11 @@ private static SafeSslHandle CreateSslContext(SslStream.JavaProxy sslStreamProxy
X509Certificate2 cert = context.TargetCertificate;
Debug.Assert(context.TargetCertificate.HasPrivateKey);

if (Interop.AndroidCrypto.IsKeyStorePrivateKeyEntry(cert.Handle))
{
return Interop.AndroidCrypto.SSLStreamCreateWithKeyStorePrivateKeyEntry(sslStreamProxy, cert.Handle);
}

PAL_KeyAlgorithm algorithm;
byte[] keyBytes;
using (AsymmetricAlgorithm key = GetPrivateKeyAlgorithm(cert, out algorithm))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ internal sealed class AndroidCertificatePal : ICertificatePal
{
private SafeX509Handle _cert;
private SafeKeyHandle? _privateKey;
private Interop.JObjectLifetime.SafeJObjectHandle? _keyStorePrivateKeyEntry;

private CertificateData _certData;

Expand All @@ -25,6 +26,13 @@ public static ICertificatePal FromHandle(IntPtr handle)
if (handle == IntPtr.Zero)
throw new ArgumentException(SR.Arg_InvalidHandle, nameof(handle));

if (Interop.AndroidCrypto.IsKeyStorePrivateKeyEntry(handle))
{
var newPrivateKeyEntryHandle = new Interop.JObjectLifetime.SafeJObjectHandle();
Marshal.InitHandle(newPrivateKeyEntryHandle, Interop.JObjectLifetime.NewGlobalReference(handle));
simonrozsival marked this conversation as resolved.
Show resolved Hide resolved
return new AndroidCertificatePal(newPrivateKeyEntryHandle);
}

var newHandle = new SafeX509Handle();
Marshal.InitHandle(newHandle, Interop.JObjectLifetime.NewGlobalReference(handle));
return new AndroidCertificatePal(newHandle);
Expand All @@ -36,6 +44,13 @@ public static ICertificatePal FromOtherCert(X509Certificate cert)

AndroidCertificatePal certPal = (AndroidCertificatePal)cert.Pal;

if (certPal._keyStorePrivateKeyEntry is not null)
{
var jobjectHandle = new Interop.JObjectLifetime.SafeJObjectHandle();
Marshal.InitHandle(jobjectHandle, Interop.JObjectLifetime.NewGlobalReference(certPal.Handle));
vcsjones marked this conversation as resolved.
Show resolved Hide resolved
return new AndroidCertificatePal(jobjectHandle);
}

// Ensure private key is copied
if (certPal.PrivateKeyHandle != null)
{
Expand Down Expand Up @@ -134,6 +149,12 @@ private static AndroidCertificatePal ReadPkcs12(ReadOnlySpan<byte> rawData, Safe
}
}

internal AndroidCertificatePal(Interop.JObjectLifetime.SafeJObjectHandle handle)
{
_cert = Interop.AndroidCrypto.GetPrivateKeyEntryCertificate(handle);
_keyStorePrivateKeyEntry = handle;
}

internal AndroidCertificatePal(SafeX509Handle handle)
{
_cert = handle;
Expand All @@ -145,9 +166,14 @@ internal AndroidCertificatePal(SafeX509Handle handle, SafeKeyHandle privateKey)
_privateKey = privateKey;
}

public bool HasPrivateKey => _privateKey != null;
public bool HasPrivateKey => _privateKey is not null || _keyStorePrivateKeyEntry is not null;

public IntPtr Handle => _cert == null ? IntPtr.Zero : _cert.DangerousGetHandle();
public IntPtr Handle => (_keyStorePrivateKeyEntry, _cert) switch
{
({} privateKeyEntry, _) => privateKeyEntry.DangerousGetHandle(),
(null, {} cert) => cert.DangerousGetHandle(),
_ => IntPtr.Zero,
};
simonrozsival marked this conversation as resolved.
Show resolved Hide resolved

internal SafeX509Handle SafeHandle => _cert;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

package net.dot.android.crypto;

import java.net.Socket;
import java.security.KeyStore;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;

import javax.net.ssl.X509KeyManager;

public final class DotnetX509KeyManager implements X509KeyManager {
private static final String CLIENT_CERTIFICATE_ALIAS = "DOTNET_SSLStream_ClientCertificateContext";

private final PrivateKey privateKey;
private final X509Certificate[] certificateChain;

public DotnetX509KeyManager(KeyStore.PrivateKeyEntry privateKeyEntry) {
if (privateKeyEntry == null) {
throw new IllegalArgumentException("PrivateKeyEntry must not be null");
}

this.privateKey = privateKeyEntry.getPrivateKey();

Certificate[] certificates = privateKeyEntry.getCertificateChain();
ArrayList<X509Certificate> x509Certificates = new ArrayList<>();
for (Certificate certificate : certificates) {
if (certificate instanceof X509Certificate) {
x509Certificates.add((X509Certificate) certificate);
}
}

if (x509Certificates.size() == 0) {
throw new IllegalArgumentException("No valid X509 certificates found in the chain");
}

this.certificateChain = x509Certificates.toArray(new X509Certificate[0]);
}

@Override
public String[] getClientAliases(String keyType, Principal[] issuers) {
return new String[] { CLIENT_CERTIFICATE_ALIAS };
}

@Override
public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {
return CLIENT_CERTIFICATE_ALIAS;
}

@Override
public String[] getServerAliases(String keyType, Principal[] issuers) {
return new String[0];
}

@Override
public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
return null;
}

@Override
public X509Certificate[] getCertificateChain(String alias) {
return certificateChain;
}

@Override
public PrivateKey getPrivateKey(String alias) {
return privateKey;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,9 @@ jmethodID g_HostnameVerifierVerify;
jclass g_HttpsURLConnection;
jmethodID g_HttpsURLConnectionGetDefaultHostnameVerifier;

// javax/net/ssl/KeyManager
jclass g_KeyManager;

// javax/net/ssl/KeyManagerFactory
jclass g_KeyManagerFactory;
jmethodID g_KeyManagerFactoryGetInstance;
Expand Down Expand Up @@ -489,6 +492,10 @@ jclass g_TrustManager;
jclass g_DotnetProxyTrustManager;
jmethodID g_DotnetProxyTrustManagerCtor;

// net/dot/android/crypto/DotnetX509KeyManager
jclass g_DotnetX509KeyManager;
jmethodID g_DotnetX509KeyManagerCtor;

// net/dot/android/crypto/PalPbkdf2
jclass g_PalPbkdf2;
jmethodID g_PalPbkdf2Pbkdf2OneShot;
Expand Down Expand Up @@ -1028,6 +1035,8 @@ JNI_OnLoad(JavaVM *vm, void *reserved)
g_HttpsURLConnection = GetClassGRef(env, "javax/net/ssl/HttpsURLConnection");
g_HttpsURLConnectionGetDefaultHostnameVerifier = GetMethod(env, true, g_HttpsURLConnection, "getDefaultHostnameVerifier", "()Ljavax/net/ssl/HostnameVerifier;");

g_KeyManager = GetClassGRef(env, "javax/net/ssl/KeyManager");

g_KeyManagerFactory = GetClassGRef(env, "javax/net/ssl/KeyManagerFactory");
g_KeyManagerFactoryGetInstance = GetMethod(env, true, g_KeyManagerFactory, "getInstance", "(Ljava/lang/String;)Ljavax/net/ssl/KeyManagerFactory;");
g_KeyManagerFactoryInit = GetMethod(env, false, g_KeyManagerFactory, "init", "(Ljava/security/KeyStore;[C)V");
Expand Down Expand Up @@ -1100,6 +1109,9 @@ JNI_OnLoad(JavaVM *vm, void *reserved)
g_DotnetProxyTrustManager = GetClassGRef(env, "net/dot/android/crypto/DotnetProxyTrustManager");
g_DotnetProxyTrustManagerCtor = GetMethod(env, false, g_DotnetProxyTrustManager, "<init>", "(J)V");

g_DotnetX509KeyManager = GetClassGRef(env, "net/dot/android/crypto/DotnetX509KeyManager");
g_DotnetX509KeyManagerCtor = GetMethod(env, false, g_DotnetX509KeyManager, "<init>", "(Ljava/security/KeyStore$PrivateKeyEntry;)V");

g_PalPbkdf2 = GetClassGRef(env, "net/dot/android/crypto/PalPbkdf2");
g_PalPbkdf2Pbkdf2OneShot = GetMethod(env, true, g_PalPbkdf2, "pbkdf2OneShot", "(Ljava/lang/String;[BLjava/nio/ByteBuffer;ILjava/nio/ByteBuffer;)I");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,9 @@ extern jmethodID g_HostnameVerifierVerify;
extern jclass g_HttpsURLConnection;
extern jmethodID g_HttpsURLConnectionGetDefaultHostnameVerifier;

// javax/net/ssl/KeyManager
extern jclass g_KeyManager;

// javax/net/ssl/KeyManagerFactory
extern jclass g_KeyManagerFactory;
extern jmethodID g_KeyManagerFactoryGetInstance;
Expand Down Expand Up @@ -503,6 +506,10 @@ extern jclass g_TrustManager;
extern jclass g_DotnetProxyTrustManager;
extern jmethodID g_DotnetProxyTrustManagerCtor;

// net/dot/android/crypto/DotnetX509KeyManager
extern jclass g_DotnetX509KeyManager;
extern jmethodID g_DotnetX509KeyManagerCtor;

// net/dot/android/crypto/PalPbkdf2
extern jclass g_PalPbkdf2;
extern jmethodID g_PalPbkdf2Pbkdf2OneShot;
Expand Down
Loading
Loading