2015-03-06

Self-signed https server en python

Estuve un rato peleando con python y aledaños para hacer un server de HTTPS pelotudo. No fue tan fácil.

Encontré la base del código acá, y un par de comentarios en el fondo donde explicaba cómo arreglarlo para que ande.

Primero generé un certificado que funque. Es importantísimo setear bien el common name (sino falla silenciosamente):

$ openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3650 -nodes
Generating a 2048 bit RSA private key
.....................+++
.............................................................+++
writing new private key to 'key2.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:
State or Province Name (full name) [Some-State]:
Locality Name (eg, city) []:
Organization Name (eg, company) [Internet Widgits Pty Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:*
Email Address []:


Con ese certificado, este código levanta un webserver:

import BaseHTTPServer, SimpleHTTPServer
import ssl

def main():
    httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler)
    httpd.socket = ssl.wrap_socket (httpd.socket, certfile='certs/cert.pem', keyfile="certs/key.pem", server_side=True)
    httpd.serve_forever()
if __name__ == '__main__':
    main()


Happy hacking,
Aureliano.

No hay comentarios.: