You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

securetransport.py 32KB

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