/gdata/tlslite/integration/TLSSocketServerMixIn.py

http://radioappz.googlecode.com/ · Python · 59 lines · 35 code · 5 blank · 19 comment · 1 complexity · 2a473ab12a11165b9f349de8ea5dddb8 MD5 · raw file

  1. """TLS Lite + SocketServer."""
  2. from gdata.tlslite.TLSConnection import TLSConnection
  3. class TLSSocketServerMixIn:
  4. """
  5. This class can be mixed in with any L{SocketServer.TCPServer} to
  6. add TLS support.
  7. To use this class, define a new class that inherits from it and
  8. some L{SocketServer.TCPServer} (with the mix-in first). Then
  9. implement the handshake() method, doing some sort of server
  10. handshake on the connection argument. If the handshake method
  11. returns True, the RequestHandler will be triggered. Below is a
  12. complete example of a threaded HTTPS server::
  13. from SocketServer import *
  14. from BaseHTTPServer import *
  15. from SimpleHTTPServer import *
  16. from tlslite.api import *
  17. s = open("./serverX509Cert.pem").read()
  18. x509 = X509()
  19. x509.parse(s)
  20. certChain = X509CertChain([x509])
  21. s = open("./serverX509Key.pem").read()
  22. privateKey = parsePEMKey(s, private=True)
  23. sessionCache = SessionCache()
  24. class MyHTTPServer(ThreadingMixIn, TLSSocketServerMixIn,
  25. HTTPServer):
  26. def handshake(self, tlsConnection):
  27. try:
  28. tlsConnection.handshakeServer(certChain=certChain,
  29. privateKey=privateKey,
  30. sessionCache=sessionCache)
  31. tlsConnection.ignoreAbruptClose = True
  32. return True
  33. except TLSError, error:
  34. print "Handshake failure:", str(error)
  35. return False
  36. httpd = MyHTTPServer(('localhost', 443), SimpleHTTPRequestHandler)
  37. httpd.serve_forever()
  38. """
  39. def finish_request(self, sock, client_address):
  40. tlsConnection = TLSConnection(sock)
  41. if self.handshake(tlsConnection) == True:
  42. self.RequestHandlerClass(tlsConnection, client_address, self)
  43. tlsConnection.close()
  44. #Implement this method to do some form of handshaking. Return True
  45. #if the handshake finishes properly and the request is authorized.
  46. def handshake(self, tlsConnection):
  47. raise NotImplementedError()