https.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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 ndg.httpsclient.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. @cvar default_ssl_method: default SSL method used if no SSL context is
  28. explicitly set - defaults to version 2/3.
  29. @type default_ssl_method: int
  30. """
  31. default_port = HTTPS_PORT
  32. default_ssl_method = SSL.SSLv23_METHOD
  33. def __init__(self, host, port=None, strict=None,
  34. timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  35. HTTPConnection.__init__(self, host, port, strict, timeout)
  36. if not hasattr(self, 'ssl_context'):
  37. self.ssl_context = None
  38. def connect(self):
  39. """Create SSL socket and connect to peer
  40. """
  41. if getattr(self, 'ssl_context', None):
  42. if not isinstance(self.ssl_context, SSL.Context):
  43. raise TypeError('Expecting OpenSSL.SSL.Context type for "'
  44. 'ssl_context" keyword; got %r instead' %
  45. self.ssl_context)
  46. ssl_context = self.ssl_context
  47. else:
  48. ssl_context = SSL.Context(self.__class__.default_ssl_method)
  49. sock = socket.create_connection((self.host, self.port), self.timeout)
  50. if getattr(self, '_tunnel_host', None):
  51. self.sock = sock
  52. self._tunnel()
  53. self.sock = SSLSocket(ssl_context, sock)
  54. # Go to client mode.
  55. self.sock.set_connect_state()
  56. def close(self):
  57. """Close socket and shut down SSL connection"""
  58. self.sock.close()
  59. class HTTPSContextHandler(AbstractHTTPHandler):
  60. '''HTTPS handler that allows a SSL context to be set for the SSL
  61. connections.
  62. '''
  63. https_request = AbstractHTTPHandler.do_request_
  64. def __init__(self, ssl_context, debuglevel=0):
  65. """
  66. @param ssl_context:SSL context
  67. @type ssl_context: OpenSSL.SSL.Context
  68. @param debuglevel: debug level for HTTPSHandler
  69. @type debuglevel: int
  70. """
  71. AbstractHTTPHandler.__init__(self, debuglevel)
  72. if ssl_context is not None:
  73. if not isinstance(ssl_context, SSL.Context):
  74. raise TypeError('Expecting OpenSSL.SSL.Context type for "'
  75. 'ssl_context" keyword; got %r instead' %
  76. ssl_context)
  77. self.ssl_context = ssl_context
  78. else:
  79. self.ssl_context = SSL.Context(SSL.SSLv23_METHOD)
  80. def https_open(self, req):
  81. """Opens HTTPS request
  82. @param req - HTTP request
  83. @return HTTP Response object
  84. """
  85. # Make a custom class extending HTTPSConnection, with the SSL context
  86. # set as a class variable so that it is available to the connect method.
  87. customHTTPSContextConnection = type('CustomHTTPSContextConnection',
  88. (HTTPSConnection, object),
  89. {'ssl_context': self.ssl_context})
  90. return self.do_open(customHTTPSContextConnection, req)