From 90352aa3238fdebd2570f2c622facf2bd1432345 Mon Sep 17 00:00:00 2001 From: Ivan Golubev Date: Thu, 10 Feb 2022 16:52:14 +0300 Subject: [PATCH] Add check the support of custom server certificate validation (#3738) * Add property IsCustomServerCertificateValidationSupported * Add using * Resolve comments * Update property * Update property * Fix EOL * Resolve comments --- src/Agent.Sdk/Util/VssUtil.cs | 44 +++++++++++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/src/Agent.Sdk/Util/VssUtil.cs b/src/Agent.Sdk/Util/VssUtil.cs index 5ca7591fea..7d85553bee 100644 --- a/src/Agent.Sdk/Util/VssUtil.cs +++ b/src/Agent.Sdk/Util/VssUtil.cs @@ -21,6 +21,11 @@ public static class VssUtil { private static UtilKnobValueContext _knobContext = UtilKnobValueContext.Instance(); + private const string _testUri = "https://microsoft.com/"; + private static bool? _isCustomServerCertificateValidationSupported; + + + public static void InitializeVssClientSettings(ProductInfoHeaderValue additionalUserAgent, IWebProxy proxy, IVssClientCertificateManager clientCert) { var headerValues = new List(); @@ -75,7 +80,7 @@ public static VssConnection CreateConnection( settings.AcceptLanguages.Remove(CultureInfo.InvariantCulture); // Setting `ServerCertificateCustomValidation` to able to capture SSL data for diagnostic - if (trace != null) + if (trace != null && IsCustomServerCertificateValidationSupported(trace)) { SslUtil sslUtil = new SslUtil(trace); settings.ServerCertificateValidationCallback = sslUtil.RequestStatusCustomValidation; @@ -106,5 +111,40 @@ public static VssCredentials GetVssCredential(ServiceEndpoint serviceEndpoint) return credentials; } + + public static bool IsCustomServerCertificateValidationSupported(ITraceWriter trace) + { + if (!PlatformUtil.RunningOnWindows && PlatformUtil.UseLegacyHttpHandler) + { + if (_isCustomServerCertificateValidationSupported == null) + { + _isCustomServerCertificateValidationSupported = CheckSupportOfCustomServerCertificateValidation(trace); + } + return (bool)_isCustomServerCertificateValidationSupported; + } + return true; + } + + private static bool CheckSupportOfCustomServerCertificateValidation(ITraceWriter trace) + { + using (var handler = new HttpClientHandler()) + { + handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; + + using (var client = new HttpClient(handler)) + { + try + { + client.GetAsync(_testUri).GetAwaiter().GetResult(); + } + catch (Exception) + { + trace.Verbose("The current system doesn't support custom server certificate validation."); + return false; + } + return true; + } + } + } } -} \ No newline at end of file +}