Using the cert we just created…

February 12, 2010

In the last post, I described how to create a keypair and self-signed certificate. Now, we need to:

  1. use them to encrypt our traffic and
  2. allow the user to install the cert in his or her browser.

Here’s how to do this using Twisted. This code creates a page at 8080 that will download the certificate to the user’s browser and a site at 8081 that uses HTTPS. Connect to http://HOSTNAME:8080 to get the cert (your browser will prompt you to install it). Then, you can connect to https://HOSTNAME:8081 and browse securely.

Note that HOSTNAME can’t be ‘localhost’. Not much you can do here – certificates are tied to the actual hostname you use.

This code assumes that the code from that last post is in a module named pki.py, btw.


from twisted.web import server, resource, http
from twisted.internet import reactor, ssl
from twisted.python import log
import sys
from OpenSSL import SSL
from pki import KEY_FILE, CERT_FILE, create_self_signed_cert

def make_ssl_context():
    create_self_signed_cert(".")
    context = ssl.DefaultOpenSSLContextFactory(KEY_FILE, CERT_FILE)
    return context

class HelloWorldPage(resource.Resource):
    isLeaf = True
    def render_GET(self, request):
        return "<html><body><h1>Hello World</h1></body></html>"

class CertPage(resource.Resource):
    isLeaf = True

    def render_GET(self, request):
        request.setHeader("Content-Type", "application/x-x509-ca-cert")
        cert = open(CERT_FILE, 'rb').read()
        request.write(cert)
        request.finish()
        return server.NOT_DONE_YET

log.startLogging(sys.stdout)
context = make_ssl_context()
cert_site = server.Site(CertPage())
site = server.Site(HelloWorldPage())
reactor.listenTCP(8080, cert_site)
reactor.listenSSL(8081, site, contextFactory = context)
reactor.run()

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.