a žSaàVã@sTddlZddlZddlmZddlmZmZddlmZm Z ddl m Z ddl m Z ddlmZmZmZddlmZmZmZmZmZmZmZ m!Z"m#Z$dd l%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+gd ¢Z,ze-Z.Wn"e/yæGd d „d e0ƒZ.Yn0ej1Z1ej2Z2ej3Z3ej4Z4ej5Z5ej6Z6ej7Z8ej9Z:d Z;dZdZ?dZ@dZAdZBdZCz"ejDZDejEZEejFZFejGZGejHZHWn(eIy†dZDdZEdZFdZGdZHYn0ejJZKejLZMejNZOejPZQejRZSz ejTZUWneIyÄYn0ejVZWejXZYejZZ[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œZejžZŸej Z ej¡Z¡ej¢Z¢ej£Z£ej¤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 „d e´ƒZµeeeµƒZ¶eeµƒZ·Gd!d"„d"eµƒZ¸Gd#d$„d$eµƒZ¹Gd%d&„d&eµƒZºGd'd(„d(eµƒZ»Gd)d*„d*eµƒZ¼Gd+d,„d,e0ƒZ½Gd-d.„d.e½ƒZ¾e0ƒZ¿Gd/d0„d0e½ƒZÀGd1d2„d2e½ƒZÁGd3d4„d4e½ƒZÂd5d6„ZÃd7d8„ZÄd9d:„ZÅeÅejÆd;ƒZÇeÅeÈedd?„d?e0ƒZÊGd@dA„dAe0ƒZËGdBdC„dCe0ƒZÌe Í¡dS)DéN)Úplatform)ÚwrapsÚpartial)ÚcountÚchain)ÚWeakValueDictionary)Ú errorcode)Ú integer_typesÚint2byteÚ indexbytes) Ú UNSPECIFIEDÚexception_from_error_queueÚffiÚlibÚ make_assertÚnativeÚ path_stringÚtext_to_bytes_and_warnÚno_zero_allocator)Ú FILETYPE_PEMÚ_PassphraseHelperÚPKeyÚX509NameÚX509Ú X509Store)\Ú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Ú TLS_METHODÚTLS_SERVER_METHODÚTLS_CLIENT_METHODÚ SSL3_VERSIONÚ TLS1_VERSIONÚTLS1_1_VERSIONÚTLS1_2_VERSIONÚTLS1_3_VERSIONÚ 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ÚNO_OVERLAPPING_PROTOCOLSÚSSLeay_versionÚSessionÚContextÚ Connectionc@s eZdZdS)Ú_bufferN©Ú__name__Ú __module__Ú __qualname__©r|r|ú//usr/lib/python3.9/site-packages/OpenSSL/SSL.pyrwƒsrwééééééééé iiiii)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)rlz4 An error occurred in an `OpenSSL.SSL` API. N©ryrzr{Ú__doc__r|r|r|r}rlsrlc@s eZdZdS)rmNrxr|r|r|r}rmsrmc@s eZdZdS)rnNrxr|r|r|r}rnsrnc@s eZdZdS)roNrxr|r|r|r}rosroc@s eZdZdS)rpNrxr|r|r|r}rpsrpc@s eZdZdS)rqNrxr|r|r|r}rq"srqc@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©Úselfr|r|r}Ú__init__2sz!_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_errorrlÚpoprŒr|r|r}Úraise_if_problem5s   z)_CallbackExceptionHelper.raise_if_problemN)ryrzr{rˆrŽr‘r|r|r|r}r‰&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)Nrr~)Ú_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_datarvÚ_reverse_mappingÚ Exceptionr‹ÚappendZX509_STORE_CTX_set_errorZ X509_V_OK) ÚokZ store_ctxZx509ÚcertZ error_numberZ error_depthÚindexÚsslZ connectionÚresultÚe©Úcallbackrr|r}ÚwrapperKs&        ÿ z'_VerifyHelper.__init__..wrapperzint (*)(int, X509_STORE_CTX *)©r‰rŽrÚ_ffir ©rr r¡r|rŸr}rŽHs  ÿz_VerifyHelper.__init__N©ryrzr{rˆrŽr|r|r|r}r’Bsr’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) Nrr~TóFz^ALPN callback must return a bytestring or the special NO_OVERLAPPING_PROTOCOLS sentinel value.zunsigned char *úunsigned char[])rvr–r£Úbufferr r˜rrÚ 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Ÿr|r}r¡us:     ÿ  þ z+_ALPNSelectHelper.__init__..wrapperz^int (*)(SSL *, unsigned char **, unsigned char *, const unsigned char *, unsigned int, void *)r¢r¤r|rŸr}rŽrs +ûz_ALPNSelectHelper.__init__Nr¥r|r|r|r}r¦msr¦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.r€rr)rvr–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Ÿr|r}r¡Ãs(      ÿ z3_OCSPServerCallbackHelper.__init__..wrapperúint (*)(SSL *, void *)r¢r¤r|rŸr}rŽÀs &z"_OCSPServerCallbackHelper.__init__Nr¥r|r|r|r}r´ª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§éÿÿÿÿ)rvr–r£rµr¶r­r“ZSSL_get_tlsext_status_ocsp_respr©ÚintÚboolr—r‹r˜) rœr·r²r¸Zocsp_ptrZocsp_lenr¹ZvalidržrŸr|r}r¡s       z3_OCSPClientCallbackHelper.__init__..wrapperrºr¢r¤r|rŸr}rŽs z"_OCSPClientCallbackHelper.__init__Nr¥r|r|r|r}r»í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Úmethr|r|r}Ú_asFileDescriptor(s     ÿ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“rs)Útyper|r|r}rs<srscs‡‡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)Úerrorr|r}ÚexplodeSsz<_make_requires.._requires_decorator..explode)r)ÚfuncrΩrÍÚflagr|r}Ú_requires_decoratorPs z+_make_requires.._requires_decoratorr|)rÑrÍrÒr|rÐr}Ú_make_requiresEs  rÓzALPN not availableZCryptography_HAS_KEYLOGzKey logging not availablec@seZdZdZdS)rtzÉ 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‡r|r|r|r}rthsrtc@sÜeZdZdZededededede de de d e d i Z ed d „e  ¡DƒƒZ d d„Zdd„Zdd„Zdjdd„Zdd„Zdkdd„Zdd„Zdd„Zdd„Zd d!„Zefd"d#„Zd$d%„Zd&d'„Zd(d)„Zefd*d+„Z d,d-„Z!d.d/„Z"d0d1„Z#d2d3„Z$d4d5„Z%d6d7„Z&dld8d9„Z'd:d;„Z(dd?„Z*d@dA„Z+dBdC„Z,dDdE„Z-dFdG„Z.dHdI„Z/dJdK„Z0dLdM„Z1dNdO„Z2e3dPdQ„ƒZ4dRdS„Z5dTdU„Z6dVdW„Z7dXdY„Z8dZd[„Z9d\d]„Z:d^d_„Z;eddde„Z?dmdfdg„Z@dndhdi„ZAdS)orua- :class:`OpenSSL.SSL.Context` instances define the parameters for setting up new SSL connections. :param method: One of TLS_METHOD, TLS_CLIENT_METHOD, or TLS_SERVER_METHOD. SSLv23_METHOD, TLSv1_METHOD, etc. are deprecated and should not be used. Z SSLv2_methodZ SSLv3_methodZ SSLv23_methodZ TLSv1_methodZTLSv1_1_methodZTLSv1_2_methodZ TLS_methodZTLS_server_methodZTLS_client_methodccs0|](\}}tt|dƒdur|tt|ƒfVqdSrŠ)rÁr“)Ú.0Z identifierÚnamer|r|r}Ú ‰sþ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 protocolr~)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Úresr|r|r}rŽs:     zContext.__init__cCstt |j|¡dkƒdS)aD Set the minimum supported protocol version. Setting the minimum version to 0 will enable protocol versions down to the lowest version supported by the library. If the underlying OpenSSL build is missing support for the selected version, this method will raise an exception. r~N)rÙr“ZSSL_CTX_set_min_proto_versionrÛ©rÚversionr|r|r}Úset_min_proto_version·s ÿzContext.set_min_proto_versioncCstt |j|¡dkƒdS)aC Set the maximum supported protocol version. Setting the maximum version to 0 will enable protocol versions up to the highest version supported by the library. If the underlying OpenSSL build is missing support for the selected version, this method will raise an exception. r~N)rÙr“ZSSL_CTX_set_max_proto_versionrÛrîr|r|r}Úset_max_proto_versionÄs ÿzContext.set_max_proto_versionNcCsN|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_resultr|r|r}Úload_verify_locationsÑsÿzContext.load_verify_locationscs&tˆƒ‡‡fdd„ƒ}tt|dddS)Ncsˆ||ˆjƒSrŠ)rÞ)ÚsizeZverifyÚuserdatarŸr|r}r¡òsz'Context._wrap_callback..wrapperT)Z more_argsÚtruncate)rrrr¤r|rŸr}Ú_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Þ)rr r÷r|r|r}Ú 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 r~Ú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_filer|r|r}Úset_default_verify_pathss(  ÿÿþ ÿþÿ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)rrrr|r|r}rÿGsþ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)rZ file_pathZdir_pathrórôr|r|r}rRs     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Úcertfilerr|r|r}Úuse_certificate_chain_filefs ÿ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)rrÚfiletypeÚ use_resultr|r|r}Úuse_certificate_filews  ÿ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)rršrr|r|r}Úuse_certificates  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)rZcertobjÚcopyÚ add_resultr|r|r}Úadd_extra_chain_cert›s   zContext.add_extra_chain_certcCs |jdur|j t¡tƒdSrŠ)rÜr‘rlrrŒr|r|r}Ú_raise_passphrase_exception¬s  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)rZkeyfilerrr|r|r}Úuse_privatekey_file²s  ÿ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)rZpkeyrr|r|r}Ú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ÛrrŒr|r|r}Ú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Û)rróZca_listr|r|r}Ú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 Úbufr~N)rrÙr“ZSSL_CTX_set_session_id_contextrÛr®)rr"r|r|r}Ú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Úmoder|r|r}Úset_session_cache_modes 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ÛrŒr|r|r}Úget_session_cache_modeszContext.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. r$Nrú) rªr r¬rßràr“ZSSL_CTX_set_verifyrÛr£rµrûr’r )rr&r r|r|r}Ú set_verifys   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Údepthr|r|r}Úset_verify_depth@s 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ÛrŒr|r|r}Úget_verify_modeMszContext.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ÛrŒr|r|r}Úget_verify_depthVszContext.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 órr~N) ròr“Z BIO_new_filer£rµrrÚZBIO_freeZPEM_read_bio_DHparamsZDH_freeZSSL_CTX_set_tmp_dhrÛrÙ)rZdhfileÚbioZdhrír|r|r}Ú 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)rZcurver|r|r}Ú set_tmp_ecdhts 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.r~N)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“r3rÛrvÚget_cipher_listrl)rr2Ztmpconnr|r|r}Úset_cipher_list€s  ÿ ÿÿ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ÈryÚ X509_NAME_dupÚ_nameZsk_X509_NAME_pushÚX509_NAME_freerr—Zsk_X509_NAME_freer rÛ)rZcertificate_authoritiesZ name_stackZca_namerZ push_resultr|r|r}Úset_client_ca_list§s(   ÿÿ      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 instancer~N)rªrr¬r“ZSSL_CTX_add_client_CArÛrrÙ)rZcertificate_authorityrr|r|r}Ú 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Útimeoutr|r|r}Ú 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ÛrŒr|r|r}Ú 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Š©rvr–)rœÚwhereZ return_code©r r|r}r¡sz*Context.set_info_callback..wrapperzvoid (*)(const SSL *, int, int)N)rr£r rár“ZSSL_CTX_set_info_callbackrÛr¤r|r@r}Ú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Çrvr–)rœÚliner@r|r}r¡s z,Context.set_keylog_callback..wrapperz#void (*)(const SSL *, const char *)N)rr£r râr“ZSSL_CTX_set_keylog_callbackrÛr¤r|r@r}Ú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ärŒr|r|r}Ú 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 NrD©rr¸r|r|r}Ú 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ÚstoreZpystorer|r|r}Úget_cert_store6s    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Úoptionsr|r|r}Ú set_optionsGs 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Ûr%r|r|r}rêTs 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±r@r|r}r¡lsz7Context.set_tlsext_servername_callback..wrapperzint (*)(SSL *, int *, void *)N)rr£r rãr“Z&SSL_CTX_set_tlsext_servername_callbackrÛr¤r|r@r}Úset_tlsext_servername_callbackas ÿÿ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Û)rZprofilesr|r|r}Úset_tlsext_use_srtpxs  ÿzContext.set_tlsext_use_srtpcCsFd t dd„|Dƒ¡¡}t d|¡}tt |j|t |ƒ¡dkƒ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ÔÚpr|r|r}rÖ•r§z*Context.set_alpn_protos..r¨rN) ÚjoinrÚ from_iterabler£r­rÙr“ZSSL_CTX_set_alpn_protosrÛr®©rZprotosZprotostrZ input_strr|r|r}Úset_alpn_protos‡s ÿ  ÿýÿ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µ)rr r|r|r}Úset_alpn_select_callback§s    ÿ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. Nr~) rçr rèr£rµréZ new_handler“ZSSL_CTX_set_tlsext_status_cbrÛrÙZSSL_CTX_set_tlsext_status_arg)rÚhelperr¸Úrcr|r|r}Ú_set_ocsp_callback¼s  ÿ 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´rY©rr r¸rWr|r|r}Ú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»rYrZr|r|r}Úset_ocsp_client_callbackâsz Context.set_ocsp_client_callback)N)N)N)N)N)Bryrzr{rˆr#r$r%r&r'r(r)r*r+r×ÚdictÚitemsrŽrðrñrõrùrürrÿrrrrrrrrrrrr!r#r'r(r)r+r,r-r0r1r5r9r:r<r=rAÚ_requires_keylogrCrErGrJrLrêrMrNÚ_requires_alpnrUrVrYr[r\r|r|r|r}ruts~ ÷ þ(   0     #    '#        ruc@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)rvNcCst|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 instanceNr~)rªrur¬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Æ)rrìÚsocketrœrr|r|r}rŽú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')rcÚAttributeErrorÚ __class__ryrÁ©rrÕr|r|r}Ú __getattr__0s  ÿÿ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)NrÚwin32r½zUnexpected EOF)rÛrßr‘rårçr“Z SSL_get_errorZSSL_ERROR_WANT_READrmZSSL_ERROR_WANT_WRITErnZSSL_ERROR_ZERO_RETURNrpZSSL_ERROR_WANT_X509_LOOKUProZSSL_ERROR_SYSCALLZERR_peek_errorrr£Z getwinerrorÚerrnorqrr rZSSL_ERROR_NONE)rrœrrÍrlr|r|r}Ú_raise_ssl_error=s8               zConnection._raise_ssl_errorcCs|jS)zh Retrieve the :class:`Context` object associated with this :class:`Connection`. )rÛrŒr|r|r}Ú get_contextbszConnection.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. raN)rªrur¬r“ZSSL_set_SSL_CTXrbrÛ)rrìr|r|r}Ú set_contextis 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_servernamerbZTLSEXT_NAMETYPE_host_namer£rµrÇrir|r|r}Úget_servernamevs ÿ 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_namerbrir|r|r}Úset_tlsext_host_name‡s   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_pendingrbrŒr|r|r}Úpending—szConnection.pendingrcCsrtd|ƒ}t |¡J}t|ƒdkr*tdƒ‚t |j|t|ƒ¡}| |j|¡|WdƒS1sd0YdS)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) rr£Ú from_bufferr®rÂr“Ú SSL_writerbrm)rr"Úflagsr¸rr|r|r}Úsend s   ÿzConnection.sendcCs†td|ƒ}t |¡^}t|ƒ}d}|r`t |j||t|dƒ¡}| |j|¡||7}||8}q"|WdƒS1sx0YdS)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 r"rrtN) rr£rur®r“rvrbÚminrm)rr"rwr¸Z left_to_sendZ total_sentrr|r|r}Úsendall¼s  ÿ 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_allocatorrfÚMSG_PEEKr“ÚSSL_peekrbÚSSL_readrmr£r©)rÚbufsizrwr"rr|r|r}Ú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. Nr{) r®ryr|rfr}r“r~rbrrmÚ memoryviewr£r©)rr©Únbytesrwr"rr|r|r}Ú 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_readrmZBIO_should_writernr…rÂr)rr/rr|r|r}Ú_handle_bio_errorss      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 integerr{r) rer¬rªr r|r“ZBIO_readr†r£r©)rr€r"rr|r|r}Úbio_read$s   zConnection.bio_readcCsxtd|ƒ}|jdurtdƒ‚t |¡>}t |j|t|ƒ¡}|dkrR| |j|¡|WdƒS1sj0YdS)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 r"Nr‡r) rrdr¬r£rur“Z BIO_writer®r†)rr"r¸rr|r|r}Ú 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 r~TF)Úrenegotiate_pendingrÙr“ZSSL_renegotiaterbrŒr|r|r}Ú renegotiateQszConnection.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_handshakerbrm©rrr|r|r}Ú do_handshake]s 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 r~)r“ZSSL_renegotiate_pendingrbrŒr|r|r}rŠhszConnection.renegotiate_pendingcCs t |j¡S)z‚ Find out the total number of renegotiations. :return: The number of renegotiations. :rtype: int )r“ZSSL_total_renegotiationsrbrŒr|r|r}Útotal_renegotiationsrszConnection.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_staterbrcÚconnect)rÚaddrr|r|r}r{s 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 )rcÚ connect_exÚset_connect_state)rr‘r’r|r|r}r’‡s 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`. )rcÚacceptrvrÛÚset_accept_state)rZclientr‘r²r|r|r}r”•s  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 Nr‡r)rer¬r“ZBIO_set_mem_eof_returnrdrŒr|r|r}Ú bio_shutdown¤s 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_shutdownrbrmrŒr|r|r}Úshutdown±s 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_listrbr£rµr˜Ú_nativerÇ)rZciphersÚirr|r|r}r4Â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_listrbr£rµÚrangeZsk_X509_NAME_numZsk_X509_NAME_valuer6rÙrrHrÚr8r7r˜)rZca_namesrr™rÕrZpynamer|r|r}Ú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É©rrËrÌr|r|r}ÚmakefileísÿzConnection.makefilecCs|jS)zr Retrieve application data as set by :meth:`set_app_data`. :return: The application data rDrŒr|r|r}rEøszConnection.get_app_datacCs ||_dS)zg Set application data :param data: The application data :return: None NrDrFr|r|r}rGszConnection.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_shutdownrbrŒr|r|r}Ú 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_shutdownrb)rÚstater|r|r}Ú set_shutdowns 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_longrbrŒr|r|r}Úget_state_stringszConnection.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_sessionrbr£rµZSSL_get_server_randomrÙr|r©©rÚsessionÚlengthÚoutpr|r|r}Ú 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“r¢rbr£rµZSSL_get_client_randomrÙr|r©r£r|r|r}Ú client_random6s    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“r¢rbr£rµZSSL_SESSION_get_master_keyrÙr|r©r£r|r|r}Ú master_keyFs    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 r¨rNr~) r|r£rµr®r“ZSSL_export_keying_materialrbrÙr©) rZlabelZolenrìr¦Z context_bufZ context_lenZ use_contextÚsuccessr|r|r}Úexport_keying_materialVs( ø 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 )rcr—rœr|r|r}Ú sock_shutdowntszConnection.sock_shutdowncCs.t |j¡}|tjkr*t |¡t |¡SdS)za Retrieve the local certificate (if any) :return: The local certificate N)r“ZSSL_get_certificaterbr£rµr”rr•©rršr|r|r}Ú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_certificaterbr£rµrr•r­r|r|r}Úget_peer_certificate‰s   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. r~) ršr“Z sk_X509_numZ sk_X509_valuerÙr£rµr”rr•r˜)Ú cert_stackrr™ršríZpycertr|r|r}Ú_cert_stack_to_list”s     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_chainrbr£rµr±©rr°r|r|r}Úget_peer_cert_chain¤s  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_chainrbr£rµr±r²r|r|r}Úget_verified_chain±s  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_readrbrŒr|r|r}Ú 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_writerbrŒr|r|r}Ú 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_staterbrŒr|r|r}r•Ö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“rrbrŒr|r|r}r“ß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_sessionrbr£rµrtrHrÚZSSL_SESSION_freeÚ_session)rr¤Z pysessionr|r|r}Ú 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 instancer~N)rªrtr¬r“ZSSL_set_sessionrbr·rÙ)rr¤rr|r|r}Ú 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` r{rN)r£r­rbr|r©)rÚfunctionÚemptyrör"r|r|r}Ú_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_finishedrŒr|r|r}Ú 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_finishedrŒr|r|r}Úget_peer_finished6 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_cipherrbr£rµrÇZSSL_CIPHER_get_namerþ)rÚcipherrÕr|r|r}Úget_cipher_nameB 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Àrbr£rµZSSL_CIPHER_get_bits)rrÁr|r|r}Úget_cipher_bitsS 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Àrbr£rµrÇZSSL_CIPHER_get_versionrþ)rrÁrïr|r|r}Úget_cipher_versionc 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_versionrbrþrîr|r|r}Úget_protocol_version_namet 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_versionrbrîr|r|r}Úget_protocol_version€ s zConnection.get_protocol_versioncCsFd t dd„|Dƒ¡¡}t d|¡}tt |j|t |ƒ¡dkƒ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|ƒƒ|fVqdSrŠrOrPr|r|r}rÖ™ r§z-Connection.set_alpn_protos..r¨rN) rRrrSr£r­rÙr“ZSSL_set_alpn_protosrbr®rTr|r|r}rU‹ 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_selectedrbr©)rr¸Zdata_lenr|r|r}Ú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`. r~N)r“ZSSL_set_tlsext_status_typerbZTLSEXT_STATUSTYPE_ocsprÙ)rrXr|r|r}Ú request_ocspº sÿzConnection.request_ocsp)N)r)r)N)NN)N)Dryrzr{rr–rŽrjrmrnrorprrrsrxÚwriterzrÚreadr„r†rˆr‰r‹rrŠrŽrr’r”r–r—r4r›rrErGržr r¡r§r¨r©r«r¬r®r¯Ú staticmethodr±r³r´rµr¶r•r“r¸r¹r¼r½r¾rÂrÃrÄrÅrÆr`rUrÇrÈr|r|r|r}rv÷s‚ 6 %     %                     "      rv)Îr rfÚsysrÚ functoolsrrÚ itertoolsrrÚweakrefrrlrZsixr r r Z OpenSSL._utilr rr Z_exception_from_error_queuerr£rr“rZ _make_assertrr˜rròrrrr|ZOpenSSL.cryptorrrrrrÚ__all__r©rwÚ NameErrorÚobjectrrrrrr ZSSL_SENT_SHUTDOWNr!ZSSL_RECEIVED_SHUTDOWNr"r#r$r%r&r'r(r)r*r+r,r-r.r/r0rgZSSL_OP_NO_SSLv2r1ZSSL_OP_NO_SSLv3r2ZSSL_OP_NO_TLSv1r3ZSSL_OP_NO_TLSv1_1r4ZSSL_OP_NO_TLSv1_2r5ZSSL_OP_NO_TLSv1_3r6ZSSL_MODE_RELEASE_BUFFERSr7ZSSL_OP_SINGLE_DH_USEr8ZSSL_OP_SINGLE_ECDH_USEr9ZSSL_OP_EPHEMERAL_RSAr:ZSSL_OP_MICROSOFT_SESS_ID_BUGr;ZSSL_OP_NETSCAPE_CHALLENGE_BUGr<Z'SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUGr=Z"SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUGr>Z!SSL_OP_MICROSOFT_BIG_SSLV3_BUFFERr?ZSSL_OP_MSIE_SSLV2_RSA_PADDINGr@ZSSL_OP_SSLEAY_080_CLIENT_DH_BUGrAZSSL_OP_TLS_D5_BUGrBZSSL_OP_TLS_BLOCK_PADDING_BUGrCZ"SSL_OP_DONT_INSERT_EMPTY_FRAGMENTSrDZSSL_OP_CIPHER_SERVER_PREFERENCErEZSSL_OP_TLS_ROLLBACK_BUGrFZSSL_OP_PKCS1_CHECK_1rGZSSL_OP_PKCS1_CHECK_2rHZSSL_OP_NETSCAPE_CA_DN_BUGrIZ&SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUGrJZSSL_OP_NO_COMPRESSIONrKZSSL_OP_NO_QUERY_MTUrLZSSL_OP_COOKIE_EXCHANGErMZSSL_OP_NO_TICKETrNZ SSL_OP_ALLrOZSSL_VERIFY_PEERrPZSSL_VERIFY_FAIL_IF_NO_PEER_CERTrQZSSL_VERIFY_CLIENT_ONCErRZSSL_VERIFY_NONErSZSSL_SESS_CACHE_OFFrTZSSL_SESS_CACHE_CLIENTrUZSSL_SESS_CACHE_SERVERrVZSSL_SESS_CACHE_BOTHrWZSSL_SESS_CACHE_NO_AUTO_CLEARrXZ!SSL_SESS_CACHE_NO_INTERNAL_LOOKUPrYZ SSL_SESS_CACHE_NO_INTERNAL_STORErZZSSL_SESS_CACHE_NO_INTERNALr[r\r]r^r_r`rarbrcrdrerfrgrhrirjrkrrrrr—rlrrÙrmrnrorprqr‰r’rrr¦r´r»rÆrsrÓZCryptography_HAS_ALPNr`rÁr_rtrurvZSSL_library_initr|r|r|r}Ús2   , _    ÿÿ ÿ (=C; ÿ ÿ  Y