bgI UdZddlmZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddl m ZddlmZddlmZmZdd lmZmZmZmZmZmZmZejd ed e j rdd l!m"Z"d dgZ#ej$j%Z&ej'Z(de)d<e j*Z+dZ,ej$j-ej.ej/fej$j0ej.ej/fiZ1e2e drej3ej3fe1e j4<e2e drej5ej5fe1e j6<e2e drej.ej.fe1e j7<e2e drej8ej8fe1e j9<e2e drej/ej/fe1e j:<e j;j<ej.e j;j=ej.e j;j>ej8e j;j?ej/e j;j@ej/iZAde)d<d4dZBd4dZCd5d"ZDd5d#ZEejFeDZGejHeEZIGd$d%ZJ d6d7d1ZKeKeJ_KGd2d3ZLdS)8a 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: .. code-block:: 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. ) annotationsN)socket)util)CoreFoundationSecurity) SecurityConst_assert_no_error_build_tls_unknown_ca_alert_cert_array_from_pem_create_cfstring_array_load_client_cert_chain_temporary_keychainz'urllib3.contrib.securetransport' module is deprecated and will be removed in urllib3 v2.1.0. Read more in this issue: https://github.com/urllib3/urllib3/issues/2681)category stacklevel)Literalinject_into_urllib3extract_from_urllib3z/weakref.WeakValueDictionary[int, WrappedSocket]_connection_refsi@PROTOCOL_SSLv2PROTOCOL_SSLv3PROTOCOL_TLSv1PROTOCOL_TLSv1_1PROTOCOL_TLSv1_2zdict[int, int]_tls_version_to_streturnNonectt_ttj_dt_dtj_dS)zG Monkey-patch urllib3 with SecureTransport-backed SSL-support. TN)SecureTransportContextr SSLContextssl_IS_SECURETRANSPORTp/builddir/build/BUILD/cloudlinux-venv-1.0.7/venv/lib/python3.11/site-packages/urllib3/contrib/securetransport.pyrrs--DO1DI"D#'DI   r%ctt_ttj_dt_dtj_dS)z> Undo monkey-patching by :func:`inject_into_urllib3`. FN)orig_util_SSLContextrr!r"r#r$r%r&rrs-+DO/DI#D#(DI   r% connection_idint data_bufferdata_length_pointer bytearrayc4d} t|}| tjS|j}|d}|}d}d} ||kr||dkr/t j||sttj d||z } tj | z ||z} || | } || z }| s|s tjSn||kng#t$rZ} | j }|G|tj kr7||d<|tjks|tjkrtjcYd} ~ SYd} ~ nd} ~ wwxYw||d<||kr tjSdS#t($r} || |_tjcYd} ~ Sd} ~ wwxYw)zs SecureTransport read callback. This is called by ST to request that data be returned from the socket. Nr timed out)rgetr errSSLInternalr gettimeoutr wait_for_readOSErrorerrnoEAGAINctypesc_char from_address recv_intoerrSSLClosedGraceful ECONNRESETEPIPEerrSSLClosedAborterrSSLWouldBlock Exception _exception) r)r+r,wrapped_socket base_socketrequested_lengthtimeouterror read_count remainingbuffer chunk_sizees r&_read_callbackrLs N.,)--m<<  ! / /$+ .q1 ++--  ///?gll-k7CCA%elK@@@,z9  -)3AA*,)2269EE j( !%B,AA///   GE Uel%:%:)3#A&E,,,0D0D(::::::: ",A ) ) ) 1 1q ,,,  %()N %+++++++,sf'E.'E.BC.&C.-E.. E8A E EE.E E. EE.. F8F FFcd} t|}| tjS|j}|d}t j||}|}d}d} | |kra||dkr/tj ||sttj d| |} | | z } || d}| |kang#t$rZ} | j }|G|tj kr7| |d<|tjks|tjkrtjcYd} ~ SYd} ~ nd} ~ wwxYw| |d<| |kr tjSdS#t$$r} || |_tjcYd} ~ Sd} ~ wwxYw)zx SecureTransport write callback. This is called by ST to request that data actually be sent on the network. Nrr/)rr0r r1rr7 string_atr2rwait_for_writer4r5r6sendr<r=r>r?r@rA) r)r+r,rBrCbytes_to_writedatarErFsent chunk_sentrKs r&_write_callbackrUsN*,)--m<<  ! / /$+ ,Q/ ^<< ++-- ''?gll.{GDDA%elK@@@(--d33  "JKK(''   GE Uel%:%:)-#A&E,,,0D0D(::::::: "&A > ! ! 1 1q ,,,  %()N %+++++++,s`'EdZ d?dZ d@d Z dAd"Z dBdCd(ZdDd+ZdEd-ZdFd/ZdGd0Zd@d1Zd@d2Zd@d3ZdHdId6ZdJd8Zd#S)K WrappedSocketzO API-compatibility wrapper for Python's OpenSSL wrapped socket object. r socket_clsrrc||_d|_d|_d|_d|_d|_d|_d|_d|_|j |_ |j ddSNrF) rcontext_io_refs_closed _real_closedrA _keychain _keychain_dir_client_cert_chainr2_timeout settimeout)selfrs r&__init__zWrappedSocket.__init__;sw    !,0)-"& ..00  q!!!!!r%"typing.Generator[None, None, None]c#xKd|_dV|j%|jdc}|_||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)rA _real_close)rd exceptions r&_raise_on_errorzWrappedSocket._raise_on_errorNsQ  ? &)-$ &It      O ' &r% protocolslist[bytes] | Nonec|sdSt|} tj|j|}t |t j|dS#t j|wxYw)z< Sets up the ALPN protocols on the context. N)rr SSLSetALPNProtocolsr[r r CFRelease)rdrk protocols_arrresults r&_set_alpn_protocolsz!WrappedSocket._set_alpn_protocolscss  F.y99  41$, NNF V $ $ $  $] 3 3 3 3 3N $] 3 3 3 3s )AA*verifybool trust_bundle bytes | Nonec6|r|dStjtjf} ||}||vrdSdt |}d}n#t $r}d|}|}Yd}~nd}~wwxYwt |}|j |tj ddd} |j tj tj| |t!jd||)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. Raises an SSLError if the connection is not trusted. Nz error code: z exception: iirrzcertificate verify failed, )r kSecTrustResultUnspecifiedkSecTrustResultProceed_evaluate_trustr*r@r versionrsendallstructpack setsockopt SOL_SOCKET SO_LINGERrhsslSSLError) rdrsru successes trust_resultreasonexcrKrecoptss r&_custom_validatezWrappedSocket._custom_validateps9 - F  4  0  // ==Ly((7C $5$577FCC   (1((FCCCCCC  *$,,..99 C   {4A&& v0&2BDIII lAAABBKsAA A+A&&A+bytesr*ctj|r>, ' ' (lD)) (Q vvxx  ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( $&& 5-l;;J .t|V\%=P=PQQF V $ $ $ El#CDDD;E:NNF V $ $ $?tLLF V $ $ $#688L.ufl<6P6PQQF V $ $ $ 0(///%(444  0(///%(4444&!!sAAA2C1F/F?server_hostnamebytes | str | None min_version max_version client_cert str | None client_keyclient_key_passphrase typing.Anyalpn_protocolsc tjdtjtj|_tj|jtt} t| t5t|dz} | tvr| dzdz} | tv|t| <dddn #1swxYwYtj |j| } t| |rat|ts|d}tj|j|t%|} t| || tj|j|} t| tj|j|} t| |r|4tj|jtjd} t| |rdt1\|_|_t7|j|||_tj|j|j} t|  |5tj|j} | tj krtCj"d| tj#kr#|$|| dddt|  ddddS#1swxYwY)z Actually performs the TLS handshake. This is run automatically by wrapped socket, and shouldn't be needed in user code. Nirzutf-8Tzhandshake timed out)%r SSLCreateContextr kSSLClientSidekSSLStreamTyper[ SSLSetIOFuncs_read_callback_pointer_write_callback_pointerr _connection_ref_lockidrSSLSetConnection isinstancerencodeSSLSetPeerDomainNamelenrrSSLSetProtocolVersionMinSSLSetProtocolVersionMaxSSLSetSessionOption"kSSLSessionOptionBreakOnServerAuthrr_r`rraSSLSetCertificaterj SSLHandshaker?rrEerrSSLServerAuthCompletedr) rdrrsrurrrrrrrqhandles r& handshakezWrappedSocket.handshakesz$ 0 -. 0L   ' L02I      " , ,XX *F,,, 1* 2,,,'+ V $  , , , , , , , , , , , , , , , *4<@@    %ou55 B"1"8"8"A"A2 os?/C/CF V $ $ $   00024<MM   24<MM    %11 mNPTF V $ $ $  %1D1F1F .DND.&= Z''D #/ d>UVVF V $ $ $ %%''  !.t|<<];;; .)>???}FFF))&,???       %V,,,                 s++7B..B25B2A%K-K--K14K1c4|jSN)rfilenords r&rzWrappedSocket.filenos{!!###r%cv|jdkr|xjdzc_|jr|dSdS)Nrr)r\r]closers r&_decref_socketioszWrappedSocket._decref_socketiossD =1   MMQ MM <  JJLLLLL  r%bufsizctj|}|||}|d|}tjt |Sr)r7create_string_bufferr:typingcastr)rdrrI bytes_readrRs r&recvzWrappedSocket.recv#sE,V44^^FF33 kzk"{5$'''r%NrIctypes.Array[ctypes.c_char]nbytes int | Nonec @|jrdS|t|}tj|z|}tjd}|5tj|j ||tj |}dddn #1swxYwY|tj kr |j dkrtjdn>|tjtjfvr|nt'||j S)Nrzrecv timed out)r^rr7r8 from_bufferc_size_trjr SSLReadr[rr r?rrrEr;errSSLClosedNoNotifyrhr )rdrIrprocessed_bytesrqs r&r:zWrappedSocket.recv_into)sa   1 >[[F-&(55f== /!,,  ! ! # #  % fffl?.K.KF                ]3 3 3 $))n%5666*  .  .           V $ $ $$$s%/B  B$'B$rEfloatc||_dSrrb)rdrEs r&rczWrappedSocket.settimeoutVs  r% float | Nonec|jSrrrs r&r2zWrappedSocket.gettimeoutYs }r%rRc tjd}|5tj|j|t |tj|}dddn #1swxYwY|tj kr|j dkrtj dt||j S)Nrzsend timed out)r7rrjr SSLWriter[rrr r?rrrEr )rdrRrrqs r&rPzWrappedSocket.send\s /!,,  ! ! # #  & dCIIv|O/L/LF                ]3 3 38MQR8R8R.!122 2 V $ $ $$$s 7  &t~ 6 6 6  $T^ 4 4 4 M$, - - -26 6DNT/{  """r%F binary_formc\|stdtj}d}d} tj|jt j|}t||s1 |rtj ||rtj |dSdStj |}|s1 |rtj ||rtj |dSdStj |d}|sJtj |}|sJtj |}tj|} t j| |}|rtj ||rtj |n2#|rtj ||rtj |wwxYw|S)Nz2SecureTransport only supports dumping binary certsr) ValueErrorr rrr[r7rr rroSecTrustGetCertificateCountSecTrustGetCertificateAtIndexSecCertificateCopyDataCFDataGetLengthCFDataGetBytePtrrN) rdrrcertdata der_bytesrq cert_countleaf data_lengthr+s r& getpeercertzWrappedSocket.getpeercerts( SQRR R$&&  0.t|V\%=P=PQQF V $ $ $ & 3(222 0(///// 0 0'"=eDDJ  3(222 0(///// 0 09%CCDKK4 6t<]9 9 9,IJJ J ^}; ; ;9 ^}; ; ;9 ^}: : :7 ^}: : :7 ^}: : :7,CxCCDD Dr%)rrXrr)rrf)rkrlrr)rsrtrurvrr)rurrr*)rrrsrtrurvrr*rr*rrrrrrrrlrrrr*rr)rr*rrr)rIrrrrr*)rErrr)rr)rRrrr*)rRrrr)F)rrtrrv)rr)__name__ __module__ __qualname____doc__re contextlibcontextmanagerrjrrrr{rrrrr:rcr2rPr}rrrhrr|r$r%r&rWrW6s""""&( 4 4 4 4#L#L#L#LJ&"&"&"&"PZZZZx$$$$ ((((IM+%+%+%+%+%Z    %%%%" ,,,, # # # #88888tEEEEEEr%rWrrdrXmodeILiteral['r'] | Literal['w'] | Literal['rw'] | Literal['wr'] | Literal[''] bufferingrargsrkwargstyping.BinaryIO | typing.TextIOc4d}tj|||g|Ri|Sr)rXmakefile)rdrrrrs r&rrs.I  tT9 Ft F F Fv F FFr%ceZdZdZd5dZed6dZejd7d Zed8d Zejd9d Zed8dZ e jd9dZ d:dZ d:dZ d;dZ dd?dZd@d"Z dAdBd.Zed8d/ZejdCd1Zed8d2ZejdDd4ZdS)Er z I am a wrapper class for the SecureTransport library, to translate the interface of the standard library ``SSLContext`` object to calls into SecureTransport. rr*rrc*tjj|_tjj|_|dtjtjfvrt|\|_ |_ d|_ d|_ d|_ d|_d|_d|_d|_dSrZ)r TLSVersionMINIMUM_SUPPORTED_minimum_versionMAXIMUM_SUPPORTED_maximum_version PROTOCOL_TLSPROTOCOL_TLS_CLIENT_protocol_to_min_max _min_version _max_version_options_verify _trust_bundle _client_cert _client_key_client_key_passphrase_alpn_protocols)rdrs r&rezSecureTransportContext.__init__s%(^%E%(^%E D#"2C4KL L L3G3Q 0D t0  +/(,'+&*#37r% Literal[True]cdS) SecureTransport cannot have its hostname checking disabled. For more, see the comment on getpeercert() in this file. Tr$rs r&check_hostnamez%SecureTransportContext.check_hostnames tr%rrcdS)r,Nr$rdrs r&r-z%SecureTransportContext.check_hostname sr%c|jSrr#rs r&optionszSecureTransportContext.optionss }r%c||_dSrr1r/s r&r2zSecureTransportContext.optionss r%c@|jr tjn tjSr)r$r CERT_REQUIRED CERT_NONErs r& verify_modez"SecureTransportContext.verify_mode!s$(LCs  cmCr%c0|tjk|_dSr)rr5r$r/s r&r7z"SecureTransportContext.verify_mode%s 11 r%cdSrr$rs r&set_default_verify_pathsz/SecureTransportContext.set_default_verify_paths)s  r%c*|Sr)r:rs r&load_default_certsz)SecureTransportContext.load_default_certs5s,,...r%ciphersc td)Nz5SecureTransport doesn't support custom cipher strings)r)rdr=s r& set_ciphersz"SecureTransportContext.set_ciphers8sPQQQr%Ncafilercapathcadatarvc|td|(t|5 dddn #1swxYwY|p||_dS)Nz1SecureTransport does not support cert directories)rrr%)rdr@rArBs r&load_verify_locationsz,SecureTransportContext.load_verify_locations;s  PQQ Q  f                 $-vs 155certfilerkeyfilepasswordc0||_||_||_dSr)r&r'_client_cert_passphrase)rdrErFrGs r&load_cert_chainz&SecureTransportContext.load_cert_chainLs" %"'/$$$r%rklist[str | bytes]cpttdstdd|D|_dS)z Sets the ALPN protocols that will later be set on the context. Raises a NotImplementedError if ALPN is not supported. rnz2SecureTransport supports ALPN only in macOS 10.12+cNg|]"}tj|d#S)ascii)rto_bytes).0ps r& z=SecureTransportContext.set_alpn_protocols..`s*RRR1 2 21g > >RRRr%N)hasattrr NotImplementedErrorr))rdrks r&set_alpn_protocolsz)SecureTransportContext.set_alpn_protocolsVsK x!677 %D  SR RRRr%FTsockrX server_sidertdo_handshake_on_connectsuppress_ragged_eofsrrrWc |rJ|sJ|sJt|}|||j|jt|jt|j|j|j|j |j |Sr) rWrr$r%rrrr&r'r(r))rdrVrWrXrYrrBs r& wrap_socketz"SecureTransportContext.wrap_socketbs&&&&####'t,,    L   t4 5 t4 5      '   r%c|jSrrrs r&minimum_versionz&SecureTransportContext.minimum_version $$r%r^c||_dSrr])rdr^s r&r^z&SecureTransportContext.minimum_version /r%c|jSrrrs r&maximum_versionz&SecureTransportContext.maximum_versionr_r%rdc||_dSrrc)rdrds r&rdz&SecureTransportContext.maximum_versionrar%)rr*rr)rr*)rrrrr)rr*rrr)r=rrr)NNN)r@rrArrBrvrr)NN)rErrFrrGrrr)rkrKrr)FTTN) rVrXrWrtrXrtrYrtrrrrW)r^r*rr)rdr*rr)rr r r repropertyr-setterr2r7r:r<r?rDrJrUr[r^rdr$r%r&r r sM 8 8 8 8X    X ^^DDDXD2222     ////RRRR "!# .....(## 00000 S S S S"(,%).2 B%%%X%0000%%%X%000000r%r r)r)r*r+r*r,r-rr*)rN) rdrXrrrrrrrrrr)Mr  __future__rr r7r5os.pathrrrrr~ threadingrwarningsweakrefrXr_securetransport.bindingsrr _securetransport.low_levelr r r r rrrwarnDeprecationWarning TYPE_CHECKINGtyping_extensionsr__all__r"r!r(WeakValueDictionaryr__annotations__Lockrrrrrrr rSrrrrrrrrrrrTLSv1_1TLSv1_2rrrrrLrU SSLReadFuncr SSLWriteFuncrrWrr r$r%r&r|s444l#"""""   '''''' 5   *)))))) "8 9y+( G!!""""&y~''  I]8-:VWI!#$$ 73 !!##0+, 73 !!##0+, 73 !!##0+, 73"##$$2-. 73"##$$2-.N$m&AN-5NM8NM8N$m&B &(((())))6,6,6,6,r2,2,2,2,p.-n==/(/@@cEcEcEcEcEcEcEcET  G G G G G" c0c0c0c0c0c0c0c0c0c0r%