https.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. """urllib2pyopenssl HTTPS module containing PyOpenSSL implementation of
  2. httplib.HTTPSConnection
  3. PyOpenSSL utility to make a httplib-like interface suitable for use with
  4. urllib2
  5. """
  6. __author__ = "P J Kershaw (STFC)"
  7. __date__ = "09/12/11"
  8. __copyright__ = "(C) 2012 Science and Technology Facilities Council"
  9. __license__ = "BSD - see LICENSE file in top-level directory"
  10. __contact__ = "Philip.Kershaw@stfc.ac.uk"
  11. __revision__ = '$Id$'
  12. import logging
  13. import socket
  14. from httplib import HTTPConnection, HTTPS_PORT
  15. from urllib2 import AbstractHTTPHandler
  16. from OpenSSL import SSL
  17. from urllib2pyopenssl.ssl_socket import SSLSocket
  18. log = logging.getLogger(__name__)
  19. class HTTPSConnection(HTTPConnection):
  20. """This class allows communication via SSL using PyOpenSSL.
  21. It is based on httplib.HTTPSConnection, modified to use PyOpenSSL.
  22. Note: This uses the constructor inherited from HTTPConnection to allow it to
  23. be used with httplib and HTTPSContextHandler. To use the class directly with
  24. an SSL context set ssl_context after construction.
  25. @cvar default_port: default port for this class (443)
  26. @type default_port: int
  27. """
  28. default_port = HTTPS_PORT
  29. def __init__(self, host, port=None, strict=None,
  30. timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  31. HTTPConnection.__init__(self, host, port, strict, timeout)
  32. if not hasattr(self, 'ssl_context'):
  33. self.ssl_context = None
  34. def connect(self):
  35. """Create SSL socket and connect to peer
  36. """
  37. if getattr(self, 'ssl_context', None):
  38. if not isinstance(self.ssl_context, SSL.Context):
  39. raise TypeError('Expecting OpenSSL.SSL.Context type for "'
  40. 'ssl_context" keyword; got %r instead' %
  41. self.ssl_context)
  42. ssl_context = self.ssl_context
  43. else:
  44. ssl_context = SSL.Context(SSL.SSLv23_METHOD)
  45. sock = socket.create_connection((self.host, self.port), self.timeout)
  46. if getattr(self, '_tunnel_host', None):
  47. self.sock = sock
  48. self._tunnel()
  49. self.sock = SSLSocket(ssl_context, sock)
  50. # Go to client mode.
  51. self.sock.set_connect_state()
  52. def close(self):
  53. """Close socket and shut down SSL connection"""
  54. self.sock.close()
  55. class HTTPSContextHandler(AbstractHTTPHandler):
  56. '''HTTPS handler that provides allows a SSL context to be set for the SSL
  57. connections.
  58. '''
  59. https_request = AbstractHTTPHandler.do_request_
  60. def __init__(self, ssl_context, debuglevel=0):
  61. """
  62. @param ssl_context - SSL context
  63. @param debuglevel - debug level for HTTPSHandler
  64. """
  65. AbstractHTTPHandler.__init__(self, debuglevel)
  66. if ssl_context is not None:
  67. if not isinstance(ssl_context, SSL.Context):
  68. raise TypeError('Expecting OpenSSL.SSL.Context type for "'
  69. 'ssl_context" keyword; got %r instead' %
  70. ssl_context)
  71. self.ssl_context = ssl_context
  72. else:
  73. self.ssl_context = SSL.Context(SSL.SSLv23_METHOD)
  74. def https_open(self, req):
  75. """Opens HTTPS request
  76. @param req - HTTP request
  77. @return HTTP Response object
  78. """
  79. # Make a custom class extending HTTPSConnection, with the SSL context
  80. # set as a class variable so that it is available to the connect method.
  81. customHTTPSContextConnection = type('CustomHTTPSContextConnection',
  82. (HTTPSConnection, object),
  83. {'ssl_context': self.ssl_context})
  84. return self.do_open(customHTTPSContextConnection, req)