securetransport.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. """
  2. SecureTranport support for urllib3 via ctypes.
  3. This makes platform-native TLS available to urllib3 users on macOS without the
  4. use of a compiler. This is an important feature because the Python Package
  5. Index is moving to become a TLSv1.2-or-higher server, and the default OpenSSL
  6. that ships with macOS is not capable of doing TLSv1.2. The only way to resolve
  7. this is to give macOS users an alternative solution to the problem, and that
  8. solution is to use SecureTransport.
  9. We use ctypes here because this solution must not require a compiler. That's
  10. because pip is not allowed to require a compiler either.
  11. This is not intended to be a seriously long-term solution to this problem.
  12. The hope is that PEP 543 will eventually solve this issue for us, at which
  13. point we can retire this contrib module. But in the short term, we need to
  14. solve the impending tire fire that is Python on Mac without this kind of
  15. contrib module. So...here we are.
  16. To use this module, simply import and inject it::
  17. import urllib3.contrib.securetransport
  18. urllib3.contrib.securetransport.inject_into_urllib3()
  19. Happy TLSing!
  20. This code is a bastardised version of the code found in Will Bond's oscrypto
  21. library. An enormous debt is owed to him for blazing this trail for us. For
  22. that reason, this code should be considered to be covered both by urllib3's
  23. license and by oscrypto's:
  24. .. code-block::
  25. Copyright (c) 2015-2016 Will Bond <will@wbond.net>
  26. Permission is hereby granted, free of charge, to any person obtaining a
  27. copy of this software and associated documentation files (the "Software"),
  28. to deal in the Software without restriction, including without limitation
  29. the rights to use, copy, modify, merge, publish, distribute, sublicense,
  30. and/or sell copies of the Software, and to permit persons to whom the
  31. Software is furnished to do so, subject to the following conditions:
  32. The above copyright notice and this permission notice shall be included in
  33. all copies or substantial portions of the Software.
  34. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  35. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  36. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  38. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  39. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  40. DEALINGS IN THE SOFTWARE.
  41. """
  42. from __future__ import absolute_import
  43. import contextlib
  44. import ctypes
  45. import errno
  46. import os.path
  47. import shutil
  48. import socket
  49. import ssl
  50. import struct
  51. import threading
  52. import weakref
  53. import six
  54. from .. import util
  55. from ..util.ssl_ import PROTOCOL_TLS_CLIENT
  56. from ._securetransport.bindings import CoreFoundation, Security, SecurityConst
  57. from ._securetransport.low_level import (
  58. _assert_no_error,
  59. _build_tls_unknown_ca_alert,
  60. _cert_array_from_pem,
  61. _create_cfstring_array,
  62. _load_client_cert_chain,
  63. _temporary_keychain,
  64. )
  65. try: # Platform-specific: Python 2
  66. from socket import _fileobject
  67. except ImportError: # Platform-specific: Python 3
  68. _fileobject = None
  69. from ..packages.backports.makefile import backport_makefile
  70. __all__ = ["inject_into_urllib3", "extract_from_urllib3"]
  71. # SNI always works
  72. HAS_SNI = True
  73. orig_util_HAS_SNI = util.HAS_SNI
  74. orig_util_SSLContext = util.ssl_.SSLContext
  75. # This dictionary is used by the read callback to obtain a handle to the
  76. # calling wrapped socket. This is a pretty silly approach, but for now it'll
  77. # do. I feel like I should be able to smuggle a handle to the wrapped socket
  78. # directly in the SSLConnectionRef, but for now this approach will work I
  79. # guess.
  80. #
  81. # We need to lock around this structure for inserts, but we don't do it for
  82. # reads/writes in the callbacks. The reasoning here goes as follows:
  83. #
  84. # 1. It is not possible to call into the callbacks before the dictionary is
  85. # populated, so once in the callback the id must be in the dictionary.
  86. # 2. The callbacks don't mutate the dictionary, they only read from it, and
  87. # so cannot conflict with any of the insertions.
  88. #
  89. # This is good: if we had to lock in the callbacks we'd drastically slow down
  90. # the performance of this code.
  91. _connection_refs = weakref.WeakValueDictionary()
  92. _connection_ref_lock = threading.Lock()
  93. # Limit writes to 16kB. This is OpenSSL's limit, but we'll cargo-cult it over
  94. # for no better reason than we need *a* limit, and this one is right there.
  95. SSL_WRITE_BLOCKSIZE = 16384
  96. # This is our equivalent of util.ssl_.DEFAULT_CIPHERS, but expanded out to
  97. # individual cipher suites. We need to do this because this is how
  98. # SecureTransport wants them.
  99. CIPHER_SUITES = [
  100. SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  101. SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  102. SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  103. SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  104. SecurityConst.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
  105. SecurityConst.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
  106. SecurityConst.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
  107. SecurityConst.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
  108. SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
  109. SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  110. SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
  111. SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  112. SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,
  113. SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  114. SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
  115. SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  116. SecurityConst.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,
  117. SecurityConst.TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
  118. SecurityConst.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
  119. SecurityConst.TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
  120. SecurityConst.TLS_AES_256_GCM_SHA384,
  121. SecurityConst.TLS_AES_128_GCM_SHA256,
  122. SecurityConst.TLS_RSA_WITH_AES_256_GCM_SHA384,
  123. SecurityConst.TLS_RSA_WITH_AES_128_GCM_SHA256,
  124. SecurityConst.TLS_AES_128_CCM_8_SHA256,
  125. SecurityConst.TLS_AES_128_CCM_SHA256,
  126. SecurityConst.TLS_RSA_WITH_AES_256_CBC_SHA256,
  127. SecurityConst.TLS_RSA_WITH_AES_128_CBC_SHA256,
  128. SecurityConst.TLS_RSA_WITH_AES_256_CBC_SHA,
  129. SecurityConst.TLS_RSA_WITH_AES_128_CBC_SHA,
  130. ]
  131. # Basically this is simple: for PROTOCOL_SSLv23 we turn it into a low of
  132. # TLSv1 and a high of TLSv1.2. For everything else, we pin to that version.
  133. # TLSv1 to 1.2 are supported on macOS 10.8+
  134. _protocol_to_min_max = {
  135. util.PROTOCOL_TLS: (SecurityConst.kTLSProtocol1, SecurityConst.kTLSProtocol12),
  136. PROTOCOL_TLS_CLIENT: (SecurityConst.kTLSProtocol1, SecurityConst.kTLSProtocol12),
  137. }
  138. if hasattr(ssl, "PROTOCOL_SSLv2"):
  139. _protocol_to_min_max[ssl.PROTOCOL_SSLv2] = (
  140. SecurityConst.kSSLProtocol2,
  141. SecurityConst.kSSLProtocol2,
  142. )
  143. if hasattr(ssl, "PROTOCOL_SSLv3"):
  144. _protocol_to_min_max[ssl.PROTOCOL_SSLv3] = (
  145. SecurityConst.kSSLProtocol3,
  146. SecurityConst.kSSLProtocol3,
  147. )
  148. if hasattr(ssl, "PROTOCOL_TLSv1"):
  149. _protocol_to_min_max[ssl.PROTOCOL_TLSv1] = (
  150. SecurityConst.kTLSProtocol1,
  151. SecurityConst.kTLSProtocol1,
  152. )
  153. if hasattr(ssl, "PROTOCOL_TLSv1_1"):
  154. _protocol_to_min_max[ssl.PROTOCOL_TLSv1_1] = (
  155. SecurityConst.kTLSProtocol11,
  156. SecurityConst.kTLSProtocol11,
  157. )
  158. if hasattr(ssl, "PROTOCOL_TLSv1_2"):
  159. _protocol_to_min_max[ssl.PROTOCOL_TLSv1_2] = (
  160. SecurityConst.kTLSProtocol12,
  161. SecurityConst.kTLSProtocol12,
  162. )
  163. def inject_into_urllib3():
  164. """
  165. Monkey-patch urllib3 with SecureTransport-backed SSL-support.
  166. """
  167. util.SSLContext = SecureTransportContext
  168. util.ssl_.SSLContext = SecureTransportContext
  169. util.HAS_SNI = HAS_SNI
  170. util.ssl_.HAS_SNI = HAS_SNI
  171. util.IS_SECURETRANSPORT = True
  172. util.ssl_.IS_SECURETRANSPORT = True
  173. def extract_from_urllib3():
  174. """
  175. Undo monkey-patching by :func:`inject_into_urllib3`.
  176. """
  177. util.SSLContext = orig_util_SSLContext
  178. util.ssl_.SSLContext = orig_util_SSLContext
  179. util.HAS_SNI = orig_util_HAS_SNI
  180. util.ssl_.HAS_SNI = orig_util_HAS_SNI
  181. util.IS_SECURETRANSPORT = False
  182. util.ssl_.IS_SECURETRANSPORT = False
  183. def _read_callback(connection_id, data_buffer, data_length_pointer):
  184. """
  185. SecureTransport read callback. This is called by ST to request that data
  186. be returned from the socket.
  187. """
  188. wrapped_socket = None
  189. try:
  190. wrapped_socket = _connection_refs.get(connection_id)
  191. if wrapped_socket is None:
  192. return SecurityConst.errSSLInternal
  193. base_socket = wrapped_socket.socket
  194. requested_length = data_length_pointer[0]
  195. timeout = wrapped_socket.gettimeout()
  196. error = None
  197. read_count = 0
  198. try:
  199. while read_count < requested_length:
  200. if timeout is None or timeout >= 0:
  201. if not util.wait_for_read(base_socket, timeout):
  202. raise socket.error(errno.EAGAIN, "timed out")
  203. remaining = requested_length - read_count
  204. buffer = (ctypes.c_char * remaining).from_address(
  205. data_buffer + read_count
  206. )
  207. chunk_size = base_socket.recv_into(buffer, remaining)
  208. read_count += chunk_size
  209. if not chunk_size:
  210. if not read_count:
  211. return SecurityConst.errSSLClosedGraceful
  212. break
  213. except (socket.error) as e:
  214. error = e.errno
  215. if error is not None and error != errno.EAGAIN:
  216. data_length_pointer[0] = read_count
  217. if error == errno.ECONNRESET or error == errno.EPIPE:
  218. return SecurityConst.errSSLClosedAbort
  219. raise
  220. data_length_pointer[0] = read_count
  221. if read_count != requested_length:
  222. return SecurityConst.errSSLWouldBlock
  223. return 0
  224. except Exception as e:
  225. if wrapped_socket is not None:
  226. wrapped_socket._exception = e
  227. return SecurityConst.errSSLInternal
  228. def _write_callback(connection_id, data_buffer, data_length_pointer):
  229. """
  230. SecureTransport write callback. This is called by ST to request that data
  231. actually be sent on the network.
  232. """
  233. wrapped_socket = None
  234. try:
  235. wrapped_socket = _connection_refs.get(connection_id)
  236. if wrapped_socket is None:
  237. return SecurityConst.errSSLInternal
  238. base_socket = wrapped_socket.socket
  239. bytes_to_write = data_length_pointer[0]
  240. data = ctypes.string_at(data_buffer, bytes_to_write)
  241. timeout = wrapped_socket.gettimeout()
  242. error = None
  243. sent = 0
  244. try:
  245. while sent < bytes_to_write:
  246. if timeout is None or timeout >= 0:
  247. if not util.wait_for_write(base_socket, timeout):
  248. raise socket.error(errno.EAGAIN, "timed out")
  249. chunk_sent = base_socket.send(data)
  250. sent += chunk_sent
  251. # This has some needless copying here, but I'm not sure there's
  252. # much value in optimising this data path.
  253. data = data[chunk_sent:]
  254. except (socket.error) as e:
  255. error = e.errno
  256. if error is not None and error != errno.EAGAIN:
  257. data_length_pointer[0] = sent
  258. if error == errno.ECONNRESET or error == errno.EPIPE:
  259. return SecurityConst.errSSLClosedAbort
  260. raise
  261. data_length_pointer[0] = sent
  262. if sent != bytes_to_write:
  263. return SecurityConst.errSSLWouldBlock
  264. return 0
  265. except Exception as e:
  266. if wrapped_socket is not None:
  267. wrapped_socket._exception = e
  268. return SecurityConst.errSSLInternal
  269. # We need to keep these two objects references alive: if they get GC'd while
  270. # in use then SecureTransport could attempt to call a function that is in freed
  271. # memory. That would be...uh...bad. Yeah, that's the word. Bad.
  272. _read_callback_pointer = Security.SSLReadFunc(_read_callback)
  273. _write_callback_pointer = Security.SSLWriteFunc(_write_callback)
  274. class WrappedSocket(object):
  275. """
  276. API-compatibility wrapper for Python's OpenSSL wrapped socket object.
  277. Note: _makefile_refs, _drop(), and _reuse() are needed for the garbage
  278. collector of PyPy.
  279. """
  280. def __init__(self, socket):
  281. self.socket = socket
  282. self.context = None
  283. self._makefile_refs = 0
  284. self._closed = False
  285. self._exception = None
  286. self._keychain = None
  287. self._keychain_dir = None
  288. self._client_cert_chain = None
  289. # We save off the previously-configured timeout and then set it to
  290. # zero. This is done because we use select and friends to handle the
  291. # timeouts, but if we leave the timeout set on the lower socket then
  292. # Python will "kindly" call select on that socket again for us. Avoid
  293. # that by forcing the timeout to zero.
  294. self._timeout = self.socket.gettimeout()
  295. self.socket.settimeout(0)
  296. @contextlib.contextmanager
  297. def _raise_on_error(self):
  298. """
  299. A context manager that can be used to wrap calls that do I/O from
  300. SecureTransport. If any of the I/O callbacks hit an exception, this
  301. context manager will correctly propagate the exception after the fact.
  302. This avoids silently swallowing those exceptions.
  303. It also correctly forces the socket closed.
  304. """
  305. self._exception = None
  306. # We explicitly don't catch around this yield because in the unlikely
  307. # event that an exception was hit in the block we don't want to swallow
  308. # it.
  309. yield
  310. if self._exception is not None:
  311. exception, self._exception = self._exception, None
  312. self.close()
  313. raise exception
  314. def _set_ciphers(self):
  315. """
  316. Sets up the allowed ciphers. By default this matches the set in
  317. util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done
  318. custom and doesn't allow changing at this time, mostly because parsing
  319. OpenSSL cipher strings is going to be a freaking nightmare.
  320. """
  321. ciphers = (Security.SSLCipherSuite * len(CIPHER_SUITES))(*CIPHER_SUITES)
  322. result = Security.SSLSetEnabledCiphers(
  323. self.context, ciphers, len(CIPHER_SUITES)
  324. )
  325. _assert_no_error(result)
  326. def _set_alpn_protocols(self, protocols):
  327. """
  328. Sets up the ALPN protocols on the context.
  329. """
  330. if not protocols:
  331. return
  332. protocols_arr = _create_cfstring_array(protocols)
  333. try:
  334. result = Security.SSLSetALPNProtocols(self.context, protocols_arr)
  335. _assert_no_error(result)
  336. finally:
  337. CoreFoundation.CFRelease(protocols_arr)
  338. def _custom_validate(self, verify, trust_bundle):
  339. """
  340. Called when we have set custom validation. We do this in two cases:
  341. first, when cert validation is entirely disabled; and second, when
  342. using a custom trust DB.
  343. Raises an SSLError if the connection is not trusted.
  344. """
  345. # If we disabled cert validation, just say: cool.
  346. if not verify:
  347. return
  348. successes = (
  349. SecurityConst.kSecTrustResultUnspecified,
  350. SecurityConst.kSecTrustResultProceed,
  351. )
  352. try:
  353. trust_result = self._evaluate_trust(trust_bundle)
  354. if trust_result in successes:
  355. return
  356. reason = "error code: %d" % (trust_result,)
  357. except Exception as e:
  358. # Do not trust on error
  359. reason = "exception: %r" % (e,)
  360. # SecureTransport does not send an alert nor shuts down the connection.
  361. rec = _build_tls_unknown_ca_alert(self.version())
  362. self.socket.sendall(rec)
  363. # close the connection immediately
  364. # l_onoff = 1, activate linger
  365. # l_linger = 0, linger for 0 seoncds
  366. opts = struct.pack("ii", 1, 0)
  367. self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, opts)
  368. self.close()
  369. raise ssl.SSLError("certificate verify failed, %s" % reason)
  370. def _evaluate_trust(self, trust_bundle):
  371. # We want data in memory, so load it up.
  372. if os.path.isfile(trust_bundle):
  373. with open(trust_bundle, "rb") as f:
  374. trust_bundle = f.read()
  375. cert_array = None
  376. trust = Security.SecTrustRef()
  377. try:
  378. # Get a CFArray that contains the certs we want.
  379. cert_array = _cert_array_from_pem(trust_bundle)
  380. # Ok, now the hard part. We want to get the SecTrustRef that ST has
  381. # created for this connection, shove our CAs into it, tell ST to
  382. # ignore everything else it knows, and then ask if it can build a
  383. # chain. This is a buuuunch of code.
  384. result = Security.SSLCopyPeerTrust(self.context, ctypes.byref(trust))
  385. _assert_no_error(result)
  386. if not trust:
  387. raise ssl.SSLError("Failed to copy trust reference")
  388. result = Security.SecTrustSetAnchorCertificates(trust, cert_array)
  389. _assert_no_error(result)
  390. result = Security.SecTrustSetAnchorCertificatesOnly(trust, True)
  391. _assert_no_error(result)
  392. trust_result = Security.SecTrustResultType()
  393. result = Security.SecTrustEvaluate(trust, ctypes.byref(trust_result))
  394. _assert_no_error(result)
  395. finally:
  396. if trust:
  397. CoreFoundation.CFRelease(trust)
  398. if cert_array is not None:
  399. CoreFoundation.CFRelease(cert_array)
  400. return trust_result.value
  401. def handshake(
  402. self,
  403. server_hostname,
  404. verify,
  405. trust_bundle,
  406. min_version,
  407. max_version,
  408. client_cert,
  409. client_key,
  410. client_key_passphrase,
  411. alpn_protocols,
  412. ):
  413. """
  414. Actually performs the TLS handshake. This is run automatically by
  415. wrapped socket, and shouldn't be needed in user code.
  416. """
  417. # First, we do the initial bits of connection setup. We need to create
  418. # a context, set its I/O funcs, and set the connection reference.
  419. self.context = Security.SSLCreateContext(
  420. None, SecurityConst.kSSLClientSide, SecurityConst.kSSLStreamType
  421. )
  422. result = Security.SSLSetIOFuncs(
  423. self.context, _read_callback_pointer, _write_callback_pointer
  424. )
  425. _assert_no_error(result)
  426. # Here we need to compute the handle to use. We do this by taking the
  427. # id of self modulo 2**31 - 1. If this is already in the dictionary, we
  428. # just keep incrementing by one until we find a free space.
  429. with _connection_ref_lock:
  430. handle = id(self) % 2147483647
  431. while handle in _connection_refs:
  432. handle = (handle + 1) % 2147483647
  433. _connection_refs[handle] = self
  434. result = Security.SSLSetConnection(self.context, handle)
  435. _assert_no_error(result)
  436. # If we have a server hostname, we should set that too.
  437. if server_hostname:
  438. if not isinstance(server_hostname, bytes):
  439. server_hostname = server_hostname.encode("utf-8")
  440. result = Security.SSLSetPeerDomainName(
  441. self.context, server_hostname, len(server_hostname)
  442. )
  443. _assert_no_error(result)
  444. # Setup the ciphers.
  445. self._set_ciphers()
  446. # Setup the ALPN protocols.
  447. self._set_alpn_protocols(alpn_protocols)
  448. # Set the minimum and maximum TLS versions.
  449. result = Security.SSLSetProtocolVersionMin(self.context, min_version)
  450. _assert_no_error(result)
  451. result = Security.SSLSetProtocolVersionMax(self.context, max_version)
  452. _assert_no_error(result)
  453. # If there's a trust DB, we need to use it. We do that by telling
  454. # SecureTransport to break on server auth. We also do that if we don't
  455. # want to validate the certs at all: we just won't actually do any
  456. # authing in that case.
  457. if not verify or trust_bundle is not None:
  458. result = Security.SSLSetSessionOption(
  459. self.context, SecurityConst.kSSLSessionOptionBreakOnServerAuth, True
  460. )
  461. _assert_no_error(result)
  462. # If there's a client cert, we need to use it.
  463. if client_cert:
  464. self._keychain, self._keychain_dir = _temporary_keychain()
  465. self._client_cert_chain = _load_client_cert_chain(
  466. self._keychain, client_cert, client_key
  467. )
  468. result = Security.SSLSetCertificate(self.context, self._client_cert_chain)
  469. _assert_no_error(result)
  470. while True:
  471. with self._raise_on_error():
  472. result = Security.SSLHandshake(self.context)
  473. if result == SecurityConst.errSSLWouldBlock:
  474. raise socket.timeout("handshake timed out")
  475. elif result == SecurityConst.errSSLServerAuthCompleted:
  476. self._custom_validate(verify, trust_bundle)
  477. continue
  478. else:
  479. _assert_no_error(result)
  480. break
  481. def fileno(self):
  482. return self.socket.fileno()
  483. # Copy-pasted from Python 3.5 source code
  484. def _decref_socketios(self):
  485. if self._makefile_refs > 0:
  486. self._makefile_refs -= 1
  487. if self._closed:
  488. self.close()
  489. def recv(self, bufsiz):
  490. buffer = ctypes.create_string_buffer(bufsiz)
  491. bytes_read = self.recv_into(buffer, bufsiz)
  492. data = buffer[:bytes_read]
  493. return data
  494. def recv_into(self, buffer, nbytes=None):
  495. # Read short on EOF.
  496. if self._closed:
  497. return 0
  498. if nbytes is None:
  499. nbytes = len(buffer)
  500. buffer = (ctypes.c_char * nbytes).from_buffer(buffer)
  501. processed_bytes = ctypes.c_size_t(0)
  502. with self._raise_on_error():
  503. result = Security.SSLRead(
  504. self.context, buffer, nbytes, ctypes.byref(processed_bytes)
  505. )
  506. # There are some result codes that we want to treat as "not always
  507. # errors". Specifically, those are errSSLWouldBlock,
  508. # errSSLClosedGraceful, and errSSLClosedNoNotify.
  509. if result == SecurityConst.errSSLWouldBlock:
  510. # If we didn't process any bytes, then this was just a time out.
  511. # However, we can get errSSLWouldBlock in situations when we *did*
  512. # read some data, and in those cases we should just read "short"
  513. # and return.
  514. if processed_bytes.value == 0:
  515. # Timed out, no data read.
  516. raise socket.timeout("recv timed out")
  517. elif result in (
  518. SecurityConst.errSSLClosedGraceful,
  519. SecurityConst.errSSLClosedNoNotify,
  520. ):
  521. # The remote peer has closed this connection. We should do so as
  522. # well. Note that we don't actually return here because in
  523. # principle this could actually be fired along with return data.
  524. # It's unlikely though.
  525. self.close()
  526. else:
  527. _assert_no_error(result)
  528. # Ok, we read and probably succeeded. We should return whatever data
  529. # was actually read.
  530. return processed_bytes.value
  531. def settimeout(self, timeout):
  532. self._timeout = timeout
  533. def gettimeout(self):
  534. return self._timeout
  535. def send(self, data):
  536. processed_bytes = ctypes.c_size_t(0)
  537. with self._raise_on_error():
  538. result = Security.SSLWrite(
  539. self.context, data, len(data), ctypes.byref(processed_bytes)
  540. )
  541. if result == SecurityConst.errSSLWouldBlock and processed_bytes.value == 0:
  542. # Timed out
  543. raise socket.timeout("send timed out")
  544. else:
  545. _assert_no_error(result)
  546. # We sent, and probably succeeded. Tell them how much we sent.
  547. return processed_bytes.value
  548. def sendall(self, data):
  549. total_sent = 0
  550. while total_sent < len(data):
  551. sent = self.send(data[total_sent : total_sent + SSL_WRITE_BLOCKSIZE])
  552. total_sent += sent
  553. def shutdown(self):
  554. with self._raise_on_error():
  555. Security.SSLClose(self.context)
  556. def close(self):
  557. # TODO: should I do clean shutdown here? Do I have to?
  558. if self._makefile_refs < 1:
  559. self._closed = True
  560. if self.context:
  561. CoreFoundation.CFRelease(self.context)
  562. self.context = None
  563. if self._client_cert_chain:
  564. CoreFoundation.CFRelease(self._client_cert_chain)
  565. self._client_cert_chain = None
  566. if self._keychain:
  567. Security.SecKeychainDelete(self._keychain)
  568. CoreFoundation.CFRelease(self._keychain)
  569. shutil.rmtree(self._keychain_dir)
  570. self._keychain = self._keychain_dir = None
  571. return self.socket.close()
  572. else:
  573. self._makefile_refs -= 1
  574. def getpeercert(self, binary_form=False):
  575. # Urgh, annoying.
  576. #
  577. # Here's how we do this:
  578. #
  579. # 1. Call SSLCopyPeerTrust to get hold of the trust object for this
  580. # connection.
  581. # 2. Call SecTrustGetCertificateAtIndex for index 0 to get the leaf.
  582. # 3. To get the CN, call SecCertificateCopyCommonName and process that
  583. # string so that it's of the appropriate type.
  584. # 4. To get the SAN, we need to do something a bit more complex:
  585. # a. Call SecCertificateCopyValues to get the data, requesting
  586. # kSecOIDSubjectAltName.
  587. # b. Mess about with this dictionary to try to get the SANs out.
  588. #
  589. # This is gross. Really gross. It's going to be a few hundred LoC extra
  590. # just to repeat something that SecureTransport can *already do*. So my
  591. # operating assumption at this time is that what we want to do is
  592. # instead to just flag to urllib3 that it shouldn't do its own hostname
  593. # validation when using SecureTransport.
  594. if not binary_form:
  595. raise ValueError("SecureTransport only supports dumping binary certs")
  596. trust = Security.SecTrustRef()
  597. certdata = None
  598. der_bytes = None
  599. try:
  600. # Grab the trust store.
  601. result = Security.SSLCopyPeerTrust(self.context, ctypes.byref(trust))
  602. _assert_no_error(result)
  603. if not trust:
  604. # Probably we haven't done the handshake yet. No biggie.
  605. return None
  606. cert_count = Security.SecTrustGetCertificateCount(trust)
  607. if not cert_count:
  608. # Also a case that might happen if we haven't handshaked.
  609. # Handshook? Handshaken?
  610. return None
  611. leaf = Security.SecTrustGetCertificateAtIndex(trust, 0)
  612. assert leaf
  613. # Ok, now we want the DER bytes.
  614. certdata = Security.SecCertificateCopyData(leaf)
  615. assert certdata
  616. data_length = CoreFoundation.CFDataGetLength(certdata)
  617. data_buffer = CoreFoundation.CFDataGetBytePtr(certdata)
  618. der_bytes = ctypes.string_at(data_buffer, data_length)
  619. finally:
  620. if certdata:
  621. CoreFoundation.CFRelease(certdata)
  622. if trust:
  623. CoreFoundation.CFRelease(trust)
  624. return der_bytes
  625. def version(self):
  626. protocol = Security.SSLProtocol()
  627. result = Security.SSLGetNegotiatedProtocolVersion(
  628. self.context, ctypes.byref(protocol)
  629. )
  630. _assert_no_error(result)
  631. if protocol.value == SecurityConst.kTLSProtocol13:
  632. raise ssl.SSLError("SecureTransport does not support TLS 1.3")
  633. elif protocol.value == SecurityConst.kTLSProtocol12:
  634. return "TLSv1.2"
  635. elif protocol.value == SecurityConst.kTLSProtocol11:
  636. return "TLSv1.1"
  637. elif protocol.value == SecurityConst.kTLSProtocol1:
  638. return "TLSv1"
  639. elif protocol.value == SecurityConst.kSSLProtocol3:
  640. return "SSLv3"
  641. elif protocol.value == SecurityConst.kSSLProtocol2:
  642. return "SSLv2"
  643. else:
  644. raise ssl.SSLError("Unknown TLS version: %r" % protocol)
  645. def _reuse(self):
  646. self._makefile_refs += 1
  647. def _drop(self):
  648. if self._makefile_refs < 1:
  649. self.close()
  650. else:
  651. self._makefile_refs -= 1
  652. if _fileobject: # Platform-specific: Python 2
  653. def makefile(self, mode, bufsize=-1):
  654. self._makefile_refs += 1
  655. return _fileobject(self, mode, bufsize, close=True)
  656. else: # Platform-specific: Python 3
  657. def makefile(self, mode="r", buffering=None, *args, **kwargs):
  658. # We disable buffering with SecureTransport because it conflicts with
  659. # the buffering that ST does internally (see issue #1153 for more).
  660. buffering = 0
  661. return backport_makefile(self, mode, buffering, *args, **kwargs)
  662. WrappedSocket.makefile = makefile
  663. class SecureTransportContext(object):
  664. """
  665. I am a wrapper class for the SecureTransport library, to translate the
  666. interface of the standard library ``SSLContext`` object to calls into
  667. SecureTransport.
  668. """
  669. def __init__(self, protocol):
  670. self._min_version, self._max_version = _protocol_to_min_max[protocol]
  671. self._options = 0
  672. self._verify = False
  673. self._trust_bundle = None
  674. self._client_cert = None
  675. self._client_key = None
  676. self._client_key_passphrase = None
  677. self._alpn_protocols = None
  678. @property
  679. def check_hostname(self):
  680. """
  681. SecureTransport cannot have its hostname checking disabled. For more,
  682. see the comment on getpeercert() in this file.
  683. """
  684. return True
  685. @check_hostname.setter
  686. def check_hostname(self, value):
  687. """
  688. SecureTransport cannot have its hostname checking disabled. For more,
  689. see the comment on getpeercert() in this file.
  690. """
  691. pass
  692. @property
  693. def options(self):
  694. # TODO: Well, crap.
  695. #
  696. # So this is the bit of the code that is the most likely to cause us
  697. # trouble. Essentially we need to enumerate all of the SSL options that
  698. # users might want to use and try to see if we can sensibly translate
  699. # them, or whether we should just ignore them.
  700. return self._options
  701. @options.setter
  702. def options(self, value):
  703. # TODO: Update in line with above.
  704. self._options = value
  705. @property
  706. def verify_mode(self):
  707. return ssl.CERT_REQUIRED if self._verify else ssl.CERT_NONE
  708. @verify_mode.setter
  709. def verify_mode(self, value):
  710. self._verify = True if value == ssl.CERT_REQUIRED else False
  711. def set_default_verify_paths(self):
  712. # So, this has to do something a bit weird. Specifically, what it does
  713. # is nothing.
  714. #
  715. # This means that, if we had previously had load_verify_locations
  716. # called, this does not undo that. We need to do that because it turns
  717. # out that the rest of the urllib3 code will attempt to load the
  718. # default verify paths if it hasn't been told about any paths, even if
  719. # the context itself was sometime earlier. We resolve that by just
  720. # ignoring it.
  721. pass
  722. def load_default_certs(self):
  723. return self.set_default_verify_paths()
  724. def set_ciphers(self, ciphers):
  725. # For now, we just require the default cipher string.
  726. if ciphers != util.ssl_.DEFAULT_CIPHERS:
  727. raise ValueError("SecureTransport doesn't support custom cipher strings")
  728. def load_verify_locations(self, cafile=None, capath=None, cadata=None):
  729. # OK, we only really support cadata and cafile.
  730. if capath is not None:
  731. raise ValueError("SecureTransport does not support cert directories")
  732. # Raise if cafile does not exist.
  733. if cafile is not None:
  734. with open(cafile):
  735. pass
  736. self._trust_bundle = cafile or cadata
  737. def load_cert_chain(self, certfile, keyfile=None, password=None):
  738. self._client_cert = certfile
  739. self._client_key = keyfile
  740. self._client_cert_passphrase = password
  741. def set_alpn_protocols(self, protocols):
  742. """
  743. Sets the ALPN protocols that will later be set on the context.
  744. Raises a NotImplementedError if ALPN is not supported.
  745. """
  746. if not hasattr(Security, "SSLSetALPNProtocols"):
  747. raise NotImplementedError(
  748. "SecureTransport supports ALPN only in macOS 10.12+"
  749. )
  750. self._alpn_protocols = [six.ensure_binary(p) for p in protocols]
  751. def wrap_socket(
  752. self,
  753. sock,
  754. server_side=False,
  755. do_handshake_on_connect=True,
  756. suppress_ragged_eofs=True,
  757. server_hostname=None,
  758. ):
  759. # So, what do we do here? Firstly, we assert some properties. This is a
  760. # stripped down shim, so there is some functionality we don't support.
  761. # See PEP 543 for the real deal.
  762. assert not server_side
  763. assert do_handshake_on_connect
  764. assert suppress_ragged_eofs
  765. # Ok, we're good to go. Now we want to create the wrapped socket object
  766. # and store it in the appropriate place.
  767. wrapped_socket = WrappedSocket(sock)
  768. # Now we can handshake
  769. wrapped_socket.handshake(
  770. server_hostname,
  771. self._verify,
  772. self._trust_bundle,
  773. self._min_version,
  774. self._max_version,
  775. self._client_cert,
  776. self._client_key,
  777. self._client_key_passphrase,
  778. self._alpn_protocols,
  779. )
  780. return wrapped_socket