Created
June 2, 2020 21:56
-
-
Save kgriffs/36b618910d9332a3fffee71b6c3376fb to your computer and use it in GitHub Desktop.
Get TLS (SSL) certificate from peer in Python
This file contains hidden or 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 ssl | |
| import certifi | |
| _CERT_BUNDLE_PATH = certifi.where() | |
| class CertificateStatus(Enum): | |
| UNKNOWN = -1 | |
| CONNECTION_ERROR = 100 | |
| VALID = 200 | |
| INVALID = 500 | |
| def get_cert(host_ip, sni_name, port=443): | |
| context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) | |
| context.load_verify_locations(_CERT_BUNDLE_PATH) | |
| status = CertificateStatus.UNKNOWN | |
| peer_cert = None | |
| try: | |
| with socket.create_connection((host_ip, port), timeout=5) as sock: | |
| with context.wrap_socket(sock, server_hostname=sni_name) as ssock: | |
| peer_cert = ssock.getpeercert() | |
| status = CertificateStatus.VALID | |
| except ssl.SSLError as err: | |
| status = CertificateStatus.INVALID | |
| except Exception: | |
| status = CertificateStatus.CONNECTION_ERROR | |
| return status, peer_cert |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment