https.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. """ndg_httpsclient 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. import sys
  15. from httplib import HTTPS_PORT
  16. if sys.version_info < (2, 6, 2):
  17. from ndg.httpsclient.httplib_proxy import HTTPConnection
  18. from ndg.httpsclient.urllib2_proxy import AbstractHTTPHandler
  19. else:
  20. from httplib import HTTPConnection
  21. from urllib2 import AbstractHTTPHandler
  22. from OpenSSL import SSL
  23. from ndg.httpsclient.ssl_socket import SSLSocket
  24. log = logging.getLogger(__name__)
  25. class HTTPSConnection(HTTPConnection):
  26. """This class allows communication via SSL using PyOpenSSL.
  27. It is based on httplib.HTTPSConnection, modified to use PyOpenSSL.
  28. Note: This uses the constructor inherited from HTTPConnection to allow it to
  29. be used with httplib and HTTPSContextHandler. To use the class directly with
  30. an SSL context set ssl_context after construction.
  31. @cvar default_port: default port for this class (443)
  32. @type default_port: int
  33. @cvar default_ssl_method: default SSL method used if no SSL context is
  34. explicitly set - defaults to version 2/3.
  35. @type default_ssl_method: int
  36. """
  37. default_port = HTTPS_PORT
  38. default_ssl_method = SSL.SSLv23_METHOD
  39. def __init__(self, host, port=None, strict=None,
  40. timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  41. HTTPConnection.__init__(self, host, port, strict, timeout)
  42. if not hasattr(self, 'ssl_context'):
  43. self.ssl_context = None
  44. def connect(self):
  45. """Create SSL socket and connect to peer
  46. """
  47. if getattr(self, 'ssl_context', None):
  48. if not isinstance(self.ssl_context, SSL.Context):
  49. raise TypeError('Expecting OpenSSL.SSL.Context type for "'
  50. 'ssl_context" keyword; got %r instead' %
  51. self.ssl_context)
  52. ssl_context = self.ssl_context
  53. else:
  54. ssl_context = SSL.Context(self.__class__.default_ssl_method)
  55. sock = socket.create_connection((self.host, self.port), self.timeout)
  56. # Tunnel if using a proxy - ONLY available for Python 2.6.2 and above
  57. if getattr(self, '_tunnel_host', None):
  58. self.sock = sock
  59. self._tunnel()
  60. self.sock = SSLSocket(ssl_context, sock)
  61. # Go to client mode.
  62. self.sock.set_connect_state()
  63. def close(self):
  64. """Close socket and shut down SSL connection"""
  65. self.sock.close()
  66. class HTTPSContextHandler(AbstractHTTPHandler):
  67. '''HTTPS handler that allows a SSL context to be set for the SSL
  68. connections.
  69. '''
  70. https_request = AbstractHTTPHandler.do_request_
  71. def __init__(self, ssl_context, debuglevel=0):
  72. """
  73. @param ssl_context:SSL context
  74. @type ssl_context: OpenSSL.SSL.Context
  75. @param debuglevel: debug level for HTTPSHandler
  76. @type debuglevel: int
  77. """
  78. AbstractHTTPHandler.__init__(self, debuglevel)
  79. if ssl_context is not None:
  80. if not isinstance(ssl_context, SSL.Context):
  81. raise TypeError('Expecting OpenSSL.SSL.Context type for "'
  82. 'ssl_context" keyword; got %r instead' %
  83. ssl_context)
  84. self.ssl_context = ssl_context
  85. else:
  86. self.ssl_context = SSL.Context(SSL.SSLv23_METHOD)
  87. def https_open(self, req):
  88. """Opens HTTPS request
  89. @param req - HTTP request
  90. @return HTTP Response object
  91. """
  92. # Make a custom class extending HTTPSConnection, with the SSL context
  93. # set as a class variable so that it is available to the connect method.
  94. customHTTPSContextConnection = type('CustomHTTPSContextConnection',
  95. (HTTPSConnection, object),
  96. {'ssl_context': self.ssl_context})
  97. return self.do_open(customHTTPSContextConnection, req)