M2Crypto == Python + OpenSSL + SWIG. It makes available to the Python programmer RSA, DSA, DH, message digests, HMACs, symmetric ciphers and sufficient SSL functionality to implement clients and servers.
This document demonstrates how to write SSL servers with M2Crypto.
M2Crypto provides the following frameworks for implementing SSL servers:
SSLServer, ForkingSSLServer, ThreadingSSLServer - these are modeled after the SocketServer interfaces and use blocking socket I/O.
ssl_dispatcher - this is modeled after asyncore.dispatcher and uses non-blocking socket I/O.
We begin with a complete example of an SSL server application, using the SSLServer framework. We then discuss the implementation. Finally, we re-implement the application using ssl_dispatcher.
echo
server We use as our example the canonical echo
server. Here is the implementation:
1 import SocketServer 2 from M2Crypto import SSL, X509 3 4 class ssl_echo_handler(SocketServer.BaseRequestHandler): 5 6 buffer="Ye Olde Echo Servre\r\n" 7 8 def handle(self): 9 10 if not self.request.verify_ok(): 11 v = self.request.get_verify_result() 12 print "peer verification failed:", Err.get_x509_verify_error(v) 13 return 14 15 peer = self.request.get_peer_cert() 16 if peer is not None: 17 print "Client CA =", peer.get_issuer() 18 print "Client =", peer.get_subject() 19 20 self.request.write(self.buffer) 21 while 1: 22 buf=self.request.read() 23 if not buf: 24 break 25 self.request.write(buf) 26 27 def finish(self): 28 self.request.close() 29 30 def main(): 31 32 ctx = SSL.Context() 33 ctx.load_cert("server.pem") 34 ctx.load_client_ca("ca.pem") 35 ctx.load_verify_info("ca.pem") 36 ctx.set_tmp_dh("dh1024.pem") 37 ctx.set_verify(SSL.verify_none, 10) 38 ctx.set_info_callback() 39 40 s = SSL.SSLServer(("", 9999), ssl_echo_handler, ctx) 41 s.serve_forever() 42 43 if __name__=="__main__": 44 main()
When invoked on the command line, echo.py
executes main(). The first part of main(),
lines 32-38, sets up an SSL.Context object ctx which acts as a policy template for
SSL communications. The following explains the operations on ctx:
ctx.load_cert("server.pem")
This loads the private key and certificate in server.pem into the server.