HowTo: Create an SSL web-server in Twisted (Crude approach, but it works...)



The Twisted web howto doesn't mention the fairly common task of creating an SSL-secured communications channel for a web server. The process of doing so is fairly simple, but it requires tracking down a few pieces of information, so I've collected them here:

First things first, to create an SSL server, you need a private key file, and an SSL server certificate. Let's assume for the moment that you're a software developer who just wants to get a testing system set up, so you're not going to go to the trouble of getting a formal public certificate, you just want something for testing. OpenSSL can help here. First, we generate a private key file:

openssl genrsa > privkey.pem
Then we generate a self-signed SSL certificate:
openssl req -new -x509 -key privkey.pem -out cacert.pem -days 1000
Okay, that's the first challenge licked. Next thing is to actually create the server. We assume that you've created a site as in the Twisted web howto, so you should now have a site object, and you know the port on which you want to listen. We import the ssl module, create an SSL context for the server, and then call listenSSL on the reactor with our port, site and context:
from twisted.internet import reactor, ssl
sslContext = ssl.DefaultOpenSSLContextFactory(
'/path/to/privkey.pem',
'/path/to/cacert.pem',
)
reactor.listenSSL(
port, # integer port
site, # our site object, see the web howto
contextFactory = sslContext,
)

There are also facilities in twisted.application for setting up the port given the context and site, but I'm going for the simple to-the-metal approach here to match up with the original howto's introductory example.

Comments

  1. Anal

    Anal on 09/17/2007 7:13 a.m. #


    thank you!

  2. Jean-Paul Calderone

    Jean-Paul Calderone on 12/03/2009 10:45 a.m. #

    The web howto link is pointed at the wrong place. It should be:

    http://twistedmatrix.com/documents/current/web/howto/web-overview.html

  3. Mike C. Fletcher

    Mike C. Fletcher on 12/03/2009 11:45 a.m. #

    Thanks, have tried to recover the content for the 3 Twisted tutorials from 2004 and have updated the URL here.

  4. ccpizz

    ccpizz on 08/11/2012 4:20 p.m. #

    This line is missing at the end:

    *reactor.run()*

Comments are closed.

Pingbacks

Pingbacks are closed.