Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a SSL certificate expiration date with aiohttp?

I know how to get certificate information such as expiration date using pyopenssl for instance, but is it possible to do it with a aiohttp response object?

like image 567
azmeuk Avatar asked May 31 '17 09:05

azmeuk


People also ask

How can I check SSL certificate expiry date?

Chrome has made it simple for any site visitor to get certificate information with just a few clicks: Click the padlock icon in the address bar for the website. Click on Certificate (Valid) in the pop-up. Check the Valid from dates to validate the SSL certificate is current.

How do I know if SSL certificate expires with openssl?

You can check the expiration of the certificate (for example to help troubleshoot certificate issues). Open a UNIX command line window. Enter a query openssl s_client -servername <NAME> -connect <HOST:PORT> 2>/dev/null | openssl x509 -noout -dates .

What time does an SSL certificate expire?

TLS/SSL certificates cannot be issued for more than 13 months (397 days), as announced by popular browsers, like Google and Apple at CA/Browser Forum in March 2020. This has reduced the certificate validity period from three or two to just over a year.


2 Answers

I couldn't find it in the documentation of aiohttp, but you can use ssl to get the cert and OpenSSL to get it's notAfter date and compare it to your current date in order to figure out if it's expired or not. More details here How to import OpenSSL in python And a snippet of code that does pretty much what you need below You will need to install OpenSSL beforehand however

pip install pyopenssl

import OpenSSL
import ssl, socket
cert=ssl.get_server_certificate(('www.google.com', 443))
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
x509.get_notAfter()

For sites that make use of SNI, see the following answer on how to get the certificate ssl.get_server_certificate for sites with SNI (Server Name Indication)

like image 188
BoboDarph Avatar answered Sep 20 '22 09:09

BoboDarph


Previous answers are correct but, you could also use the socket lib (this is test with python 3.7)

from urllib.request import Request, urlopen, ssl, socket
from urllib.error import URLError, HTTPError
import json
#some site without http/https in the path
base_url = 'CHANGE_ME_TO_YOUR_SITE'
port = '443'

hostname = base_url
context = ssl.create_default_context()

with socket.create_connection((hostname, port)) as sock:
    with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        print(ssock.version())
        data = json.dumps(ssock.getpeercert())
        # print(ssock.getpeercert())

print (data)

enter image description here

like image 21
grepit Avatar answered Sep 20 '22 09:09

grepit