VY;@sdZddlmZddlZddlmZddlmZ ddl m Z ddl m Z mZddlmZydd l mZWn(ek rdZd d lmZYnXddlZddlZddlZddlZd d lmZd dgZdZejejj ej!ejj"iZ#e$edrae$ejdraejj%e#ej&dd Z?ddZ@ddZAddZBddZCGdd d eDZEerd(d"d#ZFneZFeFeE_FGd$d%d%eDZGd&d'ZHdS))ab SSL with SNI_-support for Python 2. Follow these instructions if you would like to verify SSL certificates in Python 2. Note, the default libraries do *not* do certificate checking; you need to do additional work to validate certificates yourself. This needs the following packages installed: * pyOpenSSL (tested with 16.0.0) * cryptography (minimum 1.3.4, from pyopenssl) * idna (minimum 2.0, from cryptography) However, pyopenssl depends on cryptography, which depends on idna, so while we use all three directly here we end up having relatively few packages required. You can install them with the following command: pip install pyopenssl cryptography idna To activate certificate checking, call :func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code before you begin making HTTP requests. This can be done in a ``sitecustomize`` module, or at any other time before your application begins using ``urllib3``, like this:: try: import urllib3.contrib.pyopenssl urllib3.contrib.pyopenssl.inject_into_urllib3() except ImportError: pass Now you can use :mod:`urllib3` as you normally would, and it will support SNI when the required modules are installed. Activating this module also has the positive side effect of disabling SSL/TLS compression in Python 2 (see `CRIME attack`_). If you want to configure the default list of supported cipher suites, you can set the ``urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST`` variable. .. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication .. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit) )absolute_importN)x509)backend) _Certificate)timeouterror)BytesIO) _fileobject)backport_makefile)utilinject_into_urllib3extract_from_urllib3TPROTOCOL_TLSv1_1TLSv1_1_METHODPROTOCOL_TLSv1_2TLSv1_2_METHODccs!|]\}}||fVqdS)N).0kvrrO/tmp/pip-build-04bmskau/requests/requests/packages/urllib3/contrib/pyopenssl.py `sri@cCsAtttj_tt_ttj_dt_dtj_dS)z7Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.TN)_validate_dependencies_metPyOpenSSLContextr ssl_ SSLContextHAS_SNI IS_PYOPENSSLrrrrr ms     cCs:ttj_tt_ttj_dt_dtj_dS)z4Undo monkey-patching by :func:`inject_into_urllib3`.FN)orig_util_SSLContextr rrorig_util_HAS_SNIrrrrrrrys     cCsuddlm}t|dddkr4tdddlm}|}t|dddkrqtddS) z{ Verifies that PyOpenSSL's package-level dependencies have been met. Throws `ImportError` if they are not met. r) Extensionsget_extension_for_classNzX'cryptography' module missing required functionality. Try upgrading to v1.3.4 or newer.)X509_x509zS'pyOpenSSL' module missing required functionality. Try upgrading to v0.14 or newer.)Zcryptography.x509.extensionsr!getattr ImportErrorZOpenSSL.cryptor#)r!r#rrrrrs  rcCs:dd}||}tjdkr6|jd}|S)a Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version. Cryptography produces a dNSName as a unicode string that was idna-decoded from ASCII bytes. We need to idna-encode that string to get it back, and then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8). cSsoddl}xSddgD]E}|j|r|t|d}|jd|j|SqW|j|S)z Borrowed wholesale from the Python Cryptography Project. It turns out that we can't just safely call `idna.encode`: it can explode for wildcard names. This avoids that problem. rNz*..ascii)idna startswithlenencode)namer)prefixrrr idna_encodes  z'_dnsname_to_stdlib..idna_encoderzutf-8)r0r)sys version_infodecode)r-r/rrr_dnsname_to_stdlibs  r4cCstt|j}y|jjtjj}Wnftjk rIgSYnNtj tj tj t fk r}zt jd|gSWYdd}~XnXdd|jtjD}|jdd|jtjD|S)zU Given an PyOpenSSL certificate, provides all the subject alternative names. zA problem was encountered with the certificate that prevented urllib3 from finding the SubjectAlternativeName field. This can affect certificate validation. The error was %sNcSs"g|]}dt|fqS)DNS)r4)rr-rrr s z%get_subj_alt_name..css!|]}dt|fVqdS)z IP AddressN)str)rr-rrrrsz$get_subj_alt_name..)ropenssl_backendr$ extensionsr"rZSubjectAlternativeNamevalueZExtensionNotFoundZDuplicateExtensionZUnsupportedExtensionZUnsupportedGeneralNameType UnicodeErrorlogwarningZget_values_for_typeZDNSNameextendZ IPAddress)Z peer_certcertextenamesrrrget_subj_alt_names$    rCc@seZdZdZdddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ dddZddZddZdS) WrappedSocketzAPI-compatibility wrapper for Python OpenSSL's Connection-class. Note: _makefile_refs, _drop() and _reuse() are needed for the garbage collector of pypy. TcCs1||_||_||_d|_d|_dS)NrF) connectionsocketsuppress_ragged_eofs_makefile_refs_closed)selfrErFrGrrr__init__s     zWrappedSocket.__init__cCs |jjS)N)rFfileno)rJrrrrLszWrappedSocket.filenocCs5|jdkr|jd8_|jr1|jdS)Nr)rHrIclose)rJrrr_decref_socketioss zWrappedSocket._decref_socketioscOs#y|jj||}Wntjjk rt}z3|jrP|jdkrPdStt|WYdd}~Xntjj k r}z'|jj tjj krdSWYdd}~Xn_tjj k rt j|j|jj}|stdn|j||SYnX|SdS)NrMUnexpected EOFzThe read operation timed out)rRrP)rErecvOpenSSLSSL SysCallErrorrGargs SocketErrorr7ZeroReturnError get_shutdownRECEIVED_SHUTDOWN WantReadErrorr wait_for_readrF gettimeoutr)rJrWkwargsdatarArdrrrrSs $zWrappedSocket.recvcOsy|jj||SWntjjk rr}z3|jrN|jdkrNdStt|WYdd}~Xntjj k r}z'|jj tjj krdSWYdd}~Xn[tjj k rt j|j|jj}|stdn|j||SYnXdS)NrMUnexpected EOFrzThe read operation timed outrR)rRrb)rE recv_intorTrUrVrGrWrXr7rYrZr[r\r r]rFr^r)rJrWr_rArarrrrcs$zWrappedSocket.recv_intocCs|jj|S)N)rF settimeout)rJrrrrrd'szWrappedSocket.settimeoutcCsxy|jj|SWqtjjk ratj|j|jj}|sZt wYqtjj k r}zt t |WYdd}~XqXqWdS)N) rEsendrTrUZWantWriteErrorr Zwait_for_writerFr^rrVrXr7)rJr`wrrArrr_send_until_done*s zWrappedSocket._send_until_donecCsJd}x=|t|krE|j|||t}||7}q WdS)Nr)r+rgSSL_WRITE_BLOCKSIZE)rJr` total_sentsentrrrsendall6szWrappedSocket.sendallcCs|jjdS)N)rEshutdown)rJrrrrl<szWrappedSocket.shutdownc Cs^|jdkrKyd|_|jjSWqZtjjk rGdSYqZXn|jd8_dS)NrMT)rHrIrErNrTrUError)rJrrrrN@s  zWrappedSocket.closeFcCsc|jj}|s|S|r8tjjtjj|Sdd|jjfffdt|iS)Nsubject commonNamesubjectAltName) rEZget_peer_certificaterTZcryptoZdump_certificateZ FILETYPE_ASN1Z get_subjectZCNrC)rJ binary_formrrrr getpeercertJs  zWrappedSocket.getpeercertcCs|jd7_dS)NrM)rH)rJrrr_reuse\szWrappedSocket._reusecCs/|jdkr|jn|jd8_dS)NrM)rHrN)rJrrr_drop_s zWrappedSocket._dropN)__name__ __module__ __qualname____doc__rKrLrOrSrcrdrgrkrlrNrrrsrtrrrrrDs          rDrMcCs%|jd7_t|||ddS)NrMrNT)rHr )rJmodebufsizerrrmakefilegsr{c@seZdZdZddZeddZejddZeddZejd dZd d Z d d Z dddddZ ddddZ ddddddZ dS)rz I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible for translating the interface of the standard library ``SSLContext`` object to calls into PyOpenSSL. cCs;t||_tjj|j|_d|_d|_dS)NrF)_openssl_versionsprotocolrTrUZContext_ctx_optionscheck_hostname)rJr}rrrrKvs  zPyOpenSSLContext.__init__cCs|jS)N)r)rJrrroptions|szPyOpenSSLContext.optionscCs||_|jj|dS)N)rr~ set_options)rJr:rrrrs cCst|jjS)N)_openssl_to_stdlib_verifyr~Zget_verify_mode)rJrrr verify_modeszPyOpenSSLContext.verify_modecCs|jjt|tdS)N)r~Z set_verify_stdlib_to_openssl_verify_verify_callback)rJr:rrrrs cCs|jjdS)N)r~set_default_verify_paths)rJrrrrsz)PyOpenSSLContext.set_default_verify_pathscCs5t|tjr!|jd}|jj|dS)Nzutf-8) isinstancesix text_typer,r~Zset_cipher_list)rJciphersrrr set_ciphersszPyOpenSSLContext.set_ciphersNcCso|dk r|jd}|dk r6|jd}|jj|||dk rk|jjt|dS)Nzutf-8)r,r~load_verify_locationsr)rJcafilecapathcadatarrrrs   z&PyOpenSSLContext.load_verify_locationscsR|jj|dk r8|jjfdd|jj|pJ|dS)NcsS)Nr) max_lengthZ prompt_twiceZuserdata)passwordrrsz2PyOpenSSLContext.load_cert_chain..)r~Zuse_certificate_fileZ set_passwd_cbZuse_privatekey_file)rJcertfilekeyfilerr)rrload_cert_chains z PyOpenSSLContext.load_cert_chainFTc Cstjj|j|}t|tjr9|jd}|dk rR|j||j xy|j Wntjj k rt j ||j}|stdw_Yn>tjjk r}ztjd|WYdd}~XnXPq_Wt||S)Nzutf-8zselect timed outzbad handshake: %r)rTrU Connectionr~rrrr,Zset_tlsext_host_nameZset_connect_state do_handshaker\r r]r^rrmsslSSLErrorrD) rJsock server_sidedo_handshake_on_connectrGserver_hostnamecnxrarArrr wrap_sockets$    &zPyOpenSSLContext.wrap_socket)rurvrwrxrKpropertyrsetterrrrrrrrrrrrps     rcCs |dkS)Nrr)rrZerr_noZ err_depthZ return_coderrrrsrrR)Irx __future__rZ OpenSSL.SSLrTZ cryptographyrZ$cryptography.hazmat.backends.opensslrr8Z)cryptography.hazmat.backends.openssl.x509rrFrrrXiorr r&Zpackages.backports.makefiler loggingrrr1r __all__rPROTOCOL_SSLv23rUZ SSLv23_METHODPROTOCOL_TLSv1Z TLSv1_METHODr|hasattrrrrrupdateZPROTOCOL_SSLv3Z SSLv3_METHODAttributeError CERT_NONEZ VERIFY_NONE CERT_OPTIONALZ VERIFY_PEER CERT_REQUIREDZVERIFY_FAIL_IF_NO_PEER_CERTrdictitemsrrhr rrr getLoggerrur<r rrr4rCobjectrDr{rrrrrr+sf       !!       0 S