Skip to content

Instantly share code, notes, and snippets.

@cddmp
Forked from DannyHinshaw/simple-https-server.py
Last active May 22, 2023 12:59
Show Gist options
  • Save cddmp/748e616ae1dc704e16200284e3bc4c3f to your computer and use it in GitHub Desktop.
Save cddmp/748e616ae1dc704e16200284e3bc4c3f to your computer and use it in GitHub Desktop.
# Originally taken from http://www.piware.de/2011/01/creating-an-https-server-in-python/
from http.server import HTTPServer, SimpleHTTPRequestHandler
import os, ssl, sys
# Unfortunately, this will only work if the client sends a request and does not only do a TCP 3-way handshake
class CustomRequestHandler(SimpleHTTPRequestHandler):
def handle_one_request(self):
print(f'[*] Incoming connection: {self.client_address[0]}')
return SimpleHTTPRequestHandler.handle_one_request(self)
port = 443
try:
if len(sys.argv) > 1:
port = int(sys.argv[1])
if not 1 <= port <= 2**16-1:
raise Exception
except:
print(f'Usage: {sys.argv[0]} [port]')
os._exit(1)
if not os.path.exists('key.pem') or not os.path.exists('cert.pem'):
os.system("openssl req -nodes -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -subj '/CN=mylocalhost'")
httpd = HTTPServer(('0.0.0.0', port), CustomRequestHandler)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER, keyfile='key.pem', certfile='cert.pem', server_side=True)
httpd.socket = context.wrap_socket(httpd.socket)
print(f"[*] Server running on https://0.0.0.0:{port}")
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment