źhT6dZddlZddlZddlZddlZddlZddlZddlZddlZddl m Z m Z m Z ej dejZdZdZdZd Zd Zdd Zd Zd ZdZdZdZdZddddddZdZdS)a Low-level helpers for the SecureTransport bindings. These are Python functions that are not directly related to the high-level APIs but are necessary to get them to work. They include a whole bunch of low-level CoreFoundation messing about and memory management. The concerns in this module are almost entirely about trying to avoid memory leaks and providing appropriate and useful assistance to the higher-level code. N)CFConstCoreFoundationSecuritys;-----BEGIN CERTIFICATE----- (.*?) -----END CERTIFICATE-----c\tjtj|t|S)zv Given a bytestring, create a CFData object from it. This CFData object must be CFReleased by the caller. )r CFDataCreatekCFAllocatorDefaultlen) bytestrings /builddir/build/BUILD/imunify360-venv-2.5.2/opt/imunify360/venv/lib/python3.11/site-packages/urllib3/contrib/_securetransport/low_level.py_cf_data_from_bytesr s)  &*JJ  ct|}d|D}d|D}tj|z|}tj|z|}tjtj|||tjtjS)zK Given a list of Python tuples, create an associated CFDictionary. c3&K|] }|dV dS)rN.0ts r z-_cf_dictionary_from_tuples..,s& ! !QAaD ! ! ! ! ! !rc3&K|] }|dV dS)rNrrs r rz-_cf_dictionary_from_tuples..-s& # #qad # # # # # #r)r r CFTypeRefCFDictionaryCreater kCFTypeDictionaryKeyCallBackskCFTypeDictionaryValueCallBacks)tuplesdictionary_sizekeysvaluescf_keys cf_valuess r _cf_dictionary_from_tuplesr!%s&kkO " !& ! ! !D # #F # # #F'/9DAG)O;fEI  ,*46   rctj|}tjtj|t j}|S)zi Given a Python binary data, create a CFString. The string must be CFReleased by the caller. )ctypesc_char_prCFStringCreateWithCStringr rkCFStringEncodingUTF8)py_bstrc_strcf_strs r _cfstrr*;s; OG $ $E  5* %F Mrcd} tjtjdtjtj}|st d|D]e}t|}|st d tj||tj |M#tj |wxYwn?#t$r2}|rtj |tj d|d}~wwxYw|S)z Given a list of Python binary data, create an associated CFMutableArray. The array must be CFReleased by the caller. Raises an ssl.SSLError on failure. NrUnable to allocate memory!zUnable to allocate array: ) rCFArrayCreateMutabler r#byrefkCFTypeArrayCallBacks MemoryErrorr*CFArrayAppendValue CFRelease BaseExceptionsslSSLError)lstcf_arritemr)es r _create_cfstring_arrayr:Is)FB4  . L= > >    <:;; ; 1 1DD\\F @!">??? 11&&AAA(0000(0000 1 BBB  -  $V , , ,llQQ@AAAB Ms0A1B:6B  B: B66B:: C6-C11C6crtj|tjtj}t j|t j}|Mtjd}t j ||dt j}|std|j }|| d}|S)z Creates a Unicode string from a CFString object. Used entirely for error reporting. Yes, it annoys me quite a lot that this function is this complex. Niz'Error copying C string from CFStringRefutf-8) r#castPOINTERc_void_prCFStringGetCStringPtrrr&create_string_bufferCFStringGetCStringOSErrorvaluedecode)rDvalue_as_void_pstringbufferresults r _cf_string_to_unicoderJhsk%)H)HIIO  16F~,T222 VT7+H   ECDD D w'' Mrc|dkrdStj|d}t|}tj|||dkrd|z}| t j}||)z[ Checks the return code and throws an exception if there is an error to report rNz OSStatus %s)rSecCopyErrorMessageStringrJrr2r4r5)errorexception_classcf_error_stringoutputs r _assert_no_errorrRsv  zz8EEO "? 3 3F_--- ~3%', /& ! !!rc|dd}dt|D}|stjdt jt jdtj t j }|stjd |D]}t|}|stjdtj t j|}t j||stjdt j||t j|n$#t $rt j|YnwxYw|S)z Given a bundle of certs in PEM format, turns them into a CFArray of certs that can be used to validate a cert chain. s  c\g|])}tj|d*S)r)base64 b64decodegroup)rmatchs r z(_cert_array_from_pem..s:-2Q((rzNo root certificates specifiedrr,zUnable to build cert object!)replace _PEM_CERTS_REfinditerr4r5rr-r r#r.r/r rSecCertificateCreateWithDatar2r1 Exception) pem_bundle der_certs cert_array der_bytescertdatacerts r _cert_array_from_pemrfs ##GU33J6C6L6LZ6X6XI =l;<<<4*  ^9::J 9l7888-" + +I*955H Al#?@@@82HD  $X . . . Cl#ABBB  -j$ ? ? ?  $T * * * * + ---  ,,,,, - s$BEE"!E"cXtj}tj||kS)z= Returns True if a given CFTypeRef is a certificate. )rSecCertificateGetTypeIDr CFGetTypeIDr8expecteds r _is_certrls(/11H  %d + +x 77rcXtj}tj||kS)z; Returns True if a given CFTypeRef is an identity. )rSecIdentityGetTypeIDrrirjs r _is_identityros(,..H  %d + +x 77rc tjd}tj|ddd}tj|dd}t j}tj|| d}tj }tj |t||ddtj|}t!|||fS)a This function creates a temporary Mac keychain that we can use to work with credentials. This keychain uses a one-time password and a temporary file to store the data. We expect to have one keychain per socket. The returned SecKeychainRef must be freed by the caller, including calling SecKeychainDelete. Returns a tuple of the SecKeychainRef and the path to the temporary directory that contains it. (Nr<F)osurandomrV b16encoderEtempfilemkdtemppathjoinencoderSecKeychainRefSecKeychainCreater r#r.rR) random_bytesfilenamepassword tempdirectory keychain_pathkeychainstatuss r _temporary_keychainrs":b>>L RaR 01188AAH QRR 011H$&&MGLL99@@IIM&((H  's8}}htV\(=S=SFV ] ""rc g}g}d}t|d5}|}dddn #1swxYwY tjtj|t |}tj}tj|ddddd|tj |}t|tj |} t| D]} tj|| } tj| tj} t#| r*tj| || ot)| r)tj| ||  |rtj|tj|n/#|rtj|tj|wxYw||fS)z Given a single file, loads all the trust objects from it into arrays and the keychain. Returns a tuple of lists: the first list is a list of identities, the second a list of certs. Nrbr)openreadrrr r CFArrayRefr SecItemImportr#r.rRCFArrayGetCountrangeCFArrayGetValueAtIndexr=rrlCFRetainappendror2) rrx certificates identities result_arrayf raw_filedatafiledatarI result_countindexr8s r _load_items_from_filers,LJL dD   Qvvxx                $+!.  . c,>O>O  &022 '       L & &       &5lCC <(( ( (E!8uMMD;t^%=>>D~~ ('---##D))))d## ('---!!$''' (  3  $\ 2 2 2 ****  3  $\ 2 2 2 ****  %%s8<<EF77,G#cTg}g}d|D} |D]?}t||\}}||||@|stj}tj||dt j|}t|||tj | dtj tj dt jtj} tj||D]} tj| | | tj||D]} tj | S#tj||D]} tj | wxYw)z Load certificates and maybe keys from a number of files. Has the end goal of returning a CFArray containing one SecIdentityRef, and then zero or more SecCertificateRef objects, suitable for use as a client certificate trust chain. c3K|]}||V dSNr)rrxs r rz*_load_client_cert_chain..Qs' , ,dt ,T , , , , , ,rr)rextendrSecIdentityRef SecIdentityCreateWithCertificater#r.rRrrr2popr-r r/ itertoolschainr1) rpathsrr file_pathnew_identities new_certs new_identityr trust_chainr8objs r _load_client_cert_chainr-s@LJ - ,e , , ,E"* + +I(=h (R(R %NI   n - - -    * * * * :#244L>,q/6< +E+EF V $ $ $   l + + +  $\%5%5a%8%8 9 9 9%9  . L= > >  OJ == A AD  -k4 @ @ @ @?:|<< * *C  $S ) ) ) ) *9?:|<< * *C  $S ) ) ) ) *s D:E99.F')r)r)rr)rr)rr)SSLv2SSLv3TLSv1zTLSv1.1zTLSv1.2ct|\}}d}d}tjd||}t|}d}tjd|||||z}|S)z6 Builds a TLS alert record for an unknown CA. r0z>BBz>BBBH)TLS_PROTOCOL_VERSIONSstructpackr ) versionver_majver_minseverity_fataldescription_unknown_camsgmsg_lenrecord_type_alertrecords r _build_tls_unknown_ca_alertrsf-W5GWN! +e^-C D DC#hhG ["3Wgw O ORU UF Mrr)__doc__rVr#rrsrer4rrvbindingsrrrcompileDOTALLr\r r!r*r:rJrRrfrlrorrrrrrrr rs  7777777777 Dbi ,   >2""""****Z888888 # # #F4&4&4&nH*H*H*X        r