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 30KB

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