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

Fixing the validation of the SSL CA Certificate #2143

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
15 changes: 8 additions & 7 deletions src/Confluent.SchemaRegistry/CachedSchemaRegistryClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,14 @@ public CachedSchemaRegistryClient(IEnumerable<KeyValuePair<string, string>> conf
try { sslVerify = sslVerificationMaybe.Value == null ? DefaultEnableSslCertificateVerification : bool.Parse(sslVerificationMaybe.Value); }
catch (FormatException) { throw new ArgumentException($"Configured value for {SchemaRegistryConfig.PropertyNames.EnableSslCertificateVerification} must be a bool."); }

this.restService = new RestService(schemaRegistryUris, timeoutMs, authenticationHeaderValueProvider, SetSslConfig(config), sslVerify);
var sslCaLocation = config.FirstOrDefault(prop => prop.Key.ToLower() == SchemaRegistryConfig.PropertyNames.SslCaLocation).Value;
if (string.IsNullOrEmpty(sslCaLocation))
{
this.restService = new RestService(schemaRegistryUris, timeoutMs, authenticationHeaderValueProvider, SetSslConfig(config), sslVerify);
} else
{
this.restService = new RestService(schemaRegistryUris, timeoutMs, authenticationHeaderValueProvider, SetSslConfig(config), sslVerify, new X509Certificate2(sslCaLocation));
}
}

/// <summary>
Expand Down Expand Up @@ -306,12 +313,6 @@ private bool CleanCacheIfFull()
                certificates.Add(new X509Certificate2(certificateLocation, certificatePassword));
            }

            var caLocation = config.FirstOrDefault(prop => prop.Key.ToLower() == SchemaRegistryConfig.PropertyNames.SslCaLocation).Value ?? "";
            if (!String.IsNullOrEmpty(caLocation))
            {
                certificates.Add(new X509Certificate2(caLocation));
            }

            return certificates;
        }

Expand Down
49 changes: 43 additions & 6 deletions src/Confluent.SchemaRegistry/Rest/RestService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

namespace Confluent.SchemaRegistry
{
Expand Down Expand Up @@ -57,7 +58,7 @@ internal class RestService : IRestService
/// <summary>
/// Initializes a new instance of the RestService class.
/// </summary>
public RestService(string schemaRegistryUrl, int timeoutMs, IAuthenticationHeaderValueProvider authenticationHeaderValueProvider, List<X509Certificate2> certificates, bool enableSslCertificateVerification)
public RestService(string schemaRegistryUrl, int timeoutMs, IAuthenticationHeaderValueProvider authenticationHeaderValueProvider, List<X509Certificate2> certificates, bool enableSslCertificateVerification, X509Certificate2 sslCaCertificate = null)
{
this.authenticationHeaderValueProvider = authenticationHeaderValueProvider;

Expand All @@ -69,7 +70,7 @@ internal class RestService : IRestService
HttpClient client;
                    if (certificates.Count > 0)
                    {
                        client = new HttpClient(CreateHandler(certificates, enableSslCertificateVerification)) { BaseAddress = new Uri(uri, UriKind.Absolute), Timeout = TimeSpan.FromMilliseconds(timeoutMs) };
                        client = new HttpClient(CreateHandler(certificates, enableSslCertificateVerification, sslCaCertificate)) { BaseAddress = new Uri(uri, UriKind.Absolute), Timeout = TimeSpan.FromMilliseconds(timeoutMs) };
                    }
                    else
                    {
Expand All @@ -86,17 +87,53 @@ private static string SanitizeUri(string uri)
return $"{sanitized.TrimEnd('/')}/";
}

private static HttpClientHandler CreateHandler(List<X509Certificate2> certificates, bool enableSslCertificateVerification)
private static HttpClientHandler CreateHandler(List<X509Certificate2> certificates, bool enableSslCertificateVerification, X509Certificate2 sslCaCertificate)
{
    var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;

    certificates.ForEach(c => handler.ClientCertificates.Add(c));

if (!enableSslCertificateVerification)
{
handler.ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, certChain, policyErrors) => { return true; };
}
handler.ServerCertificateCustomValidationCallback = (_, __, ___, ____) => { return true; };
}
else if (sslCaCertificate != null)
{
handler.ServerCertificateCustomValidationCallback = (_, __, chain, policyErrors) => {

if (policyErrors == SslPolicyErrors.None)
{
return true;
}

    certificates.ForEach(c => handler.ClientCertificates.Add(c));

//The second element of the chain should be the issuer of the certificate
if (chain.ChainElements.Count < 2)
{
return false;
}
var connectionCertHash = chain.ChainElements[1].Certificate.GetCertHash();


var expectedCertHash = sslCaCertificate.GetCertHash();

if (connectionCertHash.Length != expectedCertHash.Length)
{
return false;
}

for (int i = 0; i < connectionCertHash.Length; i++)
{
if (connectionCertHash[i] != expectedCertHash[i])
{
return false;
}
}
return true;
};
}

    return handler;
}

Expand Down