securetransport.py 33 KB

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