Skip to content

Instantly share code, notes, and snippets.

@casouri
Last active December 31, 2017 22:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save casouri/c40d82ce825e8900fc0f272fc7b1b242 to your computer and use it in GitHub Desktop.
Save casouri/c40d82ce825e8900fc0f272fc7b1b242 to your computer and use it in GitHub Desktop.
how to add ssl security to a personal server

Summary

  1. Creating self signed certificate
  2. Using ssl in python server
  3. Using ssl in requests

Creating self signed certificate

ref: https://www.digitalocean.com/community/tutorials/openssl-essentials-working-with-ssl-certificates-private-keys-and-csrs

Keep private key safe!

# 2048 bit, no password, private key: root.key, self-signed certificate: root.crt
openssl req -newkey rsa:2048 -nodes -keyout root.key -x509 -days 365 -out root.crt

Using ssl in python server

ref: https://piware.de/2011/01/creating-an-https-server-in-python/

import BaseHTTPServer, SimpleHTTPServer
import ssl

# subclass BaseHTTPRequestHandler for custom server

httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler)

httpd.socket = ssl.wrap_socket (httpd.socket, keyfile="/path/to/root.key", certfile='/path/to/root.crt', server_side=True)

httpd.serve_forever()

Using ssl in requests

doc: http://docs.python-requests.org/en/latest/user/advanced/#ssl-cert-verification

Because the certificate is self-signed. It cannot defend the man-in-the-middle attack. Except you give the client a copy of your certificate! It maybe even safer than CA certificate since only you have the certificate.

import requests

r = requests.get('localhost', verify='/path/to/root.crt')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment