Don't Log 'Certificate did not match expected hostname' Error Messages

Viewed 9019

My web app requests several URLs and sometimes SSL certificate errors are raised. They are all third party URLs so I can't fix their errors and I prefer not to log them. Nevertheless, something is logging this by itself: 2017-08-05 00:22:49,496 ERROR -- : Certificate did not match expected hostname: www.improving-autonomy.org. Certificate: {'subjectAltName': [('DNS', '*.wordpress.com'), ('DNS', 'wordpress.com')], 'subject': ((('commonName', u'*.wordpress.com'),),)} Anyone knows how can I stop it? Please find my code bellow. Many thanks in advance!

try :
    ua = UserAgent()
    headers = {'Content-Type' : 'text/html', 'Accept-Encoding' : None, 'User-Agent' : ua.random}
    response = requests.get(url, headers=headers, timeout=10)
except ssl.CertificateError as e :
    pass

UPDATED -- : It looks like requests module logs it (connection.py). Why it keeps logging if I'm already catching the same exception?

def _match_hostname(cert, asserted_hostname):
    try:
        match_hostname(cert, asserted_hostname)
    except CertificateError as e:
        log.error(
            'Certificate did not match expected hostname: %s. '
            'Certificate: %s', asserted_hostname, cert
        )
    # Add cert to exception and reraise so client code can inspect
    # the cert when catching the exception, if they want to
    e._peer_cert = cert
    raise
2 Answers
Related