B L��jo�� @s�dZddlZddlZddlmZddlmZmZ m Z ddl Z ddl m Z mZmZddl mZmZmZddl mZmZmZmZmZmZmZddl mZmZdd l mZmZm Z m!Z!ydd l m"Z"Wne#k r�YnXdd l m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-dd l m.Z.m/Z/e j0d e1dd�e d�e j0de1dd�e d�e j0de1dd�e d�e j0de1dd�e d�e j0de1dd�e d�e j0de1dd�e d�e2j3Z4e2_4dd�e2j5�6�D�Z7e8e2dd�Z9Gdd�de �Z:ej;d k�r�dd!l m<Z<m=Z=dd"l>m>Z>m?Z?m@Z@mAZAdd#l>mBZBmCZCddl>ZDddlEZEddlFZFddlGZGeHZId$gZJeKe d%�ZLe.ZMeZNd&d'�ZOd(d)�ZPd*d+�ZQd,d-�ZRdWd.d/�ZSed0d1�ZTd2d3�ZUGd4d5�d5ed5d6��ZVGd7d8�d8eVe�ZWGd9d:�d:e�ZXeWjYfdddd;�d<d=�ZZe3fe[d>eWjYdddddd?�d@dA�Z\eZZ]e\Z^GdBdC�dC�Z_dDdE�Z`GdFdG�dGe>�ZaeaeX_be_eX_cddd>e[e3ddHdHdf dIdJ�ZddKdL�ZedMZfdNZgdOdP�ZhdQdR�Zie3dfdSdT�ZjdUdV�ZkdS)Xa� This module provides some more Pythonic support for SSL. Object types: SSLSocket -- subtype of socket.socket which does SSL over the socket Exceptions: SSLError -- exception raised for I/O errors Functions: cert_time_to_seconds -- convert time string used for certificate notBefore and notAfter functions to integer seconds past the Epoch (the time values returned from time.time()) fetch_server_certificate (HOST, PORT) -- fetch the certificate provided by the server running on HOST at port PORT. No validation of the certificate is performed. Integer constants: SSL_ERROR_ZERO_RETURN SSL_ERROR_WANT_READ SSL_ERROR_WANT_WRITE SSL_ERROR_WANT_X509_LOOKUP SSL_ERROR_SYSCALL SSL_ERROR_SSL SSL_ERROR_WANT_CONNECT SSL_ERROR_EOF SSL_ERROR_INVALID_ERROR_CODE The following group define certificate requirements that one side is allowing/requiring from the other side: CERT_NONE - no certificates from the other side are required (or will be looked at if provided) CERT_OPTIONAL - certificates are not required, but if provided will be validated, and if validation fails, the connection will also fail CERT_REQUIRED - certificates are required, and will be validated, and if validation fails, the connection will also fail The following constants identify various SSL protocol variants: PROTOCOL_SSLv2 PROTOCOL_SSLv3 PROTOCOL_SSLv23 PROTOCOL_TLS PROTOCOL_TLS_CLIENT PROTOCOL_TLS_SERVER PROTOCOL_TLSv1 PROTOCOL_TLSv1_1 PROTOCOL_TLSv1_2 The following constants identify various SSL alert message descriptions as per http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 ALERT_DESCRIPTION_CLOSE_NOTIFY ALERT_DESCRIPTION_UNEXPECTED_MESSAGE ALERT_DESCRIPTION_BAD_RECORD_MAC ALERT_DESCRIPTION_RECORD_OVERFLOW ALERT_DESCRIPTION_DECOMPRESSION_FAILURE ALERT_DESCRIPTION_HANDSHAKE_FAILURE ALERT_DESCRIPTION_BAD_CERTIFICATE ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE ALERT_DESCRIPTION_CERTIFICATE_REVOKED ALERT_DESCRIPTION_CERTIFICATE_EXPIRED ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN ALERT_DESCRIPTION_ILLEGAL_PARAMETER ALERT_DESCRIPTION_UNKNOWN_CA ALERT_DESCRIPTION_ACCESS_DENIED ALERT_DESCRIPTION_DECODE_ERROR ALERT_DESCRIPTION_DECRYPT_ERROR ALERT_DESCRIPTION_PROTOCOL_VERSION ALERT_DESCRIPTION_INSUFFICIENT_SECURITY ALERT_DESCRIPTION_INTERNAL_ERROR ALERT_DESCRIPTION_USER_CANCELLED ALERT_DESCRIPTION_NO_RENEGOTIATION ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE ALERT_DESCRIPTION_UNRECOGNIZED_NAME ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY �N)� namedtuple)�Enum�IntEnum�IntFlag)�OPENSSL_VERSION_NUMBER�OPENSSL_VERSION_INFO�OPENSSL_VERSION)� _SSLContext� MemoryBIO� SSLSession)�SSLError�SSLZeroReturnError�SSLWantReadError�SSLWantWriteError�SSLSyscallError� SSLEOFError�SSLCertVerificationError)�txt2obj�nid2obj)� RAND_status�RAND_add� RAND_bytes�RAND_pseudo_bytes)�RAND_egd) �HAS_SNI�HAS_ECDH�HAS_NPN�HAS_ALPN� HAS_SSLv2� HAS_SSLv3� HAS_TLSv1� HAS_TLSv1_1� HAS_TLSv1_2� HAS_TLSv1_3)�_DEFAULT_CIPHERS�_OPENSSL_API_VERSION� _SSLMethodcCs|�d�o|dkS)NZ PROTOCOL_�PROTOCOL_SSLv23)� startswith)�name�r*�(/opt/alt/python37/lib64/python3.7/ssl.py�<lambda>|�r,)�source�OptionscCs |�d�S)NZOP_)r()r)r*r*r+r,�r-ZAlertDescriptioncCs |�d�S)NZALERT_DESCRIPTION_)r()r)r*r*r+r,�r-ZSSLErrorNumbercCs |�d�S)NZ SSL_ERROR_)r()r)r*r*r+r,�r-� VerifyFlagscCs |�d�S)NZVERIFY_)r()r)r*r*r+r,�r-� VerifyModecCs |�d�S)NZCERT_)r()r)r*r*r+r,�r-cCsi|]\}}||�qSr*r*)�.0r)�valuer*r*r+� <dictcomp>�sr4ZPROTOCOL_SSLv2c@s6eZdZejZejZejZ ej Z ej Z ejZejZdS)� TLSVersionN)�__name__� __module__� __qualname__�_sslZPROTO_MINIMUM_SUPPORTEDZMINIMUM_SUPPORTEDZ PROTO_SSLv3�SSLv3Z PROTO_TLSv1ZTLSv1Z PROTO_TLSv1_1ZTLSv1_1Z PROTO_TLSv1_2ZTLSv1_2Z PROTO_TLSv1_3ZTLSv1_3ZPROTO_MAXIMUM_SUPPORTEDZMAXIMUM_SUPPORTEDr*r*r*r+r5�sr5�win32)�enum_certificates� enum_crls)�socket�AF_INET� SOCK_STREAM�create_connection)� SOL_SOCKET�SO_TYPEz tls-unique�HOSTFLAG_NEVER_CHECK_SUBJECTcCs�|sdS|�d�}|s&|��|��kS|dkr<td�|���|�d�\}}}d|krbtd�|���|sttd�|���|dkr�td�|���|�d�\}}}|r�|s�dS|��|��kS) a�Matching according to RFC 6125, section 6.4.3 - Hostnames are compared lower case. - For IDNA, both dn and hostname must be encoded as IDN A-label (ACE). - Partial wildcards like 'www*.example.org', multiple wildcards, sole wildcard or wildcards in labels other then the left-most label are not supported and a CertificateError is raised. - A wildcard must match at least one character. F�*�z1too many wildcards in certificate DNS name: {!r}.�.z9wildcard can only be present in the leftmost label: {!r}.z>sole wildcard without additional labels are not support: {!r}.z<partial wildcards in leftmost label are not supported: {!r}.)�count�lower�CertificateError�format� partition)Zdn�hostnameZ wildcardsZ dn_leftmost�sepZ dn_remainderZhostname_leftmostZhostname_remainderr*r*r+�_dnsname_match�s2   rOcCs�yt�|�}Wntk r"Yn"Xt�|�|kr6|Std�|���yt�tj|�Stk rttd�|���Yntk r�YnXtd�|���dS)z�Try to convert an IP address to packed binary form Supports IPv4 addresses on all platforms and IPv6 on platforms with IPv6 support. z'{!r} is not a quad-dotted IPv4 address.z+{!r} is neither an IPv4 nor an IP6 address.z{!r} is not an IPv4 address.N) �_socketZ inet_aton�OSErrorZ inet_ntoa� ValueErrorrKZ inet_ptonZAF_INET6�AttributeError)Zipname�addrr*r*r+� _inet_paton�s   rUcCst|���}||kS)z�Exact matching of IP addresses. RFC 6125 explicitly doesn't define an algorithm for this (section 1.7.2 - "Out of Scope"). )rU�rstrip)Zcert_ipaddress�host_ipZipr*r*r+�_ipaddress_matchs rXcCsN|s td��y t|�}Wntk r0d}YnXg}|�dd�}xb|D]Z\}}|dkrz|dkrnt||�rndS|�|�qH|dkrH|dk r�t||�r�dS|�|�qHW|s�xF|�dd�D]6}x0|D](\}}|dkr�t||�r�dS|�|�q�Wq�Wt|�d k�rtd |d �t t |��f��n,t|�d k�rBtd ||d f��ntd��dS)a�Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed. The function matches IP addresses rather than dNSNames if hostname is a valid ipaddress string. IPv4 addresses are supported on all platforms. IPv6 addresses are supported on platforms with IPv6 support (AF_INET6 and inet_pton). CertificateError is raised on failure. On success, the function returns nothing. ztempty or no certificate, match_hostname needs a SSL socket or SSL context with either CERT_OPTIONAL or CERT_REQUIREDNZsubjectAltNamer*ZDNSz IP AddressZsubjectZ commonNamerFz&hostname %r doesn't match either of %sz, zhostname %r doesn't match %rrz=no appropriate commonName or subjectAltName fields were found) rRrU�getrO�appendrX�lenrJ�join�map�repr)�certrMrWZdnsnamesZsan�keyr3�subr*r*r+�match_hostnames>      rbcCs6|r |rtd��|dk r td��|jr2|s2td��dS)zHRaises a ValueError if SSLObject._create() parameters aren't valid. z4server_hostname can only be specified in client modeNz,session can only be specified in client modez'check_hostname requires server_hostname)rR�check_hostname)� server_side�context�server_hostname�sessionr*r*r+�_check_sslobject_paramsXs rh�DefaultVerifyPathszQcafile capath openssl_cafile_env openssl_cafile openssl_capath_env openssl_capathcCsdt��}tj�|d|d�}tj�|d|d�}ttj�|�rF|ndtj�|�rX|ndf|��S)z/Return paths to default cafile and capath. rrF��N) r9�get_default_verify_paths�os�environrYri�path�isfile�isdir)�parts�cafile�capathr*r*r+rljs rlcsDeZdZdZdZ�fdd�Ze�fdd��Ze�fdd��Z�Z S) � _ASN1Objectz#ASN.1 object identifier lookup r*cst�j|ft|dd���S)NF)r))�super�__new__�_txt2obj)�cls�oid)� __class__r*r+rw}sz_ASN1Object.__new__cst�j|ft|���S)z3Create _ASN1Object from OpenSSL numeric ID )rvrw�_nid2obj)ryZnid)r{r*r+�fromnid�sz_ASN1Object.fromnidcst�j|ft|dd���S)z=Create _ASN1Object from short name, long name or OID T)r))rvrwrx)ryr))r{r*r+�fromname�sz_ASN1Object.fromname) r6r7r8�__doc__� __slots__rw� classmethodr}r~� __classcell__r*r*)r{r+ruxs  ruznid shortname longname oidc@seZdZdZdZdZdS)�PurposezDSSLContext purpose flags with X509v3 Extended Key Usage objects z1.3.6.1.5.5.7.3.1z1.3.6.1.5.5.7.3.2N)r6r7r8r� SERVER_AUTHZ CLIENT_AUTHr*r*r*r+r��sr�csneZdZdZdZdZdZefdd�Zdd�Z d/d d �Z d0d d �Z dd�Z dd�Z dd�Zdd�Zejfdd�Zeed�r�e�fdd��Zej�fdd��Ze�fdd��Zej�fdd��Ze�fdd ��Zej�fd!d ��Zeed"��red#d$��Zejd%d$��Zn ed&d$��Ze�fd'd(��Ze�fd)d*��Zej�fd+d*��Ze�fd,d-��Zej�fd.d-��Z�ZS)1� SSLContextz|An SSLContext holds various SSL-related configuration options and data, such as certificates and possibly a private key.)ZCAZROOTNcOst�||�}|S)N)r rw)ry�protocol�args�kwargs�selfr*r*r+rw�s zSSLContext.__new__cCs4|dkr dSt|t�r&|�d��d�S|�d�SdS)NZidna�ascii)� isinstance�str�encode�decode)r�rMr*r*r+�_encode_hostname�s  zSSLContext._encode_hostnameFTc Cs|jj|||||||d�S)N)�sockrd�do_handshake_on_connect�suppress_ragged_eofsrfrerg)�sslsocket_class�_create)r�r�rdr�r�rfrgr*r*r+� wrap_socket�szSSLContext.wrap_socketcCs|jj||||�|�||d�S)N)rdrfrgre)�sslobject_classr�r�)r��incoming�outgoingrdrfrgr*r*r+�wrap_bio�szSSLContext.wrap_biocCsdt�}xN|D]F}t|d�}t|�dks2t|�dkr:td��|�t|��|�|�q W|�|�dS)Nr�r�z(NPN protocols must be 1 to 255 in length)� bytearray�bytesr[r rZ�extendZ_set_npn_protocols)r�Z npn_protocols�protosr��br*r*r+�set_npn_protocols�s  zSSLContext.set_npn_protocolscs8�dkrd�_n$t��s td����fdd�}|�_dS)Nznot a callable objectcs��|�}�|||�S)N)r�)�sslobjZ servernameZsslctx)r��server_name_callbackr*r+�shim_cb�s z3SSLContext.set_servername_callback.<locals>.shim_cb)Z sni_callback�callable� TypeError)r�r�r�r*)r�r�r+�set_servername_callback�s z"SSLContext.set_servername_callbackcCsdt�}xN|D]F}t|d�}t|�dks2t|�dkr:td��|�t|��|�|�q W|�|�dS)Nr�rr�z)ALPN protocols must be 1 to 255 in length)r�r�r[r rZr�Z_set_alpn_protocols)r�Zalpn_protocolsr�r�r�r*r*r+�set_alpn_protocols�s  zSSLContext.set_alpn_protocolscCszt�}y@x:t|�D].\}}}|dkr|dks6|j|kr|�|�qWWntk rdt�d�YnX|rv|j|d�|S)NZx509_asnTz-unable to enumerate Windows certificate store)�cadata)r�r<rzr��PermissionError�warnings�warn�load_verify_locations)r�� storename�purposeZcertsr_�encodingZtrustr*r*r+�_load_windows_store_certs�s z$SSLContext._load_windows_store_certscCsDt|t�st|��tjdkr8x|jD]}|�||�q$W|��dS)Nr;)r�rur��sys�platform�_windows_cert_storesr�Zset_default_verify_paths)r�r�r�r*r*r+�load_default_certs�s    zSSLContext.load_default_certs�minimum_versioncs tt�j�S)N)r5rvr�)r�)r{r*r+r��szSSLContext.minimum_versioncs4|tjkr|jtjM_ttt�j�||�dS)N) r5r:�optionsr/Z OP_NO_SSLv3rvr�r��__set__)r�r3)r{r*r+r�s cs tt�j�S)N)r5rv�maximum_version)r�)r{r*r+r�szSSLContext.maximum_versioncsttt�j�||�dS)N)rvr�r�r�)r�r3)r{r*r+r� scs tt�j�S)N)r/rvr�)r�)r{r*r+r�szSSLContext.optionscsttt�j�||�dS)N)rvr�r�r�)r�r3)r{r*r+r�srDcCs|jtj@}|tjkS)N)� _host_flagsr9rD)r�Zncsr*r*r+�hostname_checks_common_names z&SSLContext.hostname_checks_common_namecCs,|r|jtjM_n|jtjO_dS)N)r�r9rD)r�r3r*r*r+r�scCsdS)NTr*)r�r*r*r+r�#scs tt�j�S)N)r&rvr�)r�)r{r*r+r�'szSSLContext.protocolcs tt�j�S)N)r0rv� verify_flags)r�)r{r*r+r�+szSSLContext.verify_flagscsttt�j�||�dS)N)rvr�r�r�)r�r3)r{r*r+r�/scs*t�j}yt|�Stk r$|SXdS)N)rv� verify_moder1rR)r�r3)r{r*r+r�3s zSSLContext.verify_modecsttt�j�||�dS)N)rvr�r�r�)r�r3)r{r*r+r�;s)FTTNN)FNN) r6r7r8rr�r�r�� PROTOCOL_TLSrwr�r�r�r�r�r�r�r�r�r��hasattrr �propertyr��setterr�r�r9r�r�r�r�r�r*r*)r{r+r��sB          r�)rsrtr�cCsdt|t�st|��tt�}|tjkr0t|_d|_ |s<|s<|rL|� |||�n|jt kr`|� |�|S)z�Create a SSLContext object with default settings. NOTE: The protocol and settings may change anytime without prior deprecation. The values represent a fair balance between maximum compatibility and security. T) r�rur�r�r�r�r�� CERT_REQUIREDr�rcr�� CERT_NONEr�)r�rsrtr�rer*r*r+�create_default_context@s     r�F)� cert_reqsrcr��certfile�keyfilersrtr�c Cs�t|t�st|��t|�} |s$d| _|dk r2|| _|r<d| _|rL|sLtd��|sT|r`| �||�|sl|sl|r|| �|||�n| jt kr�| � |�| S)a/Create a SSLContext object for Python stdlib modules All Python stdlib modules shall use this function to create SSLContext objects in order to keep common settings in one place. The configuration is less restrict than create_default_context()'s to increase backward compatibility. FNTzcertfile must be specified) r�rur�r�rcr�rR�load_cert_chainr�r�r�) r�r�rcr�r�r�rsrtr�rer*r*r+�_create_unverified_context^s$     r�c@s�eZdZdZdd�Zed2dd��Zedd ��Zej d d ��Zed d ��Z e j d d ��Z edd��Z edd��Z edd��Z d3dd�Zdd�Zd4dd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd5d,d-�Zd.d/�Zd0d1�ZdS)6� SSLObjectaThis class implements an interface on top of a low-level SSL object as implemented by OpenSSL. This object captures the state of an SSL connection but does not provide any network IO itself. IO needs to be performed through separate "BIO" objects which are OpenSSL's IO abstraction layer. This class does not have a public constructor. Instances are returned by ``SSLContext.wrap_bio``. This class is typically used by framework authors that want to implement asynchronous IO for SSL through memory buffers. When compared to ``SSLSocket``, this object lacks the following features: * Any form of network IO, including methods such as ``recv`` and ``send``. * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery. cOst|jj�d���dS)NzU does not have a public constructor. Instances are returned by SSLContext.wrap_bio().)r�r{r6)r�r�r�r*r*r+�__init__�szSSLObject.__init__FNc Cs:t||||d�|�|�}|j||||||d�}||_|S)N)rdrerfrg)rdrf�ownerrg)rhrwZ _wrap_bio�_sslobj) ryr�r�rdrfrgrer�r�r*r*r+r��s   zSSLObject._createcCs|jjS)z(The SSLContext that is currently in use.)r�re)r�r*r*r+re�szSSLObject.contextcCs ||j_dS)N)r�re)r��ctxr*r*r+re�scCs|jjS)z!The SSLSession for client socket.)r�rg)r�r*r*r+rg�szSSLObject.sessioncCs ||j_dS)N)r�rg)r�rgr*r*r+rg�scCs|jjS)z.Was the client session reused during handshake)r��session_reused)r�r*r*r+r��szSSLObject.session_reusedcCs|jjS)z%Whether this is a server-side socket.)r�rd)r�r*r*r+rd�szSSLObject.server_sidecCs|jjS)z]The currently set server hostname (for SNI), or ``None`` if no server hostame is set.)r�rf)r�r*r*r+rf�szSSLObject.server_hostname�cCs(|dk r|j�||�}n |j�|�}|S)z�Read up to 'len' bytes from the SSL object and return them. If 'buffer' is provided, read into this buffer and return the number of bytes read. N)r��read)r�r[�buffer�vr*r*r+r��s zSSLObject.readcCs |j�|�S)z�Write 'data' to the SSL object and return the number of bytes written. The 'data' argument must support the buffer interface. )r��write)r��datar*r*r+r��szSSLObject.writecCs |j�|�S)z�Returns a formatted version of the data in the certificate provided by the other end of the SSL channel. Return None if no certificate was provided, {} if a certificate was provided, but not validated. )r�� getpeercert)r�� binary_formr*r*r+r��szSSLObject.getpeercertcCstjr|j��SdS)z�Return the currently selected NPN protocol as a string, or ``None`` if a next protocol was not negotiated or if NPN is not supported by one of the peers.N)r9rr��selected_npn_protocol)r�r*r*r+r��szSSLObject.selected_npn_protocolcCstjr|j��SdS)z�Return the currently selected ALPN protocol as a string, or ``None`` if a next protocol was not negotiated or if ALPN is not supported by one of the peers.N)r9rr��selected_alpn_protocol)r�r*r*r+r��sz SSLObject.selected_alpn_protocolcCs |j��S)z_Return the currently selected cipher as a 3-tuple ``(name, ssl_version, secret_bits)``.)r��cipher)r�r*r*r+r�szSSLObject.ciphercCs |j��S)z�Return a list of ciphers shared by the client during the handshake or None if this is not a valid server connection. )r��shared_ciphers)r�r*r*r+r�szSSLObject.shared_cipherscCs |j��S)z�Return the current compression algorithm in use, or ``None`` if compression was not negotiated or not supported by one of the peers.)r�� compression)r�r*r*r+r� szSSLObject.compressioncCs |j��S)z8Return the number of bytes that can be read immediately.)r��pending)r�r*r*r+r�szSSLObject.pendingcCs|j��dS)zStart the SSL/TLS handshake.N)r�� do_handshake)r�r*r*r+r�szSSLObject.do_handshakecCs |j��S)z!Start the SSL shutdown handshake.)r��shutdown)r�r*r*r+�unwrapszSSLObject.unwrap� tls-uniquecCs |j�|�S)z�Get channel binding data for current connection. Raise ValueError if the requested `cb_type` is not supported. Return bytes of the data or None if the data is not available (e.g. before the handshake).)r��get_channel_binding)r��cb_typer*r*r+r�szSSLObject.get_channel_bindingcCs |j��S)zZReturn a string identifying the protocol version used by the current SSL channel. )r��version)r�r*r*r+r�"szSSLObject.versioncCs |j��S)N)r��verify_client_post_handshake)r�r*r*r+r�'sz&SSLObject.verify_client_post_handshake)FNNN)r�N)F)r�)r6r7r8rr�r�r�r�rer�rgr�rdrfr�r�r�r�r�r�r�r�r�r�r�r�r�r�r*r*r*r+r��s4        r�cCstt|j�j|_|S)z*Copy docstring from SSLObject to SSLSocket)�getattrr�r6r)�funcr*r*r+� _sslcopydoc+sr�cseZdZdZdd�ZedX�fdd� �Zeed d ���Z e j d d ��Z eed d ���Z e j dd ��Z eedd���Z dd�Z dYdd�Zdd�ZdZdd�Zdd�Zed[dd��Zedd��Zed d!��Zed"d#��Zed$d%��Zed&d'��Zd\�fd)d*� Zd]�fd+d,� Zd-d.�Zd^�fd/d0� Zd_�fd1d2� Zd`�fd3d4� Zda�fd5d6� Zdb�fd7d8� Zdc�fd9d:� Z d;d<�Z!d=d>�Z"ed?d@��Z#�fdAdB�Z$edCdD��Z%edEdF��Z&�fdGdH�Z'edddIdJ��Z(�fdKdL�Z)dMdN�Z*dOdP�Z+�fdQdR�Z,ededTdU��Z-edVdW��Z.�Z/S)f� SSLSocketz�This class implements a subtype of socket.socket that wraps the underlying OS socket in an SSL context when necessary, and provides read and write methods over that channel. cOst|jj�d���dS)NzX does not have a public constructor. Instances are returned by SSLContext.wrap_socket().)r�r{r6)r�r�r�r*r*r+r�6szSSLSocket.__init__FTNc s<|�tt�tkrtd��t||||d�t|j|j|j |� �d�}|j |f|�} t t | �jf|�|��} |��|| _|| _d| _d| _|| _|�|�| _|| _|| _y | ��Wn�tk �r�} z�| jtjkrւd} | ��dk} | �d�y| �d�}Wn>tk �r<} z| jtjtj fk�r(�d}Wdd} ~ XYnX| �| �|�r�d}t!| j|�}||_"d|_#y | �$�Wntk �r�YnXz|�Wdd}XWdd} ~ XYnXd } | �%| �| | _&| �r8yH| jj'| || j| | jd �| _|�r| ��}|d k�rt(d ��| �)�Wn$tt(fk �r6| �$��YnX| S) Nz!only stream sockets are supported)rdrerfrg)�family�type�proto�filenoFrrFr-z5Closed before TLS handshake with data in recv buffer.T)r�rggzHdo_handshake_on_connect should not be specified for non-blocking sockets)*Z getsockoptrBrCr@�NotImplementedErrorrh�dictr�r�r�r�rwrvr�r�� gettimeout�detach�_context�_sessionZ_closedr�rdr�rfr�r�� getpeernamerQ�errnoZENOTCONNZ setblocking�recvZEINVALr �reasonZlibrary�close� settimeout� _connected� _wrap_socketrRr�)ryr�rdr�r�rfrergr�r�Z sock_timeout�eZ connectedZblockingZnotconn_pre_handshake_datar�Z notconn_pre_handshake_data_error�timeout)r{r*r+r�=s~              zSSLSocket._createcCs|jS)N)r�)r�r*r*r+re�szSSLSocket.contextcCs||_||j_dS)N)r�r�re)r�r�r*r*r+re�scCs|jdk r|jjSdS)N)r�rg)r�r*r*r+rg�s zSSLSocket.sessioncCs||_|jdk r||j_dS)N)r�r�rg)r�rgr*r*r+rg�s cCs|jdk r|jjSdS)N)r�r�)r�r*r*r+r��s zSSLSocket.session_reusedcCstd|jj��dS)NzCan't dup() %s instances)r�r{r6)r�r*r*r+�dup�sz SSLSocket.dupcCsdS)Nr*)r��msgr*r*r+� _checkClosed�szSSLSocket._checkClosedcCs|js|��dS)N)r�r�)r�r*r*r+�_check_connected�szSSLSocket._check_connected�c Cs�|��|jdkrtd��y&|dk r2|j�||�S|j�|�SWnJtk r�}z,|jdtkrx|jrx|dk rrdSdSn�Wdd}~XYnXdS)zORead up to LEN bytes and return them. Return zero-length string on EOF.Nz'Read on closed or unwrapped SSL socket.rr-)r�r�rRr�r r�Z SSL_ERROR_EOFr�)r�r[r��xr*r*r+r��s zSSLSocket.readcCs&|��|jdkrtd��|j�|�S)zhWrite DATA to the underlying SSL channel. Returns number of bytes of DATA actually transmitted.Nz(Write on closed or unwrapped SSL socket.)r�r�rRr�)r�r�r*r*r+r��s zSSLSocket.writecCs|��|��|j�|�S)N)r�rr�r�)r�r�r*r*r+r��szSSLSocket.getpeercertcCs*|��|jdkstjsdS|j��SdS)N)r�r�r9rr�)r�r*r*r+r��szSSLSocket.selected_npn_protocolcCs*|��|jdkstjsdS|j��SdS)N)r�r�r9rr�)r�r*r*r+r��sz SSLSocket.selected_alpn_protocolcCs$|��|jdkrdS|j��SdS)N)r�r�r�)r�r*r*r+r��s zSSLSocket.ciphercCs$|��|jdkrdS|j��SdS)N)r�r�r�)r�r*r*r+r��s zSSLSocket.shared_cipherscCs$|��|jdkrdS|j��SdS)N)r�r�r�)r�r*r*r+r�s zSSLSocket.compressionrcsF|��|jdk r4|dkr(td|j��|j�|�St��||�SdS)Nrz3non-zero flags not allowed in calls to send() on %s)r�r�rRr{r�rv�send)r�r��flags)r{r*r+rs   zSSLSocket.sendcsL|��|jdk r"td|j��n&|dkr8t��||�St��|||�SdS)Nz%sendto not allowed on instances of %s)r�r�rRr{rv�sendto)r�r�Z flags_or_addrrT)r{r*r+rs  zSSLSocket.sendtocOstd|j��dS)Nz&sendmsg not allowed on instances of %s)r�r{)r�r�r�r*r*r+�sendmsg#szSSLSocket.sendmsgc s�|��|jdk r�|dkr(td|j��d}t|��L}|�d��6}t|�}x&||krp|�||d��}||7}qLWWdQRXWdQRXnt�� ||�SdS)Nrz6non-zero flags not allowed in calls to sendall() on %s�B) r�r�rRr{� memoryview�castr[rrv�sendall)r�r�rrHZviewZ byte_viewZamountr�)r{r*r+r )s   "zSSLSocket.sendallcs,|jdk r|�|||�St��|||�SdS)z�Send a file, possibly by using os.sendfile() if this is a clear-text socket. Return the total number of bytes sent. N)r�Z_sendfile_use_sendrv�sendfile)r��file�offsetrH)r{r*r+r 9s zSSLSocket.sendfilecsD|��|jdk r2|dkr(td|j��|�|�St��||�SdS)Nrz3non-zero flags not allowed in calls to recv() on %s)r�r�rRr{r�rvr�)r��buflenr)r{r*r+r�Cs   zSSLSocket.recvcsj|��|r|dkrt|�}n |dkr*d}|jdk rV|dkrJtd|j��|�||�St��|||�SdS)Nirz8non-zero flags not allowed in calls to recv_into() on %s)r�r[r�rRr{r�rv� recv_into)r�r��nbytesr)r{r*r+rNs     zSSLSocket.recv_intocs4|��|jdk r"td|j��nt��||�SdS)Nz'recvfrom not allowed on instances of %s)r�r�rRr{rv�recvfrom)r�rr)r{r*r+r]s   zSSLSocket.recvfromcs6|��|jdk r"td|j��nt��|||�SdS)Nz,recvfrom_into not allowed on instances of %s)r�r�rRr{rv� recvfrom_into)r�r�rr)r{r*r+res   zSSLSocket.recvfrom_intocOstd|j��dS)Nz&recvmsg not allowed on instances of %s)r�r{)r�r�r�r*r*r+�recvmsgmszSSLSocket.recvmsgcOstd|j��dS)Nz+recvmsg_into not allowed on instances of %s)r�r{)r�r�r�r*r*r+� recvmsg_intoqszSSLSocket.recvmsg_intocCs$|��|jdk r|j��SdSdS)Nr)r�r�r�)r�r*r*r+r�us  zSSLSocket.pendingcs|��d|_t��|�dS)N)r�r�rvr�)r�Zhow)r{r*r+r�}szSSLSocket.shutdowncCs.|jr|j��}d|_|Stdt|���dS)NzNo SSL wrapper around )r�r�rRr�)r��sr*r*r+r��s  zSSLSocket.unwrapcCs$|jr|j��Stdt|���dS)NzNo SSL wrapper around )r�r�rRr�)r�r*r*r+r��s z&SSLSocket.verify_client_post_handshakecsd|_t���dS)N)r�rv� _real_close)r�)r{r*r+r�szSSLSocket._real_closec CsF|��|��}z$|dkr(|r(|�d�|j��Wd|�|�XdS)Ng)rr�r�r�r�)r��blockr�r*r*r+r��s  zSSLSocket.do_handshakec s�|jrtd��|js|jdk r&td��|jj|d|j||jd�|_y>|rVt�� |�}nd}t�� |�|s~d|_|j r~|� �|St tfk r�d|_�YnXdS)Nz!can't connect in server-side modez/attempt to connect already-connected SSLSocket!F)r�rgT)rdrRr�r�rer�rfr�rv� connect_ex�connectr�r�rQ)r�rTrZrc)r{r*r+� _real_connect�s( zSSLSocket._real_connectcCs|�|d�dS)zQConnects to remote ADDR, and then wraps the connection in an SSL channel.FN)r)r�rTr*r*r+r�szSSLSocket.connectcCs |�|d�S)zQConnects to remote ADDR, and then wraps the connection in an SSL channel.T)r)r�rTr*r*r+r�szSSLSocket.connect_excs.t���\}}|jj||j|jdd�}||fS)z�Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client.T)r�r�rd)rv�acceptrer�r�r�)r�ZnewsockrT)r{r*r+r�s zSSLSocket.accept� tls-uniquecCs4|jdk r|j�|�S|tkr,td�|���dSdS)Nz({0} channel binding type not implemented)r�r��CHANNEL_BINDING_TYPESrRrK)r�r�r*r*r+r��s    zSSLSocket.get_channel_bindingcCs|jdk r|j��SdSdS)N)r�r�)r�r*r*r+r��s  zSSLSocket.version)FTTNNN)N)rN)F)r)N)r)rN)rr)Nr)rr)Nr)F)r)0r6r7r8rr�r�r�r�r�rer�rgr�r�r�rr�r�r�r�r�r�r�r�rrrr r r�rrrrrr�r�r�r�rr�rrrrr�r�r�r*r*)r{r+r�1sfV                    r�Tc Csl|r|std��|r |s td��t|�} || _|r<| �|�|rL| �||�| rZ| �| �| j||||d�S)Nz5certfile must be specified for server-side operationszcertfile must be specified)r�rdr�r�)rRr�r�r�r�Z set_ciphersr�) r�r�r�rdr�� ssl_version�ca_certsr�r�Zciphersrer*r*r+r��s    r�cCs�ddlm}ddlm}d}d}y|�|dd����d}Wn$tk rbtd ||f��Yn0X||dd�|�}||d|f|d d ��SdS) a�Return the time in seconds since the Epoch, given the timestring representing the "notBefore" or "notAfter" date from a certificate in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale). "notBefore" or "notAfter" dates must use UTC (RFC 5280). Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec UTC should be specified as GMT (see ASN1_TIME_print()) r)�strptime)�timegm) ZJanZFebZMarZAprZMayZJunZJulZAugZSepZOctZNovZDecz %d %H:%M:%S %Y GMTNrkrFz*time data %r does not match format "%%b%s"rj�)Ztimer Zcalendarr!�index�titlerR)Z cert_timer r!ZmonthsZ time_formatZ month_numberZttr*r*r+�cert_time_to_secondss  r%z-----BEGIN CERTIFICATE-----z-----END CERTIFICATE-----csRtt�|�dd��tg}|�fdd�tdt��d�D�7}|�td�d�|�S)z[Takes a certificate in binary DER format and returns the PEM version of it as a string.�ASCII�strictcsg|]}�||d��qS)�@r*)r2�i)�fr*r+� <listcomp>,sz(DER_cert_to_PEM_cert.<locals>.<listcomp>rr(� ) r��base64Zstandard_b64encode� PEM_HEADER�ranger[rZ� PEM_FOOTERr\)Zder_cert_bytesZssr*)r*r+�DER_cert_to_PEM_cert&s "r1cCs\|�t�stdt��|���t�s0tdt��|��tt�tt� �}t�|� dd��S)zhTakes a certificate in ASCII PEM format and returns the DER-encoded version of it as a byte sequencez(Invalid PEM encoding; must start with %sz&Invalid PEM encoding; must end with %sr&r') r(r.rR�strip�endswithr0r[r-Z decodebytesr�)Zpem_cert_string�dr*r*r+�PEM_cert_to_DER_cert0s r5c Csd|\}}|dk rt}nt}t|||d�}t|��&}|�|��}|�d�} WdQRXWdQRXt| �S)z�Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. If 'ca_certs' is specified, validate the server cert against it. If 'ssl_version' is specified, use it in the connection attempt.N)r�rsT)r�r��_create_stdlib_contextrAr�r�r1) rTrrZhostZportr�rer�ZsslsockZdercertr*r*r+�get_server_certificate=s  r7cCs t�|d�S)Nz <unknown>)�_PROTOCOL_NAMESrY)Z protocol_coder*r*r+�get_protocol_namePsr9)NNN)lrr�rm� collectionsr�enumrZ_EnumrZ_IntEnumrZ_IntFlagr9rrrr r r r r rrrrrrrxrr|rrrrr� ImportErrorrrrrrrr r!r"r#r$r%�_convertr6r&r�r'� __members__�itemsr8r�Z_SSLv2_IF_EXISTSr5r�r<r=r>r?r@rArBrCrPr-r�r�rQZ socket_errorrr�ZHAS_NEVER_CHECK_COMMON_NAMEZ_RESTRICTED_SERVER_CIPHERSrJrOrUrXrbrhrirlrur�r�r�r�r�r�Z_create_default_https_contextr6r�r�r�r�r�r�r%r.r0r1r5r7r9r*r*r*r+�<module>[s� $0    1# 9 -(7