Development of an internal social media platform with personalised dashboards for students
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

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