Friday, August 03, 2007

Making an SSL connection in Python

For a work project I want to make a secure point-to-point link between a Java application and a Python server. Here is the result of googling/tinkering to get the link working in Python...

The client side is pretty simple. Python comes with built in SSL support for connecting sockets. Basically you just wrap a standard socket with an SSL socket:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 12345))
sslSocket = socket.ssl(s)
print repr(sslSocket.server())
print repr(sslSocket.issuer())
sslSocket.write('Hello secure socket\n')
s.close()


The server is a bit more tricky, you need to install pyopenssl (apt-get install python-pyopenssl) for more SSL features. The server needs a private key and certificate to identify itself with.

The quick and dirty way to generate a test key+certificate is:

openssl genrsa 1024 > key
openssl req -new -x509 -nodes -sha1 -days 365 -key key > cert


And the server wraps the sockets much like the client does:

import socket
from OpenSSL import SSL

context = SSL.Context(SSL.SSLv23_METHOD)
context.use_privatekey_file('key')
context.use_certificate_file('cert')

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = SSL.Connection(context, s)
s.bind(('', 12345))
s.listen(5)

(connection, address) = s.accept()
while True:
    print repr(connection.recv(65535))


OpenSSL also provides a test SSL client/server in the style of telnet/netcat, great for debugging:

openssl s_server -accept 12345 -cert cert -key key
openssl s_client -connect localhost:12345
Post a Comment