Last active
January 2, 2026 03:51
-
-
Save stephenbradshaw/a2b72b5b58c93ca74b54f7747f18a481 to your computer and use it in GitHub Desktop.
Python 3 Simple HTTPS server (versions for above and below python3.7 and helper script to generate certificate)
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
| #!/usr/bin/env python | |
| import http.server | |
| import ssl | |
| # Create certifcate and key: https://github.com/stephenbradshaw/pentesting_stuff/blob/master/example_code/create_self_signed_https_certs.py | |
| context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) | |
| context.load_cert_chain(certfile="https_self_signed_cert.pem", keyfile="https_self_signed_key.pem") | |
| httpd = http.server.HTTPServer(('127.0.0.1', 443), http.server.SimpleHTTPRequestHandler) | |
| httpd.socket = context.wrap_socket(httpd.socket, server_side=True) | |
| httpd.serve_forever() |
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
| #!/usr/bin/env python | |
| import datetime | |
| import ipaddress | |
| from cryptography import x509 | |
| from cryptography.hazmat.primitives import hashes, serialization | |
| from cryptography.hazmat.primitives.asymmetric import rsa | |
| from cryptography.x509.oid import NameOID | |
| # Creates a self signed CA cert that can be used for a local https server | |
| def generate_private_key(exp: int=65537, size: int=2048, both: bool=True, pem: bool=False, pkcs8: bool=True): | |
| private_key = rsa.generate_private_key(public_exponent=exp, key_size=size) | |
| enc = serialization.PrivateFormat.PKCS8 if pkcs8 else serialization.PrivateFormat.TraditionalOpenSSL | |
| if both: | |
| return [private_key, private_key.private_bytes(encoding=serialization.Encoding.PEM,format=enc, encryption_algorithm=serialization.NoEncryption()).decode()] | |
| elif pem: | |
| return private_key.private_bytes(encoding=serialization.Encoding.PEM,format=enc, encryption_algorithm=serialization.NoEncryption()).decode() | |
| else: | |
| return private_key | |
| def create_certificate(signing_key: rsa.RSAPrivateKey, subject_name: str, issuer_name: str=None, | |
| public_key: rsa.RSAPublicKey=None, dns_names: list=[], ip_addresses: list=[] ) -> x509.Certificate: | |
| '''Creates a cert''' | |
| is_ca = False | |
| subject = x509.Name([ | |
| x509.NameAttribute(NameOID.COMMON_NAME, subject_name), | |
| ]) | |
| if issuer_name: | |
| issuer = x509.Name([ | |
| x509.NameAttribute(NameOID.COMMON_NAME, issuer_name), | |
| ]) | |
| else: | |
| issuer = x509.Name([ | |
| x509.NameAttribute(NameOID.COMMON_NAME, subject_name), | |
| ]) | |
| if not public_key: # this will be a CA cert if no seperate public key provided | |
| pub = signing_key.public_key() | |
| is_ca = True | |
| else: | |
| pub = public_key | |
| now = datetime.datetime.now(datetime.timezone.utc) | |
| builder = x509.CertificateBuilder() | |
| builder = builder.subject_name(subject) | |
| builder = builder.issuer_name(issuer) | |
| builder = builder.public_key(pub) | |
| builder = builder.serial_number(x509.random_serial_number()) | |
| builder = builder.not_valid_before(now - datetime.timedelta(days=1)) | |
| builder = builder.not_valid_after(now + datetime.timedelta(days=365*10)) | |
| builder = builder.add_extension(x509.BasicConstraints(ca=is_ca, path_length=None), critical=True) | |
| builder = builder.add_extension( | |
| x509.SubjectKeyIdentifier(digest=x509.SubjectKeyIdentifier.from_public_key(pub)).digest, | |
| critical=False | |
| ) | |
| builder = builder.add_extension( | |
| x509.KeyUsage(digital_signature=True, content_commitment=True, key_encipherment=True, | |
| data_encipherment=False, key_agreement=True, key_cert_sign=True, crl_sign=True, | |
| encipher_only=False, decipher_only=False), | |
| critical=True | |
| ) | |
| if dns_names or ip_addresses: | |
| names = [] | |
| for dns_name in dns_names: | |
| names.append(x509.DNSName(dns_name)) | |
| for ip_address in ip_addresses: | |
| names.append(x509.IPAddress(ipaddress.ip_address(ip_address))) | |
| builder = builder.add_extension(x509.SubjectAlternativeName(names), critical=False) | |
| cert = builder.sign(signing_key, hashes.SHA256()) | |
| return cert | |
| def write_certificate(cert: x509.Certificate, filename: str) -> int: | |
| '''Write certificate object to file in PEM format''' | |
| return open(filename, 'wb').write(cert.public_bytes(serialization.Encoding.PEM)) | |
| if __name__ == "__main__": | |
| root_key, root_key_file = generate_private_key(both=True) | |
| ca_cert = create_certificate(root_key, 'localhost', dns_names=['localhost'], ip_addresses=['127.0.0.1']) | |
| open('https_self_signed_key.pem', 'w').write(root_key_file) | |
| write_certificate(ca_cert, 'https_self_signed_cert.pem') |
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
| #!/usr/bin/env python3 | |
| # python3 update of https://gist.github.com/dergachev/7028596 | |
| # No longer works after Python 3.7 | |
| # Create a basic certificate using openssl: | |
| # openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes | |
| # Or to set CN, SAN and/or create a cert signed by your own root CA: https://thegreycorner.com/pentesting_stuff/writeups/selfsignedcert.html | |
| import http.server | |
| import ssl | |
| httpd = http.server.HTTPServer(('127.0.0.1', 443), http.server.SimpleHTTPRequestHandler) | |
| httpd.socket = ssl.wrap_socket (httpd.socket, certfile='./server.pem', server_side=True) | |
| httpd.serve_forever() |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@BagroSlave Could be a Windows thing with parsing the PEM file in the Python ssl library. You might want to try modifying the load_cert_chain line to specify the key file specifically, as discussed here. Maybe also seperate the key content into a different file from the cert, make sure the openssl command line can still parse both as with the commands above, and try either Windows or Linux line ending patterns in the PEM file in case thats causing a parsing error in Python ssl. If none of that works Im out of ideas.