Skip to content

[Mono.Android] custom validation callback for server certificates in HTTP handlers - #6972

Merged
jonpryor merged 2 commits into
dotnet:release/6.0.3xxfrom
jonathanpeppers:backport-6665
May 9, 2022
Merged

jonpryor merged 2 commits into
dotnet:release/6.0.3xxfrom
jonathanpeppers:backport-6665

Conversation

@jonathanpeppers

Copy link
Copy Markdown
Member

Backport of: #6665
Context: dotnet/runtime#62966

The AndroidClientHandler and AndroidMessageHandler classes both
have the ServerCertificateCustomValidationCallback property, which
should be useful e.g. to allow running the Android app against a
server with a self-signed SSL certificate during development, but the
callback is never used. Unfortunatelly since .NET 6 the
System.Net.Http.SocketsHttpHandler for Android doesn't support the
use case anymore. That means that the recommended way of connecting
to local web server
won't work in MAUI.

This PR introduces an implementation of IX509TrustManger which wraps
the default Java X509 trust manager and calls the user's callback on
top of the default validation.

It turns out that X509Chain Build function doesn't work on
Android, so I'm not calling it and I'm passing the chain to the
callback directly.

Additionally, we need a default proguard rule due to:

https://github.com/xamarin/xamarin-android/blob/46002b49d8c0b7b1a17532a8e104b4d31afee7a6/src/Xamarin.Android.Build.Tasks/Linker/MonoDroid.Tuner/GenerateProguardConfiguration.cs#L50-L57

-keep class xamarin.android.net.X509TrustManagerWithValidationCallback { *; <init>(...); }

Mono.Android.dll is skipped during the
GenerateProguardConfiguration linker step. It might be worth
addressing this in a future PR.

…HTTP handlers (dotnet#6665)

Backport of: dotnet#6665
Context: dotnet/runtime#62966

The `AndroidClientHandler` and `AndroidMessageHandler` classes both
have the `ServerCertificateCustomValidationCallback` property, which
should be useful e.g. to allow running the Android app against a
server with a self-signed SSL certificate during development, but the
callback is never used. Unfortunatelly since .NET 6 the
`System.Net.Http.SocketsHttpHandler` for Android doesn't support the
use case anymore. That means that [the recommended way of connecting
to local web server][0] won't work in MAUI.

This PR introduces an implementation of `IX509TrustManger` which wraps
the default Java X509 trust manager and calls the user's callback on
top of the default validation.

It turns out that `X509Chain` `Build` function doesn't work on
Android, so I'm not calling it and I'm passing the chain to the
callback directly.

Additionally, we need a default proguard rule due to:

https://github.com/xamarin/xamarin-android/blob/46002b49d8c0b7b1a17532a8e104b4d31afee7a6/src/Xamarin.Android.Build.Tasks/Linker/MonoDroid.Tuner/GenerateProguardConfiguration.cs#L50-L57

    -keep class xamarin.android.net.X509TrustManagerWithValidationCallback { *; <init>(...); }

`Mono.Android.dll` is skipped during the
`GenerateProguardConfiguration` linker step. It might be worth
addressing this in a future PR.

[0]: https://docs.microsoft.com/en-us/xamarin/cross-platform/deploy-test/connect-to-local-web-services
@jonathanpeppers
jonathanpeppers marked this pull request as draft April 29, 2022 16:48
@jonathanpeppers
jonathanpeppers marked this pull request as ready for review May 1, 2022 23:33

tmf = TrustManagerFactory.GetInstance (TrustManagerFactory.DefaultAlgorithm);
tmf?.Init (keyStore);
tmf?.Init (gotCerts ? keyStore : null); // only use the custom key store if the user defined any trusted certs

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Should it say custom instead of trusted? Certs defined by the user will most likely not be trusted in the official CA chain sense

keyStore?.Load (null, null);
gotCerts = TrustedCerts?.Count > 0;

if (gotCerts) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is an absolute nitpick on my part, but could you change the code to

if (!gotCerts) {
  return keystore;
}

for (...) {
}

I tend to prefer to keep large blocks of code outside the if statement sub-blocks - in my opinion it makes code more readable :)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I agree this is generally how we prefer stuff in XA, the "early out" option is best 👍

{
internal sealed class Helper
{
public Func<HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bool> Callback { get; }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Should Func<> be perhaps replaced by a specific delegate to be used throughout this class but also in AndroidMessageHandler? It would make it easier to modify it in the future, should there be a need for that and also reduce the signal to noise ratio when reading the code

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

If exposed publicly from a public type, you don't necessarily want "easier to modify", as changing the delegate signature is a breaking change. This should to be the same delegate type as the public AndroidMessageHandler.ServerCertificateCustomValidationCallback property, and thus is a type that cannot be changed.

{
IX509TrustManager? x509TrustManager = trustManagers?.OfType<IX509TrustManager> ().FirstOrDefault ();
IEnumerable<ITrustManager> otherTrustManagers = trustManagers?.Where (manager => manager != x509TrustManager) ?? Enumerable.Empty<ITrustManager> ();
var trustManagerWithCallback = new X509TrustManagerWithValidationCallback (x509TrustManager, requestMessage, Callback);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'm not very fond of LINQ code in frameworks or libraries, since it's not very performant. Could we use the boring loops here? :)

private readonly HttpRequestMessage _request;
private readonly Func<HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bool> _serverCertificateCustomValidationCallback;

private X509TrustManagerWithValidationCallback (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The private modifiers are superfluous since this is the default visibility of a class member.


try {
_internalTrustManager?.CheckServerTrusted (javaChain, authType);
} catch (JavaCertificateException) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I feel we should log this exception, not the whole trace, just the message, using the Debug severity so that it's not shown by default.

@jonathanpeppers

Copy link
Copy Markdown
Member Author

@grendello this is a backport of 48540d6 to the .NET 6 release branch (I think you approved). I mostly just fixed up the .apkdesc files, so the tests would pass here.

Do you want @simonrozsival to address these comments in main before we backport this?

@grendello

Copy link
Copy Markdown
Contributor

@grendello this is a backport of 48540d6 to the .NET 6 release branch (I think you approved). I mostly just fixed up the .apkdesc files, so the tests would pass here.

Do you want @simonrozsival to address these comments in main before we backport this?

DotNet follows a different style, and sinde my comments are mostly stylistic, hence my lack of comments then :)


tmf = TrustManagerFactory.GetInstance (TrustManagerFactory.DefaultAlgorithm);
tmf?.Init (keyStore);
tmf?.Init (gotCerts ? keyStore : null); // only use the custom key store if the user defined any trusted certs

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested change
tmf?.Init (gotCerts ? keyStore : null); // only use the custom key store if the user defined any trusted certs
tmf?.Init (gotCerts ? keyStore : null); // only use the custom key store if the user defined any custom certs

}
}

private readonly IX509TrustManager? _internalTrustManager;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested change
private readonly IX509TrustManager? _internalTrustManager;
readonly IX509TrustManager? _internalTrustManager;

}

private readonly IX509TrustManager? _internalTrustManager;
private readonly HttpRequestMessage _request;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested change
private readonly HttpRequestMessage _request;
readonly HttpRequestMessage _request;


private readonly IX509TrustManager? _internalTrustManager;
private readonly HttpRequestMessage _request;
private readonly Func<HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bool> _serverCertificateCustomValidationCallback;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested change
private readonly Func<HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bool> _serverCertificateCustomValidationCallback;
readonly Func<HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bool> _serverCertificateCustomValidationCallback;

private readonly HttpRequestMessage _request;
private readonly Func<HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bool> _serverCertificateCustomValidationCallback;

private X509TrustManagerWithValidationCallback (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested change
private X509TrustManagerWithValidationCallback (
X509TrustManagerWithValidationCallback (

using System.Linq;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested change
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.X509Certificates;
using Android.Runtime;


try {
_internalTrustManager?.CheckServerTrusted (javaChain, authType);
} catch (JavaCertificateException) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested change
} catch (JavaCertificateException) {
} catch (JavaCertificateException ex) {
Logger.Log (LogLevel.Debug, $"Java certificate validation exception. {ex.Message}");

public JavaX509Certificate[] GetAcceptedIssuers ()
=> _internalTrustManager?.GetAcceptedIssuers () ?? Array.Empty<JavaX509Certificate> ();

private static X509Chain CreateChain (X509Certificate2[] certificates)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested change
private static X509Chain CreateChain (X509Certificate2[] certificates)
static X509Chain CreateChain (X509Certificate2[] certificates)

return chain;
}

private static X509Certificate2[] ConvertCertificates (JavaX509Certificate[] certificates)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested change
private static X509Certificate2[] ConvertCertificates (JavaX509Certificate[] certificates)
static X509Certificate2[] ConvertCertificates (JavaX509Certificate[] certificates)

@jonpryor
jonpryor merged commit 735e6d9 into dotnet:release/6.0.3xx May 9, 2022
@jonathanpeppers
jonathanpeppers deleted the backport-6665 branch May 9, 2022 15:11
@github-actions github-actions Bot locked and limited conversation to collaborators Jan 24, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants