diff --git a/Duplicati/Library/Backend/WEBDAV/Strings.cs b/Duplicati/Library/Backend/WEBDAV/Strings.cs index 96856a4ab..802a12797 100644 --- a/Duplicati/Library/Backend/WEBDAV/Strings.cs +++ b/Duplicati/Library/Backend/WEBDAV/Strings.cs @@ -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"); } } } } diff --git a/Duplicati/Library/Backend/WEBDAV/WEBDAV.cs b/Duplicati/Library/Backend/WEBDAV/WEBDAV.cs index b211b3638..68979c14c 100644 --- a/Duplicati/Library/Backend/WEBDAV/WEBDAV.cs +++ b/Duplicati/Library/Backend/WEBDAV/WEBDAV.cs @@ -83,6 +83,16 @@ namespace Duplicati.Library.Backend // //private static readonly byte[] PROPFIND_BODY = System.Text.Encoding.UTF8.GetBytes(""); private static readonly byte[] PROPFIND_BODY = new byte[0]; + + /// + /// Option to accept any SSL certificate + /// + private readonly bool m_acceptAnyCertificate; + + /// + /// Specific hashes to be accepted by the certificate validator + /// + private readonly string[] m_acceptSpecificCertificates; /// /// 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")}"); diff --git a/Duplicati/Library/Utility/CallContextSettings.cs b/Duplicati/Library/Utility/CallContextSettings.cs index 23ce60dd2..7a0ddfe46 100644 --- a/Duplicati/Library/Utility/CallContextSettings.cs +++ b/Duplicati/Library/Utility/CallContextSettings.cs @@ -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.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) diff --git a/Duplicati/Library/Utility/HttpClientHelper.cs b/Duplicati/Library/Utility/HttpClientHelper.cs index 10cf1c6d5..82ac118c7 100644 --- a/Duplicati/Library/Utility/HttpClientHelper.cs +++ b/Duplicati/Library/Utility/HttpClientHelper.cs @@ -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; /// public static class HttpClientHelper { + + /// + /// 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. + /// + public static SslCertificateValidator CertificateValidator { get; set; } /// /// Central HttpClient singleton instance to be used across the application as @@ -72,4 +82,19 @@ public static class HttpClientHelper { return new HttpClient(handler); } + + /// + /// 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. + /// + /// The HttpClientHandler to be configured + /// If all certificates will be considered valid + /// List of hashes of certificates that will be accepted + public static void ConfigureHandlerCertificateValidator(HttpClientHandler handler, bool acceptAllCertificates, string[] acceptSpecificCertificateHashes) + { + var validator = new SslCertificateValidator(acceptAllCertificates, acceptSpecificCertificateHashes); + handler.ServerCertificateCustomValidationCallback = validator.ValidateServerCertificate; + } } \ No newline at end of file diff --git a/Duplicati/Library/Utility/SslCertificateValidator.cs b/Duplicati/Library/Utility/SslCertificateValidator.cs index f1245d699..e206e7586 100644 --- a/Duplicati/Library/Utility/SslCertificateValidator.cs +++ b/Duplicati/Library/Utility/SslCertificateValidator.cs @@ -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; } -} +} \ No newline at end of file