2019-03-29 02:20:40 +00:00
using System.Linq ;
using System.Net ;
using System.Net.Security ;
using System.Security.Cryptography.X509Certificates ;
using NLog ;
using NzbDrone.Common.Extensions ;
using NzbDrone.Core.Configuration ;
2019-04-11 02:34:21 +00:00
using NzbDrone.Core.Lifecycle ;
using NzbDrone.Core.Messaging.Events ;
2019-03-29 02:20:40 +00:00
namespace NzbDrone.Core.Security
{
2019-04-11 02:34:21 +00:00
public class X509CertificateValidationService : IHandle < ApplicationStartedEvent >
2019-03-29 02:20:40 +00:00
{
private readonly IConfigService _configService ;
private readonly Logger _logger ;
2019-04-11 02:34:21 +00:00
public X509CertificateValidationService ( IConfigService configService , Logger logger )
2019-03-29 02:20:40 +00:00
{
_configService = configService ;
_logger = logger ;
}
private bool ShouldByPassValidationError ( object sender , X509Certificate certificate , X509Chain chain , SslPolicyErrors sslPolicyErrors )
{
var request = sender as HttpWebRequest ;
if ( request = = null )
{
return true ;
}
var cert2 = certificate as X509Certificate2 ;
2019-04-11 02:34:21 +00:00
if ( cert2 ! = null & & request ! = null & & cert2 . SignatureAlgorithm . FriendlyName = = "md5RSA" )
2019-03-29 02:20:40 +00:00
{
2019-04-11 02:34:21 +00:00
_logger . Error ( "https://{0} uses the obsolete md5 hash in it's https certificate, if that is your certificate, please (re)create certificate with better algorithm as soon as possible." , request . RequestUri . Authority ) ;
2019-03-29 02:20:40 +00:00
}
if ( sslPolicyErrors = = SslPolicyErrors . None )
{
return true ;
}
2021-01-14 21:04:54 +00:00
if ( request . RequestUri . Host = = "localhost" | | request . RequestUri . Host = = "127.0.0.1" )
{
return true ;
}
2019-04-11 16:00:59 +00:00
var ipAddresses = GetIPAddresses ( request . RequestUri . Host ) ;
2019-03-29 02:20:40 +00:00
var certificateValidation = _configService . CertificateValidation ;
if ( certificateValidation = = CertificateValidationType . Disabled )
{
return true ;
}
2019-04-10 03:57:12 +00:00
if ( certificateValidation = = CertificateValidationType . DisabledForLocalAddresses & &
2020-04-27 21:58:35 +00:00
ipAddresses . All ( i = > i . IsLocalAddress ( ) ) )
2019-03-29 02:20:40 +00:00
{
return true ;
}
_logger . Error ( "Certificate validation for {0} failed. {1}" , request . Address , sslPolicyErrors ) ;
return false ;
}
2019-04-11 02:34:21 +00:00
private IPAddress [ ] GetIPAddresses ( string host )
{
if ( IPAddress . TryParse ( host , out var ipAddress ) )
{
2021-08-03 04:43:28 +00:00
return new [ ] { ipAddress } ;
2019-04-11 02:34:21 +00:00
}
return Dns . GetHostEntry ( host ) . AddressList ;
}
public void Handle ( ApplicationStartedEvent message )
{
ServicePointManager . ServerCertificateValidationCallback = ShouldByPassValidationError ;
}
2019-03-29 02:20:40 +00:00
}
}