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

[Foundation] Implement the server certificate custom validation callback usage in NSUrlSessionHandler #15117

Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
b0dbe59
WIP invoke server certificate custom validation callback
simonrozsival May 4, 2022
916b931
WIP add tests
simonrozsival May 4, 2022
6bd110a
Fix sec trust param type
simonrozsival May 4, 2022
6e20ea4
WIP improve chain building
simonrozsival May 4, 2022
f0b8dd0
Make it build
akoeplinger May 4, 2022
c6ae804
Merge branch 'main' of https://github.com/xamarin/xamarin-macios into…
simonrozsival Aug 30, 2022
4326052
Update tests
simonrozsival Aug 30, 2022
78509b2
Fix build and update implementation
simonrozsival Aug 30, 2022
9a6deda
Run the new tests only in .NET builds
simonrozsival Sep 2, 2022
09ec0ce
Fix default certificate evaluation
simonrozsival Sep 2, 2022
eeb3495
Fix tests
simonrozsival Sep 2, 2022
f9a46f4
Merge branch 'main' into nsurlsessionhandler-server-certificate-custo…
simonrozsival Sep 2, 2022
c9d822d
Fix using GetCertificateChain on systems which don't support it
simonrozsival Sep 5, 2022
06d972d
Merge branch 'nsurlsessionhandler-server-certificate-custom-validatio…
simonrozsival Sep 5, 2022
65a2df3
Minor code touchup
simonrozsival Sep 5, 2022
cee43a2
Merge branch 'main' into nsurlsessionhandler-server-certificate-custo…
rolfbjarne Sep 9, 2022
9227f2b
Fix code formatting
simonrozsival Sep 12, 2022
799ac3c
Update X509Chain building
simonrozsival Sep 12, 2022
4307863
Merge branch 'nsurlsessionhandler-server-certificate-custom-validatio…
simonrozsival Sep 12, 2022
f772124
Merge branch 'main' into nsurlsessionhandler-server-certificate-custo…
simonrozsival Sep 30, 2022
27b368f
Use helper class to fix trimming issues
simonrozsival Oct 12, 2022
40da74f
Fixes
simonrozsival Oct 12, 2022
db36a5d
Add missing setter
simonrozsival Oct 12, 2022
d691f6d
Merge remote-tracking branch 'origin/main' into nsurlsessionhandler-s…
rolfbjarne Oct 13, 2022
7fb65da
Improve code to make the linker able to remove more code.
rolfbjarne Oct 13, 2022
df170fc
Fix build.
rolfbjarne Oct 14, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 46 additions & 12 deletions src/Foundation/NSUrlSessionHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -639,13 +639,7 @@ public IWebProxy? Proxy {
[UnsupportedOSPlatform ("macos")]
public SslProtocols SslProtocols { get; set; } = SslProtocols.Tls12 | SslProtocols.Tls13;

// We're ignoring this property, just like Xamarin.Android does:
// https://github.com/xamarin/xamarin-android/blob/09e8cb5c07ea6c39383185a3f90e53186749b802/src/Mono.Android/Xamarin.Android.Net/AndroidMessageHandler.cs#L160
[UnsupportedOSPlatform ("ios")]
[UnsupportedOSPlatform ("maccatalyst")]
[UnsupportedOSPlatform ("tvos")]
[UnsupportedOSPlatform ("macos")]
public Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool>? ServerCertificateCustomValidationCallback { get; set; }
public Func<HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bool>? ServerCertificateCustomValidationCallback { get; set; }

// There's no way to turn off automatic decompression, so yes, we support it
public bool SupportsAutomaticDecompression {
Expand Down Expand Up @@ -886,19 +880,21 @@ public override void DidReceiveChallenge (NSUrlSession session, NSUrlSessionTask
#endif
var trustCallbackForUrl = sessionHandler.TrustOverrideForUrl;
#if NET
var hasCallBack = trustCallbackForUrl is not null;
var hasCallBack = trustCallbackForUrl is not null || sessionHandler.ServerCertificateCustomValidationCallback is not null;
#else
var hasCallBack = trustCallback is not null || trustCallbackForUrl is not null;
var hasCallBack = trustCallback is not null || trustCallbackForUrl is not null || sessionHandler.ServerCertificateCustomValidationCallback is not null;
#endif
if (hasCallBack && challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodServerTrust) {
#if NET
// if the trust delegate allows to ignore the cert, do it. Since we are using nullables, if the delegate is not present, by default is false
var trustSec = (trustCallbackForUrl?.Invoke (sessionHandler, inflight.RequestUrl, challenge.ProtectionSpace.ServerSecTrust) ?? false);
var trustSec = (trustCallbackForUrl?.Invoke (sessionHandler, inflight.RequestUrl, challenge.ProtectionSpace.ServerSecTrust) ?? false) ||
(InvokeServerCertificateCustomValidationCallback (inflight.Request, challenge.ProtectionSpace.ServerSecTrust));
Copy link
Member

Choose a reason for hiding this comment

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

What happens if both are set? Do we trust the native one of the manage APIs? Should we always trust first the results from ServerCertificateCustomValidationCallback ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I opted to trust the certificate if either of the callbacks trusts the certificate. It's basically the same in the #else branch. I guess the comment should be updated as well. Unless the callbacks contain some weird side effects, the order in which they are invoked doesn't matter. I'm not sure there's really a much better way of doing it.

#else
// if one of the delegates allows to ignore the cert, do it. We check first the one that takes the url because is more precisse, later the
// more general one. Since we are using nullables, if the delegate is not present, by default is false
var trustSec = (trustCallbackForUrl?.Invoke (sessionHandler, inflight.RequestUrl, challenge.ProtectionSpace.ServerSecTrust) ?? false) ||
(trustCallback?.Invoke (sessionHandler, challenge.ProtectionSpace.ServerSecTrust) ?? false);
var trustSec = (trustCallbackForUrl?.Invoke (sessionHandler, inflight.RequestUrl, challenge.ProtectionSpace.ServerSecTrust) ?? false) ||
simonrozsival marked this conversation as resolved.
Show resolved Hide resolved
(trustCallback?.Invoke (sessionHandler, challenge.ProtectionSpace.ServerSecTrust) ?? false) ||
(InvokeServerCertificateCustomValidationCallback (inflight.Request, challenge.ProtectionSpace.ServerSecTrust));
#endif

if (trustSec) {
Expand Down Expand Up @@ -973,6 +969,44 @@ public override void DidReceiveChallenge (NSUrlSession session, NSUrlSessionTask
}
}

bool InvokeServerCertificateCustomValidationCallback (HttpRequestMessage request, SecTrust secTrust)
{
if (sessionHandler.ServerCertificateCustomValidationCallback is null)
return false;

var originalChain = secTrust.GetCertificateChain (); // TODO does this work for older iOS and mac versions?
simonrozsival marked this conversation as resolved.
Show resolved Hide resolved
var certificates = new X509Certificate2 [originalChain.Length];
for (int i = 0; i < originalChain.Length; ++i)
certificates [i] = originalChain [i].ToX509Certificate2 ();

X509Certificate2? certificate = certificates.Length > 0 ? certificates [0] : null;

// TODO is NSURLAuthenticationMethodServerTrust used for every request or only when there is a problem
simonrozsival marked this conversation as resolved.
Show resolved Hide resolved
// with the remote certificate?
var sslPolicyErrors = SslPolicyErrors.None;
// var sslPolicyErrors = SslPolicyErrors.RemoteCertificateChainErrors;

// the chain initialization is based on dotnet/runtime implementation in System.Net.Security.SecureChannel
simonrozsival marked this conversation as resolved.
Show resolved Hide resolved
var chain = new X509Chain ();
chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
chain.ChainPolicy.ExtraStore.AddRange (certificates);

// TODO the Build function doesn't work on Android, but maybe it works on iOS/OSX?
try {
if (certificate is null) {
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNotAvailable;
}
else if (!chain.Build (certificate)) {
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateChainErrors;
}
} catch {
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateChainErrors;
}

return sessionHandler.ServerCertificateCustomValidationCallback (request, certificate, chain, sslPolicyErrors);
}

static readonly string RejectProtectionSpaceAuthType = "reject";

static bool TryGetAuthenticationType (NSUrlProtectionSpace protectionSpace, [NotNullWhen (true)] out string? authenticationType)
Expand Down
93 changes: 93 additions & 0 deletions tests/monotouch-test/System.Net.Http/MessageHandlers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,58 @@ public void RejectSslCertificatesServicePointManager (Type handlerType)
}
}

[Test]
public void RejectSslCertificatesWithCustomValidationCallbackNSUrlSessionHandler ()
{
TestRuntime.AssertSystemVersion (ApplePlatform.MacOSX, 10, 9, throwIfOtherPlatform: false);
TestRuntime.AssertSystemVersion (ApplePlatform.iOS, 7, 0, throwIfOtherPlatform: false);

#if __MACOS__
if (TestRuntime.CheckSystemVersion (ApplePlatform.MacOSX, 10, 10, 0) && !TestRuntime.CheckSystemVersion (ApplePlatform.MacOSX, 10, 11, 0))
Assert.Ignore ("Fails on macOS 10.10: https://github.com/xamarin/maccore/issues/1645");
#endif

bool validationCbWasExecuted = false;
bool done = false;
Exception ex = null;
Type expectedExceptionType = null;
HttpResponseMessage result = null;

var handler = new NSUrlSessionHandler {
ServerCertificateCustomValidationCallback = (sender, certificate, chain, errors) => {
validationCbWasExecuted = true;
// return false, since we want to test that the exception is raised
return false;
}
};

TestRuntime.RunAsync (DateTime.Now.AddSeconds (30), async () =>
{
try {
HttpClient client = new HttpClient (handler);
client.BaseAddress = NetworkResources.Httpbin.Uri;
var byteArray = new UTF8Encoding ().GetBytes ("username:password");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue ("Basic", Convert.ToBase64String(byteArray));
result = await client.GetAsync (NetworkResources.Httpbin.GetRedirectUrl (3));
} catch (Exception e) {
ex = e;
} finally {
done = true;
}
}, () => done);

if (!done) { // timeouts happen in the bots due to dns issues, connection issues etc.. we do not want to fail
Assert.Inconclusive ("Request timedout.");
} else {
Assert.True (validationCbWasExecuted, "Validation Callback called");
// assert the exception type
Assert.IsNotNull (ex, (result == null)? "Expected exception is missing and got no result" : $"Expected exception but got {result.Content.ReadAsStringAsync ().Result}");
Assert.IsInstanceOf (typeof (HttpRequestException), ex, "Exception type");
Assert.IsNotNull (ex.InnerException, "InnerException");
Assert.IsInstanceOf (expectedExceptionType, ex.InnerException, "InnerException type");
}
}

#if !__WATCHOS__
[TestCase (typeof (HttpClientHandler))]
#endif
Expand Down Expand Up @@ -546,6 +598,47 @@ public void AcceptSslCertificatesServicePointManager (Type handlerType)
}
}

[Test]
public void AcceptSslCertificatesWithCustomValidationCallbackNSUrlSessionHandler ()
{
TestRuntime.AssertSystemVersion (ApplePlatform.MacOSX, 10, 9, throwIfOtherPlatform: false);
TestRuntime.AssertSystemVersion (ApplePlatform.iOS, 7, 0, throwIfOtherPlatform: false);

bool callbackWasExecuted = false;
bool done = false;
Exception ex = null;

var handler = new NSUrlSessionHandler {
ServerCertificateCustomValidationCallback = (sender, certificate, chain, errors) => {
callbackWasExecuted = true;
return true;
}
};

TestRuntime.RunAsync (DateTime.Now.AddSeconds (30), async () =>
{
try {
var client = new HttpClient (handler);
var result = await client.GetAsync ("https://self-signed.badssl.com/"); // TODO move the URL to a constant
} catch (Exception e) {
ex = e;
} finally {
done = true;
}
}, () => done);

if (!done) { // timeouts happen in the bots due to dns issues, connection issues etc.. we do not want to fail
Assert.Inconclusive ("Request timedout.");
} else {
Assert.True (validationCbWasExecuted, "Validation Callback called");
// assert that we did not get an exception
if (ex != null && ex.InnerException != null) {
// we could get here.. if we have a diff issue, in that case, lets get the exception message and assert is not the trust issue
Assert.AreNotEqual (ex.InnerException.Message, "Error: TrustFailure");
}
}
}

[Test]
public void AssertDefaultValuesNSUrlSessionHandler ()
{
Expand Down