a ®ÖØ_±Lã@sddlZddlZddlmZddlmZmZddlmZm Z ddl m Z ddl m Z ddlmZmZmZddlmZmZmZmZmZmZmZ m!Z"m#Z$m%Z&dd l'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-gd ¢Z.ze/Z0Wn"e1yêGd d „d e2ƒZ0Yn0ej3Z3ej4Z4ej5Z5ej6Z6ej7Z7ej8Z8ej9Z:ej;ZdZ?dZ@dZAdZBejCZDejEZFejGZHejIZJejKZLz ejMZNWneOypYn0ejPZQejRZSejTZUejVZWejXZYejZZ[ej\Z]ej^Z_ej`ZaejbZcejdZeejfZgejhZiejjZkejlZmejnZoejpZqejrZsejtZuejvZwejxZyejzZ{ej|Z}ej~Zej€Zej‚Zƒej„Z…ej†Z‡ejˆZ‰ejŠZ‹ejŒZejŽZejZ‘ej’Z“ej”Z•ej–Z—ej˜Z™ejšZšej›Z›ejœZœejZejžZžejŸZŸej Z ej¡Z¡ej¢Z¢ej£Z£ej¤Z¤ej¥Z¥ej¦Z¦ej§Z§ej¨Z¨ej©Z©gd¢ZªdgZ«dZ¬dZ­Gdd„de®ƒZ¯eee¯ƒZ°ee¯ƒZ±Gdd„de¯ƒZ²Gdd„de¯ƒZ³Gdd„de¯ƒZ´Gdd „d e¯ƒZµGd!d"„d"e¯ƒZ¶Gd#d$„d$e2ƒZ·Gd%d&„d&e·ƒZ¸e2ƒZ¹Gd'd(„d(e·ƒZºGd)d*„d*e·ƒZ»Gd+d,„d,e·ƒZ¼d-d.„Z½d/d0„Z¾d1d2„Z¿e¿ejÀd3ƒZÁe¿eÂed4dƒd5ƒZÃGd6d7„d7e2ƒZÄGd8d9„d9e2ƒZÅGd:d;„d;e2ƒZÆe Ç¡dS)<éN)Úplatform)ÚwrapsÚpartial)ÚcountÚchain)ÚWeakValueDictionary)Ú errorcode)Ú integer_typesÚint2byteÚ indexbytes) Ú UNSPECIFIEDÚexception_from_error_queueÚffiÚ from_bufferÚlibÚ make_assertÚnativeÚ path_stringÚtext_to_bytes_and_warnÚno_zero_allocator)Ú FILETYPE_PEMÚ_PassphraseHelperÚPKeyÚX509NameÚX509Ú X509Store)SÚOPENSSL_VERSION_NUMBERÚSSLEAY_VERSIONÚ SSLEAY_CFLAGSÚSSLEAY_PLATFORMÚ SSLEAY_DIRÚSSLEAY_BUILT_ONÚ SENT_SHUTDOWNÚRECEIVED_SHUTDOWNÚ SSLv2_METHODÚ SSLv3_METHODÚ SSLv23_METHODÚ TLSv1_METHODÚTLSv1_1_METHODÚTLSv1_2_METHODÚ OP_NO_SSLv2Ú OP_NO_SSLv3Ú OP_NO_TLSv1Ú OP_NO_TLSv1_1Ú OP_NO_TLSv1_2Ú OP_NO_TLSv1_3ÚMODE_RELEASE_BUFFERSÚOP_SINGLE_DH_USEÚOP_SINGLE_ECDH_USEÚOP_EPHEMERAL_RSAÚOP_MICROSOFT_SESS_ID_BUGÚOP_NETSCAPE_CHALLENGE_BUGÚ#OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUGÚOP_SSLREF2_REUSE_CERT_TYPE_BUGÚOP_MICROSOFT_BIG_SSLV3_BUFFERÚOP_MSIE_SSLV2_RSA_PADDINGÚOP_SSLEAY_080_CLIENT_DH_BUGÚ OP_TLS_D5_BUGÚOP_TLS_BLOCK_PADDING_BUGÚOP_DONT_INSERT_EMPTY_FRAGMENTSÚOP_CIPHER_SERVER_PREFERENCEÚOP_TLS_ROLLBACK_BUGÚOP_PKCS1_CHECK_1ÚOP_PKCS1_CHECK_2ÚOP_NETSCAPE_CA_DN_BUGÚ"OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUGÚOP_NO_COMPRESSIONÚOP_NO_QUERY_MTUÚOP_COOKIE_EXCHANGEÚ OP_NO_TICKETÚOP_ALLÚ VERIFY_PEERÚVERIFY_FAIL_IF_NO_PEER_CERTÚVERIFY_CLIENT_ONCEÚ VERIFY_NONEÚSESS_CACHE_OFFÚSESS_CACHE_CLIENTÚSESS_CACHE_SERVERÚSESS_CACHE_BOTHÚSESS_CACHE_NO_AUTO_CLEARÚSESS_CACHE_NO_INTERNAL_LOOKUPÚSESS_CACHE_NO_INTERNAL_STOREÚSESS_CACHE_NO_INTERNALÚSSL_ST_CONNECTÚ SSL_ST_ACCEPTÚ SSL_ST_MASKÚ SSL_CB_LOOPÚ SSL_CB_EXITÚ SSL_CB_READÚ SSL_CB_WRITEÚ SSL_CB_ALERTÚSSL_CB_READ_ALERTÚSSL_CB_WRITE_ALERTÚSSL_CB_ACCEPT_LOOPÚSSL_CB_ACCEPT_EXITÚSSL_CB_CONNECT_LOOPÚSSL_CB_CONNECT_EXITÚSSL_CB_HANDSHAKE_STARTÚSSL_CB_HANDSHAKE_DONEÚErrorÚ WantReadErrorÚWantWriteErrorÚWantX509LookupErrorÚZeroReturnErrorÚ SysCallErrorÚSSLeay_versionÚSessionÚContextÚ Connectionc@s eZdZdS)Ú_bufferN©Ú__name__Ú __module__Ú __qualname__©rtrtú-/usr/lib/python3/dist-packages/OpenSSL/SSL.pyro{sroéééééé)z"/etc/ssl/certs/ca-certificates.crtz /etc/pki/tls/certs/ca-bundle.crtz/etc/ssl/ca-bundle.pemz/etc/pki/tls/cacert.pemz1/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pemz/etc/ssl/certss$/opt/pyca/cryptography/openssl/certss'/opt/pyca/cryptography/openssl/cert.pemc@seZdZdZdS)rez4 An error occurred in an `OpenSSL.SSL` API. N©rqrrrsÚ__doc__rtrtrtrureîsrec@s eZdZdS)rfNrprtrtrtrurføsrfc@s eZdZdS)rgNrprtrtrtrurgüsrgc@s eZdZdS)rhNrprtrtrtrurhsrhc@s eZdZdS)riNrprtrtrtrurisric@s eZdZdS)rjNrprtrtrtrurjsrjc@s eZdZdZdd„Zdd„ZdS)Ú_CallbackExceptionHelperaÅ A base class for wrapper classes that allow for intelligent exception handling in OpenSSL callbacks. :ivar list _problems: Any exceptions that occurred while executing in a context where they could not be raised in the normal way. Typically this is because OpenSSL has called into some Python code and requires a return value. The exceptions are saved to be raised later when it is possible to do so. cCs g|_dS©N)Ú _problems©ÚselfrtrtruÚ__init__sz!_CallbackExceptionHelper.__init__cCs4|jr0z tƒWnty"Yn0|j d¡‚dS)z Raise an exception from the OpenSSL error queue or that was previously captured whe running a callback. rN)r€Ú_raise_current_errorreÚpoprrtrtruÚraise_if_problems   z)_CallbackExceptionHelper.raise_if_problemN)rqrrrsr}rƒr†rtrtrtrur~ s r~c@seZdZdZdd„ZdS)Ú _VerifyHelperz^ Wrap a callback such that it can be used as a certificate verification callback. cs2t ˆ¡tˆƒ‡‡fdd„ƒ}t d|¡ˆ_dS)Nc s¶t |¡}t |¡t |¡}t |¡}t |¡}t ¡}t ||¡}t j |}zˆ|||||ƒ} Wn2t y–} zˆj   | ¡WYd} ~ dSd} ~ 00| r®t |tj¡dSdSdS)Nrrv)Ú_libZX509_STORE_CTX_get_current_certÚ X509_up_refrÚ_from_raw_x509_ptrZX509_STORE_CTX_get_errorZX509_STORE_CTX_get_error_depthZ"SSL_get_ex_data_X509_STORE_CTX_idxZX509_STORE_CTX_get_ex_datarnÚ_reverse_mappingÚ Exceptionr€ÚappendZX509_STORE_CTX_set_errorZ X509_V_OK) ÚokZ store_ctxZx509ÚcertZ error_numberZ error_depthÚindexÚsslZ connectionÚresultÚe©Úcallbackr‚rtruÚwrapper1s&        ÿ z'_VerifyHelper.__init__..wrapperzint (*)(int, X509_STORE_CTX *)©r~rƒrÚ_ffir•©r‚r•r–rtr”rurƒ.s  ÿz_VerifyHelper.__init__N©rqrrrsr}rƒrtrtrtrur‡(sr‡c@seZdZdZdd„ZdS)Ú_ALPNSelectHelperzQ Wrap a callback such that it can be used as an ALPN selection callback. cs2t ˆ¡tˆƒ‡‡fdd„ƒ}t d|¡ˆ_dS)Nc szàtj|}t ||¡dd…}g}|r^t|dƒ} |d| d…} | | ¡|| dd…}q$ˆ||ƒ} d} | tur~d} d} nt| tƒst dƒ‚t  dt | ƒ¡t  d| ¡g|_ |j dd|d<|j d|d<| sÚt jWSt jWSty} zˆj | ¡t jWYd} ~ Sd} ~ 00dS) NrrvTóFz^ALPN callback must return a bytestring or the special NO_OVERLAPPING_PROTOCOLS sentinel value.zunsigned char *úunsigned char[])rnr‹r˜Úbufferr rÚNO_OVERLAPPING_PROTOCOLSÚ isinstanceÚbytesÚ TypeErrorÚnewÚlenÚ_alpn_select_callback_argsrˆZSSL_TLSEXT_ERR_NOACKZSSL_TLSEXT_ERR_OKrŒr€ZSSL_TLSEXT_ERR_ALERT_FATAL)r‘ÚoutZoutlenZin_ZinlenÚargÚconnZinstrZ protolistZ encoded_lenÚprotoZoutbytesZ any_acceptedr“r”rtrur–[s:     ÿ  þ z+_ALPNSelectHelper.__init__..wrapperz^int (*)(SSL *, unsigned char **, unsigned char *, const unsigned char *, unsigned int, void *)r—r™rtr”rurƒXs +ûz_ALPNSelectHelper.__init__Nršrtrtrtrur›Ssr›c@seZdZdZdd„ZdS)Ú_OCSPServerCallbackHelperað Wrap a callback such that it can be used as an OCSP callback for the server side. Annoyingly, OpenSSL defines one OCSP callback but uses it in two different ways. For servers, that callback is expected to retrieve some OCSP data and hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK, SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback is expected to check the OCSP data, and returns a negative value on error, 0 if the response is not acceptable, or positive if it is. These are mutually exclusive return code behaviours, and they mean that we need two helpers so that we always return an appropriate error code if the user's code throws an exception. Given that we have to have two helpers anyway, these helpers are a bit more helpery than most: specifically, they hide a few more of the OpenSSL functions so that the user has an easier time writing these callbacks. This helper implements the server side. cs2t ˆ¡tˆƒ‡‡fdd„ƒ}t d|¡ˆ_dS)Nc s¼z„tj|}|tjkr"t |¡}nd}ˆ||ƒ}t|tƒsBtdƒ‚|sLWdSt|ƒ}t   |¡}|t  ||¡dd…<t   |||¡WdSt y¶}zˆj |¡WYd}~dSd}~00dS)Nz'OCSP callback must return a bytestring.rxrrw)rnr‹r˜ÚNULLÚ from_handler r¡r¢r¤rˆZOPENSSL_mallocržZSSL_set_tlsext_status_ocsp_resprŒr€r)r‘Úcdatar¨ÚdataÚ ocsp_dataZocsp_data_lengthZdata_ptrr“r”rtrur–©s(      ÿ z3_OCSPServerCallbackHelper.__init__..wrapperúint (*)(SSL *, void *)r—r™rtr”rurƒ¦s &z"_OCSPServerCallbackHelper.__init__Nršrtrtrtrurªsrªc@seZdZdZdd„ZdS)Ú_OCSPClientCallbackHelperað Wrap a callback such that it can be used as an OCSP callback for the client side. Annoyingly, OpenSSL defines one OCSP callback but uses it in two different ways. For servers, that callback is expected to retrieve some OCSP data and hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK, SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback is expected to check the OCSP data, and returns a negative value on error, 0 if the response is not acceptable, or positive if it is. These are mutually exclusive return code behaviours, and they mean that we need two helpers so that we always return an appropriate error code if the user's code throws an exception. Given that we have to have two helpers anyway, these helpers are a bit more helpery than most: specifically, they hide a few more of the OpenSSL functions so that the user has an easier time writing these callbacks. This helper implements the client side. cs2t ˆ¡tˆƒ‡‡fdd„ƒ}t d|¡ˆ_dS)Nc s²zztj|}|tjkr"t |¡}nd}t d¡}t ||¡}|dkrJd}nt |d|¡dd…}ˆ|||ƒ}t t |ƒƒWSt y¬}zˆj   |¡WYd}~dSd}~00dS)Núunsigned char **rrœéÿÿÿÿ)rnr‹r˜r«r¬r£rˆZSSL_get_tlsext_status_ocsp_respržÚintÚboolrŒr€r) r‘r­r¨r®Zocsp_ptrZocsp_lenr¯Zvalidr“r”rtrur–ìs       z3_OCSPClientCallbackHelper.__init__..wrapperr°r—r™rtr”rurƒés z"_OCSPClientCallbackHelper.__init__Nršrtrtrtrur±Ósr±cCsdd}t|tƒs(t|ddƒ}|dur(|ƒ}t|tƒr6|}t|tƒsJtdƒ‚n|dkr`td|fƒ‚|S)NÚfilenoz3argument must be an int, or have a fileno() method.rz1file descriptor cannot be a negative integer (%i))r r Úgetattrr¢Ú ValueError)ÚobjÚfdÚmethrtrtruÚ_asFileDescriptors     ÿr¼cCst t |¡¡S)z“ Return a string describing the version of OpenSSL in use. :param type: One of the :const:`SSLEAY_` constants defined in this module. )r˜Ústringrˆrk)Útypertrtrurk"srkcs‡‡fdd„}|S)a” Builds a decorator that ensures that functions that rely on OpenSSL functions that are not present in this build raise NotImplementedError, rather than AttributeError coming out of cryptography. :param flag: A cryptography flag that guards the functions, e.g. ``Cryptography_HAS_NEXTPROTONEG``. :param error: The string to be used in the exception if the flag is false. cs$ˆst|ƒ‡fdd„ƒ}|S|SdS)Ncs tˆƒ‚dSr©ÚNotImplementedError)ÚargsÚkwargs)ÚerrorrtruÚexplode9sz<_make_requires.._requires_decorator..explode)r)ÚfuncrÄ©rÃÚflagrtruÚ_requires_decorator6s z+_make_requires.._requires_decoratorrt)rÇrÃrÈrtrÆruÚ_make_requires+s  rÉzALPN not availableZCryptography_HAS_KEYLOGzKey logging not availablec@seZdZdZdS)rlzÉ A class representing an SSL session. A session defines certain connection parameters which may be re-used to speed up the setup of subsequent connections. .. versionadded:: 0.14 Nr|rtrtrtrurlNsrlc @sÀeZdZdZededededede diZ e dd „e   ¡DƒƒZ d d „Z dcd d„Zdd„Zdddd„Zdd„Zdd„Zdd„Zdd„Zefdd„Zdd„Zdd „Zd!d"„Zefd#d$„Zd%d&„Zd'd(„Zd)d*„Zd+d,„Zd-d.„Z d/d0„Z!ded1d2„Z"d3d4„Z#d5d6„Z$d7d8„Z%d9d:„Z&d;d<„Z'd=d>„Z(d?d@„Z)dAdB„Z*dCdD„Z+dEdF„Z,dGdH„Z-e.dIdJ„ƒZ/dKdL„Z0dMdN„Z1dOdP„Z2dQdR„Z3dSdT„Z4dUdV„Z5dWdX„Z6e7dYdZ„ƒZ8e7d[d\„ƒZ9d]d^„Z:dfd_d`„Z;dgdadb„ZksþzContext.cCsøt|tƒstdƒ‚z|j|}Wnty:tdƒ‚Yn0|ƒ}t|tjkƒt   |¡}t|tjkƒt  |t j ¡}t   |d¡}t|dkƒ||_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_| t j¡dS)Nzmethod must be an integerzNo such protocolrv)r r r¢Ú_methodsÚKeyErrorr¸Ú_openssl_assertr˜r«rˆZ SSL_CTX_newÚgcZ SSL_CTX_freeZSSL_CTX_set_ecdh_autoÚ_contextÚ_passphrase_helperÚ_passphrase_callbackÚ_passphrase_userdataÚ_verify_helperÚ_verify_callbackÚ_info_callbackÚ_keylog_callbackÚ_tlsext_servername_callbackÚ _app_dataÚ_alpn_select_helperÚ_alpn_select_callbackÚ _ocsp_helperÚ_ocsp_callbackÚ _ocsp_dataÚset_modeZSSL_MODE_ENABLE_PARTIAL_WRITE)r‚ÚmethodZ method_funcZ method_objÚcontextÚresrtrtrurƒqs:     zContext.__init__NcCsN|durtj}nt|ƒ}|dur(tj}nt|ƒ}t |j||¡}|sJtƒdS)aU Let SSL know where we can find trusted certificates for the certificate chain. Note that the certificates have to be in PEM format. If capath is passed, it must be a directory prepared using the ``c_rehash`` tool included with OpenSSL. Either, but not both, of *pemfile* or *capath* may be :data:`None`. :param cafile: In which file we can find the certificates (``bytes`` or ``unicode``). :param capath: In which directory we can find the certificates (``bytes`` or ``unicode``). :return: None N)r˜r«Ú _path_stringrˆZSSL_CTX_load_verify_locationsrÑr„)r‚ÚcafileÚcapathZ load_resultrtrtruÚload_verify_locations™sÿzContext.load_verify_locationscs&tˆƒ‡‡fdd„ƒ}tt|dddS)Ncsˆ||ˆjƒSr)rÔ)ÚsizeZverifyÚuserdatar”rtrur–ºsz'Context._wrap_callback..wrapperT)Z more_argsÚtruncate)rrrr™rtr”ruÚ_wrap_callback¹s ÿzContext._wrap_callbackcCs@t|ƒstdƒ‚| |¡|_|jj|_t |j|j¡||_ dS)aò Set the passphrase callback. This function will be called when a private key with a passphrase is loaded. :param callback: The Python callback to use. This must accept three positional arguments. First, an integer giving the maximum length of the passphrase it may return. If the returned passphrase is longer than this, it will be truncated. Second, a boolean value which will be true if the user should be prompted for the passphrase twice and the callback should verify that the two values supplied are equal. Third, the value given as the *userdata* parameter to :meth:`set_passwd_cb`. The *callback* must return a byte string. If an error occurs, *callback* should return a false value (e.g. an empty string). :param userdata: (optional) A Python object which will be given as argument to the callback :return: None úcallback must be callableN) Úcallabler¢rërÒr•rÓrˆZSSL_CTX_set_default_passwd_cbrÑrÔ)r‚r•rértrtruÚ set_passwd_cbÂs  ÿzContext.set_passwd_cbcCsˆt |j¡}t|dkƒt t ¡¡ d¡}t t ¡¡ d¡}|  ||¡s„t t  ¡¡}t t  ¡¡}|t kr„|t kr„| tt¡dS)aÙ Specify that the platform provided CA certificates are to be used for verification purposes. This method has some caveats related to the binary wheels that cryptography (pyOpenSSL's primary dependency) ships: * macOS will only load certificates using this method if the user has the ``openssl@1.1`` `Homebrew `_ formula installed in the default location. * Windows will not work. * manylinux1 cryptography wheels will work on most common Linux distributions in pyOpenSSL 17.1.0 and above. pyOpenSSL detects the manylinux1 wheel and attempts to load roots via a fallback path. :return: None rvÚasciiN)rˆZ SSL_CTX_set_default_verify_pathsrÑrÏr˜r½ZX509_get_default_cert_dir_envÚdecodeZX509_get_default_cert_file_envÚ_check_env_vars_setZX509_get_default_cert_dirZX509_get_default_cert_fileÚ_CRYPTOGRAPHY_MANYLINUX1_CA_DIRÚ _CRYPTOGRAPHY_MANYLINUX1_CA_FILEÚ_fallback_default_verify_pathsÚ_CERTIFICATE_FILE_LOCATIONSÚ_CERTIFICATE_PATH_LOCATIONS)r‚Ú set_resultÚ dir_env_varÚ file_env_varZ default_dirZ default_filertrtruÚset_default_verify_pathsßs(  ÿÿþ ÿþÿz Context.set_default_verify_pathscCs tj |¡duptj |¡duS)zp Check to see if the default cert dir/file environment vars are present. :return: bool N)ÚosÚenvironÚget)r‚rørùrtrtrurñsþzContext._check_env_vars_setcCsN|D]}tj |¡r| |¡q$q|D] }tj |¡r(| d|¡qJq(dS)aW Default verify paths are based on the compiled version of OpenSSL. However, when pyca/cryptography is compiled as a manylinux1 wheel that compiled location can potentially be wrong. So, like Go, we will try a predefined set of paths and attempt to load roots from there. :return: None N)rûÚpathÚisfilerçÚisdir)r‚Z file_pathZdir_pathrårærtrtrurôs     z&Context._fallback_default_verify_pathscCs$t|ƒ}t |j|¡}|s tƒdS)zÍ Load a certificate chain from a file. :param certfile: The name of the certificate chain file (``bytes`` or ``unicode``). Must be PEM encoded. :return: None N)rärˆZ"SSL_CTX_use_certificate_chain_filerÑr„)r‚Úcertfiler’rtrtruÚuse_certificate_chain_file.s ÿz"Context.use_certificate_chain_filecCs8t|ƒ}t|tƒstdƒ‚t |j||¡}|s4tƒdS)ah Load a certificate from a file :param certfile: The name of the certificate file (``bytes`` or ``unicode``). :param filetype: (optional) The encoding of the file, which is either :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is :const:`FILETYPE_PEM`. :return: None úfiletype must be an integerN)rär r r¢rˆZSSL_CTX_use_certificate_filerÑr„)r‚rÚfiletypeÚ use_resultrtrtruÚuse_certificate_file?s  ÿzContext.use_certificate_filecCs0t|tƒstdƒ‚t |j|j¡}|s,tƒdS)zs Load a certificate from a X509 object :param cert: The X509 object :return: None zcert must be an X509 instanceN)r rr¢rˆZSSL_CTX_use_certificaterÑÚ_x509r„)r‚rrrtrtruÚuse_certificateUs  zContext.use_certificatecCsDt|tƒstdƒ‚t |j¡}t |j|¡}|s@t |¡t ƒdS)z‰ Add certificate to chain :param certobj: The X509 certificate object to add to the chain :return: None z certobj must be an X509 instanceN) r rr¢rˆZX509_duprZSSL_CTX_add_extra_chain_certrÑZ X509_freer„)r‚ZcertobjÚcopyÚ add_resultrtrtruÚadd_extra_chain_certcs   zContext.add_extra_chain_certcCs |jdur|j t¡tƒdSr)rÒr†rer„rrtrtruÚ_raise_passphrase_exceptionts  z#Context._raise_passphrase_exceptioncCsHt|ƒ}|turt}nt|tƒs(tdƒ‚t |j||¡}|sD|  ¡dS)aR Load a private key from a file :param keyfile: The name of the key file (``bytes`` or ``unicode``) :param filetype: (optional) The encoding of the file, which is either :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is :const:`FILETYPE_PEM`. :return: None rN) räÚ _UNSPECIFIEDrr r r¢rˆZSSL_CTX_use_PrivateKey_filerÑr )r‚ZkeyfilerrrtrtruÚuse_privatekey_filezs  ÿzContext.use_privatekey_filecCs2t|tƒstdƒ‚t |j|j¡}|s.| ¡dS)zs Load a private key from a PKey object :param pkey: The PKey object :return: None zpkey must be a PKey instanceN)r rr¢rˆZSSL_CTX_use_PrivateKeyrÑZ_pkeyr )r‚ZpkeyrrtrtruÚuse_privatekey’s  zContext.use_privatekeycCst |j¡stƒdS)zß Check if the private key (loaded with :meth:`use_privatekey`) matches the certificate (loaded with :meth:`use_certificate`) :return: :data:`None` (raises :exc:`Error` if something's wrong) N)rˆZSSL_CTX_check_private_keyrÑr„rrtrtruÚcheck_privatekey s zContext.check_privatekeycCs0t td|ƒ¡}t|tjkƒt |j|¡dS)a% Load the trusted certificates that will be sent to the client. Does not actually imply any of the certificates are trusted; that must be configured separately. :param bytes cafile: The path to a certificates file in PEM format. :return: None råN)rˆZSSL_load_client_CA_fileÚ_text_to_bytes_and_warnrÏr˜r«ÚSSL_CTX_set_client_CA_listrÑ)r‚råZca_listrtrtruÚload_client_caªs ÿzContext.load_client_cacCs*td|ƒ}tt |j|t|ƒ¡dkƒdS)aV Set the session id to *buf* within which a session can be reused for this Context object. This is needed when doing session resumption, because there is no way for a stored session to know which Context object it is associated with. :param bytes buf: The session id. :returns: None ÚbufrvN)rrÏrˆZSSL_CTX_set_session_id_contextrÑr¤)r‚rrtrtruÚset_session_id¹s ÿÿzContext.set_session_idcCs t|tƒstdƒ‚t |j|¡S)aŽ Set the behavior of the session cache used by all connections using this Context. The previously set mode is returned. See :const:`SESS_CACHE_*` for details about particular modes. :param mode: One or more of the SESS_CACHE_* flags (combine using bitwise or) :returns: The previously set caching mode. .. versionadded:: 0.14 úmode must be an integer)r r r¢rˆZSSL_CTX_set_session_cache_moderÑ©r‚ÚmodertrtruÚset_session_cache_modeÊs zContext.set_session_cache_modecCs t |j¡S)z‡ Get the current session cache mode. :returns: The currently used cache mode. .. versionadded:: 0.14 )rˆZSSL_CTX_get_session_cache_moderÑrrtrtruÚget_session_cache_modeÛszContext.get_session_cache_modecCstt|tƒstdƒ‚|dur:d|_d|_t |j|tj ¡n6t |ƒsJtdƒ‚t |ƒ|_|jj |_t |j||j¡dS)aÚ Set the verification flags for this Context object to *mode* and specify that *callback* should be used for verification callbacks. :param mode: The verify mode, this should be one of :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If :const:`VERIFY_PEER` is used, *mode* can be OR:ed with :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and :const:`VERIFY_CLIENT_ONCE` to further control the behaviour. :param callback: The optional Python verification callback to use. This should take five arguments: A Connection object, an X509 object, and three integer variables, which are in turn potential error number, error depth and return code. *callback* should return True if verification passes and False otherwise. If omitted, OpenSSL's default verification is used. :return: None See SSL_CTX_set_verify(3SSL) for further details. rNrì) r r r¢rÕrÖrˆZSSL_CTX_set_verifyrÑr˜r«rír‡r•)r‚rr•rtrtruÚ set_verifyås   zContext.set_verifycCs$t|tƒstdƒ‚t |j|¡dS)zÙ Set the maximum depth for the certificate chain verification that shall be allowed for this Context object. :param depth: An integer specifying the verify depth :return: None zdepth must be an integerN)r r r¢rˆZSSL_CTX_set_verify_depthrÑ)r‚ZdepthrtrtruÚset_verify_depths zContext.set_verify_depthcCs t |j¡S)z„ Retrieve the Context object's verify mode, as set by :meth:`set_verify`. :return: The verify mode )rˆZSSL_CTX_get_verify_moderÑrrtrtruÚget_verify_modeszContext.get_verify_modecCs t |j¡S)zŒ Retrieve the Context object's verify depth, as set by :meth:`set_verify_depth`. :return: The verify depth )rˆZSSL_CTX_get_verify_depthrÑrrtrtruÚget_verify_depthszContext.get_verify_depthcCstt|ƒ}t |d¡}|tjkr$tƒt |tj¡}t |tjtjtj¡}t |tj ¡}t  |j |¡}t |dkƒdS)zº Load parameters for Ephemeral Diffie-Hellman :param dhfile: The file to load EDH parameters from (``bytes`` or ``unicode``). :return: None órrvN) rärˆZ BIO_new_filer˜r«r„rÐZBIO_freeZPEM_read_bio_DHparamsZDH_freeZSSL_CTX_set_tmp_dhrÑrÏ)r‚ZdhfileÚbioZdhrãrtrtruÚ load_tmp_dh's   zContext.load_tmp_dhcCst |j| ¡¡dS)a  Select a curve to use for ECDHE key exchange. :param curve: A curve object to use as returned by either :meth:`OpenSSL.crypto.get_elliptic_curve` or :meth:`OpenSSL.crypto.get_elliptic_curves`. :return: None N)rˆZSSL_CTX_set_tmp_ecdhrÑZ _to_EC_KEY)r‚ZcurvertrtruÚ set_tmp_ecdh<s zContext.set_tmp_ecdhcCsZtd|ƒ}t|tƒstdƒ‚tt |j|¡dkƒt|dƒ}|  ¡gd¢krVt dgƒ‚dS)zó Set the list of ciphers to be used in this context. See the OpenSSL manual for more information (e.g. :manpage:`ciphers(1)`). :param bytes cipher_list: An OpenSSL cipher string. :return: None Ú cipher_listz"cipher_list must be a byte string.rvN)ZTLS_AES_256_GCM_SHA384ZTLS_CHACHA20_POLY1305_SHA256ZTLS_AES_128_GCM_SHA256)z SSL routinesÚSSL_CTX_set_cipher_listzno cipher match) rr r¡r¢rÏrˆr$rÑrnÚget_cipher_listre)r‚r#ZtmpconnrtrtruÚset_cipher_listHs  ÿ ÿÿzContext.set_cipher_listcCs®t ¡}t|tjkƒzf|D]\}t|tƒs>tdt|ƒj fƒ‚t  |j ¡}t|tjkƒt  ||¡}|st  |¡tƒqWntyšt |¡‚Yn0t |j|¡dS)a_ Set the list of preferred client certificate signers for this server context. This list of certificate authorities will be sent to the client when the server requests a client certificate. :param certificate_authorities: a sequence of X509Names. :return: None .. versionadded:: 0.10 z3client CAs must be X509Name objects, not %s objectsN)rˆZsk_X509_NAME_new_nullrÏr˜r«r rr¢r¾rqÚ X509_NAME_dupÚ_nameZsk_X509_NAME_pushÚX509_NAME_freer„rŒZsk_X509_NAME_freerrÑ)r‚Zcertificate_authoritiesZ name_stackZca_namer Z push_resultrtrtruÚset_client_ca_listos(   ÿÿ      zContext.set_client_ca_listcCs2t|tƒstdƒ‚t |j|j¡}t|dkƒdS)ai Add the CA certificate to the list of preferred signers for this context. The list of certificate authorities will be sent to the client when the server requests a client certificate. :param certificate_authority: certificate authority's X509 certificate. :return: None .. versionadded:: 0.10 z.certificate_authority must be an X509 instancervN)r rr¢rˆZSSL_CTX_add_client_CArÑrrÏ)r‚Zcertificate_authorityr rtrtruÚ add_client_ca’s ÿzContext.add_client_cacCs t|tƒstdƒ‚t |j|¡S)aQ Set the timeout for newly created sessions for this Context object to *timeout*. The default value is 300 seconds. See the OpenSSL manual for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`). :param timeout: The timeout in (whole) seconds :return: The previous session timeout ztimeout must be an integer)r r r¢rˆZSSL_CTX_set_timeoutrÑ)r‚ZtimeoutrtrtruÚ set_timeout§s zContext.set_timeoutcCs t |j¡S)z” Retrieve session timeout, as set by :meth:`set_timeout`. The default is 300 seconds. :return: The session timeout )rˆZSSL_CTX_get_timeoutrÑrrtrtruÚ get_timeoutµszContext.get_timeoutcs6tˆƒ‡fdd„ƒ}t d|¡|_t |j|j¡dS)að Set the information callback to *callback*. This function will be called from time to time during SSL handshakes. :param callback: The Python callback to use. This should take three arguments: a Connection object and two integers. The first integer specifies where in the SSL handshake the function was called, and the other the return code from a (possibly failed) internal function call. :return: None csˆtj|||ƒdSr©rnr‹)r‘ÚwhereZ return_code©r•rtrur–Ësz*Context.set_info_callback..wrapperzvoid (*)(const SSL *, int, int)N)rr˜r•r×rˆZSSL_CTX_set_info_callbackrÑr™rtr0ruÚset_info_callback¾s ÿzContext.set_info_callbackcs6tˆƒ‡fdd„ƒ}t d|¡|_t |j|j¡dS)a Set the TLS key logging callback to *callback*. This function will be called whenever TLS key material is generated or received, in order to allow applications to store this keying material for debugging purposes. :param callback: The Python callback to use. This should take two arguments: a Connection object and a bytestring that contains the key material in the format used by NSS for its SSLKEYLOGFILE debugging output. :return: None cst |¡}ˆtj||ƒdSr)r˜r½rnr‹)r‘Úliner0rtrur–ãs z,Context.set_keylog_callback..wrapperz#void (*)(const SSL *, const char *)N)rr˜r•rØrˆZSSL_CTX_set_keylog_callbackrÑr™rtr0ruÚset_keylog_callbackÔs ÿzContext.set_keylog_callbackcCs|jS)zw Get the application data (supplied via :meth:`set_app_data()`) :return: The application data ©rÚrrtrtruÚ get_app_dataíszContext.get_app_datacCs ||_dS)z Set the application data (will be returned from get_app_data()) :param data: Any Python object :return: None Nr4©r‚r®rtrtruÚ set_app_dataõszContext.set_app_datacCs.t |j¡}|tjkrdSt t¡}||_|S)zú Get the certificate store for the context. This can be used to add "trusted" certificates without using the :meth:`load_verify_locations` method. :return: A X509Store object or None if it does not have one. N)rˆZSSL_CTX_get_cert_storerÑr˜r«rÚ__new__Z_store)r‚ZstoreZpystorertrtruÚget_cert_storeþs    zContext.get_cert_storecCs t|tƒstdƒ‚t |j|¡S)zÝ Add options. Options set before are not cleared! This method should be used with the :const:`OP_*` constants. :param options: The options to add. :return: The new option bitmask. zoptions must be an integer)r r r¢rˆZSSL_CTX_set_optionsrÑ)r‚ZoptionsrtrtruÚ set_optionss zContext.set_optionscCs t|tƒstdƒ‚t |j|¡S)zà Add modes via bitmask. Modes set before are not cleared! This method should be used with the :const:`MODE_*` constants. :param mode: The mode to add. :return: The new mode bitmask. r)r r r¢rˆZSSL_CTX_set_moderÑrrtrtruràs zContext.set_modecs6tˆƒ‡fdd„ƒ}t d|¡|_t |j|j¡dS)a Specify a callback function to be called when clients specify a server name. :param callback: The callback function. It will be invoked with one argument, the Connection instance. .. versionadded:: 0.13 csˆtj|ƒdS)Nrr.)r‘Zalertr§r0rtrur–4sz7Context.set_tlsext_servername_callback..wrapperzint (*)(SSL *, int *, void *)N)rr˜r•rÙrˆZ&SSL_CTX_set_tlsext_servername_callbackrÑr™rtr0ruÚset_tlsext_servername_callback)s ÿÿz&Context.set_tlsext_servername_callbackcCs,t|tƒstdƒ‚tt |j|¡dkƒdS)z÷ Enable support for negotiating SRTP keying material. :param bytes profiles: A colon delimited list of protection profile names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``. :return: None zprofiles must be a byte string.rN)r r¡r¢rÏrˆZSSL_CTX_set_tlsext_use_srtprÑ)r‚ZprofilesrtrtruÚset_tlsext_use_srtp@s  ÿzContext.set_tlsext_use_srtpcCs>d t dd„|Dƒ¡¡}t d|¡}t |j|t|ƒ¡dS)a• Specify the protocols that the client is prepared to speak after the TLS connection has been negotiated using Application Layer Protocol Negotiation. :param protos: A list of the protocols to be offered to the server. This list should be a Python list of bytestrings representing the protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``. rœcss|]}tt|ƒƒ|fVqdSr©r r¤©rÊÚprtrtrurÌ]rœz*Context.set_alpn_protos..rN) ÚjoinrÚ from_iterabler˜r£rˆZSSL_CTX_set_alpn_protosrÑr¤©r‚ZprotosZprotostrZ input_strrtrtruÚset_alpn_protosOs ÿ zContext.set_alpn_protoscCs,t|ƒ|_|jj|_t |j|jtj¡dS)aœ Specify a callback function that will be called on the server when a client offers protocols using ALPN. :param callback: The callback function. It will be invoked with two arguments: the Connection, and a list of offered protocols as bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It can return one of those bytestrings to indicate the chosen protocol, the empty bytestring to terminate the TLS connection, or the :py:obj:`NO_OVERLAPPING_PROTOCOLS` to indicate that no offered protocol was selected, but that the connection should not be aborted. N) r›rÛr•rÜrˆZSSL_CTX_set_alpn_select_cbrÑr˜r«)r‚r•rtrtruÚset_alpn_select_callbackes    ÿz Context.set_alpn_select_callbackcCsh||_|j|_|dur tj|_n t |¡|_t |j |j¡}t |dkƒt  |j |j¡}t |dkƒdS)z© This internal helper does the common work for ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is almost all of it. Nrv) rÝr•rÞr˜r«rßZ new_handlerˆZSSL_CTX_set_tlsext_status_cbrÑrÏZSSL_CTX_set_tlsext_status_arg)r‚Úhelperr®ÚrcrtrtruÚ_set_ocsp_callbackzs  ÿ zContext._set_ocsp_callbackcCst|ƒ}| ||¡dS)aû Set a callback to provide OCSP data to be stapled to the TLS handshake on the server side. :param callback: The callback function. It will be invoked with two arguments: the Connection, and the optional arbitrary data you have provided. The callback must return a bytestring that contains the OCSP data to staple to the handshake. If no OCSP data is available for this connection, return the empty bytestring. :param data: Some opaque data that will be passed into the callback function when called. This can be used to avoid needing to do complex data lookups or to keep track of what context is being used. This parameter is optional. N)rªrG©r‚r•r®rErtrtruÚset_ocsp_server_callbackŽsz Context.set_ocsp_server_callbackcCst|ƒ}| ||¡dS)a Set a callback to validate OCSP data stapled to the TLS handshake on the client side. :param callback: The callback function. It will be invoked with three arguments: the Connection, a bytestring containing the stapled OCSP assertion, and the optional arbitrary data you have provided. The callback must return a boolean that indicates the result of validating the OCSP data: ``True`` if the OCSP data is valid and the certificate can be trusted, or ``False`` if either the OCSP data is invalid or the certificate has been revoked. :param data: Some opaque data that will be passed into the callback function when called. This can be used to avoid needing to do complex data lookups or to keep track of what context is being used. This parameter is optional. N)r±rGrHrtrtruÚset_ocsp_client_callback sz Context.set_ocsp_client_callback)N)N)N)N)N)=rqrrrsr}r$r%r&r'r(r)rÍÚdictÚitemsrƒrçrërîrúrñrôrrrrr r r rrrrrrrrrrrr!r"r&r*r+r,r-r1Ú_requires_keylogr3r5r7r9r:ràr;r<Ú_requires_alpnrCrDrGrIrJrtrtrtrurmZst úþ(  0     #    '#        rmc@s eZdZeƒZdydd„Zdd„Zdd„Zdd „Zd d „Z d d „Z dd„Z dd„Z dzdd„Z e Zd{dd„Zd|dd„ZeZd}dd„Zdd„Zdd„Zdd „Zd!d"„Zd#d$„Zd%d&„Zd'd(„Zd)d*„Zd+d,„Zd-d.„Zd/d0„Zd1d2„Zd3d4„Zd5d6„Z d7d8„Z!d9d:„Z"d;d<„Z#d=d>„Z$d?d@„Z%dAdB„Z&dCdD„Z'dEdF„Z(dGdH„Z)d~dIdJ„Z*dKdL„Z+dMdN„Z,dOdP„Z-e.dQdR„ƒZ/dSdT„Z0dUdV„Z1dWdX„Z2dYdZ„Z3d[d\„Z4d]d^„Z5d_d`„Z6dadb„Z7dcdd„Z8dedf„Z9dgdh„Z:didj„Z;dkdl„Zdqdr„Z?e@dsdt„ƒZAe@dudv„ƒZBdwdx„ZCdS)rnNcCst|tƒstdƒ‚t |j¡}t |tj¡|_ t  |j tj ¡||_d|_ d|_ |j|_|j|_||j|j <|durÐd|_t t ¡¡|_t|jtjkƒt t ¡¡|_t|jtjkƒt |j |j|j¡n2d|_d|_||_t |j t|jƒ¡}t|dkƒdS)zò Create a new Connection object, using the given OpenSSL.SSL.Context instance and socket. :param context: An SSL Context to use for this connection :param socket: The socket to use for transport layer ú"context must be a Context instanceNrv)r rmr¢rˆZSSL_newrÑr˜rÐZSSL_freeÚ_sslZ SSL_set_modeZSSL_MODE_AUTO_RETRYrÚr¥rÕrÖr‹Ú_socketZBIO_newZ BIO_s_memÚ _into_sslrÏr«Ú _from_sslZ SSL_set_bioZ SSL_set_fdr¼)r‚râÚsocketr‘r÷rtrtrurƒ¸s2    ÿzConnection.__init__cCs0|jdur td|jj|fƒ‚n t|j|ƒSdS)zy Look up attributes on the wrapped socket object if they are not found on the Connection object. Nz!'%s' object has no attribute '%s')rQÚAttributeErrorÚ __class__rqr·©r‚rËrtrtruÚ __getattr__îs  ÿÿzConnection.__getattr__cCs|jjdur|jj ¡|jjdur0|jj ¡|jjdurH|jj ¡t ||¡}|tjkrftƒ‚n²|tj krxt ƒ‚n |tj krŠt ƒ‚nŽ|tj krœtƒ‚n||tjkrt ¡dkrü|dkrðtdkrÒt ¡d}ntj}|dkrðt|t |¡ƒ‚tddƒ‚ntƒn|tjkrntƒdS)NrZwin32r³zUnexpected EOF)rÑrÕr†rÛrÝrˆZ SSL_get_errorZSSL_ERROR_WANT_READrfZSSL_ERROR_WANT_WRITErgZSSL_ERROR_ZERO_RETURNriZSSL_ERROR_WANT_X509_LOOKUPrhZSSL_ERROR_SYSCALLZERR_peek_errorrr˜Z getwinerrorÚerrnorjrrýr„ZSSL_ERROR_NONE)r‚r‘r’rÃrYrtrtruÚ_raise_ssl_errorûs8               zConnection._raise_ssl_errorcCs|jS)zh Retrieve the :class:`Context` object associated with this :class:`Connection`. )rÑrrtrtruÚ get_context szConnection.get_contextcCs,t|tƒstdƒ‚t |j|j¡||_dS)zª Switch this connection to a new session context. :param context: A :class:`Context` instance giving the new session context to use. rON)r rmr¢rˆZSSL_set_SSL_CTXrPrÑ)r‚rârtrtruÚ set_context's zConnection.set_contextcCs(t |jtj¡}|tjkrdSt |¡S)zï Retrieve the servername extension value if provided in the client hello message, or None if there wasn't one. :return: A byte string giving the server name or :data:`None`. .. versionadded:: 0.13 N)rˆZSSL_get_servernamerPZTLSEXT_NAMETYPE_host_namer˜r«r½rWrtrtruÚget_servername4s ÿ zConnection.get_servernamecCs6t|tƒstdƒ‚nd|vr$tdƒ‚t |j|¡dS)z­ Set the value of the servername extension to send in the client hello. :param name: A byte string giving the name. .. versionadded:: 0.13 zname must be a byte stringózname must not contain NUL byteN)r r¡r¢rˆZSSL_set_tlsext_host_namerPrWrtrtruÚset_tlsext_host_nameEs   zConnection.set_tlsext_host_namecCs t |j¡S)zÏ Get the number of bytes that can be safely read from the SSL buffer (**not** the underlying transport buffer). :return: The number of bytes available in the receive buffer. )rˆZ SSL_pendingrPrrtrtruÚpendingUszConnection.pendingrcCsptd|ƒ}t|ƒJ}t|ƒdkr(tdƒ‚t |j|t|ƒ¡}| |j|¡|WdƒS1sb0YdS)a³ Send data on the connection. NOTE: If you get one of the WantRead, WantWrite or WantX509Lookup exceptions on this, you have to call the method again with the SAME buffer. :param buf: The string, buffer or memoryview to send :param flags: (optional) Included for compatibility with the socket API, the value is ignored :return: The number of bytes written réÿÿÿz,Cannot send more than 2**31-1 bytes at once.N)rÚ _from_bufferr¤r¸rˆÚ SSL_writerPrZ)r‚rÚflagsr®r’rtrtruÚsend^s   ÿzConnection.sendcCs„td|ƒ}t|ƒ^}t|ƒ}d}|r^t |j||t|dƒ¡}| |j|¡||7}||8}q |WdƒS1sv0YdS)a© Send "all" data on the connection. This calls send() repeatedly until all data is sent. If an error occurs, it's impossible to tell how much data has been sent. :param buf: The string, buffer or memoryview to send :param flags: (optional) Included for compatibility with the socket API, the value is ignored :return: The number of bytes written rrraN)rrbr¤rˆrcrPÚminrZ)r‚rrdr®Z left_to_sendZ total_sentr’rtrtruÚsendallzs  ÿ zConnection.sendallcCs`td|ƒ}|dur.|tj@r.t |j||¡}nt |j||¡}| |j|¡t  ||¡dd…S)a Receive data on the connection. :param bufsiz: The maximum number of bytes to read :param flags: (optional) The only supported flag is ``MSG_PEEK``, all other flags are ignored. :return: The string read from the Connection úchar[]N) Ú_no_zero_allocatorrTÚMSG_PEEKrˆÚSSL_peekrPÚSSL_readrZr˜rž)r‚Úbufsizrdrr’rtrtruÚrecv˜s zConnection.recvcCsˆ|durt|ƒ}nt|t|ƒƒ}td|ƒ}|durN|tj@rNt |j||¡}nt |j||¡}|  |j|¡t t   ||¡ƒ|d|…<|S)ae Receive data on the connection and copy it directly into the provided buffer, rather than creating a new string. :param buffer: The buffer to copy into. :param nbytes: (optional) The maximum number of bytes to read into the buffer. If not present, defaults to the size of the buffer. If larger than the size of the buffer, is reduced to the size of the buffer. :param flags: (optional) The only supported flag is ``MSG_PEEK``, all other flags are ignored. :return: The number of bytes read into the buffer. Nrh) r¤rfrirTrjrˆrkrPrlrZÚ memoryviewr˜rž)r‚ržÚnbytesrdrr’rtrtruÚ recv_into«s  zConnection.recv_intocCsVt |¡rLt |¡rtƒ‚qRt |¡r.tƒ‚qRt |¡rBtdƒ‚qRtdƒ‚ntƒdS)NÚBIO_should_io_specialzunknown bio failure) rˆZBIO_should_retryZBIO_should_readrfZBIO_should_writergrrr¸r„)r‚r r’rtrtruÚ_handle_bio_errorsÐs      zConnection._handle_bio_errorscCsh|jdurtdƒ‚t|tƒs$tdƒ‚td|ƒ}t |j||¡}|dkrT| |j|¡t  ||¡dd…S)a¹ If the Connection was created with a memory BIO, this method can be used to read bytes from the write end of that memory BIO. Many Connection methods will add bytes which must be read in this manner or the buffer will eventually fill up and the Connection will be able to take no further actions. :param bufsiz: The maximum number of bytes to read :return: The string read. NúConnection sock was not Nonezbufsiz must be an integerrhr) rSr¢r r rirˆZBIO_readrsr˜rž)r‚rmrr’rtrtruÚbio_readâs   zConnection.bio_readcCsvtd|ƒ}|jdurtdƒ‚t|ƒ>}t |j|t|ƒ¡}|dkrP| |j|¡|WdƒS1sh0YdS)aj If the Connection was created with a memory BIO, this method can be used to add bytes to the read end of that memory BIO. The Connection can then read the bytes (for example, in response to a call to :meth:`recv`). :param buf: The string to put into the memory BIO. :return: The number of bytes written rNrtr)rrRr¢rbrˆZ BIO_writer¤rs)r‚rr®r’rtrtruÚ bio_writeús   zConnection.bio_writecCs$| ¡s tt |j¡dkƒdSdS)z‹ Renegotiate the session. :return: True if the renegotiation can be started, False otherwise :rtype: bool rvTF)Úrenegotiate_pendingrÏrˆZSSL_renegotiaterPrrtrtruÚ renegotiateszConnection.renegotiatecCst |j¡}| |j|¡dS)a Perform an SSL handshake (usually called after :meth:`renegotiate` or one of :meth:`set_accept_state` or :meth:`set_connect_state`). This can raise the same exceptions as :meth:`send` and :meth:`recv`. :return: None. N)rˆZSSL_do_handshakerPrZ©r‚r’rtrtruÚ do_handshakes zConnection.do_handshakecCst |j¡dkS)zÑ Check if there's a renegotiation in progress, it will return False once a renegotiation is finished. :return: Whether there's a renegotiation in progress :rtype: bool rv)rˆZSSL_renegotiate_pendingrPrrtrtrurw&szConnection.renegotiate_pendingcCs t |j¡S)z‚ Find out the total number of renegotiations. :return: The number of renegotiations. :rtype: int )rˆZSSL_total_renegotiationsrPrrtrtruÚtotal_renegotiations0szConnection.total_renegotiationscCst |j¡|j |¡S)a4 Call the :meth:`connect` method of the underlying socket and set up SSL on the socket, using the :class:`Context` object supplied to this :class:`Connection` object at creation. :param addr: A remote address :return: What the socket's connect method returns )rˆÚSSL_set_connect_staterPrQÚconnect)r‚Úaddrrtrtrur}9s zConnection.connectcCs|jj}| ¡||ƒS)a• Call the :meth:`connect_ex` method of the underlying socket and set up SSL on the socket, using the Context object supplied to this Connection object at creation. Note that if the :meth:`connect_ex` method of the socket doesn't return 0, SSL won't be initialized. :param addr: A remove address :return: What the socket's connect_ex method returns )rQÚ connect_exÚset_connect_state)r‚r~rrtrtrurEs zConnection.connect_excCs*|j ¡\}}t|j|ƒ}| ¡||fS)a‹ Call the :meth:`accept` method of the underlying socket and set up SSL on the returned socket, using the Context object supplied to this :class:`Connection` object at creation. :return: A *(conn, addr)* pair where *conn* is the new :class:`Connection` object created, and *address* is as returned by the socket's :meth:`accept`. )rQÚacceptrnrÑÚset_accept_state)r‚Zclientr~r¨rtrtrurSs  zConnection.acceptcCs$|jdurtdƒ‚t |jd¡dS)zÕ If the Connection was created with a memory BIO, this method can be used to indicate that *end of file* has been reached on the read end of that memory BIO. :return: None Nrtr)rSr¢rˆZBIO_set_mem_eof_returnrRrrtrtruÚ bio_shutdownbs zConnection.bio_shutdowncCs8t |j¡}|dkr$| |j|¡n|dkr0dSdSdS)aQ Send the shutdown message to the Connection. :return: True if the shutdown completed successfully (i.e. both sides have sent closure alerts), False otherwise (in which case you call :meth:`recv` or :meth:`send` when the connection becomes readable/writeable). rTFN)rˆZ SSL_shutdownrPrZryrtrtruÚshutdownos zConnection.shutdowncCsDg}tƒD]4}t |j|¡}|tjkr*q@| tt |¡ƒ¡q |S)z€ Retrieve the list of ciphers used by the Connection object. :return: A list of native cipher strings. ) rrˆZSSL_get_cipher_listrPr˜r«rÚ_nativer½)r‚ZciphersÚir’rtrtrur%€s  zConnection.get_cipher_listcCs~t |j¡}|tjkrgSg}tt |¡ƒD]L}t ||¡}t |¡}t |tjkƒt   t ¡}t  |tj ¡|_| |¡q,|S)aØ Get CAs whose certificates are suggested for client authentication. :return: If this is a server connection, the list of certificate authorities that will be sent or has been sent to the client, as controlled by this :class:`Connection`'s :class:`Context`. If this is a client connection, the list will be empty until the connection with the server is established. .. versionadded:: 0.10 )rˆZSSL_get_client_CA_listrPr˜r«ÚrangeZsk_X509_NAME_numZsk_X509_NAME_valuer'rÏrr8rÐr)r(r)r‚Zca_namesr’r†rËr ZpynamertrtruÚget_client_ca_listŽs      zConnection.get_client_ca_listcOs tdƒ‚dS)zœ The makefile() method is not implemented, since there is no dup semantics for SSL connections :raise: NotImplementedError z1Cannot make file object of OpenSSL.SSL.ConnectionNr¿©r‚rÁrÂrtrtruÚmakefile«sÿzConnection.makefilecCs|jS)zr Retrieve application data as set by :meth:`set_app_data`. :return: The application data r4rrtrtrur5¶szConnection.get_app_datacCs ||_dS)zg Set application data :param data: The application data :return: None Nr4r6rtrtrur7¾szConnection.set_app_datacCs t |j¡S)zž Get the shutdown state of the Connection. :return: The shutdown state, a bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN. )rˆZSSL_get_shutdownrPrrtrtruÚ get_shutdownÇszConnection.get_shutdowncCs$t|tƒstdƒ‚t |j|¡dS)z— Set the shutdown state of the Connection. :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN. :return: None zstate must be an integerN)r r r¢rˆZSSL_set_shutdownrP)r‚ÚstatertrtruÚ set_shutdownÐs zConnection.set_shutdowncCst t |j¡¡S)zš Retrieve a verbose string detailing the state of the Connection. :return: A string representing the state :rtype: bytes )r˜r½rˆZSSL_state_string_longrPrrtrtruÚget_state_stringÜszConnection.get_state_stringcCsft |j¡}|tjkrdSt |jtjd¡}t|dkƒtd|ƒ}t |j||¡t ||¡dd…S)z Retrieve the random value used with the server hello message. :return: A string representing the state Nrr) rˆÚSSL_get_sessionrPr˜r«ZSSL_get_server_randomrÏrirž©r‚ÚsessionZlengthÚoutprtrtruÚ server_randomås    zConnection.server_randomcCsft |j¡}|tjkrdSt |jtjd¡}t|dkƒtd|ƒ}t |j||¡t ||¡dd…S)z Retrieve the random value used with the client hello message. :return: A string representing the state Nrr) rˆrrPr˜r«ZSSL_get_client_randomrÏriržrrtrtruÚ client_randomôs    zConnection.client_randomcCsbt |j¡}|tjkrdSt |tjd¡}t|dkƒtd|ƒ}t |||¡t ||¡dd…S)zz Retrieve the value of the master key for this session. :return: A string representing the state Nrr) rˆrrPr˜r«ZSSL_SESSION_get_master_keyrÏriržrrtrtruÚ master_keys    zConnection.master_keyc Csntd|ƒ}tj}d}d}|dur0|}t|ƒ}d}t |j|||t|ƒ|||¡}t|dkƒt ||¡dd…S)aH Obtain keying material for application use. :param: label - a disambiguating label string as described in RFC 5705 :param: olen - the length of the exported key material in bytes :param: context - a per-association context value :return: the exported key material bytes or None rrNrv) rir˜r«r¤rˆZSSL_export_keying_materialrPrÏrž) r‚ZlabelZolenrâr’Z context_bufZ context_lenZ use_contextZsuccessrtrtruÚexport_keying_materials( ø z!Connection.export_keying_materialcOs|jj|i|¤ŽS)z® Call the :meth:`shutdown` method of the underlying socket. See :manpage:`shutdown(2)`. :return: What the socket's shutdown() method returns )rQr„r‰rtrtruÚ sock_shutdown2szConnection.sock_shutdowncCs.t |j¡}|tjkr*t |¡t |¡SdS)za Retrieve the local certificate (if any) :return: The local certificate N)rˆZSSL_get_certificaterPr˜r«r‰rrŠ©r‚rrtrtruÚget_certificate;s     zConnection.get_certificatecCs$t |j¡}|tjkr t |¡SdS)zi Retrieve the other side's certificate (if any) :return: The peer's certificate N)rˆZSSL_get_peer_certificaterPr˜r«rrŠr˜rtrtruÚget_peer_certificateGs   zConnection.get_peer_certificatecCs`g}tt |¡ƒD]H}t ||¡}t|tjkƒt |¡}t|dkƒt  |¡}|  |¡q|S)zb Internal helper to convert a STACK_OF(X509) to a list of X509 instances. rv) r‡rˆZ sk_X509_numZ sk_X509_valuerÏr˜r«r‰rrŠr)Ú cert_stackr’r†rrãZpycertrtrtruÚ_cert_stack_to_listRs     zConnection._cert_stack_to_listcCs$t |j¡}|tjkrdS| |¡S)z Retrieve the other side's certificate (if any) :return: A list of X509 instances giving the peer's certificate chain, or None if it does not have one. N)rˆZSSL_get_peer_cert_chainrPr˜r«rœ©r‚r›rtrtruÚget_peer_cert_chainbs  zConnection.get_peer_cert_chaincCs$t |j¡}|tjkrdS| |¡S)aÑ Retrieve the verified certificate chain of the peer including the peer's end entity certificate. It must be called after a session has been successfully established. If peer verification was not successful the chain may be incomplete, invalid, or None. :return: A list of X509 instances giving the peer's verified certificate chain, or None if it does not have one. .. versionadded:: 20.0 N)rˆZSSL_get0_verified_chainrPr˜r«rœrrtrtruÚget_verified_chainos  zConnection.get_verified_chaincCs t |j¡S)z£ Checks if more data has to be read from the transport layer to complete an operation. :return: True iff more data has to be read )rˆZ SSL_want_readrPrrtrtruÚ want_read‚szConnection.want_readcCs t |j¡S)z Checks if there is data to write to the transport layer to complete an operation. :return: True iff there is data to write )rˆZSSL_want_writerPrrtrtruÚ want_write‹szConnection.want_writecCst |j¡dS)z– Set the connection to work in server mode. The handshake will be handled automatically by read/write. :return: None N)rˆZSSL_set_accept_staterPrrtrtrur‚”szConnection.set_accept_statecCst |j¡dS)z– Set the connection to work in client mode. The handshake will be handled automatically by read/write. :return: None N)rˆr|rPrrtrtrur€szConnection.set_connect_statecCs8t |j¡}|tjkrdSt t¡}t |tj¡|_ |S)zÄ Returns the Session currently used. :return: An instance of :class:`OpenSSL.SSL.Session` or :obj:`None` if no session exists. .. versionadded:: 0.14 N) rˆZSSL_get1_sessionrPr˜r«rlr8rÐZSSL_SESSION_freeÚ_session)r‚r‘Z pysessionrtrtruÚ get_session¦s   zConnection.get_sessioncCs2t|tƒstdƒ‚t |j|j¡}t|dkƒdS)zÜ Set the session to be used when the TLS/SSL connection is established. :param session: A Session instance representing the session to use. :returns: None .. versionadded:: 0.14 z"session must be a Session instancervN)r rlr¢rˆZSSL_set_sessionrPr¢rÏ)r‚r‘r’rtrtruÚ set_session·s zConnection.set_sessioncCsRt dd¡}||j|dƒ}|dkr&dStd|ƒ}||j||ƒt ||¡dd…S)a‚ Helper to implement :meth:`get_finished` and :meth:`get_peer_finished`. :param function: Either :data:`SSL_get_finished`: or :data:`SSL_get_peer_finished`. :return: :data:`None` if the desired message has not yet been received, otherwise the contents of the message. :rtype: :class:`bytes` or :class:`NoneType` rhrN)r˜r£rPrirž)r‚ZfunctionÚemptyrèrrtrtruÚ_get_finished_messageÆs  z Connection._get_finished_messagecCs | tj¡S)a Obtain the latest TLS Finished message that we sent. :return: The contents of the message or :obj:`None` if the TLS handshake has not yet completed. :rtype: :class:`bytes` or :class:`NoneType` .. versionadded:: 0.15 )r¦rˆZSSL_get_finishedrrtrtruÚ get_finishedès zConnection.get_finishedcCs | tj¡S)a! Obtain the latest TLS Finished message that we received from the peer. :return: The contents of the message or :obj:`None` if the TLS handshake has not yet completed. :rtype: :class:`bytes` or :class:`NoneType` .. versionadded:: 0.15 )r¦rˆZSSL_get_peer_finishedrrtrtruÚget_peer_finishedôs zConnection.get_peer_finishedcCs8t |j¡}|tjkrdSt t |¡¡}| d¡SdS)a Obtain the name of the currently used cipher. :returns: The name of the currently used cipher or :obj:`None` if no connection has been established. :rtype: :class:`unicode` or :class:`NoneType` .. versionadded:: 0.15 Núutf-8)rˆÚSSL_get_current_cipherrPr˜r«r½ZSSL_CIPHER_get_namerð)r‚ÚcipherrËrtrtruÚget_cipher_name s  zConnection.get_cipher_namecCs,t |j¡}|tjkrdSt |tj¡SdS)a. Obtain the number of secret bits of the currently used cipher. :returns: The number of secret bits of the currently used cipher or :obj:`None` if no connection has been established. :rtype: :class:`int` or :class:`NoneType` .. versionadded:: 0.15 N)rˆrªrPr˜r«ZSSL_CIPHER_get_bits)r‚r«rtrtruÚget_cipher_bits s  zConnection.get_cipher_bitscCs8t |j¡}|tjkrdSt t |¡¡}| d¡SdS)a% Obtain the protocol version of the currently used cipher. :returns: The protocol name of the currently used cipher or :obj:`None` if no connection has been established. :rtype: :class:`unicode` or :class:`NoneType` .. versionadded:: 0.15 Nr©)rˆrªrPr˜r«r½ZSSL_CIPHER_get_versionrð)r‚r«ÚversionrtrtruÚget_cipher_version! s  zConnection.get_cipher_versioncCst t |j¡¡}| d¡S)a> Retrieve the protocol version of the current connection. :returns: The TLS version of the current connection, for example the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown`` for connections that were not successfully established. :rtype: :class:`unicode` r©)r˜r½rˆZSSL_get_versionrPrð©r‚r®rtrtruÚget_protocol_version_name2 s z$Connection.get_protocol_version_namecCst |j¡}|S)a  Retrieve the SSL or TLS protocol version of the current connection. :returns: The TLS version of the current connection. For example, it will return ``0x769`` for connections made over TLS version 1. :rtype: :class:`int` )rˆZ SSL_versionrPr°rtrtruÚget_protocol_version> s zConnection.get_protocol_versioncCs>d t dd„|Dƒ¡¡}t d|¡}t |j|t|ƒ¡dS)ah Specify the client's ALPN protocol list. These protocols are offered to the server during protocol negotiation. :param protos: A list of the protocols to be offered to the server. This list should be a Python list of bytestrings representing the protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``. rœcss|]}tt|ƒƒ|fVqdSrr=r>rtrtrurÌW rœz-Connection.set_alpn_protos..rN) r@rrAr˜r£rˆZSSL_set_alpn_protosrPr¤rBrtrtrurCI s ÿ zConnection.set_alpn_protoscCsHt d¡}t d¡}t |j||¡|s,dSt |d|d¡dd…S)zà Get the protocol that was negotiated by ALPN. :returns: A bytestring of the protocol name. If no protocol has been negotiated yet, returns an empty string. r²zunsigned int *rœrN)r˜r£rˆZSSL_get0_alpn_selectedrPrž)r‚r®Zdata_lenrtrtruÚget_alpn_proto_negotiated_ s   z$Connection.get_alpn_proto_negotiatedcCs t |jtj¡}t|dkƒdS)a Called to request that the server sends stapled OCSP data, if available. If this is not called on the client side then the server will not send OCSP data. Should be used in conjunction with :meth:`Context.set_ocsp_client_callback`. rvN)rˆZSSL_set_tlsext_status_typerPZTLSEXT_STATUSTYPE_ocsprÏ)r‚rFrtrtruÚ request_ocspq sÿzConnection.request_ocsp)N)r)r)N)NN)N)Drqrrrsrr‹rƒrXrZr[r\r]r_r`reÚwritergrnÚreadrqrsrurvrxrzrwr{r}rrrƒr„r%rˆrŠr5r7r‹rrŽr“r”r•r–r—r™ršÚ staticmethodrœržrŸr r¡r‚r€r£r¤r¦r§r¨r¬r­r¯r±r²rNrCr³r´rtrtrtrurnµs‚ 6 %     %                     "      rn)ÈrûrTÚsysrÚ functoolsrrÚ itertoolsrrÚweakrefrrYrZsixr r r Z OpenSSL._utilr r r Z_exception_from_error_queuerr˜rrbrrˆrZ _make_assertrr…rrärrrriZOpenSSL.cryptorrrrrrÚ__all__ržroÚ NameErrorÚobjectrrrrr r!ZSSL_SENT_SHUTDOWNr"ZSSL_RECEIVED_SHUTDOWNr#r$r%r&r'r(r)ZSSL_OP_NO_SSLv2r*ZSSL_OP_NO_SSLv3r+ZSSL_OP_NO_TLSv1r,ZSSL_OP_NO_TLSv1_1r-ZSSL_OP_NO_TLSv1_2r.ZSSL_OP_NO_TLSv1_3r/rUZSSL_MODE_RELEASE_BUFFERSr0ZSSL_OP_SINGLE_DH_USEr1ZSSL_OP_SINGLE_ECDH_USEr2ZSSL_OP_EPHEMERAL_RSAr3ZSSL_OP_MICROSOFT_SESS_ID_BUGr4ZSSL_OP_NETSCAPE_CHALLENGE_BUGr5Z'SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUGr6Z"SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUGr7Z!SSL_OP_MICROSOFT_BIG_SSLV3_BUFFERr8ZSSL_OP_MSIE_SSLV2_RSA_PADDINGr9ZSSL_OP_SSLEAY_080_CLIENT_DH_BUGr:ZSSL_OP_TLS_D5_BUGr;ZSSL_OP_TLS_BLOCK_PADDING_BUGr<Z"SSL_OP_DONT_INSERT_EMPTY_FRAGMENTSr=ZSSL_OP_CIPHER_SERVER_PREFERENCEr>ZSSL_OP_TLS_ROLLBACK_BUGr?ZSSL_OP_PKCS1_CHECK_1r@ZSSL_OP_PKCS1_CHECK_2rAZSSL_OP_NETSCAPE_CA_DN_BUGrBZ&SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUGrCZSSL_OP_NO_COMPRESSIONrDZSSL_OP_NO_QUERY_MTUrEZSSL_OP_COOKIE_EXCHANGErFZSSL_OP_NO_TICKETrGZ SSL_OP_ALLrHZSSL_VERIFY_PEERrIZSSL_VERIFY_FAIL_IF_NO_PEER_CERTrJZSSL_VERIFY_CLIENT_ONCErKZSSL_VERIFY_NONErLZSSL_SESS_CACHE_OFFrMZSSL_SESS_CACHE_CLIENTrNZSSL_SESS_CACHE_SERVERrOZSSL_SESS_CACHE_BOTHrPZSSL_SESS_CACHE_NO_AUTO_CLEARrQZ!SSL_SESS_CACHE_NO_INTERNAL_LOOKUPrRZ SSL_SESS_CACHE_NO_INTERNAL_STORErSZSSL_SESS_CACHE_NO_INTERNALrTrUrVrWrXrYrZr[r\r]r^r_r`rarbrcrdrõröròrórŒrer„rÏrfrgrhrirjr~r‡rŸr›rªr±r¼rkrÉZCryptography_HAS_ALPNrNr·rMrlrmrnZSSL_library_initrtrtrtruÚs   0 V  ÿÿ ÿ (=C; ÿ ÿ aR