3

I wish to make a verified request (using Python 3.5's urllib) to a URL that is using my self-signed certificate.

Here is a minimal example:

import ssl
from urllib.request import urlopen
from urllib.error import URLError

# <version 1>
ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
ssl_ctx.verify_mode = ssl.CERT_REQUIRED
ssl_ctx.load_cert_chain(certfile="/path/to/cert.pem", keyfile="/path/to/cert.key")
# </version 1>

try:
    urlopen("https://localhost/", context=ssl_ctx)
except URLError as e:
    print(e)

This prints:

<urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:720)>
  • I checked the value of ssl_ctx.get_ca_certs() -> []
  • I also check the value of ssl_ctx.cert_store_stats() -> {'x509_ca': 0, 'crl': 0, 'x509': 0}

As pointed by an answer given for Python 3 urllib with self-signed certificates, I can work around this with:

# <version 2>
ssl_ctx = ssl.create_default_context()
ssl_ctx.check_hostname = False
ssl_ctx.verify_mode = ssl.CERT_NONE
# </version 2>

But is there a way to actually verify my cert?

Chen Levy
  • 15,438
  • 17
  • 74
  • 92
  • What specifically do you want to verify? – Oliver Charlesworth Sep 27 '18 at 14:59
  • 1
    @oliver-charlesworth, I want to verify that the ssl cert I get is indeed *my* self singed cert, or put an ither way, given I trust my self singed key, my ssl session should be valid, and hence there are no man in the middle shananigens here. – Chen Levy Sep 27 '18 at 16:45
  • I believe this question has been answered here: https://stackoverflow.com/a/52961564/515368 – supermitch Jul 15 '21 at 16:07

0 Answers0