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 @@ -42,6 +42,13 @@ protected override bool ReleaseHandle()
return true;
}

internal static SafeJObjectHandle CreateGlobalReferenceFromHandle(IntPtr handle)
{
var jObjectHandle = new SafeJObjectHandle();
Marshal.InitHandle(jObjectHandle, NewGlobalReference(handle));
return jObjectHandle;
}

public override bool IsInvalid => handle == IntPtr.Zero;
}
}
Expand Down
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,31 @@ 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)
{
bool addedRef = false;
try
{
privatKeyEntryHandle.DangerousAddRef(ref addedRef);
IntPtr certificatePtr = GetPrivateKeyEntryCertificate(privatKeyEntryHandle.DangerousGetHandle());

SafeX509Handle certificateHandle = new();
Marshal.InitHandle(certificateHandle, certificatePtr);
return certificateHandle;
}
finally
{
if (addedRef)
{
privatKeyEntryHandle.DangerousRelease();
}
}
}

[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 });
}
}

#if TARGETS_ANDROID
[Fact]
public async Task Android_GetCertificateFromKeyStoreViaAlias()
{
var options = new LoopbackServer.Options { UseSsl = true };

(X509Store store, string alias) = AndroidKeyStoreHelper.AddCertificate(Configuration.Certificates.GetClientCertificate());
try
{
X509Certificate2 clientCertificate = AndroidKeyStoreHelper.GetCertificateViaAlias(store, alias);
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();
}
}
#endif
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Security.Cryptography.X509Certificates;

namespace System.Net.Http.Functional.Tests
{
public static 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)
{
IntPtr 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);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<DefineConstants>$(DefineConstants);SYSNETHTTP_NO_OPENSSL;HTTP3</DefineConstants>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IncludeRemoteExecutor>true</IncludeRemoteExecutor>
<TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-linux;$(NetCoreAppCurrent)-browser;$(NetCoreAppCurrent)-osx</TargetFrameworks>
<TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-linux;$(NetCoreAppCurrent)-android;$(NetCoreAppCurrent)-browser;$(NetCoreAppCurrent)-osx</TargetFrameworks>
<EnablePreviewFeatures>true</EnablePreviewFeatures>
<EventSourceSupport Condition="'$(TestNativeAot)' == 'true'">true</EventSourceSupport>
</PropertyGroup>
Expand All @@ -29,6 +29,10 @@
<WasmXHarnessTestsTimeout>01:15:00</WasmXHarnessTestsTimeout>
</PropertyGroup>

<PropertyGroup Condition="'$(TargetPlatformIdentifier)' == 'android'">
<DefineConstants>$(DefineConstants);TARGETS_ANDROID</DefineConstants>
</PropertyGroup>

<ItemGroup>
<WasmExtraFilesToDeploy Include="package.json" />
<WasmExtraFilesToDeploy Include="package-lock.json" />
Expand Down Expand Up @@ -242,6 +246,22 @@
<Compile Include="$(CommonPath)Interop\OSX\Interop.Libraries.cs"
Link="Common\Interop\OSX\Interop.Libraries.cs" />
</ItemGroup>
<!-- Android specific files -->
<ItemGroup Condition=" '$(TargetPlatformIdentifier)' == 'android' ">
<Compile Include="AndroidKeyStoreHelper.cs" />
<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>
<Compile Include="CustomContent.netcore.cs" />
<Compile Include="HPackTest.cs" />
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 @@ -11,12 +11,15 @@
using System.Text;
using Microsoft.Win32.SafeHandles;

using SafeJObjectHandle = Interop.JObjectLifetime.SafeJObjectHandle;

namespace System.Security.Cryptography.X509Certificates
{
internal sealed class AndroidCertificatePal : ICertificatePal
{
private SafeX509Handle _cert;
private SafeKeyHandle? _privateKey;
private SafeJObjectHandle? _keyStorePrivateKeyEntry;

private CertificateData _certData;

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

if (Interop.AndroidCrypto.IsKeyStorePrivateKeyEntry(handle))
{
SafeJObjectHandle newPrivateKeyEntryHandle = SafeJObjectHandle.CreateGlobalReferenceFromHandle(handle);
return new AndroidCertificatePal(newPrivateKeyEntryHandle);
}

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

AndroidCertificatePal certPal = (AndroidCertificatePal)cert.Pal;

if (certPal._keyStorePrivateKeyEntry is SafeJObjectHandle privateKeyEntry)
{
bool addedRef = false;
try
{
privateKeyEntry.DangerousAddRef(ref addedRef);
SafeJObjectHandle newSafeHandle = SafeJObjectHandle.CreateGlobalReferenceFromHandle(privateKeyEntry.DangerousGetHandle());
return new AndroidCertificatePal(newSafeHandle);
}
finally
{
if (addedRef)
{
privateKeyEntry.DangerousRelease();
}
}
}

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

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

internal AndroidCertificatePal(SafeX509Handle handle)
{
_cert = handle;
Expand All @@ -145,9 +178,11 @@ 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?.DangerousGetHandle()
?? _cert?.DangerousGetHandle()
?? IntPtr.Zero;

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;
}
}
Loading
Loading