Skip to content

Commit

Permalink
Add check the support of custom server certificate validation (#3738)
Browse files Browse the repository at this point in the history
* Add property IsCustomServerCertificateValidationSupported

* Add using

* Resolve comments

* Update property

* Update property

* Fix EOL

* Resolve comments
  • Loading branch information
Ivan Golubev committed Feb 10, 2022
1 parent 0940cd3 commit 90352aa
Showing 1 changed file with 42 additions and 2 deletions.
44 changes: 42 additions & 2 deletions src/Agent.Sdk/Util/VssUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ProductInfoHeaderValue>();
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}
}
}
}
}
}

0 comments on commit 90352aa

Please sign in to comment.