Created
February 5, 2024 23:18
-
-
Save egglessness/a5c59f1e00ed43079779a91120387995 to your computer and use it in GitHub Desktop.
Helper functions to extract redirect chains and cert SAN
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 re | |
import ssl | |
import socket | |
import requests | |
import urllib3 | |
from OpenSSL import crypto | |
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) | |
def certificate_san(site, port=443): | |
site = _strip_schema(site) | |
context = ssl.create_default_context() | |
context.check_hostname = False | |
with socket.create_connection((site, port)) as sock: | |
with context.wrap_socket(sock, server_hostname=site) as ssock: | |
cert = ssock.getpeercert(binary_form=True) | |
x509 = crypto.load_certificate(crypto.FILETYPE_ASN1, cert) | |
san_list = [] | |
for i in range(x509.get_extension_count()): | |
ext = x509.get_extension(i) | |
if "subjectAltName" in ext.get_short_name().decode("utf-8"): | |
san_list.extend(str(ext).split(", ")) | |
return san_list | |
def redirect_chain(url): | |
url = _ensure_https(url) | |
chain = [url] | |
while True: | |
response = requests.get(url, verify=False, allow_redirects=False) | |
url = response.headers.get("Location") | |
if url is None: | |
break | |
chain.append(url) | |
return chain | |
def final_url(url): | |
url = _ensure_https(url) | |
response = requests.get(url, verify=False) | |
return response.url | |
def _ensure_https(url): | |
if not "https://" in url: | |
return "https://" + url | |
return url | |
def _strip_schema(url): | |
return re.sub("^https://", "", url) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment