25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

854 lines
32KB

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