Fix to Webdav issue around certificate validation

Fix to Webdav to process the options accept-specified-ssl-hash and accept-any-ssl-certificate

Minor refactoring
This commit is contained in:
Marcelo Ceccon
2024-10-09 16:15:05 +02:00
parent bf7d0f18f5
commit 5d49ee9ef4
5 changed files with 116 additions and 85 deletions
@@ -40,5 +40,9 @@ Error message: {3}", foldername, filename, extension, errormessage); }
public static string DescriptionUseSSLShort { get { return LC.L(@"Instruct Duplicati to use an SSL (https) connection"); } }
public static string DescriptionDebugPropfindLong { get { return LC.L(@"To aid in debugging issues, it is possible to set a path to a file that will be overwritten with the PROPFIND response."); } }
public static string DescriptionDebugPropfindShort { get { return LC.L(@"Dump the PROPFIND response"); } }
public static string DescriptionAcceptAnyCertificateLong { get { return LC.L(@"Use this option to accept any server certificate, regardless of what errors it may have. Please use --{0} instead, whenever possible.", "accept-specified-ssl-hash"); } }
public static string DescriptionAcceptAnyCertificateShort { get { return LC.L(@"Accept any server certificate"); } }
public static string DescriptionAcceptHashLong2 { get { return LC.L(@"If your server certificate is reported as invalid (e.g. with self-signed certificates), you can supply the certificate hash (SHA1) to approve it anyway. The hash value must be entered in hex format without spaces or colons. You can enter multiple hashes separated by commas."); } }
public static string DescriptionAcceptHashShort { get { return LC.L(@"Optionally accept a known SSL certificate"); } }
}
}
+24 -12
View File
@@ -83,6 +83,16 @@ namespace Duplicati.Library.Backend
//
//private static readonly byte[] PROPFIND_BODY = System.Text.Encoding.UTF8.GetBytes("<?xml version=\"1.0\"?><D:propfind xmlns:D=\"DAV:\"><D:allprop/></D:propfind>");
private static readonly byte[] PROPFIND_BODY = new byte[0];
/// <summary>
/// Option to accept any SSL certificate
/// </summary>
private readonly bool m_acceptAnyCertificate;
/// <summary>
/// Specific hashes to be accepted by the certificate validator
/// </summary>
private readonly string[] m_acceptSpecificCertificates;
/// <summary>
/// The default timeout in seconds for PUT/GET file operations
@@ -150,6 +160,8 @@ namespace Duplicati.Library.Backend
m_rawurlPort = new Utility.Uri(m_useSSL ? "https" : "http", u.Host, m_path, null, null, null, port).ToString();
m_sanitizedUrl = new Utility.Uri(m_useSSL ? "https" : "http", u.Host, m_path).ToString();
m_reverseProtocolUrl = new Utility.Uri(m_useSSL ? "http" : "https", u.Host, m_path).ToString();
m_acceptAnyCertificate = options.ContainsKey("accept-any-ssl-certificate") && Utility.Utility.ParseBoolOption(options, "accept-any-ssl-certificate");
m_acceptSpecificCertificates = options.ContainsKey("accept-specified-ssl-hash") ? options["accept-specified-ssl-hash"].Split([",", ";"], StringSplitOptions.RemoveEmptyEntries): null;
}
#region IBackend Members
@@ -314,6 +326,8 @@ namespace Duplicati.Library.Backend
new CommandLineArgument("integrated-authentication", CommandLineArgument.ArgumentType.Boolean, Strings.WEBDAV.DescriptionIntegratedAuthenticationShort, Strings.WEBDAV.DescriptionIntegratedAuthenticationLong),
new CommandLineArgument("force-digest-authentication", CommandLineArgument.ArgumentType.Boolean, Strings.WEBDAV.DescriptionForceDigestShort, Strings.WEBDAV.DescriptionForceDigestLong),
new CommandLineArgument("use-ssl", CommandLineArgument.ArgumentType.Boolean, Strings.WEBDAV.DescriptionUseSSLShort, Strings.WEBDAV.DescriptionUseSSLLong),
new CommandLineArgument("accept-any-ssl-certificate", CommandLineArgument.ArgumentType.Boolean, Strings.WEBDAV.DescriptionAcceptAnyCertificateShort, Strings.WEBDAV.DescriptionAcceptAnyCertificateLong),
new CommandLineArgument("accept-specified-ssl-hash", CommandLineArgument.ArgumentType.String, Strings.WEBDAV.DescriptionAcceptHashShort, Strings.WEBDAV.DescriptionAcceptHashLong2)
});
}
}
@@ -357,33 +371,31 @@ namespace Duplicati.Library.Backend
private RequestResources CreateRequest(string remotename, HttpMethod method = null)
{
HttpClient httpClient;
HttpClientHandler httpHandler = new HttpClientHandler();
HttpClientHelper.ConfigureHandlerCertificateValidator(httpHandler, m_acceptAnyCertificate, m_acceptSpecificCertificates);
if (m_useIntegratedAuthentication)
{
httpClient = HttpClientHelper.CreateClient(new HttpClientHandler
{
UseDefaultCredentials = true
});
httpHandler.UseDefaultCredentials = true;
httpClient = HttpClientHelper.CreateClient(httpHandler);
}
else if (m_forceDigestAuthentication)
{
httpClient = HttpClientHelper.CreateClient(new HttpClientHandler
httpHandler.Credentials = new CredentialCache
{
Credentials = new CredentialCache
{
{ new System.Uri(m_url), "Digest", m_userInfo }
}
});
{ new System.Uri(m_url), "Digest", m_userInfo }
};
httpClient = HttpClientHelper.CreateClient(httpHandler);
}
else
{
httpClient = HttpClientHelper.CreateClient();
httpClient = HttpClientHelper.CreateClient(httpHandler);
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{m_userInfo.UserName}:{m_userInfo.Password}"))
);
}
httpClient.Timeout = Timeout.InfiniteTimeSpan;
var request = new HttpRequestMessage(HttpMethod.Get, $"{m_url}{Utility.Uri.UrlEncode(remotename).Replace("+", "%20")}");
@@ -172,7 +172,7 @@ namespace Duplicati.Library.Utility
{
// If we have a custom SSL validator, invoke it
if (HttpContextSettings.CertificateValidator != null)
return CertificateValidator.ValidateServerCertficate(sender, certificate, chain, sslPolicyErrors);
return CertificateValidator.ValidateServerCertificate(sender, certificate, chain, sslPolicyErrors);
// Default is to only approve certificates without errors
var result = sslPolicyErrors == SslPolicyErrors.None;
@@ -183,7 +183,7 @@ namespace Duplicati.Library.Utility
foreach (var v in CallContextSettings<HttpSettings>.GetAllInstances())
if (v.CertificateValidator != null)
{
var t = v.CertificateValidator.ValidateServerCertficate(sender, certificate, chain, sslPolicyErrors);
var t = v.CertificateValidator.ValidateServerCertificate(sender, certificate, chain, sslPolicyErrors);
// First instance overrides framework result
if (!any)
@@ -19,7 +19,10 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Net.Http;
using Duplicati.Library.Interface;
namespace Duplicati.Library.Utility;
@@ -30,6 +33,13 @@ namespace Duplicati.Library.Utility;
/// </summary>
public static class HttpClientHelper
{
/// <summary>
/// Globally configured certificate validator to be used across the application.
/// Each backend can choose when creating the httpclient/requesthandler if it will
/// use this or the default (null) validator.
/// </summary>
public static SslCertificateValidator CertificateValidator { get; set; }
/// <summary>
/// Central HttpClient singleton instance to be used across the application as
@@ -72,4 +82,19 @@ public static class HttpClientHelper
{
return new HttpClient(handler);
}
/// <summary>
/// Configures the httphandler with the certificate validator, if needed.
///
/// The parameters indicate if it should accept all certificates or only the ones specified in the
/// hashes array.
/// </summary>
/// <param name="handler">The HttpClientHandler to be configured</param>
/// <param name="acceptAllCertificates">If all certificates will be considered valid</param>
/// <param name="acceptSpecificCertificateHashes">List of hashes of certificates that will be accepted</param>
public static void ConfigureHandlerCertificateValidator(HttpClientHandler handler, bool acceptAllCertificates, string[] acceptSpecificCertificateHashes)
{
var validator = new SslCertificateValidator(acceptAllCertificates, acceptSpecificCertificateHashes);
handler.ServerCertificateCustomValidationCallback = validator.ValidateServerCertificate;
}
}
@@ -1,89 +1,79 @@
// Copyright (C) 2024, The Duplicati Team
// https://duplicati.com, hello@duplicati.com
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// Copyright (C) 2024, The Duplicati Team
// https://duplicati.com, hello@duplicati.com
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using Duplicati.Library.Common;
using System.Security.Cryptography.X509Certificates;
namespace Duplicati.Library.Utility
namespace Duplicati.Library.Utility;
public class SslCertificateValidator(bool acceptAll, string[] validHashes)
{
public class SslCertificateValidator
[Serializable]
public class InvalidCertificateException : Exception
{
[Serializable]
public class InvalidCertificateException : Exception
private readonly string m_certificate;
private readonly SslPolicyErrors m_errors = SslPolicyErrors.None;
public string Certificate => m_certificate;
public SslPolicyErrors SslError => m_errors;
public InvalidCertificateException(string certificate, SslPolicyErrors error)
: base(Strings.SslCertificateValidator.VerifyCertificateException(error, certificate))
{
private readonly string m_certificate = null;
private readonly SslPolicyErrors m_errors = SslPolicyErrors.None;
public string Certificate { get { return m_certificate; } }
public SslPolicyErrors SslError { get { return m_errors; } }
public InvalidCertificateException(string certificate, SslPolicyErrors error)
: base(Strings.SslCertificateValidator.VerifyCertificateException(error, certificate))
{
m_certificate = certificate;
m_errors = error;
}
m_certificate = certificate;
m_errors = error;
}
}
public SslCertificateValidator(bool acceptAll, string[] validHashes)
public bool ValidateServerCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
if (acceptAll)
return true;
string certHash;
try
{
m_acceptAll = acceptAll;
m_validHashes = validHashes;
}
private readonly bool m_acceptAll = false;
private readonly string[] m_validHashes = null;
public bool ValidateServerCertficate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
if (m_acceptAll)
return true;
string certHash = null;
try
certHash = Utility.ByteArrayAsHexString(cert.GetCertHash());
if (certHash != null && validHashes != null)
{
certHash = Utility.ByteArrayAsHexString(cert.GetCertHash());
if (certHash != null && m_validHashes != null)
foreach (var hash in validHashes)
{
foreach (var hash in m_validHashes)
if (!string.IsNullOrEmpty(hash) && certHash.Equals(hash, StringComparison.OrdinalIgnoreCase))
{
if (!string.IsNullOrEmpty(hash) && certHash.Equals(hash, StringComparison.OrdinalIgnoreCase))
{
return true;
}
return true;
}
}
}
catch (Exception ex)
{
throw new Exception(Strings.SslCertificateValidator.VerifyCertificateHashError(ex, sslPolicyErrors), ex);
}
return false;
}
catch (Exception ex)
{
throw new Exception(Strings.SslCertificateValidator.VerifyCertificateHashError(ex, sslPolicyErrors), ex);
}
return false;
}
}
}