U
    k]e                  
   @   s  d Z ddlZddlZddlmZ ddlmZmZ	m
Z ddlZddlmZmZmZ ddlmZmZmZ ddlmZmZmZmZmZmZmZ ddlmZmZ dd	lmZmZm Z m!Z! zdd
lm"Z" W n e#k
r   Y nX ddlm$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z- ddlm.Z.m/Z/ e	j0de1dd ed ej0de1dd ed e	j0de1dd ed e	j0de1dd ed ej0de1dd ed e	j0de1dd ed e2j3 Z4e2_4dd e2j56 D Z7e8e2ddZ9G dd de	Z:G d d! d!e	Z;G d"d# d#e	Z<G d$d% d%e	Z=ej>d&kr"dd'lm?Z?m@Z@ dd(lAmAZAmBZBmCZCmDZD dd)lAmEZEmFZF ddlAZGddlHZHddlIZIddlJZJeKZLd*gZMeNed+ZOe.ZPeZQd,d- ZRd.d/ ZSd0d1 ZTd2d3 ZUed4d5ZVd6d7 ZWG d8d9 d9ed9d:ZXG d;d< d<eXeZYG d=d> d>eZZeYj[fdddd?d@dAZ\e3fe]dBeYj[ddddddCdDdEZ^e\Z_e^Z`G dFdG dGZadHdI ZbG dJdK dKeAZceceZ_deaeZ_edddBe]e3ddLdLdf	dMdNZfdOdP ZgdQZhdRZidSdT ZjdUdV Zke3dfdWdXZldYdZ ZmdS )[a
  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
_SSLMethodc                 C   s   |  do| dkS )NZ	PROTOCOL_PROTOCOL_SSLv23
startswithname r,   /usr/lib/python3.8/ssl.py<lambda>|       r.   )sourceOptionsc                 C   s
   |  dS )NZOP_r(   r*   r,   r,   r-   r.      r/   ZAlertDescriptionc                 C   s
   |  dS )NZALERT_DESCRIPTION_r(   r*   r,   r,   r-   r.      r/   ZSSLErrorNumberc                 C   s
   |  dS )NZ
SSL_ERROR_r(   r*   r,   r,   r-   r.      r/   VerifyFlagsc                 C   s
   |  dS )NZVERIFY_r(   r*   r,   r,   r-   r.      r/   
VerifyModec                 C   s
   |  dS )NZCERT_r(   r*   r,   r,   r-   r.      r/   c                 C   s   i | ]\}}||qS r,   r,   ).0r+   valuer,   r,   r-   
<dictcomp>   s      r6   ZPROTOCOL_SSLv2c                   @   s6   e Zd ZejZejZejZ	ej
ZejZejZejZdS )
TLSVersionN)__name__
__module____qualname___sslZPROTO_MINIMUM_SUPPORTEDZMINIMUM_SUPPORTEDZPROTO_SSLv3SSLv3ZPROTO_TLSv1ZTLSv1ZPROTO_TLSv1_1ZTLSv1_1ZPROTO_TLSv1_2ZTLSv1_2ZPROTO_TLSv1_3ZTLSv1_3ZPROTO_MAXIMUM_SUPPORTEDZMAXIMUM_SUPPORTEDr,   r,   r,   r-   r7      s   r7   c                   @   s(   e Zd ZdZdZdZdZdZdZdZ	dS )	_TLSContentTypez@Content types (record layer)

    See RFC 8446, section B.1
                     N)
r8   r9   r:   __doc__CHANGE_CIPHER_SPECALERTZ	HANDSHAKEZAPPLICATION_DATAHEADERZINNER_CONTENT_TYPEr,   r,   r,   r-   r=      s   r=   c                   @   s   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!d Z"d!Z#d"Z$d#Z%d$S )%_TLSAlertTypezQAlert types for TLSContentType.ALERT messages

    See RFC 8466, section B.2
    r   
   r>   r?   r@      (   )   *   +   ,   -   .   /   0   1   2   3   <   F   G   P   V   Z   d   m   n   o   p   q   r   s   t   x   N)&r8   r9   r:   rD   ZCLOSE_NOTIFYZUNEXPECTED_MESSAGEZBAD_RECORD_MACZDECRYPTION_FAILEDZRECORD_OVERFLOWZDECOMPRESSION_FAILUREZHANDSHAKE_FAILUREZNO_CERTIFICATEZBAD_CERTIFICATEZUNSUPPORTED_CERTIFICATEZCERTIFICATE_REVOKEDZCERTIFICATE_EXPIREDZCERTIFICATE_UNKNOWNZILLEGAL_PARAMETERZ
UNKNOWN_CAZACCESS_DENIEDZDECODE_ERRORZDECRYPT_ERRORZEXPORT_RESTRICTIONZPROTOCOL_VERSIONZINSUFFICIENT_SECURITYZINTERNAL_ERRORZINAPPROPRIATE_FALLBACKZUSER_CANCELEDZNO_RENEGOTIATIONZMISSING_EXTENSIONZUNSUPPORTED_EXTENSIONZCERTIFICATE_UNOBTAINABLEZUNRECOGNIZED_NAMEZBAD_CERTIFICATE_STATUS_RESPONSEZBAD_CERTIFICATE_HASH_VALUEZUNKNOWN_PSK_IDENTITYZCERTIFICATE_REQUIREDZNO_APPLICATION_PROTOCOLr,   r,   r,   r-   rH      sF   rH   c                   @   sh   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdZdZdZdZdZdZdZdZdZdZdS )_TLSMessageTypezFMessage types (handshake protocol)

    See RFC 8446, section B.3
    r                                          r>   r?   r@   rA      C      rC   N)r8   r9   r:   rD   ZHELLO_REQUESTZCLIENT_HELLOZSERVER_HELLOZHELLO_VERIFY_REQUESTZNEWSESSION_TICKETZEND_OF_EARLY_DATAZHELLO_RETRY_REQUESTZENCRYPTED_EXTENSIONSZCERTIFICATEZSERVER_KEY_EXCHANGEZCERTIFICATE_REQUESTZSERVER_DONEZCERTIFICATE_VERIFYZCLIENT_KEY_EXCHANGEZFINISHEDZCERTIFICATE_URLZCERTIFICATE_STATUSZSUPPLEMENTAL_DATAZ
KEY_UPDATEZ
NEXT_PROTOZMESSAGE_HASHrE   r,   r,   r,   r-   rg      s.   rg   win32)enum_certificates	enum_crls)socketAF_INETSOCK_STREAMcreate_connection)
SOL_SOCKETSO_TYPE
tls-uniqueHOSTFLAG_NEVER_CHECK_SUBJECTc                 C   s   | sdS |  d}|s&|  | kS |dkr<td| | d\}}}d|krbtd| |sttd| |dkrtd| |d\}}}|r|sdS | | kS )	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*rh   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)ZdnhostnameZ	wildcardsZdn_leftmostsepZdn_remainderZhostname_leftmostZhostname_remainderr,   r,   r-   _dnsname_match  s@    

r   c                 C   s   zt | }W n tk
r"   Y n"X t || kr6|S td| zt t j| W S  tk
rv   td| Y n tk
r   Y nX td| dS )zTry 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
ValueErrorr   Z	inet_ptonZAF_INET6AttributeError)Zipnameaddrr,   r,   r-   _inet_patonD  s$    
r   c                 C   s   t |  }||kS )zExact matching of IP addresses.

    RFC 6125 explicitly doesn't define an algorithm for this
    (section 1.7.2 - "Out of Scope").
    )r   rstrip)Zcert_ipaddresshost_ipZipr,   r,   r-   _ipaddress_matchg  s    r   c                 C   sJ  | st dzt|}W n t k
r0   d}Y nX g }| dd}|D ]^\}}|dkrz|dkrnt||rn dS || qF|dkrF|dk	rt||r dS || qF|s| ddD ]6}|D ],\}}|dkrt||r  dS || qqt|d	krtd
|dt	t
|f n,t|d	kr>td||d f ntddS )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_REQUIREDNZsubjectAltNamer,   ZDNSz
IP AddressZsubjectZ
commonNamerh   z&hostname %r doesn't match either of %sz, zhostname %r doesn't match %rr   z=no appropriate commonName or subjectAltName fields were found)r   r   getr   appendr   lenr   joinmaprepr)certr   r   ZdnsnamesZsankeyr5   subr,   r,   r-   match_hostnames  sB    


r   DefaultVerifyPathszQcafile capath openssl_cafile_env openssl_cafile openssl_capath_env openssl_capathc                  C   sd   t  } tj| d | d }tj| d | d }ttj|rF|ndtj|rX|ndf|  S )z/Return paths to default cafile and capath.
    r   rh   ri   rj   N)	r;   get_default_verify_pathsosenvironr   r   pathisfileisdir)partscafilecapathr,   r,   r-   r     s    r   c                       sD   e Zd ZdZdZ fddZe fddZe fddZ  Z	S )	_ASN1Objectz#ASN.1 object identifier lookup
    r,   c                    s   t  j| ft|dd S )NFr*   super__new___txt2obj)clsoid	__class__r,   r-   r     s    z_ASN1Object.__new__c                    s   t  j| ft| S )z3Create _ASN1Object from OpenSSL numeric ID
        )r   r   _nid2obj)r   Znidr   r,   r-   fromnid  s    z_ASN1Object.fromnidc                    s   t  j| ft|dd S )z=Create _ASN1Object from short name, long name or OID
        Tr*   r   )r   r+   r   r,   r-   fromname  s    z_ASN1Object.fromname)
r8   r9   r:   rD   	__slots__r   classmethodr   r   __classcell__r,   r,   r   r-   r     s   r   znid shortname longname oidc                   @   s   e Zd ZdZdZdZdS )PurposezDSSLContext purpose flags with X509v3 Extended Key Usage objects
    z1.3.6.1.5.5.7.3.1z1.3.6.1.5.5.7.3.2N)r8   r9   r:   rD   SERVER_AUTHZCLIENT_AUTHr,   r,   r,   r-   r     s   r   c                       s  e Zd ZdZdZdZdZefddZdd Z	d2d
dZ
d3ddZdd Zdd Zdd Zdd ZejfddZeedre fddZej fddZe fddZej fddZe fdd Zej fd!d Zeed"red#d$ Zejd%d$ Zned&d$ Ze fd'd(Zej fd)d(Ze fd*d+Ze fd,d-Zej fd.d-Ze fd/d0Zej fd1d0Z  Z S )4
SSLContextz|An SSLContext holds various SSL-related configuration options and
    data, such as certificates and possibly a private key.)ZCAZROOTNc                 O   s   t | |}|S N)r	   r   )r   protocolargskwargsselfr,   r,   r-   r     s    zSSLContext.__new__c                 C   s4   |d krd S t |tr&|ddS |dS d S )NZidnaascii)
isinstancestrencodedecode)r   r   r,   r,   r-   _encode_hostname  s
    
zSSLContext._encode_hostnameFTc              	   C   s   | j j|||||| |dS )N)sockserver_sidedo_handshake_on_connectsuppress_ragged_eofsserver_hostnamecontextsession)sslsocket_class_create)r   r   r   r   r   r   r   r,   r,   r-   wrap_socket  s    zSSLContext.wrap_socketc                 C   s   | j j|||| ||| dS )N)r   r   r   r   )sslobject_classr   r   )r   incomingoutgoingr   r   r   r,   r,   r-   wrap_bio  s       zSSLContext.wrap_bioc                 C   s`   t  }|D ]F}t|d}t|dks0t|dkr8td|t| || q
| | d S )Nr   r      z(NPN protocols must be 1 to 255 in length)	bytearraybytesr   r   r   extendZ_set_npn_protocols)r   Znpn_protocolsprotosr   br,   r,   r-   set_npn_protocols  s    
zSSLContext.set_npn_protocolsc                    s8   d krd  _ n$ts td fdd}| _ d S )Nznot a callable objectc                    s     |}| ||S r   )r   )sslobjZ
servernameZsslctx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-   set_servername_callback  s    z"SSLContext.set_servername_callbackc                 C   s`   t  }|D ]F}t|d}t|dks0t|dkr8td|t| || q
| | d S )Nr   r   r   z)ALPN protocols must be 1 to 255 in length)r   r   r   r   r   r   Z_set_alpn_protocols)r   Zalpn_protocolsr   r   r   r,   r,   r-   set_alpn_protocols   s    
zSSLContext.set_alpn_protocolsc                 C   sv   t  }z<t|D ].\}}}|dkr|dks4|j|kr|| qW n tk
r`   td Y nX |rr| j|d |S )NZx509_asnTz-unable to enumerate Windows certificate store)cadata)r   ry   r   r   PermissionErrorwarningswarnload_verify_locations)r   	storenamepurposeZcertsr   encodingZtrustr,   r,   r-   _load_windows_store_certs+  s    z$SSLContext._load_windows_store_certsc                 C   s@   t |tst|tjdkr4| jD ]}| || q"|   d S )Nrx   )r   r   r   sysplatform_windows_cert_storesr   Zset_default_verify_paths)r   r   r   r,   r,   r-   load_default_certs9  s    


zSSLContext.load_default_certsminimum_versionc                    s   t t jS r   )r7   r   r   r   r   r,   r-   r   B  s    zSSLContext.minimum_versionc                    s4   |t jkr|  jtj M  _tttj| | d S r   )	r7   r<   optionsr1   ZOP_NO_SSLv3r   r   r   __set__r   r5   r   r,   r-   r   F  s    
c                    s   t t jS r   )r7   r   maximum_versionr   r   r,   r-   r   L  s    zSSLContext.maximum_versionc                    s   t ttj| | d S r   )r   r   r   r   r   r   r,   r-   r   P  s    c                    s   t t jS r   )r1   r   r   r   r   r,   r-   r   T  s    zSSLContext.optionsc                    s   t ttj| | d S r   )r   r   r   r   r   r   r,   r-   r   X  s    r   c                 C   s   | j tj@ }|tjkS r   Z_host_flagsr;   r   )r   Zncsr,   r,   r-   hostname_checks_common_name]  s    z&SSLContext.hostname_checks_common_namec                 C   s,   |r|  j tj M  _ n|  j tjO  _ d S r   r   r   r,   r,   r-   r   b  s    c                 C   s   dS )NTr,   r   r,   r,   r-   r   i  s    c                    s   t  j}|dk	r|jS dS dS )a9  TLS message callback

        The message callback provides a debugging hook to analyze TLS
        connections. The callback is called for any TLS protocol message
        (header, handshake, alert, and more), but not for application data.
        Due to technical  limitations, the callback can't be used to filter
        traffic or to abort a connection. Any exception raised in the
        callback is delayed until the handshake, read, or write operation
        has been performed.

        def msg_cb(conn, direction, version, content_type, msg_type, data):
            pass

        conn
            :class:`SSLSocket` or :class:`SSLObject` instance
        direction
            ``read`` or ``write``
        version
            :class:`TLSVersion` enum member or int for unknown version. For a
            frame header, it's the header version.
        content_type
            :class:`_TLSContentType` enum member or int for unsupported
            content type.
        msg_type
            Either a :class:`_TLSContentType` enum number for a header
            message, a :class:`_TLSAlertType` enum member for an alert
            message, a :class:`_TLSMessageType` enum member for other
            messages, or int for unsupported message types.
        data
            Raw, decrypted message content as bytes
        N)r   _msg_callbackuser_function)r   innerr   r,   r-   r   m  s    !zSSLContext._msg_callbackc                    sb    d kr t ttj| d  d S t ds8t  d fdd} |_t ttj| | d S )N__call__z is not callable.c                    s   zt |}W n tk
r    Y nX zt|}W n tk
rB   Y nX |tjkrTt}n|tjkrdt}nt}z||}W n tk
r   Y nX  | |||||S r   )r7   r   r=   rG   rF   rH   rg   )Zconn	directionversionZcontent_typeZmsg_typedataZmsg_enumcallbackr,   r-   r     s,    

  z'SSLContext._msg_callback.<locals>.inner)r   r   r   r   hasattrr   r   )r   r  r   r   r   r-   r     s    
c                    s   t t jS r   )r&   r   r   r   r   r,   r-   r     s    zSSLContext.protocolc                    s   t t jS r   )r2   r   verify_flagsr   r   r,   r-   r    s    zSSLContext.verify_flagsc                    s   t ttj| | d S r   )r   r   r  r   r   r   r,   r-   r    s    c                    s0   t  j}z
t|W S  tk
r*   | Y S X d S r   )r   verify_moder3   r   r   r   r,   r-   r    s
    
zSSLContext.verify_modec                    s   t ttj| | d S r   )r   r   r  r   r   r   r,   r-   r    s    )FTTNN)FNN)!r8   r9   r:   rD   r   r   r   PROTOCOL_TLSr   r   r   r   r   r   r   r   r   r   r   r  r	   propertyr   setterr   r   r;   r   r   r   r  r  r   r,   r,   r   r-   r     sn         
    




&%r   )r   r   r   c                C   s   t | tst| tt}| tjkr0t|_d|_	|s<|s<|rL|
||| n|jtkr`||  t|drtjd}|rtjjs||_|S )zCreate 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keylog_filenameSSLKEYLOGFILE)r   r   r   r   r  r   r   CERT_REQUIREDr  check_hostnamer   	CERT_NONEr   r  r   r   r   r   flagsignore_environmentr  )r   r   r   r   r   
keylogfiler,   r,   r-   create_default_context  s    




r  F)	cert_reqsr  r   certfilekeyfiler   r   r   c                C   s   t |tst|t| }	|s$d|	_|dk	r2||	_|r<d|	_|rL|sLtd|sT|r`|	|| |sl|sl|r||	||| n|	jt	kr|	
| t|	drtjd}
|
rtjjs|
|	_|	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.
    FNTcertfile must be specifiedr  r	  )r   r   r   r   r  r  r   load_cert_chainr   r  r   r  r   r   r   r   r  r  r  )r   r  r  r   r  r  r   r   r   r   r  r,   r,   r-   _create_unverified_context  s,    



r  c                   @   s   e Zd ZdZdd Zed2ddZedd	 Zej	d
d	 Zedd Z
e
j	dd Z
edd Zedd Zedd Zd3ddZdd Zd4ddZdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd5d,d-Zd.d/ Zd0d1 ZdS )6	SSLObjecta  This 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.
    c                 O   s   t | jj dd S )NzU does not have a public constructor. Instances are returned by SSLContext.wrap_bio().r   r   r8   r   r   r   r,   r,   r-   __init__;  s    zSSLObject.__init__FNc           	      C   s*   |  | }|j||||||d}||_|S )N)r   r   ownerr   )r   Z	_wrap_bio_sslobj)	r   r   r   r   r   r   r   r   r   r,   r,   r-   r   A  s    
   zSSLObject._createc                 C   s   | j jS )z(The SSLContext that is currently in use.r  r   r   r,   r,   r-   r   M  s    zSSLObject.contextc                 C   s   || j _d S r   r  r   Zctxr,   r,   r-   r   R  s    c                 C   s   | j jS )z!The SSLSession for client socket.r  r   r   r,   r,   r-   r   V  s    zSSLObject.sessionc                 C   s   || j _d S r   r  r   r   r,   r,   r-   r   [  s    c                 C   s   | j jS )z.Was the client session reused during handshaker  session_reusedr   r,   r,   r-   r"  _  s    zSSLObject.session_reusedc                 C   s   | j jS )z%Whether this is a server-side socket.)r  r   r   r,   r,   r-   r   d  s    zSSLObject.server_sidec                 C   s   | j jS )z^The currently set server hostname (for SNI), or ``None`` if no
        server hostname is set.)r  r   r   r,   r,   r-   r   i  s    zSSLObject.server_hostname   c                 C   s(   |dk	r| j ||}n| j |}|S )zRead 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$  o  s    zSSLObject.readc                 C   s   | j |S )zWrite 'data' to the SSL object and return the number of bytes
        written.

        The 'data' argument must support the buffer interface.
        )r  writer   r   r,   r,   r-   r'  {  s    zSSLObject.writec                 C   s   | j |S )zReturns 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   Zbinary_formr,   r,   r-   r)    s    zSSLObject.getpeercertc                 C   s   t jr| j S dS )zReturn 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)r;   r   r  selected_npn_protocolr   r,   r,   r-   r+    s    zSSLObject.selected_npn_protocolc                 C   s   t jr| j S dS )zReturn 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)r;   r   r  selected_alpn_protocolr   r,   r,   r-   r,    s    z SSLObject.selected_alpn_protocolc                 C   s
   | j  S )z_Return the currently selected cipher as a 3-tuple ``(name,
        ssl_version, secret_bits)``.)r  cipherr   r,   r,   r-   r-    s    zSSLObject.cipherc                 C   s
   | j  S )zReturn a list of ciphers shared by the client during the handshake or
        None if this is not a valid server connection.
        )r  shared_ciphersr   r,   r,   r-   r.    s    zSSLObject.shared_ciphersc                 C   s
   | j  S )zReturn the current compression algorithm in use, or ``None`` if
        compression was not negotiated or not supported by one of the peers.)r  compressionr   r,   r,   r-   r/    s    zSSLObject.compressionc                 C   s
   | j  S )z8Return the number of bytes that can be read immediately.)r  pendingr   r,   r,   r-   r0    s    zSSLObject.pendingc                 C   s   | j   dS )zStart the SSL/TLS handshake.N)r  do_handshaker   r,   r,   r-   r1    s    zSSLObject.do_handshakec                 C   s
   | j  S )z!Start the SSL shutdown handshake.)r  shutdownr   r,   r,   r-   unwrap  s    zSSLObject.unwrapr   c                 C   s   | j |S )zGet 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   Zcb_typer,   r,   r-   r4    s    zSSLObject.get_channel_bindingc                 C   s
   | j  S )zZReturn a string identifying the protocol version used by the
        current SSL channel. r  r   r   r,   r,   r-   r     s    zSSLObject.versionc                 C   s
   | j  S r   )r  verify_client_post_handshaker   r,   r,   r-   r7    s    z&SSLObject.verify_client_post_handshake)FNNN)r#  N)F)r   )r8   r9   r:   rD   r  r   r   r  r   r  r   r"  r   r   r$  r'  r)  r+  r,  r-  r.  r/  r0  r1  r3  r4  r   r7  r,   r,   r,   r-   r  ,  sH         








	
r  c                 C   s   t t| jj| _| S )z*Copy docstring from SSLObject to SSLSocket)getattrr  r8   rD   )funcr,   r,   r-   _sslcopydoc  s    r:  c                       s  e Zd ZdZdd ZedX fdd	Zeed	d
 Z	e	j
dd
 Z	eedd Zej
dd Zeedd Zdd ZdYddZdd ZdZddZdd Zed[ddZedd Zed d! Zed"d# Zed$d% Zed&d' Zd\ fd)d*	Zd] fd+d,	Zd-d. Zd^ fd/d0	Zd_ fd1d2	Zd` fd3d4	Zda fd5d6	Zdb fd7d8	Zdc fd9d:	Z d;d< Z!d=d> Z"ed?d@ Z# fdAdBZ$edCdD Z%edEdF Z& fdGdHZ'edddIdJZ( fdKdLZ)dMdN Z*dOdP Z+ fdQdRZ,ededTdUZ-edVdW Z.  Z/S )f	SSLSocketzThis 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. c                 O   s   t | jj dd S )NzX does not have a public constructor. Instances are returned by SSLContext.wrap_socket().r  r  r,   r,   r-   r    s    zSSLSocket.__init__FTNc                    sN  | tttkrtd|r8|r(td|d k	r8td|jrJ|sJtdt|j|j	|j
| d}| j| f|}	tt|	jf | | }
|  ||	_||	_d|	_d |	_||	_|||	_||	_||	_z|	  W n tk
r } z|jtjkr d}|	 }|	 d z|	!d}W n> tk
rZ } z|jtjtj"fkrF d}W 5 d }~X Y nX |	 | |rd	}t#|j|}||_$d |_%z|	&  W n tk
r   Y nX |W 5 d }~X Y nX d
}|	'|
 ||	_(|rJzH|	jj)|	||	j|	|	jd|	_|r"|	 }|dkrtd|	*  W n$ ttfk
rH   |	&   Y nX |	S )Nz!only stream sockets are supportedz4server_hostname can only be specified in client modez,session can only be specified in client modez'check_hostname requires server_hostname)familytypeprotofilenoFrh   r/   z5Closed before TLS handshake with data in recv buffer.Tr  r           zHdo_handshake_on_connect should not be specified for non-blocking sockets)+Z
getsockoptr   r   r}   NotImplementedErrorr   r  dictr<  r=  r>  r?  r   r   r;  r  
gettimeoutdetach_context_sessionZ_closedr  r   r   r   r   r   getpeernamer   errnoZENOTCONNZgetblockingZsetblockingrecvZEINVALr   reasonZlibraryclose
settimeout
_connected_wrap_socketr1  )r   r   r   r   r   r   r   r   r   r   Zsock_timeouteZ	connectedZblockingZnotconn_pre_handshake_datarK  Z notconn_pre_handshake_data_errortimeoutr   r,   r-   r     s    
  


   
zSSLSocket._createc                 C   s   | j S r   )rF  r   r,   r,   r-   r   3  s    zSSLSocket.contextc                 C   s   || _ || j_d S r   )rF  r  r   r  r,   r,   r-   r   8  s    c                 C   s   | j d k	r| j jS d S r   r  r   r,   r,   r-   r   =  s    
zSSLSocket.sessionc                 C   s   || _ | jd k	r|| j_d S r   )rG  r  r   r   r,   r,   r-   r   C  s    
c                 C   s   | j d k	r| j jS d S r   r!  r   r,   r,   r-   r"  I  s    
zSSLSocket.session_reusedc                 C   s   t d| jj d S )NzCan't dup() %s instances)rB  r   r8   r   r,   r,   r-   dupO  s    zSSLSocket.dupc                 C   s   d S r   r,   )r   msgr,   r,   r-   _checkClosedS  s    zSSLSocket._checkClosedc                 C   s   | j s|   d S r   )rN  rH  r   r,   r,   r-   _check_connectedW  s    zSSLSocket._check_connectedr#  c              
   C   s   |    | jdkrtdz*|dk	r4| j||W S | j|W S W nV tk
r } z8|jd tkr| jr|dk	r|W Y dS W Y dS n W 5 d}~X Y nX dS )zORead up to LEN bytes and return them.
        Return zero-length string on EOF.Nz'Read on closed or unwrapped SSL socket.r   r/   )rT  r  r   r$  r   r   ZSSL_ERROR_EOFr   )r   r   r%  xr,   r,   r-   r$  _  s    

zSSLSocket.readc                 C   s&   |    | jdkrtd| 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.)rT  r  r   r'  r(  r,   r,   r-   r'  t  s    
zSSLSocket.writec                 C   s   |    |   | j|S r   )rT  rU  r  r)  r*  r,   r,   r-   r)  }  s    zSSLSocket.getpeercertc                 C   s*   |    | jd kstjsd S | j S d S r   )rT  r  r;   r   r+  r   r,   r,   r-   r+    s    zSSLSocket.selected_npn_protocolc                 C   s*   |    | jd kstjsd S | j S d S r   )rT  r  r;   r   r,  r   r,   r,   r-   r,    s    z SSLSocket.selected_alpn_protocolc                 C   s$   |    | jd krd S | j S d S r   )rT  r  r-  r   r,   r,   r-   r-    s    
zSSLSocket.cipherc                 C   s$   |    | jd krd S | j S d S r   )rT  r  r.  r   r,   r,   r-   r.    s    
zSSLSocket.shared_ciphersc                 C   s$   |    | jd krd S | j S d S r   )rT  r  r/  r   r,   r,   r-   r/    s    
zSSLSocket.compressionr   c                    sF   |    | jd k	r4|dkr(td| j | j|S t ||S d S )Nr   z3non-zero flags not allowed in calls to send() on %s)rT  r  r   r   r'  r   send)r   r   r  r   r,   r-   rW    s    
zSSLSocket.sendc                    sL   |    | jd k	r"td| j n&|d kr8t ||S t |||S d S )Nz%sendto not allowed on instances of %s)rT  r  r   r   r   sendto)r   r   Zflags_or_addrr   r   r,   r-   rX    s    
zSSLSocket.sendtoc                 O   s   t d| j d S )Nz&sendmsg not allowed on instances of %srB  r   r  r,   r,   r-   sendmsg  s    zSSLSocket.sendmsgc              
      s   |    | jd k	r|dkr(td| j d}t|H}|d2}t|}||k rn| ||d  }||7 }qJW 5 Q R X W 5 Q R X nt 	||S d S )Nr   z6non-zero flags not allowed in calls to sendall() on %sB)
rT  r  r   r   
memoryviewcastr   rW  r   sendall)r   r   r  r   ZviewZ	byte_viewZamountr&  r   r,   r-   r^    s    
 zSSLSocket.sendallc                    s,   | j dk	r| |||S t |||S dS )zSend 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_sendr   sendfile)r   fileoffsetr   r   r,   r-   r_    s    
zSSLSocket.sendfilec                    sD   |    | jd k	r2|dkr(td| j | |S t ||S d S )Nr   z3non-zero flags not allowed in calls to recv() on %s)rT  r  r   r   r$  r   rJ  r   Zbuflenr  r   r,   r-   rJ    s    

zSSLSocket.recvc                    sj   |    |r|d krt|}n|d kr*d}| jd k	rV|dkrJtd| j | ||S t |||S d S )Nr#  r   z8non-zero flags not allowed in calls to recv_into() on %s)rT  r   r  r   r   r$  r   	recv_intor   r%  nbytesr  r   r,   r-   rc    s    

zSSLSocket.recv_intoc                    s4   |    | jd k	r"td| j nt ||S d S )Nz'recvfrom not allowed on instances of %s)rT  r  r   r   r   recvfromrb  r   r,   r-   rf    s    
zSSLSocket.recvfromc                    s6   |    | jd k	r"td| j nt |||S d S )Nz,recvfrom_into not allowed on instances of %s)rT  r  r   r   r   recvfrom_intord  r   r,   r-   rg    s    
zSSLSocket.recvfrom_intoc                 O   s   t d| j d S )Nz&recvmsg not allowed on instances of %srY  r  r,   r,   r-   recvmsg
  s    zSSLSocket.recvmsgc                 O   s   t d| j d S )Nz+recvmsg_into not allowed on instances of %srY  r  r,   r,   r-   recvmsg_into  s    zSSLSocket.recvmsg_intoc                 C   s$   |    | jd k	r| j S dS d S )Nr   )rT  r  r0  r   r,   r,   r-   r0    s    

zSSLSocket.pendingc                    s   |    d | _t | d S r   )rT  r  r   r2  )r   Zhowr   r,   r-   r2    s    zSSLSocket.shutdownc                 C   s.   | j r| j  }d | _ |S tdt|  d S NzNo SSL wrapper around )r  r2  r   r   )r   sr,   r,   r-   r3    s
    
zSSLSocket.unwrapc                 C   s$   | j r| j  S tdt|  d S rj  )r  r7  r   r   r   r,   r,   r-   r7  (  s    
z&SSLSocket.verify_client_post_handshakec                    s   d | _ t   d S r   )r  r   _real_closer   r   r,   r-   rl  /  s    zSSLSocket._real_closec              	   C   sF   |    |  }z$|dkr(|r(| d  | j  W 5 | | X d S )NrA  )rU  rD  rM  r  r1  )r   blockrQ  r,   r,   r-   r1  3  s    
zSSLSocket.do_handshakec              	      s   | j rtd| js| jd k	r&td| jj| d| j| | jd| _z@|rVt 	|}nd }t 
| |s~d| _| jr~|   |W S  ttfk
r   d | _ Y nX d S )Nz!can't connect in server-side modez/attempt to connect already-connected SSLSocket!Fr@  T)r   r   rN  r  r   rO  r   rG  r   
connect_exconnectr   r1  r   )r   r   rn  Zrcr   r,   r-   _real_connect>  s0       zSSLSocket._real_connectc                 C   s   |  |d dS )QConnects to remote ADDR, and then wraps the connection in
        an SSL channel.FNrp  r   r   r,   r,   r-   ro  X  s    zSSLSocket.connectc                 C   s   |  |dS )rq  Trr  rs  r,   r,   r-   rn  ]  s    zSSLSocket.connect_exc                    s.   t   \}}| jj|| j| jdd}||fS )zAccepts 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   r   )r   acceptr   r   r   r   )r   Znewsockr   r   r,   r-   rt  b  s    zSSLSocket.acceptr   c                 C   s4   | j d k	r| j |S |tkr,td|d S d S )Nz({0} channel binding type not implemented)r  r4  CHANNEL_BINDING_TYPESr   r   r5  r,   r,   r-   r4  n  s    
zSSLSocket.get_channel_bindingc                 C   s   | j d k	r| j  S d S d S r   r6  r   r,   r,   r-   r   y  s    

zSSLSocket.version)FTTNNN)N)r#  N)F)r   )N)r   )r   N)r#  r   )Nr   )r#  r   )Nr   )F)r   )0r8   r9   r:   rD   r  r   r   r  r:  r   r  r   r"  rR  rT  rU  r$  r'  r)  r+  r,  r-  r.  r/  rW  rX  rZ  r^  r_  rJ  rc  rf  rg  rh  ri  r0  r2  r3  r7  rl  r1  rp  ro  rn  rt  r4  r   r   r,   r,   r   r-   r;    s          [



	











r;  Tc
                 C   sl   |r|st d|r |s t dt|}
||
_|r<|
| |rL|
|| |	rZ|
|	 |
j| |||dS )Nz5certfile must be specified for server-side operationsr  )r   r   r   r   )r   r   r  r   r  Zset_ciphersr   )r   r  r  r   r  ssl_versionca_certsr   r   Zciphersr   r,   r,   r-   r     s$    

 r   c                 C   s   ddl m} ddlm} d}d}z|| dd  d }W n$ tk
rb   td	| |f Y n0X || dd |}||d |f|d
d  S dS )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)ZJanZFebZMarZAprZMayZJunZJulZAugZSepZOctZNovZDecz %d %H:%M:%S %Y GMTNrj   rh   z*time data %r does not match format "%%b%s"ri   rm   )timerx  Zcalendarry  indextitler   )Z	cert_timerx  ry  ZmonthsZtime_formatZmonth_numberZttr,   r,   r-   cert_time_to_seconds  s    
r}  z-----BEGIN CERTIFICATE-----z-----END CERTIFICATE-----c                    sR   t t| dd tg}| fddtdt dD 7 }|td  d|S )z[Takes a certificate in binary DER format and returns the
    PEM version of it as a string.ASCIIstrictc                    s   g | ]} ||d   qS )@   r,   )r4   ifr,   r-   
<listcomp>  s     z(DER_cert_to_PEM_cert.<locals>.<listcomp>r   r  
)	r   base64Zstandard_b64encode
PEM_HEADERranger   r   
PEM_FOOTERr   )Zder_cert_bytesZssr,   r  r-   DER_cert_to_PEM_cert  s
    "r  c                 C   s\   |  tstdt |  ts0tdt |  tttt  }t|	dd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  r   stripendswithr  r   r  Zdecodebytesr   )Zpem_cert_stringdr,   r,   r-   PEM_cert_to_DER_cert  s    
r  c           
   
   C   sd   | \}}|dk	rt }nt}t|||d}t| &}||}|d}	W 5 Q R X W 5 Q R X t|	S )zRetrieve 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  r   T)r
  r  _create_stdlib_contextr~   r   r)  r  )
r   rv  rw  ZhostZportr  r   r   ZsslsockZdercertr,   r,   r-   get_server_certificate  s    
r  c                 C   s   t | dS )Nz	<unknown>)_PROTOCOL_NAMESr   )Zprotocol_coder,   r,   r-   get_protocol_name  s    r  )nrD   r   r   collectionsr   enumr   Z_Enumr   Z_IntEnumr   Z_IntFlagr;   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ImportErrorr   r   r   r   r   r   r    r!   r"   r#   r$   r%   	_convert_r8   r&   r  r'   __members__itemsr  r8  Z_SSLv2_IF_EXISTSr7   r=   rH   rg   r   ry   rz   r{   r|   r}   r~   r   r   r   r  rI  r   r   Zsocket_errorru  r  ZHAS_NEVER_CHECK_COMMON_NAMEZ_RESTRICTED_SERVER_CIPHERSr   r   r   r   r   r   r   r   r   r   r   r  r  r  Z_create_default_https_contextr  r  r:  r;  r   r   r   r}  r  r  r  r  r  r  r,   r,   r,   r-   <module>   s   Y$0      
)
1#9 z #    /    :  

