-
-
Save SeanPesce/af5f6b7665305b4c45941634ff725b7a to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3 | |
# Author: Sean Pesce | |
# References: | |
# https://stackoverflow.com/questions/19705785/python-3-simple-https-server | |
# https://docs.python.org/3/library/ssl.html | |
# https://docs.python.org/3/library/http.server.html | |
# Shell command to create a self-signed TLS certificate and private key: | |
# openssl req -new -newkey rsa:4096 -x509 -sha256 -days 365 -nodes -out cert.crt -keyout private.key | |
import http.server | |
import ssl | |
import sys | |
def serve(host, port, cert_fpath, privkey_fpath): | |
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) # Might need to use ssl.PROTOCOL_TLS for older versions of Python | |
context.load_cert_chain(certfile=cert_fpath, keyfile=privkey_fpath, password='') | |
server_address = (host, port) | |
httpd = http.server.HTTPServer(server_address, http.server.SimpleHTTPRequestHandler) | |
httpd.socket = context.wrap_socket(httpd.socket, server_side=True) | |
httpd.serve_forever() | |
if __name__ == '__main__': | |
if len(sys.argv) < 4: | |
print(f'Usage:\n {sys.argv[0]} <port> <PEM certificate file> <private key file>') | |
sys.exit() | |
PORT = int(sys.argv[1]) | |
CERT_FPATH = sys.argv[2] | |
PRIVKEY_FPATH = sys.argv[3] | |
serve('0.0.0.0', PORT, CERT_FPATH, PRIVKEY_FPATH) |
The deprecation warning won't break anything for now, but I just fixed the code so that you won't get that warning anymore.
As far as the untrusted certificate, that's the expected behavior for self-signed keys (i.e., the ones generated in my example command). I don't recommend using this implementation for public/production servers, but if you really need a trusted certificate, it has to be signed by a trusted CA (the example commands I provided aren't sufficient). For more information on that, I'd recommend reading up on TLS and PKI.
The deprecation warning won't break anything for now, but I just fixed the code so that you won't get that warning anymore.
As far as the untrusted certificate, that's the expected behavior for self-signed keys (i.e., the ones generated in my example command). I don't recommend using this implementation for public/production servers, but if you really need a trusted certificate, it has to be signed by a trusted CA (the example commands I provided aren't sufficient). For more information on that, I'd recommend reading up on TLS and PKI.
thank you bro! i deleted my comment, thinking I was an idiot xD but your reply makes perfect sense!
This Python 3 script mimics the behavior of
python2.7 -m SimpleHTTPServer 80
andpython3 -m http.server 80
, but with support for SSL/TLS/HTTPS.Usage:
Example:
Example command to create a self-signed TLS certificate and private key: