Advertisement
Guest User

Python TLSv1 Monkey Patch

a guest
Jun 26th, 2012
530
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.12 KB | None | 0 0
  1. from http.client import HTTPConnection, _strict_sentinel, HTTPS_PORT
  2. import socket, ssl
  3.  
  4. class HTTPSConnection(HTTPConnection):
  5.     "This class allows communication via SSL."
  6.  
  7.     default_port = HTTPS_PORT
  8.  
  9.     # XXX Should key_file and cert_file be deprecated in favour of context?
  10.  
  11.     def __init__(self, host, port=None, key_file=None, cert_file=None,
  12.                  strict=_strict_sentinel, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
  13.                  source_address=None, *, context=None, check_hostname=None):
  14.         super(HTTPSConnection, self).__init__(host, port, strict, timeout,
  15.                                               source_address)
  16.         self.key_file = key_file
  17.         self.cert_file = cert_file
  18.         if context is None:
  19.             # Some reasonable defaults
  20.             context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  21.             context.options |= ssl.OP_NO_SSLv2
  22.         will_verify = context.verify_mode != ssl.CERT_NONE
  23.         if check_hostname is None:
  24.             check_hostname = will_verify
  25.         elif check_hostname and not will_verify:
  26.             raise ValueError("check_hostname needs a SSL context with "
  27.                              "either CERT_OPTIONAL or CERT_REQUIRED")
  28.         if key_file or cert_file:
  29.             context.load_cert_chain(cert_file, key_file)
  30.         self._context = context
  31.         self._check_hostname = check_hostname
  32.  
  33.     def connect(self):
  34.         "Connect to a host on a given (SSL) port."
  35.  
  36.         sock = socket.create_connection((self.host, self.port),
  37.                                         self.timeout, self.source_address)
  38.  
  39.         if self._tunnel_host:
  40.             self.sock = sock
  41.             self._tunnel()
  42.  
  43.         server_hostname = self.host if ssl.HAS_SNI else None
  44.         self.sock = self._context.wrap_socket(sock,
  45.                                               server_hostname=server_hostname)
  46.         try:
  47.             if self._check_hostname:
  48.                 ssl.match_hostname(self.sock.getpeercert(), self.host)
  49.         except Exception:
  50.             self.sock.shutdown(socket.SHUT_RDWR)
  51.             self.sock.close()
  52.             raise
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement