Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch the SSL certificate to see whether it's expired or not

I am not getting any output from this code.The good thing is that i am not getting any error.Please tell me where i am doing wrong.Here is my Code or any alternative way to find the expired date of the ssl certificate(using Python only)

import datetime
import logging
import socket
import ssl

YOUR_DOMAIN = 'google.com'
WARNING_BUFFER = 14

logger = logging.getLogger()
logger.setLevel(logging.INFO)

ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'

class AlreadyExpired(Exception):
    pass

def ssl_expires_in(hostname, buffer_days=14):
    """Gets the SSL cert from a given hostname and checks if it expires within buffer_days"""
    context = ssl.create_default_context()
    conn = context.wrap_socket(
        socket.socket(socket.AF_INET),
        server_hostname=hostname,

    )
    # 3 second timeout because Lambda has runtime limitations
    conn.settimeout(3.0)
    conn.connect((hostname, 443))
    ssl_info = conn.getpeercert()
    expires = datetime.datetime.strptime(ssl_info['notAfter'], ssl_date_fmt)

    # if the cert expires in less than two weeks, we should reissue it
    if expires < (datetime.datetime.utcnow() + datetime.timedelta(days=buffer_days)):
        # expires sooner than the buffer
        return True
    elif expires < datetime.datetime.utcnow():
        # cert has already expired - uhoh!
        raise AlreadyExpired("Cert expired at %s" % ssl_info['notAfter'])
    else:
        # everything is fine
        return False


def lambda_handler(event, context):
    try:
        if not ssl_expires_in(YOUR_DOMAIN, WARNING_BUFFER):
            logger.info("SSL certificate doesn't expire for a while - you're set!")
            return {"success": True, "cert_status": "valid"}
        else:
            logger.warning("SSL certificate expires soon")
            return {"success": True, "cert_status": "expiring soon"}
    except AlreadyExpired as e:
        logger.exception("Certificate is expired, get worried!")
        return {"success": True, "cert_status": "expired"}
    except Exception as e:
        logger.exception("Failed to get certificate info")
        return {"success": False, "cert_status": "unknown"}
like image 490
Balvinder Singh Avatar asked Mar 09 '23 06:03

Balvinder Singh


1 Answers

You can do it with "pyOpenSSL"(pip install pyOpenSSL) and "ssl"(inbuilt in python) packages.

import ssl
import OpenSSL

def get_SSL_Expiry_Date(host, port):
    cert = ssl.get_server_certificate((host, port))
    x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
    print(x509.get_notAfter())

get_SSL_Expiry_Date("google.com", 443)

Output: b'20181113080500Z'

Or you can do it only with python like this:

import ssl
import socket
import datetime

def ssl_expiry_datetime(host, port=443):
    ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'

    context = ssl.create_default_context()
    conn = context.wrap_socket(
        socket.socket(socket.AF_INET),
        server_hostname=host,
    )
    # 3 second timeout because Lambda has runtime limitations
    conn.settimeout(3.0)
    conn.connect((host, port))
    ssl_info = conn.getpeercert()
    print(ssl_info)
    # parse the string from the certificate into a Python datetime object
    res = datetime.datetime.strptime(ssl_info['notAfter'], ssl_date_fmt)
    return res

print(ssl_expiry_datetime("google.com"))

Output: 2018-11-13 08:04:00

like image 127
Suman Niroula Avatar answered Apr 06 '23 09:04

Suman Niroula