3 nf\=@sddZddlmZddlZddlmZddlmZ ddl m Z yddl m Z Wn$ek rpGdd d eZ YnXdd lmZmZdd lmZydd lmZWn$ek rdZd dlmZYnXddlZddlZd dlmZddlZd dlmZddgZ dZ!ej"ej#j$ej%ej#j&iZ'e(edr@e(ej#dr@ej#j)e'ej*<e(edrhe(ej#drhej#j+e'ej,<ye'j-ej.ej#j/iWne0k rYnXej1ej#j2ej3ej#j4ej5ej#j4ej#j6iZ7e8dde7j9DZ:dZ;ej!ZZ?ej@eAZBddZCddZDddZEdd ZFd!d"ZGGd#d$d$eHZIer>d-d&d'ZJneZJeJeI_JGd(d)d)eHZKd*d+ZLdS).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)UnsupportedExtensionc@s eZdZdS)rN)__name__ __module__ __qualname__r r /usr/lib/python3.6/pyopenssl.pyr6sr)timeouterror)BytesIO) _fileobject)backport_makefile)six)utilinject_into_urllib3extract_from_urllib3TPROTOCOL_TLSv1_1TLSv1_1_METHODPROTOCOL_TLSv1_2TLSv1_2_METHODccs|]\}}||fVqdS)Nr ).0kvr r r fsri@cCs.tttj_tt_ttj_dt_dtj_dS)z7Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.TN)_validate_dependencies_metPyOpenSSLContextrssl_ SSLContextHAS_SNI IS_PYOPENSSLr r r r rss cCs(ttj_tt_ttj_dt_dtj_dS)z4Undo monkey-patching by :func:`inject_into_urllib3`.FN)orig_util_SSLContextrr r!orig_util_HAS_SNIr"r#r r r r rs cCsRddlm}t|dddkr$tdddlm}|}t|dddkrNtddS) 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(rr r r rs  rcCs@dd}d|kr|S||}|dkr(dStjdkr<|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). If the name cannot be idna-encoded then we return None signalling that the name given should be skipped. c Sslddl}yFx:dD]2}|j|r|t|d}|jd|j|SqW|j|S|jjk rfdSXdS)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. rN*..ascii)r,r-)idna startswithlenencodeZcoreZ IDNAError)namer/prefixr r r idna_encodes   z'_dnsname_to_stdlib..idna_encode:Nrzutf-8)r7r)sys version_infodecode)r3r5r r r _dnsname_to_stdlibs   r;cCst|dr|j}n tt|j}y|jjtjj }WnLtj k rJgStj t tj tfk r}ztjd|gSd}~XnXddtt|jtjD}|jdd|jtjD|S)zU Given an PyOpenSSL certificate, provides all the subject alternative names. to_cryptographyzA problem was encountered with the certificate that prevented urllib3 from finding the SubjectAlternativeName field. This can affect certificate validation. The error was %sNcSsg|]}|dk rd|fqS)NZDNSr )rr3r r r sz%get_subj_alt_name..css|]}dt|fVqdS)z IP AddressN)str)rr3r r r rsz$get_subj_alt_name..)hasattrr<ropenssl_backendr) extensionsr'rZSubjectAlternativeNamevalueZExtensionNotFoundZDuplicateExtensionrZUnsupportedGeneralNameType UnicodeErrorlogZwarningmapr;Zget_values_for_typeZDNSNameextendZ IPAddress)Z peer_certZcertZextenamesr r r get_subj_alt_names&    rIc@s|eZdZdZdddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ d ddZddZddZdS)! WrappedSocketzAPI-compatibility wrapper for Python OpenSSL's Connection-class. Note: _makefile_refs, _drop() and _reuse() are needed for the garbage collector of pypy. TcCs"||_||_||_d|_d|_dS)NrF) connectionsocketsuppress_ragged_eofs_makefile_refs_closed)selfrKrLrMr r r __init__s zWrappedSocket.__init__cCs |jjS)N)rLfileno)rPr r r rRszWrappedSocket.filenocCs*|jdkr|jd8_|jr&|jdS)Nr)rNrOclose)rPr r r _decref_socketios s zWrappedSocket._decref_socketioscOsy|jj||}Wntjjk rX}z&|jr<|jdkrZeroReturnError get_shutdownRECEIVED_SHUTDOWN WantReadErrorr wait_for_readrL gettimeoutr )rPr]kwargsdatarGr r r rYs zWrappedSocket.recvcOsy|jj||Stjjk rT}z&|jr8|jdkr8dStt|WYdd}~Xn~tjj k r}z|jj tjj kr~dSWYdd}~XnBtjj k rt j|j|jjstdn |j||SYnXdS)NrSUnexpected EOFrzThe read operation timed outrX)rXrg)rK recv_intorZr[r\rMr]r^r>r_r`rarbrrcrLrdr )rPr]rerGr r r rh's zWrappedSocket.recv_intocCs |jj|S)N)rL settimeout)rPr r r r ri:szWrappedSocket.settimeoutcCs|xvy |jj|Stjjk rBtj|j|jjs)rPrfrGr r r _send_until_done=s zWrappedSocket._send_until_donecCs8d}x.|t|kr2|j|||t}||7}qWdS)Nr)r1rkSSL_WRITE_BLOCKSIZE)rPrfZ total_sentZsentr r r sendallHszWrappedSocket.sendallcCs|jjdS)N)rKshutdown)rPr r r rnNszWrappedSocket.shutdownc CsH|jdkr6yd|_|jjStjjk r2dSXn|jd8_dS)NrST)rNrOrKrTrZr[Error)rPr r r rTRs  zWrappedSocket.closeFcCsD|jj}|s|S|r(tjjtjj|Sd|jjffft|dS)NZ commonName)ZsubjectZsubjectAltName) rKZget_peer_certificaterZZcryptoZdump_certificateZ FILETYPE_ASN1Z get_subjectZCNrI)rPZ binary_formrr r r getpeercert\s zWrappedSocket.getpeercertcCs|jd7_dS)NrS)rN)rPr r r _reusenszWrappedSocket._reusecCs&|jdkr|jn|jd8_dS)NrS)rNrT)rPr r r _dropqs  zWrappedSocket._dropN)T)F)rrr __doc__rQrRrUrYrhrirkrmrnrTrprqrrr r r r rJs   rJrScCs|jd7_t|||ddS)NrST)rT)rNr)rPmodebufsizer r r makefileysrvc@szeZdZdZddZeddZejddZeddZejd dZd d Z d d Z dddZ dddZ dddZ 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_versionsprotocolrZr[ZContext_ctx_optionsZcheck_hostname)rPrxr r r rQs zPyOpenSSLContext.__init__cCs|jS)N)rz)rPr r r optionsszPyOpenSSLContext.optionscCs||_|jj|dS)N)rzryZ set_options)rPrBr r r r{scCst|jjS)N)_openssl_to_stdlib_verifyryZget_verify_mode)rPr r r verify_modeszPyOpenSSLContext.verify_modecCs|jjt|tdS)N)ryZ set_verify_stdlib_to_openssl_verify_verify_callback)rPrBr r r r}scCs|jjdS)N)ryset_default_verify_paths)rPr r r rsz)PyOpenSSLContext.set_default_verify_pathscCs&t|tjr|jd}|jj|dS)Nzutf-8) isinstancer text_typer2ryZset_cipher_list)rPZciphersr r r set_cipherss  zPyOpenSSLContext.set_ciphersNcCsN|dk r|jd}|dk r$|jd}|jj|||dk rJ|jjt|dS)Nzutf-8)r2ryload_verify_locationsr)rPZcafileZcapathZcadatar r r rs  z&PyOpenSSLContext.load_verify_locationscs<|jj|dk r(|jjfdd|jj|p4|dS)NcsS)Nr )Z max_lengthZ prompt_twiceZuserdata)passwordr r sz2PyOpenSSLContext.load_cert_chain..)ryZuse_certificate_chain_fileZ set_passwd_cbZuse_privatekey_file)rPZcertfileZkeyfilerr )rr load_cert_chains z PyOpenSSLContext.load_cert_chainFTcCstjj|j|}t|tjr&|jd}|dk r8|j||j xxy |j Wndtjj k rt j ||jsztdwBYn4tjjk r}ztjd|WYdd}~XnXPqBWt||S)Nzutf-8zselect timed outzbad handshake: %r)rZr[Z Connectionryrrrr2Zset_tlsext_host_nameZset_connect_stateZ do_handshakerbrrcrdr rosslZSSLErrorrJ)rPZsockZ server_sideZdo_handshake_on_connectrMZserver_hostnamecnxrGr r r wrap_sockets"     zPyOpenSSLContext.wrap_socket)NNN)NN)FTTN)rrr rsrQpropertyr{setterr}rrrrrr r r r rs   rcCs|dkS)Nrr )rrZerr_noZ err_depthZ return_coder r r rsrrX)rX)MrsZ __future__rZ OpenSSL.SSLrZZ cryptographyrZ$cryptography.hazmat.backends.opensslrr@Z)cryptography.hazmat.backends.openssl.x509rZcryptography.x509rr+ ExceptionrLr r r^iorrZpackages.backports.makefilerZloggingrZpackagesrr8r__all__r"ZPROTOCOL_SSLv23r[Z SSLv23_METHODZPROTOCOL_TLSv1Z TLSv1_METHODrwr?rrrrupdateZPROTOCOL_SSLv3Z SSLv3_METHODAttributeErrorZ CERT_NONEZ VERIFY_NONEZ CERT_OPTIONALZ VERIFY_PEERZ CERT_REQUIREDZVERIFY_FAIL_IF_NO_PEER_CERTr~dictitemsr|rlr%r r!r$Z getLoggerrrDrrrr;rIobjectrJrvrrr r r r +sn             )4~ R