U .e@sdZddlmZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl mZddlmZmZmZddlmZmZmZmZzdd l mZWn$ek rdZdd lmZYnXd d gZd ZejZejj Z!e "Z#e $Z%dZ&ej'ej(ej)ej*ej+ej,ej-ej.ej/ej0ej1ej2ej3ej4ej5ej6ej7ej8ej9ej:ej;ejej?ej@ejAejBejCejDgZEejFejGejHfiZIeJe drejKejKfeIe jL<eJe drejMejMfeIe jN<eJe drejGejGfeIe jO<eJe drejPejPfeIe jQ<eJe drejRejRfeIe jS<dd ZTdd ZUddZVddZWeXeVZYeZeWZ[Gddde\Z]ernd#ddZ^n d$d dZ^e^e]_^Gd!d"d"e\Z_dS)%a SecureTranport support for urllib3 via ctypes. This makes platform-native TLS available to urllib3 users on macOS without the use of a compiler. This is an important feature because the Python Package Index is moving to become a TLSv1.2-or-higher server, and the default OpenSSL that ships with macOS is not capable of doing TLSv1.2. The only way to resolve this is to give macOS users an alternative solution to the problem, and that solution is to use SecureTransport. We use ctypes here because this solution must not require a compiler. That's because pip is not allowed to require a compiler either. This is not intended to be a seriously long-term solution to this problem. The hope is that PEP 543 will eventually solve this issue for us, at which point we can retire this contrib module. But in the short term, we need to solve the impending tire fire that is Python on Mac without this kind of contrib module. So...here we are. To use this module, simply import and inject it:: import urllib3.contrib.securetransport urllib3.contrib.securetransport.inject_into_urllib3() Happy TLSing! This code is a bastardised version of the code found in Will Bond's oscrypto library. An enormous debt is owed to him for blazing this trail for us. For that reason, this code should be considered to be covered both by urllib3's license and by oscrypto's: Copyright (c) 2015-2016 Will Bond Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. )absolute_importN)util)Security SecurityConstCoreFoundation)_assert_no_error_cert_array_from_pem_temporary_keychain_load_client_cert_chain) _fileobjectbackport_makefileinject_into_urllib3extract_from_urllib3Ti@PROTOCOL_SSLv2PROTOCOL_SSLv3PROTOCOL_TLSv1PROTOCOL_TLSv1_1PROTOCOL_TLSv1_2cCs.tt_ttj_tt_ttj_dt_dtj_dS)zG Monkey-patch urllib3 with SecureTransport-backed SSL-support. TN)SecureTransportContextr SSLContextssl_HAS_SNIIS_SECURETRANSPORTrrO/usr/lib/python3.8/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyrs cCs.tt_ttj_tt_ttj_dt_dtj_dS)z> Undo monkey-patching by :func:`inject_into_urllib3`. FN)orig_util_SSLContextrrrorig_util_HAS_SNIrrrrrrrs c Csd}zJt|}|dkr"tjWS|j}|d}|}d}d}z|||kr|dksZ|dkrtt||sttt j d||} t j |  ||} || | } || 7}| sB|stjWWSqqBWnttjk r0} zR| j }|dk r |t j kr ||d<|t jks|t jkrtjWY WSW5d} ~ XYnX||d<||krLtjWSWdStk r} z|dk rt| |_tjWYSd} ~ XYnXdS)zs SecureTransport read callback. This is called by ST to request that data be returned from the socket. Nr timed out)_connection_refsgetrerrSSLInternalsocket gettimeoutrZ wait_for_readerrorerrnoEAGAINctypesc_charZ from_address recv_intoerrSSLClosedGraceful ECONNRESETEPIPEerrSSLClosedAborterrSSLWouldBlock Exception _exception) connection_id data_bufferdata_length_pointerwrapped_socket base_socketZrequested_lengthtimeoutr&Z read_countZ remainingbufferZ chunk_sizeerrr_read_callbacksP       r;c Csrd}z(t|}|dkr"tjWS|j}|d}t||}|}d}d} zV| |kr|dksf|dkrt ||st t j d| |} | | 7} || d}qNWnltj k r} zJ| j }|dk r|t j kr| |d<|t jks|t jkrtjWY WSW5d} ~ XYnX| |d<| |kr*tjWSWdStk rl} z|dk rR| |_tjWYSd} ~ XYnXdS)zx SecureTransport write callback. This is called by ST to request that data actually be sent on the network. Nrr )r!r"rr#r$r) string_atr%rZwait_for_writer&r'r(sendr-r.r/r0r1r2) r3r4r5r6r7Zbytes_to_writedatar8r&sentZ chunk_sentr:rrr_write_callbacksD      r@c@seZdZdZddZejddZddZdd Z d d Z d d Z ddZ ddZ d*ddZddZddZddZddZddZdd Zd+d"d#Zd$d%Zd&d'Zd(d)ZdS), WrappedSocketz API-compatibility wrapper for Python's OpenSSL wrapped socket object. Note: _makefile_refs, _drop(), and _reuse() are needed for the garbage collector of PyPy. cCsL||_d|_d|_d|_d|_d|_d|_d|_|j|_ |j ddSNrF) r$context_makefile_refs_closedr2 _keychain _keychain_dir_client_cert_chainr%_timeout settimeout)selfr$rrr__init__Hs zWrappedSocket.__init__ccs4d|_dV|jdk r0|jd}|_||dS)a] A context manager that can be used to wrap calls that do I/O from SecureTransport. If any of the I/O callbacks hit an exception, this context manager will correctly propagate the exception after the fact. This avoids silently swallowing those exceptions. It also correctly forces the socket closed. N)r2close)rKZ exceptionrrr_raise_on_errorZs  zWrappedSocket._raise_on_errorcCs2tjttt}t|j|tt}t|dS)a4 Sets up the allowed ciphers. By default this matches the set in util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done custom and doesn't allow changing at this time, mostly because parsing OpenSSL cipher strings is going to be a freaking nightmare. N)rZSSLCipherSuitelen CIPHER_SUITESZSSLSetEnabledCiphersrCr )rKciphersresultrrr _set_ciphersoszWrappedSocket._set_ciphersc Cs|sdStj|r2t|d}|}W5QRXd}t}zt |}t |j t |}t||srtdt||}t|t|d}t|t}t|t |}t|W5|rt||dk rt|Xtjtjf}|j|kr td|jdS)z Called when we have set custom validation. We do this in two cases: first, when cert validation is entirely disabled; and second, when using a custom trust DB. NrbzFailed to copy trust referenceTz)certificate verify failed, error code: %d)ospathisfileopenreadr SecTrustRefr CFReleaser SSLCopyPeerTrustrCr)byrefr sslSSLErrorZSecTrustSetAnchorCertificatesZ!SecTrustSetAnchorCertificatesOnlyZSecTrustResultTypeZSecTrustEvaluaterZkSecTrustResultUnspecifiedZkSecTrustResultProceedvalue) rKverify trust_bundlefZ cert_arraytrustrRZ trust_resultZ successesrrr_custom_validate|s>         zWrappedSocket._custom_validatec Cstdtjtj|_t|jtt} t | t 0t |d} | t krT| dd} q>|t | <W5QRXt |j| } t | |rt|ts|d}t|j|t|} t | |t|j|} t | t|j|} | dkr|tjkrt|jtj} t | |r|dk r0t|jtjd} t | |rlt\|_|_t|j|||_t|j|j} t | | ht!|j} | tj"krt#$dn>| tj%kr|&||W5QRqlnt | W5QRqW5QRXqldS)z Actually performs the TLS handshake. This is run automatically by wrapped socket, and shouldn't be needed in user code. Nirzutf-8rTzhandshake timed out)'rZSSLCreateContextrZkSSLClientSideZkSSLStreamTyperCZ SSLSetIOFuncs_read_callback_pointer_write_callback_pointerr _connection_ref_lockidr!ZSSLSetConnection isinstancebytesencodeZSSLSetPeerDomainNamerOrSZSSLSetProtocolVersionMinZSSLSetProtocolVersionMaxkTLSProtocolMaxSupportedkTLSProtocol12ZSSLSetSessionOptionZ"kSSLSessionOptionBreakOnServerAuthr rFrGr rHZSSLSetCertificaterNZ SSLHandshaker0r$r8ZerrSSLServerAuthCompletedre) rKserver_hostnamerarbZ min_versionZ max_versionZ client_certZ client_keyZclient_key_passphraserRZhandlerrr handshakes|         zWrappedSocket.handshakecCs |jSN)r$filenorKrrrrrszWrappedSocket.filenocCs*|jdkr|jd8_|jr&|dS)Nrr)rDrErMrsrrr_decref_socketioss zWrappedSocket._decref_socketioscCs&t|}|||}|d|}|Srq)r)Zcreate_string_bufferr+)rKZbufsizr9Z bytes_readr>rrrrecv s   zWrappedSocket.recvNc Cs|jr dS|dkrt|}tj||}td}|t|j ||t |}W5QRX|t j kr|j dkrtdn"|t jt jfkr|nt||j S)Nrzrecv timed out)rErOr)r*Z from_bufferc_size_trNrZSSLReadrCr]rr0r`r$r8r,ZerrSSLClosedNoNotifyrMr )rKr9nbytesprocessed_bytesrRrrrr+&s.      zWrappedSocket.recv_intocCs ||_dSrqrI)rKr8rrrrJQszWrappedSocket.settimeoutcCs|jSrqryrsrrrr%TszWrappedSocket.gettimeoutc Cshtd}|"t|j|t|t|}W5QRX|tj krZ|j dkrZt dnt ||j S)Nrzsend timed out)r)rvrNrZSSLWriterCrOr]rr0r`r$r8r )rKr>rxrRrrrr=Ws   zWrappedSocket.sendcCs4d}|t|kr0||||t}||7}qdSNr)rOr=SSL_WRITE_BLOCKSIZE)rKr>Z total_sentr?rrrsendallhs zWrappedSocket.sendallc Cs$|t|jW5QRXdSrq)rNrZSSLCloserCrsrrrshutdownns zWrappedSocket.shutdowncCs|jdkrd|_|jr(t|jd|_|jr@t|jd|_|jrvt|jt|jt |j d|_|_ |j S|jd8_dS)NrT)rDrErCrr[rHrFrZSecKeychainDeleteshutilZrmtreerGr$rMrsrrrrMrs        zWrappedSocket.closeFc Cs|s tdt}d}d}zt|jt|}t ||sFWddSt |}|s\WNdSt |d}|spt t |}|st t|}t|} t| |}W5|rt||rt|X|S)Nz2SecureTransport only supports dumping binary certsr) ValueErrorrrZrr[r\rCr)r]r ZSecTrustGetCertificateCountZSecTrustGetCertificateAtIndexAssertionErrorZSecCertificateCopyDataZCFDataGetLengthZCFDataGetBytePtrr<) rKZ binary_formrdZcertdataZ der_bytesrRZ cert_countZleafZ data_lengthr4rrr getpeercerts2       zWrappedSocket.getpeercertcCst}t|jt|}t||jtj kr4dS|jtj krDdS|jtj krTdS|jtj krddS|jtj krtdS|jtjkrdStd|dS)NzTLSv1.3zTLSv1.2zTLSv1.1ZTLSv1ZSSLv3ZSSLv2zUnknown TLS version: %r)rZ SSLProtocolZSSLGetNegotiatedProtocolVersionrCr)r]r r`rZkTLSProtocol13rnkTLSProtocol11 kTLSProtocol1 kSSLProtocol3 kSSLProtocol2r^r_)rKprotocolrRrrrversions&      zWrappedSocket.versioncCs|jd7_dSNr)rDrsrrr_reuseszWrappedSocket._reusecCs&|jdkr|n|jd8_dSr)rDrMrsrrr_drops  zWrappedSocket._drop)N)F)__name__ __module__ __qualname____doc__rL contextlibcontextmanagerrNrSrerprrrtrur+rJr%r=r|r}rMrrrrrrrrrA@s*  9a + :rAcCs|jd7_t|||ddS)NrT)rM)rDr )rKmodebufsizerrrmakefilesrrcOsd}t|||f||Srzr)rKr bufferingargskwargsrrrrsc@seZdZdZddZeddZejddZeddZejd dZed d Z e jd d Z d dZ ddZ ddZ dddZ dddZdddZdS)rz I am a wrapper class for the SecureTransport library, to translate the interface of the standard library ``SSLContext`` object to calls into SecureTransport. cCs8t|\|_|_d|_d|_d|_d|_d|_d|_dSrB) _protocol_to_min_max _min_version _max_version_options_verify _trust_bundle _client_cert _client_key_client_key_passphrase)rKrrrrrLszSecureTransportContext.__init__cCsdS) SecureTransport cannot have its hostname checking disabled. For more, see the comment on getpeercert() in this file. Trrsrrrcheck_hostnamesz%SecureTransportContext.check_hostnamecCsdS)rNrrKr`rrrr scCs|jSrqrrsrrroptionsszSecureTransportContext.optionscCs ||_dSrqrrrrrrscCs|jr tjStjSrq)rr^ CERT_REQUIREDZ CERT_NONErsrrr verify_mode sz"SecureTransportContext.verify_modecCs|tjkrdnd|_dS)NTF)r^rrrrrrr$scCsdSrqrrsrrrset_default_verify_paths(s z/SecureTransportContext.set_default_verify_pathscCs|Srq)rrsrrrload_default_certs4sz)SecureTransportContext.load_default_certscCs|tjjkrtddS)Nz5SecureTransport doesn't support custom cipher strings)rrZDEFAULT_CIPHERSr)rKrQrrr set_ciphers7s z"SecureTransportContext.set_ciphersNcCs|dk rtd|p||_dS)Nz1SecureTransport does not support cert directories)rr)rKZcafileZcapathZcadatarrrload_verify_locations<sz,SecureTransportContext.load_verify_locationscCs||_||_||_dSrq)rrZ_client_cert_passphrase)rKZcertfileZkeyfileZpasswordrrrload_cert_chainCsz&SecureTransportContext.load_cert_chainFTc CsJ|rt|st|stt|}|||j|j|j|j|j|j|j |Srq) rrArprrrrrrr)rKZsockZ server_sideZdo_handshake_on_connectZsuppress_ragged_eofsror6rrr wrap_socketHs  z"SecureTransportContext.wrap_socket)NNN)NN)FTTN)rrrrrLpropertyrsetterrrrrrrrrrrrrrs0          r)r)rN)`rZ __future__rrr)r'Zos.pathrUr~r$r^Z threadingweakrefrZ_securetransport.bindingsrrrZ_securetransport.low_levelr r r r r ImportErrorZpackages.backports.makefiler__all__rrrrrZWeakValueDictionaryr!ZLockrhr{Z'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384Z'TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256Z%TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384Z%TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256Z-TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256Z+TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256Z#TLS_DHE_RSA_WITH_AES_256_GCM_SHA384Z#TLS_DHE_RSA_WITH_AES_128_GCM_SHA256Z'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384Z$TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHAZ'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256Z$TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHAZ%TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384Z"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHAZ%TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256Z"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHAZ#TLS_DHE_RSA_WITH_AES_256_CBC_SHA256Z TLS_DHE_RSA_WITH_AES_256_CBC_SHAZ#TLS_DHE_RSA_WITH_AES_128_CBC_SHA256Z TLS_DHE_RSA_WITH_AES_128_CBC_SHAZTLS_AES_256_GCM_SHA384ZTLS_AES_128_GCM_SHA256ZTLS_RSA_WITH_AES_256_GCM_SHA384ZTLS_RSA_WITH_AES_128_GCM_SHA256ZTLS_AES_128_CCM_8_SHA256ZTLS_AES_128_CCM_SHA256ZTLS_RSA_WITH_AES_256_CBC_SHA256ZTLS_RSA_WITH_AES_128_CBC_SHA256ZTLS_RSA_WITH_AES_256_CBC_SHAZTLS_RSA_WITH_AES_128_CBC_SHArPZ PROTOCOL_TLSrrmrhasattrrrrrrrrrnrrrr;r@Z SSLReadFuncrfZ SSLWriteFuncrgobjectrArrrrrrs3  %            76  !