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
2 comments:
Hi bob,
good to see your sample code.. it looks really helpful..
But when i do "from OpenSSL import SSL" it comes up with error "No module named OpenSSL". i dont think OpenSSL is installed in my unix machine. where do you think i can download this ?
google that or use your packet manager :)
Post a Comment