Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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 33KB

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