o SaV@sPddlZddlZddlmZddlmZmZddlmZm 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.Wne/ysGd d d e0Z.Ynwej1Z1ej2Z2ej3Z3ej4Z4ej5Z5ej6Z6ej7Z8ej9Z:d Z;dZdZ?dZ@dZAdZBdZCzejDZDejEZEejFZFejGZGejHZHWneIydZDdZEdZFdZGdZHYnwejJZKejLZMejNZOejPZQejRZSzejTZUWn eIyYnwejVZWejXZYejZZ[ej\Z]ej^Z_ej`ZaejbZcejdZeejfZgejhZiejjZkejlZmejnZoejpZqejrZsejtZuejvZwejxZyejzZ{ej|Z}ej~ZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZgdZdgZdZdZGdd d eZeeeZeeZGd!d"d"eZGd#d$d$eZGd%d&d&eZGd'd(d(eZGd)d*d*eZGd+d,d,e0ZGd-d.d.eZe0ZGd/d0d0eZGd1d2d2eZGd3d4d4eZd5d6Zd7d8Zd9d:Zeejd;Zeeedd?d?e0ZGd@dAdAe0ZGdBdCdCe0Ze͡dS)DN)platform)wrapspartial)countchain)WeakValueDictionary) errorcode) integer_typesint2byte indexbytes) UNSPECIFIEDexception_from_error_queueffilib make_assertnative path_stringtext_to_bytes_and_warnno_zero_allocator) FILETYPE_PEM_PassphraseHelperPKeyX509NameX509 X509Store)\OPENSSL_VERSION_NUMBERSSLEAY_VERSION SSLEAY_CFLAGSSSLEAY_PLATFORM SSLEAY_DIRSSLEAY_BUILT_ON SENT_SHUTDOWNRECEIVED_SHUTDOWN SSLv2_METHOD SSLv3_METHOD SSLv23_METHOD TLSv1_METHODTLSv1_1_METHODTLSv1_2_METHOD TLS_METHODTLS_SERVER_METHODTLS_CLIENT_METHOD SSL3_VERSION TLS1_VERSIONTLS1_1_VERSIONTLS1_2_VERSIONTLS1_3_VERSION OP_NO_SSLv2 OP_NO_SSLv3 OP_NO_TLSv1 OP_NO_TLSv1_1 OP_NO_TLSv1_2 OP_NO_TLSv1_3MODE_RELEASE_BUFFERSOP_SINGLE_DH_USEOP_SINGLE_ECDH_USEOP_EPHEMERAL_RSAOP_MICROSOFT_SESS_ID_BUGOP_NETSCAPE_CHALLENGE_BUG#OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUGOP_SSLREF2_REUSE_CERT_TYPE_BUGOP_MICROSOFT_BIG_SSLV3_BUFFEROP_MSIE_SSLV2_RSA_PADDINGOP_SSLEAY_080_CLIENT_DH_BUG OP_TLS_D5_BUGOP_TLS_BLOCK_PADDING_BUGOP_DONT_INSERT_EMPTY_FRAGMENTSOP_CIPHER_SERVER_PREFERENCEOP_TLS_ROLLBACK_BUGOP_PKCS1_CHECK_1OP_PKCS1_CHECK_2OP_NETSCAPE_CA_DN_BUG"OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUGOP_NO_COMPRESSIONOP_NO_QUERY_MTUOP_COOKIE_EXCHANGE OP_NO_TICKETOP_ALL VERIFY_PEERVERIFY_FAIL_IF_NO_PEER_CERTVERIFY_CLIENT_ONCE VERIFY_NONESESS_CACHE_OFFSESS_CACHE_CLIENTSESS_CACHE_SERVERSESS_CACHE_BOTHSESS_CACHE_NO_AUTO_CLEARSESS_CACHE_NO_INTERNAL_LOOKUPSESS_CACHE_NO_INTERNAL_STORESESS_CACHE_NO_INTERNALSSL_ST_CONNECT SSL_ST_ACCEPT SSL_ST_MASK SSL_CB_LOOP SSL_CB_EXIT SSL_CB_READ SSL_CB_WRITE SSL_CB_ALERTSSL_CB_READ_ALERTSSL_CB_WRITE_ALERTSSL_CB_ACCEPT_LOOPSSL_CB_ACCEPT_EXITSSL_CB_CONNECT_LOOPSSL_CB_CONNECT_EXITSSL_CB_HANDSHAKE_STARTSSL_CB_HANDSHAKE_DONEError WantReadErrorWantWriteErrorWantX509LookupErrorZeroReturnError SysCallErrorNO_OVERLAPPING_PROTOCOLSSSLeay_versionSessionContext Connectionc@ eZdZdS)_bufferN__name__ __module__ __qualname__r}r}-/usr/lib/python3/dist-packages/OpenSSL/SSL.pyrxrx 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@eZdZdZdS)rlz4 An error occurred in an `OpenSSL.SSL` API. Nrzr{r|__doc__r}r}r}r~rlsrlc@rw)rmNryr}r}r}r~rmrrmc@rw)rnNryr}r}r}r~rnrrnc@rw)roNryr}r}r}r~rorroc@rw)rpNryr}r}r}r~rprrpc@rw)rqNryr}r}r}r~rq"rrqc@s eZdZdZddZddZdS)_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|_dSN) _problemsselfr}r}r~__init__2s z!_CallbackExceptionHelper.__init__cCs4|jrztWn tyYnw|jddS)z Raise an exception from the OpenSSL error queue or that was previously captured whe running a callback. rN)r_raise_current_errorrlpoprr}r}r~raise_if_problem5s   z)_CallbackExceptionHelper.raise_if_problemN)rzr{r|rrrr}r}r}r~r&s rc@eZdZdZddZdS) _VerifyHelperz^ Wrap a callback such that it can be used as a certificate verification callback. c2ttfdd}td|_dS)Nc st|}t|t|}t|}t|}t}t||}t j |}z |||||} Wnt yK} z j | WYd} ~ dSd} ~ ww| rWt|tjdSdS)Nrr)_libX509_STORE_CTX_get_current_cert X509_up_refr_from_raw_x509_ptrX509_STORE_CTX_get_errorX509_STORE_CTX_get_error_depth"SSL_get_ex_data_X509_STORE_CTX_idxX509_STORE_CTX_get_ex_datarv_reverse_mapping ExceptionrappendX509_STORE_CTX_set_error X509_V_OK) ok store_ctxx509cert error_number error_depthindexssl connectionresultecallbackrr}r~wrapperKs*         z'_VerifyHelper.__init__..wrapperzint (*)(int, X509_STORE_CTX *)rrr_ffirrrrr}rr~rHs  z_VerifyHelper.__init__Nrzr{r|rrr}r}r}r~rBs rc@r)_ALPNSelectHelperzQ Wrap a callback such that it can be used as an ALPN selection callback. cr)Nc szqtj|}t||dd}g}|r0t|d} |d| d} || || dd}|s||} d} | tur@d} d} n t| tsIt dt dt | t d| g|_ |j dd|d<|j d|d<| snt jWSt jWSty} zj| t jWYd} ~ Sd} ~ ww) NrrTFz^ALPN callback must return a bytestring or the special NO_OVERLAPPING_PROTOCOLS sentinel value.zunsigned char *unsigned char[])rvrrbufferr rrr isinstancebytes TypeErrornewlen_alpn_select_callback_argsrSSL_TLSEXT_ERR_NOACKSSL_TLSEXT_ERR_OKrrSSL_TLSEXT_ERR_ALERT_FATAL)routoutlenin_inlenargconninstr protolist encoded_lenprotooutbytes any_acceptedrrr}r~rus@       z+_ALPNSelectHelper.__init__..wrapperz^int (*)(SSL *, unsigned char **, unsigned char *, const unsigned char *, unsigned int, void *)rrr}rr~rrs + z_ALPNSelectHelper.__init__Nrr}r}r}r~rms rc@r)_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. cr)Nc szBtj|}|tjkrt|}nd}||}t|ts!td|s&WdSt|}t |}|t ||dd<t |||WdSt y[}z j|WYd}~dSd}~ww)Nz'OCSP callback must return a bytestring.rrr)rvrrNULL from_handlerrrrrOPENSSL_mallocrSSL_set_tlsext_status_ocsp_resprrr)rcdatardata ocsp_dataocsp_data_lengthdata_ptrrrr}r~rs,       z3_OCSPServerCallbackHelper.__init__..wrapperint (*)(SSL *, void *)rrr}rr~rs &z"_OCSPServerCallbackHelper.__init__Nrr}r}r}r~r rc@r)_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. cr)Nc sz=tj|}|tjkrt|}nd}td}t||}|dkr%d}n t|d|dd}|||}t t |WSt yV}z j |WYd}~dSd}~ww)Nunsigned char **rr)rvrrrrrrSSL_get_tlsext_status_ocsp_resprintboolrrr) rrrrocsp_ptrocsp_lenrvalidrrr}r~rs"       z3_OCSPClientCallbackHelper.__init__..wrapperrrrr}rr~rs z"_OCSPClientCallbackHelper.__init__Nrr}r}r}r~rrrcCsbd}t|tst|dd}|dur|}t|tr|}t|ts$td|dkr/td|f|S)Nfilenoz3argument must be an int, or have a fileno() method.rz1file descriptor cannot be a negative integer (%i))rr getattrr ValueError)objfdmethr}r}r~_asFileDescriptor(s    rcCstt|S)z Return a string describing the version of OpenSSL in use. :param type: One of the :const:`SSLEAY_` constants defined in this module. )rstringrrs)typer}r}r~rs<srscsfdd}|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|S)NcstrNotImplementedError)argskwargs)errorr}r~explodeSsz<_make_requires.._requires_decorator..explode)r)funcrrflagr}r~_requires_decoratorPs z+_make_requires.._requires_decoratorr})rrrr}rr~_make_requiresEs  rzALPN not availableCryptography_HAS_KEYLOGzKey logging not availablec@r)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 Nrr}r}r}r~rthsrtc@seZdZdZededededede de de d e d i Z ed d e DZ d dZddZddZdjddZddZdjddZddZddZddZd d!Zefd"d#Zd$d%Zd&d'Zd(d)Zefd*d+Z d,d-Z!d.d/Z"d0d1Z#d2d3Z$d4d5Z%d6d7Z&djd8d9Z'd:d;Z(dd?Z*d@dAZ+dBdCZ,dDdEZ-dFdGZ.dHdIZ/dJdKZ0dLdMZ1dNdOZ2e3dPdQZ4dRdSZ5dTdUZ6dVdWZ7dXdYZ8dZd[Z9d\d]Z:d^d_Z;edddeZ?djdfdgZ@djdhdiZAdS)krua- :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. SSLv2_method SSLv3_method SSLv23_method TLSv1_methodTLSv1_1_methodTLSv1_2_method TLS_methodTLS_server_methodTLS_client_methodccs2|]\}}tt|ddur|tt|fVqdSr)rr).0 identifiernamer}r}r~ s zContext.cCst|ts tdz|j|}Wn tytdw|}t|tjkt |}t|tjkt |t j }t |d}t|dk||_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_|t jdS)Nzmethod must be an integerzNo such protocolr)rr r_methodsKeyErrorr_openssl_assertrrr SSL_CTX_newgc SSL_CTX_freeSSL_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_dataset_modeSSL_MODE_ENABLE_PARTIAL_WRITE)rmethod method_func method_objcontextresr}r}r~rs<     zContext.__init__cCtt|j|dkdS)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. rN)r rSSL_CTX_set_min_proto_versionrrversionr}r}r~set_min_proto_version zContext.set_min_proto_versioncCr$)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. rN)r rSSL_CTX_set_max_proto_versionrr&r}r}r~set_max_proto_versionr)zContext.set_max_proto_versionNcCsR|durtj}nt|}|durtj}nt|}t|j||}|s'tdSdS)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)rr _path_stringrSSL_CTX_load_verify_locationsrr)rcafilecapath load_resultr}r}r~load_verify_locationss zContext.load_verify_locationscs&tfdd}tt|dddS)Ncs||jSr)r)sizeverifyuserdatarr}r~rsz'Context._wrap_callback..wrapperT) more_argstruncate)rrrrr}rr~_wrap_callbacks 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) callablerr7rrrrSSL_CTX_set_default_passwd_cbrr)rrr4r}r}r~ set_passwd_cbs   zContext.set_passwd_cbcCst|j}t|dkttd}ttd}| ||sDtt }tt }|t krF|t krH|ttdSdSdSdS)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 rasciiN)r SSL_CTX_set_default_verify_pathsrr rrX509_get_default_cert_dir_envdecodeX509_get_default_cert_file_env_check_env_vars_setX509_get_default_cert_dirX509_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_var default_dir 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)osenvironget)rrJrKr}r}r~rAGszContext._check_env_vars_setcCsP|D]}tj|r||nq|D]}tj|r%|d|dSqdS)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)rOpathisfiler1isdir)r file_pathdir_pathr.r/r}r}r~rFRs    z&Context._fallback_default_verify_pathscCs(t|}t|j|}|stdSdS)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"SSL_CTX_use_certificate_chain_filerr)rcertfilerr}r}r~use_certificate_chain_filefs  z"Context.use_certificate_chain_filecCs<t|}t|ts tdt|j||}|stdSdS)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,rr rrSSL_CTX_use_certificate_filerr)rrXfiletype use_resultr}r}r~use_certificate_filews  zContext.use_certificate_filecCs4t|ts tdt|j|j}|stdSdS)zs Load a certificate from a X509 object :param cert: The X509 object :return: None zcert must be an X509 instanceN)rrrrSSL_CTX_use_certificater_x509r)rrr]r}r}r~use_certificates  zContext.use_certificatecCsHt|ts tdt|j}t|j|}|s"t|t dSdS)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) rrrrX509_dupr`SSL_CTX_add_extra_chain_certr X509_freer)rcertobjcopy add_resultr}r}r~add_extra_chain_certs    zContext.add_extra_chain_certcCs |jdur |jttdSr)rrrlrrr}r}r~_raise_passphrase_exceptions   z#Context._raise_passphrase_exceptioncCsLt|}|tur t}n t|tstdt|j||}|s$| dSdS)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 rZN) r, _UNSPECIFIEDrrr rrSSL_CTX_use_PrivateKey_filerri)rkeyfiler\r]r}r}r~use_privatekey_files   zContext.use_privatekey_filecCs6t|ts tdt|j|j}|s|dSdS)zs Load a private key from a PKey object :param pkey: The PKey object :return: None zpkey must be a PKey instanceN)rrrrSSL_CTX_use_PrivateKeyr_pkeyri)rpkeyr]r}r}r~use_privatekeys  zContext.use_privatekeycCst|js tdSdS)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)rSSL_CTX_check_private_keyrrrr}r}r~check_privatekeys  zContext.check_privatekeycCs0ttd|}t|tjkt|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)rSSL_load_client_CA_file_text_to_bytes_and_warnr rrSSL_CTX_set_client_CA_listr)rr.ca_listr}r}r~load_client_cas  zContext.load_client_cacCs*td|}tt|j|t|dkdS)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 bufrN)rur rSSL_CTX_set_session_id_contextrr)rryr}r}r~set_session_ids zContext.set_session_idcC t|ts tdt|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)rr rrSSL_CTX_set_session_cache_moderrmoder}r}r~set_session_cache_modes zContext.set_session_cache_modecC t|jS)z Get the current session cache mode. :returns: The currently used cache mode. .. versionadded:: 0.14 )rSSL_CTX_get_session_cache_moderrr}r}r~get_session_cache_modes zContext.get_session_cache_modecCsvt|ts td|durd|_d|_t|j|tj dSt |s&tdt ||_|jj |_t|j||jdS)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}Nr8) rr rrrrSSL_CTX_set_verifyrrrr9rr)rrrr}r}r~ set_verifys   zContext.set_verifycC$t|ts tdt|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)rr rrSSL_CTX_set_verify_depthr)rdepthr}r}r~set_verify_depth@ zContext.set_verify_depthcCr)z Retrieve the Context object's verify mode, as set by :meth:`set_verify`. :return: The verify mode )rSSL_CTX_get_verify_moderrr}r}r~get_verify_modeM zContext.get_verify_modecCr)z Retrieve the Context object's verify depth, as set by :meth:`set_verify_depth`. :return: The verify depth )rSSL_CTX_get_verify_depthrrr}r}r~get_verify_depthVrzContext.get_verify_depthcCstt|}t|d}|tjkrtt|tj}t|tjtjtj}t|tj }t |j |}t |dkdS)z Load parameters for Ephemeral Diffie-Hellman :param dhfile: The file to load EDH parameters from (``bytes`` or ``unicode``). :return: None rrN) r,r BIO_new_filerrrr BIO_freePEM_read_bio_DHparamsDH_freeSSL_CTX_set_tmp_dhrr )rdhfilebiodhr#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)rSSL_CTX_set_tmp_ecdhr _to_EC_KEY)rcurver}r}r~ set_tmp_ecdhts zContext.set_tmp_ecdhcCsZtd|}t|tstdtt|j|dkt|d}| gdkr+t dgdS)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.rN)TLS_AES_256_GCM_SHA384TLS_CHACHA20_POLY1305_SHA256TLS_AES_128_GCM_SHA256)z SSL routinesSSL_CTX_set_cipher_listzno cipher match) rurrrr rrrrvget_cipher_listrl)rrtmpconnr}r}r~set_cipher_lists  zContext.set_cipher_listcCst}t|tjkz3|D].}t|tstdt|j ft |j }t|tjkt ||}|s.wrapperzvoid (*)(const SSL *, int, int)N)rrrrrSSL_CTX_set_info_callbackrrr}rr~set_info_callbacks  zContext.set_info_callbackcr)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)rrrvr)rlinerr}r~rs z,Context.set_keylog_callback..wrapperz#void (*)(const SSL *, const char *)N)rrrrrSSL_CTX_set_keylog_callbackrrr}rr~set_keylog_callback s zContext.set_keylog_callbackcC|jS)zw Get the application data (supplied via :meth:`set_app_data()`) :return: The application data rrr}r}r~ get_app_data%zContext.get_app_datacC ||_dS)z Set the application data (will be returned from get_app_data()) :param data: Any Python object :return: None Nrrrr}r}r~ set_app_data- zContext.set_app_datacCs.t|j}|tjkr dStt}||_|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)rSSL_CTX_get_cert_storerrrr__new___store)rstorepystorer}r}r~get_cert_store6s   zContext.get_cert_storecCr|)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)rr rrSSL_CTX_set_optionsr)roptionsr}r}r~ set_optionsG zContext.set_optionscCr|)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})rr rrSSL_CTX_set_moderrr}r}r~rTrzContext.set_modecr)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 cstj|dS)Nrr)ralertrrr}r~rlsz7Context.set_tlsext_servername_callback..wrapperzint (*)(SSL *, int *, void *)N)rrrrr&SSL_CTX_set_tlsext_servername_callbackrrr}rr~set_tlsext_servername_callbackas z&Context.set_tlsext_servername_callbackcCs,t|ts tdtt|j|dkdS)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)rrrr rSSL_CTX_set_tlsext_use_srtpr)rprofilesr}r}r~set_tlsext_use_srtpxs zContext.set_tlsext_use_srtpcCFdtdd|D}td|}tt|j|t |dkdS)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']``. rcs |] }tt||fVqdSrr rrpr}r}r~rz*Context.set_alpn_protos..rrN) joinr from_iterablerrr rSSL_CTX_set_alpn_protosrrrprotosprotostr input_strr}r}r~set_alpn_protoss   zContext.set_alpn_protoscCs,t||_|jj|_t|j|jtjdS)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) rrrrrSSL_CTX_set_alpn_select_cbrrr)rrr}r}r~set_alpn_select_callbacks   z Context.set_alpn_select_callbackcCsh||_|j|_|durtj|_nt||_t|j |j}t |dkt |j |j}t |dkdS)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) rrrrrr new_handlerSSL_CTX_set_tlsext_status_cbrr SSL_CTX_set_tlsext_status_arg)rhelperrrcr}r}r~_set_ocsp_callbacks   zContext._set_ocsp_callbackcCt|}|||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)rrrrrrr}r}r~set_ocsp_server_callbacksz Context.set_ocsp_server_callbackcCr)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)rrrr}r}r~set_ocsp_client_callbacksz Context.set_ocsp_client_callbackr)Brzr{r|rr#r$r%r&r'r(r)r*r+rdictitemsrr(r+r1r7r;rNrArFrYrr^rarhrirjrmrqrsrxr{rrrrrrrrrrrrrr_requires_keylogrrrrrrrr_requires_alpnrrrrrr}r}r}r~ruts  (  0     #    '#        ruc@s eZdZeZdyddZddZddZdd Zd d Z d d Z ddZ ddZ dzddZ e ZdzddZdyddZeZd{ddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.Zd/d0Zd1d2Zd3d4Zd5d6Z d7d8Z!d9d:Z"d;d<Z#d=d>Z$d?d@Z%dAdBZ&dCdDZ'dEdFZ(dGdHZ)dydIdJZ*dKdLZ+dMdNZ,dOdPZ-e.dQdRZ/dSdTZ0dUdVZ1dWdXZ2dYdZZ3d[d\Z4d]d^Z5d_d`Z6dadbZ7dcddZ8dedfZ9dgdhZ:didjZ;dkdlZdqdrZ?e@dsdtZAe@dudvZBdwdxZCdS)|rvNcCst|ts tdt|j}t|tj|_ t |j tj ||_d|_ d|_ |j|_|j|_||j|j <|durid|_tt|_t|jtjktt|_t|jtjkt|j |j|jdSd|_d|_||_t|j t|j}t|dkdS)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)rrurrSSL_newrrr SSL_free_ssl SSL_set_modeSSL_MODE_AUTO_RETRYrrrrr_socketBIO_new BIO_s_mem _into_sslr r _from_ssl SSL_set_bio SSL_set_fdr)rr"socketrrIr}r}r~rs2    zConnection.__init__cCs*|jdurtd|jj|ft|j|S)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')rAttributeError __class__rzrrrr}r}r~ __getattr__0s   zConnection.__getattr__cCs|jjdur |jj|jjdur|jj|jjdur$|jjt||}|tjkr2t|tj kr:t |tj krBt |tj krJt|tjkr}tdkrx|dkrstdkrdtd}ntj}|dkrst|t|tddtdS|tjkrdStdS)Nrwin32rzUnexpected EOF)rrrrrr SSL_get_errorSSL_ERROR_WANT_READrmSSL_ERROR_WANT_WRITErnSSL_ERROR_ZERO_RETURNrpSSL_ERROR_WANT_X509_LOOKUProSSL_ERROR_SYSCALLERR_peek_errorrr getwinerrorerrnorqrrQrSSL_ERROR_NONE)rrrrrr}r}r~_raise_ssl_error=s8                 zConnection._raise_ssl_errorcCr)zh Retrieve the :class:`Context` object associated with this :class:`Connection`. )rrr}r}r~ get_contextbszConnection.get_contextcCs,t|ts tdt|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. rN)rrurrSSL_set_SSL_CTXrr)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)rSSL_get_servernamerTLSEXT_NAMETYPE_host_namerrrr r}r}r~get_servernamevs    zConnection.get_servernamecCs4t|ts tdd|vrtdt|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 stringzname must not contain NUL byteN)rrrrSSL_set_tlsext_host_namerr r}r}r~set_tlsext_host_names zConnection.set_tlsext_host_namecCr)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 SSL_pendingrrr}r}r~pendingrzConnection.pendingrcCsrtd|}t|%}t|dkrtdt|j|t|}||j||WdS1s2wYdS)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 ryz,Cannot send more than 2**31-1 bytes at once.N) rur from_bufferrrr SSL_writerr)rryflagsrrr}r}r~sends  $zConnection.sendcCstd|}t|0}t|}d}|r1t|j||t|d}||j|||7}||8}|s|WdS1s=wYdS)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 ryrr%N) rurr&rrr'rminr)rryr(r left_to_send total_sentrr}r}r~sendalls  $zConnection.sendallcCs`td|}|dur|tj@rt|j||}nt|j||}||j|t ||ddS)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_allocatorr MSG_PEEKrSSL_peekrSSL_readrrr)rbufsizr(ryrr}r}r~recvs zConnection.recvcCs|dur t|}nt|t|}td|}|dur'|tj@r't|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.) rr*r/r r0rr1rr2r memoryviewrr)rrnbytesr(ryrr}r}r~ recv_intos  zConnection.recv_intocCsNt|r"t|r tt|rtt|rtdtdtdS)NBIO_should_io_specialzunknown bio failure) rBIO_should_retryBIO_should_readrmBIO_should_writernr8rr)rrrr}r}r~_handle_bio_errorss     zConnection._handle_bio_errorscCsh|jdur tdt|tstdtd|}t|j||}|dkr*||j|t ||ddS)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. NConnection sock was not Nonezbufsiz must be an integerr.r) rrrr r/rBIO_readr<rr)rr3ryrr}r}r~bio_read$s   zConnection.bio_readcCsxtd|}|jdurtdt|}t|j|t|}|dkr)||j||WdS1s5wYdS)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 ryNr=r) rurrrr&r BIO_writerr<)rryrrr}r}r~ bio_write<s  $zConnection.bio_writecCs$|stt|jdkdSdS)z Renegotiate the session. :return: True if the renegotiation can be started, False otherwise :rtype: bool rTF)renegotiate_pendingr rSSL_renegotiaterrr}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)rSSL_do_handshakerrrrr}r}r~ do_handshake]s zConnection.do_handshakecCst|jdkS)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)rSSL_renegotiate_pendingrrr}r}r~rBhszConnection.renegotiate_pendingcCr)z Find out the total number of renegotiations. :return: The number of renegotiations. :rtype: int )rSSL_total_renegotiationsrrr}r}r~total_renegotiationsrrzConnection.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 )rSSL_set_connect_staterrconnect)raddrr}r}r~rL{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 )r connect_exset_connect_state)rrMrNr}r}r~rNs 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`. )racceptrvrset_accept_state)rclientrMrr}r}r~rPs zConnection.acceptcCs$|jdur tdt|jddS)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)rrrBIO_set_mem_eof_returnrrr}r}r~ bio_shutdownrzConnection.bio_shutdowncCs6t|j}|dkr||j|dS|dkrdSdS)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 SSL_shutdownrrrFr}r}r~shutdowns zConnection.shutdowncCsFg}tD]}t|j|}|tjkr|S|tt|q|S)z Retrieve the list of ciphers used by the Connection object. :return: A list of native cipher strings. ) rrSSL_get_cipher_listrrrr_nativer)rciphersirr}r}r~rs  zConnection.get_cipher_listcCs~t|j}|tjkr gSg}tt|D]&}t||}t|}t |tjkt 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 )rSSL_get_client_CA_listrrrrangesk_X509_NAME_numsk_X509_NAME_valuerr rrr rrr)rca_namesrrZrrfpynamer}r}r~get_client_ca_lists     zConnection.get_client_ca_listcOstd)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.Connectionrrrrr}r}r~makefileszConnection.makefilecCr)zr Retrieve application data as set by :meth:`set_app_data`. :return: The application data rrr}r}r~rrzConnection.get_app_datacCr)zg Set application data :param data: The application data :return: None Nrrr}r}r~rrzConnection.set_app_datacCr)z Get the shutdown state of the Connection. :return: The shutdown state, a bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN. )rSSL_get_shutdownrrr}r}r~ get_shutdown rzConnection.get_shutdowncCr)z Set the shutdown state of the Connection. :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN. :return: None zstate must be an integerN)rr rrSSL_set_shutdownr)rstater}r}r~ set_shutdowns zConnection.set_shutdowncCstt|jS)z Retrieve a verbose string detailing the state of the Connection. :return: A string representing the state :rtype: bytes )rrrSSL_state_string_longrrr}r}r~get_state_stringzConnection.get_state_stringcCft|j}|tjkr dSt|jtjd}t|dktd|}t|j||t||ddS)z Retrieve the random value used with the server hello message. :return: A string representing the state Nrr) rSSL_get_sessionrrrSSL_get_server_randomr r/rrsessionlengthoutpr}r}r~ server_random's    zConnection.server_randomcCrl)z Retrieve the random value used with the client hello message. :return: A string representing the state Nrr) rrmrrrSSL_get_client_randomr r/rror}r}r~ client_random6s    zConnection.client_randomcCsbt|j}|tjkr dSt|tjd}t|dktd|}t|||t||ddS)zz Retrieve the value of the master key for this session. :return: A string representing the state Nrr) rrmrrrSSL_SESSION_get_master_keyr r/rror}r}r~ master_keyFs    zConnection.master_keyc Csntd|}tj}d}d}|dur|}t|}d}t|j|||t||||}t|dkt||ddS)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 rrNr) r/rrrrSSL_export_keying_materialrr r) rlabelolenr"rr context_buf context_len use_contextsuccessr}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 )rrVrbr}r}r~ sock_shutdowntrkzConnection.sock_shutdowncCs.t|j}|tjkrt|t|SdS)za Retrieve the local certificate (if any) :return: The local certificate N)rSSL_get_certificaterrrrrrrrr}r}r~get_certificate}s    zConnection.get_certificatecCs$t|j}|tjkrt|SdS)zi Retrieve the other side's certificate (if any) :return: The peer's certificate N)rSSL_get_peer_certificaterrrrrrr}r}r~get_peer_certificates   zConnection.get_peer_certificatecCs`g}tt|D]$}t||}t|tjkt|}t|dkt |}| |q |S)zb Internal helper to convert a STACK_OF(X509) to a list of X509 instances. r) r\r sk_X509_num sk_X509_valuer rrrrrr) cert_stackrrZrr#pycertr}r}r~_cert_stack_to_lists     zConnection._cert_stack_to_listcC$t|j}|tjkr dS||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)rSSL_get_peer_cert_chainrrrrrrr}r}r~get_peer_cert_chains   zConnection.get_peer_cert_chaincCr)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)rSSL_get0_verified_chainrrrrrr}r}r~get_verified_chains  zConnection.get_verified_chaincCr)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 SSL_want_readrrr}r}r~ want_readrzConnection.want_readcCr)z Checks if there is data to write to the transport layer to complete an operation. :return: True iff there is data to write )rSSL_want_writerrr}r}r~ want_writerzConnection.want_writecCt|jdS)z Set the connection to work in server mode. The handshake will be handled automatically by read/write. :return: None N)rSSL_set_accept_staterrr}r}r~rQzConnection.set_accept_statecCr)z Set the connection to work in client mode. The handshake will be handled automatically by read/write. :return: None N)rrKrrr}r}r~rOrzConnection.set_connect_statecCs8t|j}|tjkr dStt}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) rSSL_get1_sessionrrrrtrr SSL_SESSION_free_session)rrp pysessionr}r}r~ get_sessions  zConnection.get_sessioncCr)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 instancerN)rrtrrSSL_set_sessionrrr )rrprr}r}r~ set_sessions zConnection.set_sessioncCsRtdd}||j|d}|dkrdStd|}||j||t||ddS)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)rrrr/r)rfunctionemptyr2ryr}r}r~_get_finished_message s  z Connection._get_finished_messagecC |tjS)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 )rrSSL_get_finishedrr}r}r~ get_finished*  zConnection.get_finishedcCr)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 )rrSSL_get_peer_finishedrr}r}r~get_peer_finished6 rzConnection.get_peer_finishedcC4t|j}|tjkr dStt|}|dS)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 Nutf-8)rSSL_get_current_cipherrrrrSSL_CIPHER_get_namer?)rcipherrr}r}r~get_cipher_nameB  zConnection.get_cipher_namecCs(t|j}|tjkr dSt|tjS)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)rrrrrSSL_CIPHER_get_bits)rrr}r}r~get_cipher_bitsS s zConnection.get_cipher_bitscCr)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)rrrrrrSSL_CIPHER_get_versionr?)rrr'r}r}r~get_cipher_versionc rzConnection.get_cipher_versioncCstt|j}|dS)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)rrrSSL_get_versionrr?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 SSL_versionrr&r}r}r~get_protocol_version s zConnection.get_protocol_versioncCr)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']``. rcsrrrrr}r}r~r rz-Connection.set_alpn_protos..rrN) rrrrrr rSSL_set_alpn_protosrrrr}r}r~r s  zConnection.set_alpn_protoscCsHtd}td}t|j|||sdSt|d|dddS)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. rzunsigned int *rrN)rrrSSL_get0_alpn_selectedrr)rrdata_lenr}r}r~get_alpn_proto_negotiated s  z$Connection.get_alpn_proto_negotiatedcCs t|jtj}t|dkdS)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`. rN)rSSL_set_tlsext_status_typerTLSEXT_STATUSTYPE_ocspr )rrr}r}r~ request_ocsp szConnection.request_ocspr)r)NN)Drzr{r|rrrr rrrrr"r$r)writer-r4readr7r<r?rArDrGrBrJrLrNrPrTrVrrarcrrrerhrjrsrurwrrrr staticmethodrrrrrrQrOrrrrrrrrrrrrrrr}r}r}r~rvs 6 %     %                    "      rv)rOr sysr functoolsrr itertoolsrrweakrefrrrsixr r r OpenSSL._utilr rjr _exception_from_error_queuerrrrr _make_assertrrXrr,rrurr/OpenSSL.cryptorrrrrr__all__rrx NameErrorobjectrrrrrr SSL_SENT_SHUTDOWNr!SSL_RECEIVED_SHUTDOWNr"r#r$r%r&r'r(r)r*r+r,r-r.r/r0r SSL_OP_NO_SSLv2r1SSL_OP_NO_SSLv3r2SSL_OP_NO_TLSv1r3SSL_OP_NO_TLSv1_1r4SSL_OP_NO_TLSv1_2r5SSL_OP_NO_TLSv1_3r6SSL_MODE_RELEASE_BUFFERSr7SSL_OP_SINGLE_DH_USEr8SSL_OP_SINGLE_ECDH_USEr9SSL_OP_EPHEMERAL_RSAr:SSL_OP_MICROSOFT_SESS_ID_BUGr;SSL_OP_NETSCAPE_CHALLENGE_BUGr<'SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUGr="SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUGr>!SSL_OP_MICROSOFT_BIG_SSLV3_BUFFERr?SSL_OP_MSIE_SSLV2_RSA_PADDINGr@SSL_OP_SSLEAY_080_CLIENT_DH_BUGrASSL_OP_TLS_D5_BUGrBSSL_OP_TLS_BLOCK_PADDING_BUGrC"SSL_OP_DONT_INSERT_EMPTY_FRAGMENTSrDSSL_OP_CIPHER_SERVER_PREFERENCErESSL_OP_TLS_ROLLBACK_BUGrFSSL_OP_PKCS1_CHECK_1rGSSL_OP_PKCS1_CHECK_2rHSSL_OP_NETSCAPE_CA_DN_BUGrI&SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUGrJSSL_OP_NO_COMPRESSIONrKSSL_OP_NO_QUERY_MTUrLSSL_OP_COOKIE_EXCHANGErMSSL_OP_NO_TICKETrN SSL_OP_ALLrOSSL_VERIFY_PEERrPSSL_VERIFY_FAIL_IF_NO_PEER_CERTrQSSL_VERIFY_CLIENT_ONCErRSSL_VERIFY_NONErSSSL_SESS_CACHE_OFFrTSSL_SESS_CACHE_CLIENTrUSSL_SESS_CACHE_SERVERrVSSL_SESS_CACHE_BOTHrWSSL_SESS_CACHE_NO_AUTO_CLEARrX!SSL_SESS_CACHE_NO_INTERNAL_LOOKUPrY SSL_SESS_CACHE_NO_INTERNAL_STORErZSSL_SESS_CACHE_NO_INTERNALr[r\r]r^r_r`rarbrcrdrerfrgrhrirjrkrGrHrDrErrlrr rmrnrorprqrrrrrrrrrsrCryptography_HAS_ALPNrrrrtrurvSSL_library_initr}r}r}r~s:   ,  _        (=C;     Y