_sslgte279.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. # Wrapper module for _ssl. Written by Bill Janssen.
  2. # Ported to gevent by Denis Bilenko.
  3. """SSL wrapper for socket objects on Python 2.7.9 and above.
  4. For the documentation, refer to :mod:`ssl` module manual.
  5. This module implements cooperative SSL socket wrappers.
  6. """
  7. from __future__ import absolute_import
  8. # Our import magic sadly makes this warning useless
  9. # pylint: disable=undefined-variable
  10. # pylint: disable=too-many-instance-attributes,too-many-locals,too-many-statements,too-many-branches
  11. # pylint: disable=arguments-differ,too-many-public-methods
  12. import ssl as __ssl__
  13. _ssl = __ssl__._ssl # pylint:disable=no-member
  14. import errno
  15. from gevent._socket2 import socket
  16. from gevent.socket import timeout_default
  17. from gevent.socket import create_connection
  18. from gevent.socket import error as socket_error
  19. from gevent.socket import timeout as _socket_timeout
  20. from gevent._compat import PYPY
  21. from gevent._util import copy_globals
  22. __implements__ = [
  23. 'SSLContext',
  24. 'SSLSocket',
  25. 'wrap_socket',
  26. 'get_server_certificate',
  27. 'create_default_context',
  28. '_create_unverified_context',
  29. '_create_default_https_context',
  30. '_create_stdlib_context',
  31. ]
  32. # Import all symbols from Python's ssl.py, except those that we are implementing
  33. # and "private" symbols.
  34. __imports__ = copy_globals(__ssl__, globals(),
  35. # SSLSocket *must* subclass gevent.socket.socket; see issue 597 and 801
  36. names_to_ignore=__implements__ + ['socket', 'create_connection'],
  37. dunder_names_to_keep=())
  38. try:
  39. _delegate_methods
  40. except NameError: # PyPy doesn't expose this detail
  41. _delegate_methods = ('recv', 'recvfrom', 'recv_into', 'recvfrom_into', 'send', 'sendto')
  42. __all__ = __implements__ + __imports__
  43. if 'namedtuple' in __all__:
  44. __all__.remove('namedtuple')
  45. orig_SSLContext = __ssl__.SSLContext # pylint: disable=no-member
  46. class SSLContext(orig_SSLContext):
  47. def wrap_socket(self, sock, server_side=False,
  48. do_handshake_on_connect=True,
  49. suppress_ragged_eofs=True,
  50. server_hostname=None):
  51. return SSLSocket(sock=sock, server_side=server_side,
  52. do_handshake_on_connect=do_handshake_on_connect,
  53. suppress_ragged_eofs=suppress_ragged_eofs,
  54. server_hostname=server_hostname,
  55. _context=self)
  56. def create_default_context(purpose=Purpose.SERVER_AUTH, cafile=None,
  57. capath=None, cadata=None):
  58. """Create a SSLContext object with default settings.
  59. NOTE: The protocol and settings may change anytime without prior
  60. deprecation. The values represent a fair balance between maximum
  61. compatibility and security.
  62. """
  63. if not isinstance(purpose, _ASN1Object):
  64. raise TypeError(purpose)
  65. context = SSLContext(PROTOCOL_SSLv23)
  66. # SSLv2 considered harmful.
  67. context.options |= OP_NO_SSLv2
  68. # SSLv3 has problematic security and is only required for really old
  69. # clients such as IE6 on Windows XP
  70. context.options |= OP_NO_SSLv3
  71. # disable compression to prevent CRIME attacks (OpenSSL 1.0+)
  72. context.options |= getattr(_ssl, "OP_NO_COMPRESSION", 0)
  73. if purpose == Purpose.SERVER_AUTH:
  74. # verify certs and host name in client mode
  75. context.verify_mode = CERT_REQUIRED
  76. context.check_hostname = True # pylint: disable=attribute-defined-outside-init
  77. elif purpose == Purpose.CLIENT_AUTH:
  78. # Prefer the server's ciphers by default so that we get stronger
  79. # encryption
  80. context.options |= getattr(_ssl, "OP_CIPHER_SERVER_PREFERENCE", 0)
  81. # Use single use keys in order to improve forward secrecy
  82. context.options |= getattr(_ssl, "OP_SINGLE_DH_USE", 0)
  83. context.options |= getattr(_ssl, "OP_SINGLE_ECDH_USE", 0)
  84. # disallow ciphers with known vulnerabilities
  85. context.set_ciphers(_RESTRICTED_SERVER_CIPHERS)
  86. if cafile or capath or cadata:
  87. context.load_verify_locations(cafile, capath, cadata)
  88. elif context.verify_mode != CERT_NONE:
  89. # no explicit cafile, capath or cadata but the verify mode is
  90. # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
  91. # root CA certificates for the given purpose. This may fail silently.
  92. context.load_default_certs(purpose)
  93. return context
  94. def _create_unverified_context(protocol=PROTOCOL_SSLv23, cert_reqs=None,
  95. check_hostname=False, purpose=Purpose.SERVER_AUTH,
  96. certfile=None, keyfile=None,
  97. cafile=None, capath=None, cadata=None):
  98. """Create a SSLContext object for Python stdlib modules
  99. All Python stdlib modules shall use this function to create SSLContext
  100. objects in order to keep common settings in one place. The configuration
  101. is less restrict than create_default_context()'s to increase backward
  102. compatibility.
  103. """
  104. if not isinstance(purpose, _ASN1Object):
  105. raise TypeError(purpose)
  106. context = SSLContext(protocol)
  107. # SSLv2 considered harmful.
  108. context.options |= OP_NO_SSLv2
  109. # SSLv3 has problematic security and is only required for really old
  110. # clients such as IE6 on Windows XP
  111. context.options |= OP_NO_SSLv3
  112. if cert_reqs is not None:
  113. context.verify_mode = cert_reqs
  114. context.check_hostname = check_hostname # pylint: disable=attribute-defined-outside-init
  115. if keyfile and not certfile:
  116. raise ValueError("certfile must be specified")
  117. if certfile or keyfile:
  118. context.load_cert_chain(certfile, keyfile)
  119. # load CA root certs
  120. if cafile or capath or cadata:
  121. context.load_verify_locations(cafile, capath, cadata)
  122. elif context.verify_mode != CERT_NONE:
  123. # no explicit cafile, capath or cadata but the verify mode is
  124. # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
  125. # root CA certificates for the given purpose. This may fail silently.
  126. context.load_default_certs(purpose)
  127. return context
  128. # Used by http.client if no context is explicitly passed.
  129. _create_default_https_context = create_default_context
  130. # Backwards compatibility alias, even though it's not a public name.
  131. _create_stdlib_context = _create_unverified_context
  132. class SSLSocket(socket):
  133. """
  134. gevent `ssl.SSLSocket <https://docs.python.org/2/library/ssl.html#ssl-sockets>`_
  135. for Pythons >= 2.7.9 but less than 3.
  136. """
  137. def __init__(self, sock=None, keyfile=None, certfile=None,
  138. server_side=False, cert_reqs=CERT_NONE,
  139. ssl_version=PROTOCOL_SSLv23, ca_certs=None,
  140. do_handshake_on_connect=True,
  141. family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
  142. suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
  143. server_hostname=None,
  144. _context=None):
  145. # fileno is ignored
  146. # pylint: disable=unused-argument
  147. if _context:
  148. self._context = _context
  149. else:
  150. if server_side and not certfile:
  151. raise ValueError("certfile must be specified for server-side "
  152. "operations")
  153. if keyfile and not certfile:
  154. raise ValueError("certfile must be specified")
  155. if certfile and not keyfile:
  156. keyfile = certfile
  157. self._context = SSLContext(ssl_version)
  158. self._context.verify_mode = cert_reqs
  159. if ca_certs:
  160. self._context.load_verify_locations(ca_certs)
  161. if certfile:
  162. self._context.load_cert_chain(certfile, keyfile)
  163. if npn_protocols:
  164. self._context.set_npn_protocols(npn_protocols)
  165. if ciphers:
  166. self._context.set_ciphers(ciphers)
  167. self.keyfile = keyfile
  168. self.certfile = certfile
  169. self.cert_reqs = cert_reqs
  170. self.ssl_version = ssl_version
  171. self.ca_certs = ca_certs
  172. self.ciphers = ciphers
  173. # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
  174. # mixed in.
  175. if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
  176. raise NotImplementedError("only stream sockets are supported")
  177. if PYPY:
  178. socket.__init__(self, _sock=sock)
  179. sock._drop()
  180. else:
  181. # CPython: XXX: Must pass the underlying socket, not our
  182. # potential wrapper; test___example_servers fails the SSL test
  183. # with a client-side EOF error. (Why?)
  184. socket.__init__(self, _sock=sock._sock)
  185. # The initializer for socket overrides the methods send(), recv(), etc.
  186. # in the instance, which we don't need -- but we want to provide the
  187. # methods defined in SSLSocket.
  188. for attr in _delegate_methods:
  189. try:
  190. delattr(self, attr)
  191. except AttributeError:
  192. pass
  193. if server_side and server_hostname:
  194. raise ValueError("server_hostname can only be specified "
  195. "in client mode")
  196. if self._context.check_hostname and not server_hostname:
  197. raise ValueError("check_hostname requires server_hostname")
  198. self.server_side = server_side
  199. self.server_hostname = server_hostname
  200. self.do_handshake_on_connect = do_handshake_on_connect
  201. self.suppress_ragged_eofs = suppress_ragged_eofs
  202. self.settimeout(sock.gettimeout())
  203. # See if we are connected
  204. try:
  205. self.getpeername()
  206. except socket_error as e:
  207. if e.errno != errno.ENOTCONN:
  208. raise
  209. connected = False
  210. else:
  211. connected = True
  212. self._makefile_refs = 0
  213. self._closed = False
  214. self._sslobj = None
  215. self._connected = connected
  216. if connected:
  217. # create the SSL object
  218. try:
  219. self._sslobj = self._context._wrap_socket(self._sock, server_side,
  220. server_hostname, ssl_sock=self)
  221. if do_handshake_on_connect:
  222. timeout = self.gettimeout()
  223. if timeout == 0.0:
  224. # non-blocking
  225. raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
  226. self.do_handshake()
  227. except socket_error as x:
  228. self.close()
  229. raise x
  230. @property
  231. def context(self):
  232. return self._context
  233. @context.setter
  234. def context(self, ctx):
  235. self._context = ctx
  236. self._sslobj.context = ctx
  237. def dup(self):
  238. raise NotImplementedError("Can't dup() %s instances" %
  239. self.__class__.__name__)
  240. def _checkClosed(self, msg=None):
  241. # raise an exception here if you wish to check for spurious closes
  242. pass
  243. def _check_connected(self):
  244. if not self._connected:
  245. # getpeername() will raise ENOTCONN if the socket is really
  246. # not connected; note that we can be connected even without
  247. # _connected being set, e.g. if connect() first returned
  248. # EAGAIN.
  249. self.getpeername()
  250. def read(self, len=1024, buffer=None):
  251. """Read up to LEN bytes and return them.
  252. Return zero-length string on EOF."""
  253. self._checkClosed()
  254. while 1:
  255. if not self._sslobj:
  256. raise ValueError("Read on closed or unwrapped SSL socket.")
  257. if len == 0:
  258. return b'' if buffer is None else 0
  259. if len < 0 and buffer is None:
  260. # This is handled natively in python 2.7.12+
  261. raise ValueError("Negative read length")
  262. try:
  263. if buffer is not None:
  264. return self._sslobj.read(len, buffer)
  265. return self._sslobj.read(len or 1024)
  266. except SSLWantReadError:
  267. if self.timeout == 0.0:
  268. raise
  269. self._wait(self._read_event, timeout_exc=_SSLErrorReadTimeout)
  270. except SSLWantWriteError:
  271. if self.timeout == 0.0:
  272. raise
  273. # note: using _SSLErrorReadTimeout rather than _SSLErrorWriteTimeout below is intentional
  274. self._wait(self._write_event, timeout_exc=_SSLErrorReadTimeout)
  275. except SSLError as ex:
  276. if ex.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
  277. if buffer is not None:
  278. return 0
  279. return b''
  280. else:
  281. raise
  282. def write(self, data):
  283. """Write DATA to the underlying SSL channel. Returns
  284. number of bytes of DATA actually transmitted."""
  285. self._checkClosed()
  286. while 1:
  287. if not self._sslobj:
  288. raise ValueError("Write on closed or unwrapped SSL socket.")
  289. try:
  290. return self._sslobj.write(data)
  291. except SSLError as ex:
  292. if ex.args[0] == SSL_ERROR_WANT_READ:
  293. if self.timeout == 0.0:
  294. raise
  295. self._wait(self._read_event, timeout_exc=_SSLErrorWriteTimeout)
  296. elif ex.args[0] == SSL_ERROR_WANT_WRITE:
  297. if self.timeout == 0.0:
  298. raise
  299. self._wait(self._write_event, timeout_exc=_SSLErrorWriteTimeout)
  300. else:
  301. raise
  302. def getpeercert(self, binary_form=False):
  303. """Returns a formatted version of the data in the
  304. certificate provided by the other end of the SSL channel.
  305. Return None if no certificate was provided, {} if a
  306. certificate was provided, but not validated."""
  307. self._checkClosed()
  308. self._check_connected()
  309. return self._sslobj.peer_certificate(binary_form)
  310. def selected_npn_protocol(self):
  311. self._checkClosed()
  312. if not self._sslobj or not _ssl.HAS_NPN:
  313. return None
  314. return self._sslobj.selected_npn_protocol()
  315. if hasattr(_ssl, 'HAS_ALPN'):
  316. # 2.7.10+
  317. def selected_alpn_protocol(self):
  318. self._checkClosed()
  319. if not self._sslobj or not _ssl.HAS_ALPN: # pylint:disable=no-member
  320. return None
  321. return self._sslobj.selected_alpn_protocol()
  322. def cipher(self):
  323. self._checkClosed()
  324. if not self._sslobj:
  325. return None
  326. return self._sslobj.cipher()
  327. def compression(self):
  328. self._checkClosed()
  329. if not self._sslobj:
  330. return None
  331. return self._sslobj.compression()
  332. def __check_flags(self, meth, flags):
  333. if flags != 0:
  334. raise ValueError(
  335. "non-zero flags not allowed in calls to %s on %s" %
  336. (meth, self.__class__))
  337. def send(self, data, flags=0, timeout=timeout_default):
  338. self._checkClosed()
  339. self.__check_flags('send', flags)
  340. if timeout is timeout_default:
  341. timeout = self.timeout
  342. if not self._sslobj:
  343. return socket.send(self, data, flags, timeout)
  344. while True:
  345. try:
  346. return self._sslobj.write(data)
  347. except SSLWantReadError:
  348. if self.timeout == 0.0:
  349. return 0
  350. self._wait(self._read_event)
  351. except SSLWantWriteError:
  352. if self.timeout == 0.0:
  353. return 0
  354. self._wait(self._write_event)
  355. def sendto(self, data, flags_or_addr, addr=None):
  356. self._checkClosed()
  357. if self._sslobj:
  358. raise ValueError("sendto not allowed on instances of %s" %
  359. self.__class__)
  360. elif addr is None:
  361. return socket.sendto(self, data, flags_or_addr)
  362. else:
  363. return socket.sendto(self, data, flags_or_addr, addr)
  364. def sendmsg(self, *args, **kwargs):
  365. # Ensure programs don't send data unencrypted if they try to
  366. # use this method.
  367. raise NotImplementedError("sendmsg not allowed on instances of %s" %
  368. self.__class__)
  369. def sendall(self, data, flags=0):
  370. self._checkClosed()
  371. self.__check_flags('sendall', flags)
  372. try:
  373. socket.sendall(self, data)
  374. except _socket_timeout as ex:
  375. if self.timeout == 0.0:
  376. # Python 2 simply *hangs* in this case, which is bad, but
  377. # Python 3 raises SSLWantWriteError. We do the same.
  378. raise SSLWantWriteError("The operation did not complete (write)")
  379. # Convert the socket.timeout back to the sslerror
  380. raise SSLError(*ex.args)
  381. def recv(self, buflen=1024, flags=0):
  382. self._checkClosed()
  383. if self._sslobj:
  384. if flags != 0:
  385. raise ValueError(
  386. "non-zero flags not allowed in calls to recv() on %s" %
  387. self.__class__)
  388. if buflen == 0:
  389. return b''
  390. return self.read(buflen)
  391. else:
  392. return socket.recv(self, buflen, flags)
  393. def recv_into(self, buffer, nbytes=None, flags=0):
  394. self._checkClosed()
  395. if buffer is not None and (nbytes is None):
  396. # Fix for python bug #23804: bool(bytearray()) is False,
  397. # but we should read 0 bytes.
  398. nbytes = len(buffer)
  399. elif nbytes is None:
  400. nbytes = 1024
  401. if self._sslobj:
  402. if flags != 0:
  403. raise ValueError(
  404. "non-zero flags not allowed in calls to recv_into() on %s" %
  405. self.__class__)
  406. return self.read(nbytes, buffer)
  407. else:
  408. return socket.recv_into(self, buffer, nbytes, flags)
  409. def recvfrom(self, buflen=1024, flags=0):
  410. self._checkClosed()
  411. if self._sslobj:
  412. raise ValueError("recvfrom not allowed on instances of %s" %
  413. self.__class__)
  414. else:
  415. return socket.recvfrom(self, buflen, flags)
  416. def recvfrom_into(self, buffer, nbytes=None, flags=0):
  417. self._checkClosed()
  418. if self._sslobj:
  419. raise ValueError("recvfrom_into not allowed on instances of %s" %
  420. self.__class__)
  421. else:
  422. return socket.recvfrom_into(self, buffer, nbytes, flags)
  423. def recvmsg(self, *args, **kwargs):
  424. raise NotImplementedError("recvmsg not allowed on instances of %s" %
  425. self.__class__)
  426. def recvmsg_into(self, *args, **kwargs):
  427. raise NotImplementedError("recvmsg_into not allowed on instances of "
  428. "%s" % self.__class__)
  429. def pending(self):
  430. self._checkClosed()
  431. if self._sslobj:
  432. return self._sslobj.pending()
  433. return 0
  434. def shutdown(self, how):
  435. self._checkClosed()
  436. self._sslobj = None
  437. socket.shutdown(self, how)
  438. def close(self):
  439. if self._makefile_refs < 1:
  440. self._sslobj = None
  441. socket.close(self)
  442. else:
  443. self._makefile_refs -= 1
  444. if PYPY:
  445. def _reuse(self):
  446. self._makefile_refs += 1
  447. def _drop(self):
  448. if self._makefile_refs < 1:
  449. self.close()
  450. else:
  451. self._makefile_refs -= 1
  452. def _sslobj_shutdown(self):
  453. while True:
  454. try:
  455. return self._sslobj.shutdown()
  456. except SSLError as ex:
  457. if ex.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
  458. return ''
  459. elif ex.args[0] == SSL_ERROR_WANT_READ:
  460. if self.timeout == 0.0:
  461. raise
  462. sys.exc_clear()
  463. self._wait(self._read_event, timeout_exc=_SSLErrorReadTimeout)
  464. elif ex.args[0] == SSL_ERROR_WANT_WRITE:
  465. if self.timeout == 0.0:
  466. raise
  467. sys.exc_clear()
  468. self._wait(self._write_event, timeout_exc=_SSLErrorWriteTimeout)
  469. else:
  470. raise
  471. def unwrap(self):
  472. if self._sslobj:
  473. s = self._sslobj_shutdown()
  474. self._sslobj = None
  475. return socket(_sock=s) # match _ssl2; critical to drop/reuse here on PyPy
  476. else:
  477. raise ValueError("No SSL wrapper around " + str(self))
  478. def _real_close(self):
  479. self._sslobj = None
  480. socket._real_close(self) # pylint: disable=no-member
  481. def do_handshake(self):
  482. """Perform a TLS/SSL handshake."""
  483. self._check_connected()
  484. while True:
  485. try:
  486. self._sslobj.do_handshake()
  487. break
  488. except SSLWantReadError:
  489. if self.timeout == 0.0:
  490. raise
  491. self._wait(self._read_event, timeout_exc=_SSLErrorHandshakeTimeout)
  492. except SSLWantWriteError:
  493. if self.timeout == 0.0:
  494. raise
  495. self._wait(self._write_event, timeout_exc=_SSLErrorHandshakeTimeout)
  496. if self._context.check_hostname:
  497. if not self.server_hostname:
  498. raise ValueError("check_hostname needs server_hostname "
  499. "argument")
  500. match_hostname(self.getpeercert(), self.server_hostname)
  501. def _real_connect(self, addr, connect_ex):
  502. if self.server_side:
  503. raise ValueError("can't connect in server-side mode")
  504. # Here we assume that the socket is client-side, and not
  505. # connected at the time of the call. We connect it, then wrap it.
  506. if self._connected:
  507. raise ValueError("attempt to connect already-connected SSLSocket!")
  508. self._sslobj = self._context._wrap_socket(self._sock, False, self.server_hostname, ssl_sock=self)
  509. try:
  510. if connect_ex:
  511. rc = socket.connect_ex(self, addr)
  512. else:
  513. rc = None
  514. socket.connect(self, addr)
  515. if not rc:
  516. self._connected = True
  517. if self.do_handshake_on_connect:
  518. self.do_handshake()
  519. return rc
  520. except socket_error:
  521. self._sslobj = None
  522. raise
  523. def connect(self, addr):
  524. """Connects to remote ADDR, and then wraps the connection in
  525. an SSL channel."""
  526. self._real_connect(addr, False)
  527. def connect_ex(self, addr):
  528. """Connects to remote ADDR, and then wraps the connection in
  529. an SSL channel."""
  530. return self._real_connect(addr, True)
  531. def accept(self):
  532. """Accepts a new connection from a remote client, and returns
  533. a tuple containing that new connection wrapped with a server-side
  534. SSL channel, and the address of the remote client."""
  535. newsock, addr = socket.accept(self)
  536. newsock = self._context.wrap_socket(newsock,
  537. do_handshake_on_connect=self.do_handshake_on_connect,
  538. suppress_ragged_eofs=self.suppress_ragged_eofs,
  539. server_side=True)
  540. return newsock, addr
  541. def makefile(self, mode='r', bufsize=-1):
  542. """Make and return a file-like object that
  543. works with the SSL connection. Just use the code
  544. from the socket module."""
  545. if not PYPY:
  546. self._makefile_refs += 1
  547. # close=True so as to decrement the reference count when done with
  548. # the file-like object.
  549. return _fileobject(self, mode, bufsize, close=True)
  550. def get_channel_binding(self, cb_type="tls-unique"):
  551. """Get channel binding data for current connection. Raise ValueError
  552. if the requested `cb_type` is not supported. Return bytes of the data
  553. or None if the data is not available (e.g. before the handshake).
  554. """
  555. if cb_type not in CHANNEL_BINDING_TYPES:
  556. raise ValueError("Unsupported channel binding type")
  557. if cb_type != "tls-unique":
  558. raise NotImplementedError(
  559. "{0} channel binding type not implemented"
  560. .format(cb_type))
  561. if self._sslobj is None:
  562. return None
  563. return self._sslobj.tls_unique_cb()
  564. def version(self):
  565. """
  566. Return a string identifying the protocol version used by the
  567. current SSL channel, or None if there is no established channel.
  568. """
  569. if self._sslobj is None:
  570. return None
  571. return self._sslobj.version()
  572. if PYPY or not hasattr(SSLSocket, 'timeout'):
  573. # PyPy (and certain versions of CPython) doesn't have a direct
  574. # 'timeout' property on raw sockets, because that's not part of
  575. # the documented specification. We may wind up wrapping a raw
  576. # socket (when ssl is used with PyWSGI) or a gevent socket, which
  577. # does have a read/write timeout property as an alias for
  578. # get/settimeout, so make sure that's always the case because
  579. # pywsgi can depend on that.
  580. SSLSocket.timeout = property(lambda self: self.gettimeout(),
  581. lambda self, value: self.settimeout(value))
  582. _SSLErrorReadTimeout = SSLError('The read operation timed out')
  583. _SSLErrorWriteTimeout = SSLError('The write operation timed out')
  584. _SSLErrorHandshakeTimeout = SSLError('The handshake operation timed out')
  585. def wrap_socket(sock, keyfile=None, certfile=None,
  586. server_side=False, cert_reqs=CERT_NONE,
  587. ssl_version=PROTOCOL_SSLv23, ca_certs=None,
  588. do_handshake_on_connect=True,
  589. suppress_ragged_eofs=True,
  590. ciphers=None):
  591. return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
  592. server_side=server_side, cert_reqs=cert_reqs,
  593. ssl_version=ssl_version, ca_certs=ca_certs,
  594. do_handshake_on_connect=do_handshake_on_connect,
  595. suppress_ragged_eofs=suppress_ragged_eofs,
  596. ciphers=ciphers)
  597. def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
  598. """Retrieve the certificate from the server at the specified address,
  599. and return it as a PEM-encoded string.
  600. If 'ca_certs' is specified, validate the server cert against it.
  601. If 'ssl_version' is specified, use it in the connection attempt."""
  602. _, _ = addr
  603. if ca_certs is not None:
  604. cert_reqs = CERT_REQUIRED
  605. else:
  606. cert_reqs = CERT_NONE
  607. context = _create_stdlib_context(ssl_version,
  608. cert_reqs=cert_reqs,
  609. cafile=ca_certs)
  610. with closing(create_connection(addr)) as sock:
  611. with closing(context.wrap_socket(sock)) as sslsock:
  612. dercert = sslsock.getpeercert(True)
  613. return DER_cert_to_PEM_cert(dercert)