Created
December 2, 2020 13:24
-
-
Save alastairhm/a2b1b5e6adde9d9626d84e531adf39ed to your computer and use it in GitHub Desktop.
Python Class to get CA thumbprint from the root certificate, useful for AWS OIDC EKS cluters providers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import certifi | |
from OpenSSL import SSL | |
from eks_oidc.logger import Logger | |
logger = Logger(__name__).get_logger() | |
class ThumbNail: | |
"""Generate CA thumbnail.""" | |
def __init__(self, url): | |
"""Init.""" | |
self.url = url | |
self.cert_url = self.url.split("/")[2] | |
self.cert_chain_print = [] | |
self.thumbnail = "" | |
try: | |
self.get_cert_chain() | |
except Exception as e: | |
logger.exception( | |
"Exception openning socket for the CERT" + repr(e) | |
) | |
def get_cert_chain(self): | |
"""Get the URLs certificate chain.""" | |
hostname = self.cert_url | |
port = 443 | |
context = SSL.Context(method=SSL.TLSv1_METHOD) | |
context.load_verify_locations(cafile=certifi.where()) | |
conn = SSL.Connection( | |
context, socket=socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
) | |
conn.settimeout(5) | |
conn.connect((hostname, port)) | |
conn.setblocking(1) | |
conn.do_handshake() | |
conn.set_tlsext_host_name(hostname.encode()) | |
for (idx, cert) in enumerate(conn.get_peer_cert_chain()): | |
logger.debug(f"{idx} subject: {cert.get_subject()}") | |
logger.debug(f" issuer: {cert.get_issuer()})") | |
logger.debug(f' fingerprint: {cert.digest("sha1")}') | |
self.cert_chain_print.append( | |
cert.digest("sha1").decode("utf8").replace(":", "").lower() | |
) | |
self.thumbnail = self.cert_chain_print[-1] | |
def get_thumbnail(self): | |
return self.thumbnail |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment