3 F\[R@sddlZddlZddlmZddlmZmZddlmZm Z ddl m Z ddl m Z ddlmZddlmZmZmZmZdd lmZmZmZmZmZ m!Z"m#Z$m%Z&m'Z(dd l)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;dd?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\gRZ0ye1Z2Wn&e3k rGd]d^d^e4Z2YnXej5Z5ej6Z6ej7Z7ej8Z8ej9Z9ej:Z:ej;Zd_Z?d`Z@daZAdbZBdcZCddZDejEZFejGZHejIZJejKZLejMZNejOZPejQZRejSZTejUZVejWZXejYZZej[Z\ej]Z^ej_Z`ejaZbejcZdejeZfejgZhejiZjejkZlejmZnejoZpejqZrejsZtejuZvejwZxejyZzej{Z|ej}Z~ejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejZejr$ejZejZejZejZe0jdedfdgdhgejZejZejZejZejZejZejZejZejZejZejZejZejZdidjdkdldmgZdngZdoZdpZGdqdSdSeZeeeZe eZGdrdTdTeZGdsdUdUeZGdtdVdVeZGdudWdWeZGdvdXdXeZGdwdxdxe4ZGdydzdzeZGd{d|d|eZGd}d~d~eZGdddeZGdddeZGdddeZddZddYZddZeejdZeejdZeejdZGddZdZe4ZGdd[d[e4ZeeedeσZGdd\d\e4ZeeedeσZejӃdS)N)platform)wrapspartial)countchain)WeakValueDictionary) errorcode) deprecated) binary_type integer_typesint2byte indexbytes) UNSPECIFIEDexception_from_error_queueffilib make_assertnative path_stringtext_to_bytes_and_warnno_zero_allocator) FILETYPE_PEM_PassphraseHelperPKeyX509NameX509 X509StoreOPENSSL_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 OP_NO_SSLv2 OP_NO_SSLv3 OP_NO_TLSv1 OP_NO_TLSv1_1 OP_NO_TLSv1_2MODE_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 SysCallErrorSSLeay_versionSessionContext Connectionc@s eZdZdS)_bufferN)__name__ __module__ __qualname__rsrs/usr/lib/python3.6/SSL.pyrovsro SSL_ST_INIT SSL_ST_BEFORE SSL_ST_OKSSL_ST_RENEGOTIATEz"/etc/ssl/certs/ca-certificates.crtz /etc/pki/tls/certs/ca-bundle.crtz/etc/ssl/ca-bundle.pemz/etc/pki/tls/cacert.pemz1/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pemz/etc/ssl/certss$/opt/pyca/cryptography/openssl/certss'/opt/pyca/cryptography/openssl/cert.pemc@seZdZdZdS)rez4 An error occurred in an `OpenSSL.SSL` API. N)rprqrr__doc__rsrsrsrtresc@s eZdZdS)rfN)rprqrrrsrsrsrtrfsc@s eZdZdS)rgN)rprqrrrsrsrsrtrgsc@s eZdZdS)rhN)rprqrrrsrsrsrtrhsc@s eZdZdS)riN)rprqrrrsrsrsrtrisc@s eZdZdS)rjN)rprqrrrsrsrsrtrj sc@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|_dS)N) _problems)selfrsrsrt__init__sz!_CallbackExceptionHelper.__init__c Cs6|jr2y tWntk r$YnX|jjddS)z Raise an exception from the OpenSSL error queue or that was previously captured whe running a callback. rN)r_raise_current_errorrepop)rrsrsrtraise_if_problems  z)_CallbackExceptionHelper.raise_if_problemN)rprqrrrrrrsrsrsrtr s rc@seZdZdZddZdS) _VerifyHelperz^ Wrap a callback such that it can be used as a certificate verification callback. cs2tjtfdd}tjd|_dS)Nc stj|}tj|tj|}tj|}tj|}tj}tj||}t j |}y|||||} Wn,t k r} zj j | dSd} ~ XnX| rtj|tjdSdSdS)Nrru)_libZX509_STORE_CTX_get_current_cert X509_up_refr_from_raw_x509_ptrZX509_STORE_CTX_get_errorZX509_STORE_CTX_get_error_depthZ"SSL_get_ex_data_X509_STORE_CTX_idxZX509_STORE_CTX_get_ex_datarn_reverse_mapping ExceptionrappendZX509_STORE_CTX_set_errorZ X509_V_OK) okZ store_ctxZx509certZ error_numberZ error_depthindexsslZ connectionresulte)callbackrrsrtwrapper2s$        z'_VerifyHelper.__init__..wrapperzint (*)(int, X509_STORE_CTX *))rrr_ffir)rrrrs)rrrtr/s z_VerifyHelper.__init__N)rprqrrrrrsrsrsrtr)src@seZdZdZddZdS)_NpnAdvertiseHelperzT Wrap a callback such that it can be used as an NPN advertisement callback. cs2tjtfdd}tjd|_dS)Ncsyntj|}|}djtjdd|D}tjdt|tjd|g|_|jdd|d<|jd|d<dSt k r}zj j |dSd}~XnXdS) Ncss|]}tt||fVqdS)N)r len).0prsrsrt asz@_NpnAdvertiseHelper.__init__..wrapper..zunsigned int *zunsigned char[]rrurv) rnrjoinr from_iterablernewr_npn_advertise_callback_argsrrr)routoutlenargconnprotosprotostrr)rrrsrtrXs  z-_NpnAdvertiseHelper.__init__..wrapperz>int (*)(SSL *, const unsigned char **, unsigned int *, void *))rrrrr)rrrrs)rrrtrUs  z_NpnAdvertiseHelper.__init__N)rprqrrrrrsrsrsrtrPsrc@seZdZdZddZdS)_NpnSelectHelperzP Wrap a callback such that it can be used as an NPN selection callback. cs2tjtfdd}tjd|_dS)Nc sytj|}tj||dd}g}x<|r`t|d} |d| d} |j| || dd}q&W||} tjdt| tjd| g|_|jdd|d<|jd|d<dSt k r} zj j| dSd} ~ XnXdS)Nrruzunsigned char *zunsigned char[]rv) rnrrbufferr rrr_npn_select_callback_argsrr) rrrin_inlenrrinstr protolistlengthprotooutstrr)rrrsrtrs$     z*_NpnSelectHelper.__init__..wrapperz^int (*)(SSL *, unsigned char **, unsigned char *, const unsigned char *, unsigned int, void *))rrrrr)rrrrs)rrrtr~s  "z_NpnSelectHelper.__init__N)rprqrrrrrsrsrsrtrysrc@seZdZdZddZdS)_ALPNSelectHelperzQ Wrap a callback such that it can be used as an ALPN selection callback. cs2tjtfdd}tjd|_dS)Nc sytj|}tj||dd}g}x<|r`t|d} |d| d} |j| || dd}q&W||} t| ts~tdtj dt | tj d| g|_ |j dd|d<|j d|d<dSt k r} zj j| dSd} ~ XnXdS)Nrruz'ALPN callback must return a bytestring.zunsigned char *zunsigned char[]rv)rnrrrr r isinstance _binary_type TypeErrorrr_alpn_select_callback_argsrr) rrrrrrrrrZ encoded_lenrrr)rrrsrtrs(      z+_ALPNSelectHelper.__init__..wrapperz^int (*)(SSL *, unsigned char **, unsigned char *, const unsigned char *, unsigned int, void *))rrrrr)rrrrs)rrrtrs  $z_ALPNSelectHelper.__init__N)rprqrrrrrsrsrsrtrsrc@seZdZdZddZdS)_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. cs2tjtfdd}tjd|_dS)Ncsytj|}|tjkr"tj|}nd}||}t|tsBtd|sJdSt|}t j |}|tj ||dd<t j |||dSt k r}zjj|dSd}~XnXdS)Nz'OCSP callback must return a bytestring.rwrrv)rnrrNULL from_handlerrrrrZOPENSSL_mallocrZSSL_set_tlsext_status_ocsp_resprrr)rcdatardata ocsp_dataZocsp_data_lengthZdata_ptrr)rrrsrtrs&        z3_OCSPServerCallbackHelper.__init__..wrapperzint (*)(SSL *, void *))rrrrr)rrrrs)rrrtrs 'z"_OCSPServerCallbackHelper.__init__N)rprqrrrrrsrsrsrtrsrc@seZdZdZddZdS)_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. cs2tjtfdd}tjd|_dS)Nc syxtj|}|tjkr"tj|}nd}tjd}tj||}|dkrJd}ntj|d|dd}|||}t t |St k r}zj j |dSd}~XnXdS)Nzunsigned char **rrru)rnrrrrrrZSSL_get_tlsext_status_ocsp_resprintboolrrr) rrrrZocsp_ptrZocsp_lenrZvalidr)rrrsrtr9s        z3_OCSPClientCallbackHelper.__init__..wrapperzint (*)(SSL *, void *))rrrrr)rrrrs)rrrtr6s z"_OCSPClientCallbackHelper.__init__N)rprqrrrrrsrsrsrtr srcCsdd}t|ts(t|dd}|dk r(|}t|tr6|}t|tsJtdn|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)objfdmethrsrsrt_asFileDescriptor[s      rcCstjtj|S)z Return a string describing the version of OpenSSL in use. :param type: One of the :const:`SSLEAY_` constants defined in this module. )rstringrrk)typersrsrtrknscsfdd}|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 tdS)N)NotImplementedError)argskwargs)errorrsrtexplodesz<_make_requires.._requires_decorator..explode)r)funcr)rflagrsrt_requires_decoratorsz+_make_requires.._requires_decoratorrs)rrrrs)rrrt_make_requiresws  rzNPN not availablezALPN not availablezSNI not availablec@seZdZdZdS)rlz A class representing an SSL session. A session defines certain connection parameters which may be re-used to speed up the setup of subsequent connections. .. versionadded:: 0.14 N)rprqrrrrsrsrsrtrlsc @seZdZdZededededede diZ e dd e j DZ d d Z ded dZddZdfddZddZddZddZddZefddZddZdd Zd!d"Zefd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.Z d/d0Z!d1d2Z"d3d4Z#d5d6Z$d7d8Z%d9d:Z&d;d<Z'd=d>Z(d?d@Z)dAdBZ*dCdDZ+dEdFZ,dGdHZ-dIdJZ.dKdLZ/dMdNZ0dOdPZ1dQdRZ2e3dSdTZ4dUdVZ5e6dWdXZ7e6dYdZZ8e9d[d\Z:e9d]d^Z;d_d`Zd S)irmz :class:`OpenSSL.SSL.Context` instances define the parameters for setting up new SSL connections. :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or TLSv1_METHOD. Z SSLv2_methodZ SSLv3_methodZ SSLv23_methodZ TLSv1_methodZTLSv1_1_methodZTLSv1_2_methodccs0|](\}}tt|ddk r|tt|fVqdS)N)rr)rZ identifiernamersrsrtrszContext.cCs&t|tstdy|j|}Wntk r<tdYnX|}t|tjkt j |}t|tjktj |t j }yt j |d}t|dkWntk rYnX||_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_ |j!t j"dS)Nzmethod must be an integerzNo such protocolru)#rr r_methodsKeyErrorr_openssl_assertrrrZ SSL_CTX_newgcZ SSL_CTX_freeZSSL_CTX_set_ecdh_autoAttributeError_context_passphrase_helper_passphrase_callback_passphrase_userdata_verify_helper_verify_callback_info_callback_tlsext_servername_callback _app_data_npn_advertise_helper_npn_advertise_callback_npn_select_helper_npn_select_callback_alpn_select_helper_alpn_select_callback _ocsp_helper_ocsp_callback _ocsp_dataset_modeZSSL_MODE_ENABLE_PARTIAL_WRITE)rmethodZ method_funcZ method_objcontextresrsrsrtrsF   zContext.__init__NcCsN|dkrtj}nt|}|dkr(tj}nt|}tj|j||}|sJtdS)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_stringrZSSL_CTX_load_verify_locationsrr)rcafilecapathZ load_resultrsrsrtload_verify_locationss zContext.load_verify_locationscs&tfdd}tt|dddS)Ncs||jS)N)r)sizeZverifyuserdata)rrrsrtr sz'Context._wrap_callback..wrapperT)Z more_argstruncate)rrr)rrrrs)rrrt_wrap_callback szContext._wrap_callbackcCs@t|std|j||_|jj|_tj|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 zcallback must be callableN) callablerrrrrrZSSL_CTX_set_default_passwd_cbrr)rrrrsrsrt set_passwd_cbs   zContext.set_passwd_cbcCstj|j}t|dktjtjjd}tjtjjd}|j ||stjtj }tjtj }|t kr|t kr|jttdS)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 ruasciiN)rZ SSL_CTX_set_default_verify_pathsrrrrZX509_get_default_cert_dir_envdecodeZX509_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_filersrsrtset_default_verify_paths-s      z Context.set_default_verify_pathscCs tjj|dk ptjj|dk S)zp Check to see if the default cert dir/file environment vars are present. :return: bool N)osenvironget)rrrrsrsrtr^szContext._check_env_vars_setcCsRx$|D]}tjj|r|j|PqWx&|D]}tjj|r,|jd|Pq,WdS)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)rpathisfilerisdir)rZ file_pathZdir_pathrrrsrsrtris      z&Context._fallback_default_verify_pathscCs$t|}tj|j|}|s tdS)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)rrZ"SSL_CTX_use_certificate_chain_filerr)rcertfilerrsrsrtuse_certificate_chain_file}s  z"Context.use_certificate_chain_filecCs8t|}t|tstdtj|j||}|s4tdS)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 zfiletype must be an integerN)rrr rrZSSL_CTX_use_certificate_filerr)rr filetype use_resultrsrsrtuse_certificate_files   zContext.use_certificate_filecCs0t|tstdtj|j|j}|s,tdS)zs Load a certificate from a X509 object :param cert: The X509 object :return: None zcert must be an X509 instanceN)rrrrZSSL_CTX_use_certificater_x509r)rrr rsrsrtuse_certificates  zContext.use_certificatecCsDt|tstdtj|j}tj|j|}|s@tj|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) rrrrX509_duprZSSL_CTX_add_extra_chain_certrZ X509_freer)rZcertobjcopy add_resultrsrsrtadd_extra_chain_certs   zContext.add_extra_chain_certcCs |jdk r|jjttdS)N)rrrer)rrsrsrt_raise_passphrase_exceptions  z#Context._raise_passphrase_exceptioncCsHt|}|tkrt}nt|ts(tdtj|j||}|sD|j 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 zfiletype must be an integerN) r _UNSPECIFIEDrrr rrZSSL_CTX_use_PrivateKey_filerr)rZkeyfiler r rsrsrtuse_privatekey_files   zContext.use_privatekey_filecCs2t|tstdtj|j|j}|s.|jdS)zs Load a private key from a PKey object :param pkey: The PKey object :return: None zpkey must be a PKey instanceN)rrrrZSSL_CTX_use_PrivateKeyrZ_pkeyr)rZpkeyr rsrsrtuse_privatekeys  zContext.use_privatekeycCstj|jstdS)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)rZSSL_CTX_check_private_keyrr)rrsrsrtcheck_privatekeys zContext.check_privatekeycCs0tjtd|}t|tjktj|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 rN)rZSSL_load_client_CA_file_text_to_bytes_and_warnrrrSSL_CTX_set_client_CA_listr)rrZca_listrsrsrtload_client_cas  zContext.load_client_cacCs*td|}ttj|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 bufruN)rrrZSSL_CTX_set_session_id_contextrr)rrrsrsrtset_session_ids zContext.set_session_idcCs t|tstdtj|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 zmode must be an integer)rr rrZSSL_CTX_set_session_cache_moder)rmodersrsrtset_session_cache_modes zContext.set_session_cache_modecCs tj|jS)z Get the current session cache mode. :returns: The currently used cache mode. .. versionadded:: 0.14 )rZSSL_CTX_get_session_cache_moder)rrsrsrtget_session_cache_mode,szContext.get_session_cache_modecCsLt|tstdt|s"tdt||_|jj|_tj |j ||jdS)a et 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 Python 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. :return: None See SSL_CTX_set_verify(3SSL) for further details. zmode must be an integerzcallback must be callableN) rr rrrrrrrZSSL_CTX_set_verifyr)rrrrsrsrt set_verify6s   zContext.set_verifycCs$t|tstdtj|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 rrZSSL_CTX_set_verify_depthr)rdepthrsrsrtset_verify_depthSs zContext.set_verify_depthcCs tj|jS)z Retrieve the Context object's verify mode, as set by :meth:`set_verify`. :return: The verify mode )rZSSL_CTX_get_verify_moder)rrsrsrtget_verify_mode`szContext.get_verify_modecCs tj|jS)z Retrieve the Context object's verify depth, as set by :meth:`set_verify_depth`. :return: The verify depth )rZSSL_CTX_get_verify_depthr)rrsrsrtget_verify_depthiszContext.get_verify_depthcCsht|}tj|d}|tjkr$ttj|tj}tj|tjtjtj}tj|tj }tj |j |dS)z Load parameters for Ephemeral Diffie-Hellman :param dhfile: The file to load EDH parameters from (``bytes`` or ``unicode``). :return: None rN) rrZ BIO_new_filerrrrZBIO_freeZPEM_read_bio_DHparamsZDH_freeZSSL_CTX_set_tmp_dhr)rZdhfilebioZdhrsrsrt load_tmp_dhrs   zContext.load_tmp_dhcCstj|j|jdS)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)rZSSL_CTX_set_tmp_ecdhrZ _to_EC_KEY)rZcurversrsrt set_tmp_ecdhs zContext.set_tmp_ecdhcCsVtd|}t|tstdttj|j|dkt|d}t|j dddgkdS)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.ruNZTLS_AES_256_GCM_SHA384ZTLS_CHACHA20_POLY1305_SHA256ZTLS_AES_128_GCM_SHA256) rrbytesrrrZSSL_CTX_set_cipher_listrrnget_cipher_list)rr+Ztmpconnrsrsrtset_cipher_lists   zContext.set_cipher_listc Cstj}t|tjkyjxd|D]\}t|ts@tdt|j ftj |j }t|tjktj ||}|stj |tqWWn tk rtj|YnXtj|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)rZsk_X509_NAME_new_nullrrrrrrrrp X509_NAME_dup_nameZsk_X509_NAME_pushX509_NAME_freerrZsk_X509_NAME_freerr)rZcertificate_authoritiesZ name_stackZca_namerZ push_resultrsrsrtset_client_ca_lists$       zContext.set_client_ca_listcCs2t|tstdtj|j|j}t|dkdS)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 instanceruN)rrrrZSSL_CTX_add_client_CArrr)rZcertificate_authorityrrsrsrt add_client_cas  zContext.add_client_cacCs t|tstdtj|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)rr rrZSSL_CTX_set_timeoutr)rZtimeoutrsrsrt set_timeouts zContext.set_timeoutcCs tj|jS)z Retrieve session timeout, as set by :meth:`set_timeout`. The default is 300 seconds. :return: The session timeout )rZSSL_CTX_get_timeoutr)rrsrsrt get_timeoutszContext.get_timeoutcs6tfdd}tjd||_tj|j|jdS)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 cstj|||dS)N)rnr)rwhereZ return_code)rrsrtrsz*Context.set_info_callback..wrapperzvoid (*)(const SSL *, int, int)N)rrrrrZSSL_CTX_set_info_callbackr)rrrrs)rrtset_info_callbacks  zContext.set_info_callbackcCs|jS)zw Get the application data (supplied via :meth:`set_app_data()`) :return: The application data )r)rrsrsrt get_app_dataszContext.get_app_datacCs ||_dS)z Set the application data (will be returned from get_app_data()) :param data: Any Python object :return: None N)r)rrrsrsrt set_app_dataszContext.set_app_datacCs.tj|j}|tjkrdStjt}||_|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)rZSSL_CTX_get_cert_storerrrr__new__Z_store)rZstoreZpystorersrsrtget_cert_store&s    zContext.get_cert_storecCs t|tstdtj|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)rr rrZSSL_CTX_set_optionsr)rZoptionsrsrsrt set_options7s zContext.set_optionscCs t|tstdtj|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. zmode must be an integer)rr rrZSSL_CTX_set_moder)rrrsrsrtrDs zContext.set_modecs6tfdd}tjd||_tj|j|jdS)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)Nr)rnr)rZalertr)rrsrtr\sz7Context.set_tlsext_servername_callback..wrapperzint (*)(SSL *, int *, void *)N)rrrrrZ&SSL_CTX_set_tlsext_servername_callbackr)rrrrs)rrtset_tlsext_servername_callbackQs  z&Context.set_tlsext_servername_callbackcCs,t|tstdttj|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)rr,rrrZSSL_CTX_set_tlsext_use_srtpr)rZprofilesrsrsrtset_tlsext_use_srtpfs zContext.set_tlsext_use_srtpcCs,t||_|jj|_tj|j|jtjdS)a Specify a callback function that will be called when offering `Next Protocol Negotiation `_ as a server. :param callback: The callback function. It will be invoked with one argument, the :class:`Connection` instance. It should return a list of bytestrings representing the advertised protocols, like ``[b'http/1.1', b'spdy/2']``. .. versionadded:: 0.15 N) rrrrrZ%SSL_CTX_set_next_protos_advertised_cbrrr)rrrsrsrtset_npn_advertise_callbackus  z"Context.set_npn_advertise_callbackcCs,t||_|jj|_tj|j|jtjdS)a Specify a callback function that will be called when a server offers Next Protocol Negotiation options. :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 should return one of those bytestrings, the chosen protocol. .. versionadded:: 0.15 N) rrrrrZ SSL_CTX_set_next_proto_select_cbrrr)rrrsrsrtset_npn_select_callbacks  zContext.set_npn_select_callbackcCs>djtjdd|D}tjd|}tj|j|t|dS)a Specify the protocols that the client is prepared to speak after the TLS connection has been negotiated using Application Layer Protocol Negotiation. :param protos: A list of the protocols to be offered to the server. This list should be a Python list of bytestrings representing the protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``. rcss|]}tt||fVqdS)N)r r)rrrsrsrtrsz*Context.set_alpn_protos..zunsigned char[]N) rrrrrrZSSL_CTX_set_alpn_protosrr)rrr input_strrsrsrtset_alpn_protoss  zContext.set_alpn_protoscCs,t||_|jj|_tj|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 should return one of those bytestrings, the chosen protocol. N) rrrrrZSSL_CTX_set_alpn_select_cbrrr)rrrsrsrtset_alpn_select_callbacks  z Context.set_alpn_select_callbackcCsh||_|j|_|dkr tj|_n tj||_tj|j |j}t |dktj |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. Nru) rrrrrrZ new_handlerZSSL_CTX_set_tlsext_status_cbrrZSSL_CTX_set_tlsext_status_arg)rhelperrrcrsrsrt_set_ocsp_callbacks    zContext._set_ocsp_callbackcCst|}|j||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)rrF)rrrrDrsrsrtset_ocsp_server_callbacksz Context.set_ocsp_server_callbackcCst|}|j||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)rrF)rrrrDrsrsrtset_ocsp_client_callbacksz Context.set_ocsp_client_callback)N)N)N)N)?rprqrrrr%r&r'r(r)r*rdictitemsrrrrrrrr rrrrrrrrrrrr r!r"r$r%r&r)r*r.r2r3r4r5r7r8r9r;r<r _requires_snir=r> _requires_npnr?r@_requires_alpnrBrCrFrGrHrsrsrsrtrmsn.  1          %         z4ContextType has been deprecated, use Context insteadc@seZdZdZeZdxddZddZddZd d Z d d Z e d dZ e ddZ ddZdyddZeZdzddZd{ddZeZd|ddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Zd2d3Z d4d5Z!d6d7Z"d8d9Z#d:d;Z$dd?Z&d@dAZ'dBdCZ(dDdEZ)dFdGZ*dHdIZ+d}dJdKZ,dLdMZ-dNdOZ.dPdQZ/dRdSZ0dTdUZ1dVdWZ2dXdYZ3dZd[Z4d\d]Z5d^d_Z6d`daZ7dbdcZ8dddeZ9dfdgZ:dhdiZ;djdkZe?dpdqZ@eAdrdsZBeAdtduZCdvdwZDdS)~rnz NcCst|tstdtj|j}tj|tj|_ tj |j tj ||_d|_ d|_ d|_d|_||j|j <|dkrd|_tjtj|_t|jtjktjtj|_t|jtjktj|j |j|jn2d|_d|_||_tj|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 z"context must be a Context instanceNru)rrmrrZSSL_newrrrZSSL_free_sslZ SSL_set_modeZSSL_MODE_AUTO_RETRYrrrrr_socketZBIO_newZ BIO_s_mem _into_sslrr _from_sslZ SSL_set_bioZ SSL_set_fdr)rrsocketrrrsrsrtrs0   zConnection.__init__cCs0|jdkr td|jj|fn 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')rOr __class__rpr)rrrsrsrt __getattr__<s zConnection.__getattr__cCsT|jjdk r|jjj|jjdk r0|jjj|jjdk rH|jjj|jjdk r`|jjj|jjdk rx|jjjtj||}|tj krt n|tj krt n|tj krtn|tjkrtn|tjkr 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` zutf-8)rrrZSSL_get_versionrNr)rrrsrsrtget_protocol_version_namef s z$Connection.get_protocol_version_namecCstj|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` )rZ SSL_versionrN)rrrsrsrtget_protocol_versionr s zConnection.get_protocol_versioncCs@tjd}tjd}tj|j||tj|d|dddS)z Get the protocol that was negotiated by NPN. :returns: A bytestring of the protocol name. If no protocol has been negotiated yet, returns an empty string. .. versionadded:: 0.15 zunsigned char **zunsigned int *rN)rrrZSSL_get0_next_proto_negotiatedrNr)rrdata_lenrsrsrtget_next_proto_negotiated} s  z$Connection.get_next_proto_negotiatedcCs>djtjdd|D}tjd|}tj|j|t|dS)ah Specify the client's ALPN protocol list. These protocols are offered to the server during protocol negotiation. :param protos: A list of the protocols to be offered to the server. This list should be a Python list of bytestrings representing the protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``. rcss|]}tt||fVqdS)N)r r)rrrsrsrtr sz-Connection.set_alpn_protos..zunsigned char[]N) rrrrrrZSSL_set_alpn_protosrNr)rrrrArsrsrtrB s  zConnection.set_alpn_protoscCsHtjd}tjd}tj|j|||s,dStj|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. zunsigned char **zunsigned int *rrN)rrrZSSL_get0_alpn_selectedrNr)rrrrsrsrtget_alpn_proto_negotiated s   z$Connection.get_alpn_proto_negotiatedcCs tj|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`. ruN)rZSSL_set_tlsext_status_typerNZTLSEXT_STATUSTYPE_ocspr)rrErsrsrt request_ocsp s zConnection.request_ocsp)N)r)r)N)NN)N)ErprqrrrrrrrTrVrWrXrKrYr[r\rbwriterdrjreadrlrnrorprrrsrqrtrvrxrzr|r}r-rrr8r9rrrrrrrrrrrrrr{ryrrrrrrrrrrrLrrMrBrrrsrsrsrtrns| 6 )    $  %                   "      z:ConnectionType has been deprecated, use Connection instead)rrRsysr functoolsrr itertoolsrrweakrefrrUrZcryptography.utilsr Zsixr rr r r Z OpenSSL._utilrrrZ_exception_from_error_queuerrrrrZ _make_assertrr~rrrrrreZOpenSSL.cryptorrrrrr__all__rro NameErrorobjectrrrr r!r"ZSSL_SENT_SHUTDOWNr#ZSSL_RECEIVED_SHUTDOWNr$r%r&r'r(r)r*ZSSL_OP_NO_SSLv2r+ZSSL_OP_NO_SSLv3r,ZSSL_OP_NO_TLSv1r-ZSSL_OP_NO_TLSv1_1r.ZSSL_OP_NO_TLSv1_2r/ZSSL_MODE_RELEASE_BUFFERSr0ZSSL_OP_SINGLE_DH_USEr1ZSSL_OP_SINGLE_ECDH_USEr2ZSSL_OP_EPHEMERAL_RSAr3ZSSL_OP_MICROSOFT_SESS_ID_BUGr4ZSSL_OP_NETSCAPE_CHALLENGE_BUGr5Z'SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUGr6Z"SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUGr7Z!SSL_OP_MICROSOFT_BIG_SSLV3_BUFFERr8ZSSL_OP_MSIE_SSLV2_RSA_PADDINGr9ZSSL_OP_SSLEAY_080_CLIENT_DH_BUGr:ZSSL_OP_TLS_D5_BUGr;ZSSL_OP_TLS_BLOCK_PADDING_BUGr<Z"SSL_OP_DONT_INSERT_EMPTY_FRAGMENTSr=ZSSL_OP_CIPHER_SERVER_PREFERENCEr>ZSSL_OP_TLS_ROLLBACK_BUGr?ZSSL_OP_PKCS1_CHECK_1r@ZSSL_OP_PKCS1_CHECK_2rAZSSL_OP_NETSCAPE_CA_DN_BUGrBZ&SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUGrCZSSL_OP_NO_COMPRESSIONrDZSSL_OP_NO_QUERY_MTUrEZSSL_OP_COOKIE_EXCHANGErFZSSL_OP_NO_TICKETrGZ SSL_OP_ALLrHZSSL_VERIFY_PEERrIZSSL_VERIFY_FAIL_IF_NO_PEER_CERTrJZSSL_VERIFY_CLIENT_ONCErKZSSL_VERIFY_NONErLZSSL_SESS_CACHE_OFFrMZSSL_SESS_CACHE_CLIENTrNZSSL_SESS_CACHE_SERVERrOZSSL_SESS_CACHE_BOTHrPZSSL_SESS_CACHE_NO_AUTO_CLEARrQZ!SSL_SESS_CACHE_NO_INTERNAL_LOOKUPrRZ SSL_SESS_CACHE_NO_INTERNAL_STORErSZSSL_SESS_CACHE_NO_INTERNALrTrUrVrWZCryptography_HAS_SSL_STr{r|r}r~extendrXrYrZr[r\r]r^r_r`rarbrcrdrrrrrrerrrfrgrhrirjrrrrrrrrrkrZCryptography_HAS_NEXTPROTONEGrLZCryptography_HAS_ALPNrMZ Cryptography_HAS_TLSEXT_HOSTNAMErKrlrmrpDeprecationWarningZ ContextTypernZConnectionTypeZSSL_library_initrsrsrsrts    ,  ')13C;     ZI