o
    b\                    @   s  d dl Z d dlmZ d dlmZ d dlmZ d dlmZm	Z	 d dl
mZmZ d dlmZ d dlZd dlmZmZmZmZ d d	lmZ d d
lmZmZ d dlmZ d dlmZmZ d dl m!Z!m"Z"m#Z#m$Z$ d dl%m&Z&m'Z' d dl(m)Z) d dl*m+Z+m,Z, d dl-m.Z. d dl/m0Z0 ddl1m2Z2 G dd deZ3e3j4ej5e3j6ej7e3j8ej9e3j:ej;e3j<e=edd iZ>dd Z?G dd de@ZAdd ZBdd ZCd d! ZDd"d# ZEeE \ZFZGZHG d$d% d%eZIeIjJeIjJA eI_Kd&d' ZLd(d(d)d)d*d*d+d+d,d,d-d-d.d/ZMG d0d1 d1eNZOeOZPG d2d3 d3ZQd4d5 ZRG d6d7 d7eQZSG d8d9 d9eQZTG d:d; d;eSZUG d<d= d=ZVG d>d? d?eVZWG d@dA dAeZXe	eXG dBdC dCZYdDdE ZZe	eXG dFdG dGZ[dHdI Z\dJdK Z]e	e#G dLdM dMZ^			dkddNdOdPZ_e	e$G dQdR dRZ`e,edSdTd d dUe`jae`_ae,edSdTd d dUe`jbe`_be	e"ejcdVdVdWG dXdY dYZdedZd[d\d] Zeed^d[d_d` Zfe	e!G dadb dbZgeghdcZiddZjG dedf dfZkG dgdh dhZldidj ZmdS )l    N)hexlify)	lru_cachemd5)	Interfaceimplementer)SSLcrypto)lib)FlagConstantFlagsNamedConstantNames)Version)isIPAddressisIPv6Address)Deferred)CertificateErrorVerifyError)IAcceptableCiphersICipherIOpenSSLClientConnectionCreatorIOpenSSLContextFactory)logutil)nativeString)_mutuallyExclusiveArguments
deprecated)Failure)secureRandom   )
_idnaBytesc                   @   s.   e Zd ZdZe Ze Ze Ze Ze Z	dS )
TLSVersionzD
    TLS versions that we can negotiate with the client/server.
    N)
__name__
__module____qualname____doc__r   SSLv3TLSv1_0TLSv1_1TLSv1_2TLSv1_3 r,   r,   =/usr/lib/python3/dist-packages/twisted/internet/_sslverify.pyr"   &   s    
r"   OP_NO_TLSv1_3c                 C   sR   t t }dd |d||  D }|r'|dd |||d D  |S )a  
    Given a pair of L{TLSVersion} constants, figure out what versions we want
    to disable (as OpenSSL is an exclusion based API).

    @param oldest: The oldest L{TLSVersion} we want to allow.
    @type oldest: L{TLSVersion} constant

    @param newest: The newest L{TLSVersion} we want to allow, or L{None} for no
        upper limit.
    @type newest: L{TLSVersion} constant or L{None}

    @return: The versions we want to disable.
    @rtype: L{list} of L{TLSVersion} constants.
    c                 S      g | ]}|qS r,   r,   .0xr,   r,   r-   
<listcomp>N       z,_getExcludedTLSProtocols.<locals>.<listcomp>Nc                 S   r/   r,   r,   r0   r,   r,   r-   r3   Q   r4   )listr"   iterconstantsindexextend)oldestnewestversionsexcludedVersionsr,   r,   r-   _getExcludedTLSProtocols>   s
   "r=   c                   @   s   e Zd ZdZdS )SimpleVerificationErrorz/
    Not a very useful verification error.
    N)r#   r$   r%   r&   r,   r,   r,   r-   r>   V   s    r>   c                 C   s2   |    j}||krtt|d t| dS )a  
    Check only the common name in the certificate presented by the peer and
    only for an exact match.

    This is to provide I{something} in the way of hostname verification to
    users who haven't installed C{service_identity}. This check is overly
    strict, relies on a deprecated TLS feature (you're supposed to ignore the
    commonName if the subjectAlternativeName extensions are present, I
    believe), and lots of valid certificates will fail.

    @param connection: the OpenSSL connection to verify.
    @type connection: L{OpenSSL.SSL.Connection}

    @param hostname: The hostname expected by the user.
    @type hostname: L{unicode}

    @raise twisted.internet.ssl.VerificationError: if the common name and
        hostname don't match.
    z!=N)get_peer_certificateget_subject
commonNamer>   repr)
connectionhostnamerA   r,   r,   r-   simpleVerifyHostname\   s   rE   c                 C      t d)a5  
    Always fails validation of IP addresses

    @param connection: the OpenSSL connection to verify.
    @type connection: L{OpenSSL.SSL.Connection}

    @param hostname: The hostname expected by the user.
    @type hostname: L{unicode}

    @raise twisted.internet.ssl.VerificationError: Always raised
    z&Cannot verify certificate IP addresses)r>   )rC   rD   r,   r,   r-   simpleVerifyIPAddressu   s   rG   c                 C   s,   dd |  ddd D \}}||fdkS )z
    Check pyOpenSSL version string whether we can use it for host verification.

    @param version: A pyOpenSSL version string.
    @type version: L{str}

    @rtype: L{bool}
    c                 s       | ]}t |V  qd S N)int)r1   partr,   r,   r-   	<genexpr>       z#_usablePyOpenSSL.<locals>.<genexpr>.N   )r      )split)versionmajorminorr,   r,   r-   _usablePyOpenSSL   s    	rU   c               
   C   s~   d} zddl m} ddlm}m} |||fW S  ty9 } ztjdt| d |  t	ddd W Y d	}~nd	}~ww t
ttfS )
a  
    Determine if C{service_identity} is installed. If so, use it. If not, use
    simplistic and incorrect checking as implemented in
    L{simpleVerifyHostname}.

    @return: 2-tuple of (C{verify_hostname}, C{VerificationError})
    @rtype: L{tuple}
    zWithout the service_identity module, Twisted can perform only rudimentary TLS client hostname verification.  Many valid certificate/hostname mappings may be rejected.r   )VerificationError)verify_hostnameverify_ip_addresszHYou do not have a working installation of the service_identity module: 'z'.  Please install it from <https://pypi.python.org/pypi/service_identity> and make sure all of its dependencies are satisfied.   )categoryfilenamelinenoN)service_identityrV   service_identity.pyopensslrW   rX   ImportErrorwarningswarn_explicitstrUserWarningrE   rG   r>   )
whatsWrongrV   rW   rX   er,   r,   r-   _selectVerifyImplementation   s,   
rf   c                   @   s    e Zd ZdZedZedZdS )ProtocolNegotiationSupporta  
    L{ProtocolNegotiationSupport} defines flags which are used to indicate the
    level of NPN/ALPN support provided by the TLS backend.

    @cvar NOSUPPORT: There is no support for NPN or ALPN. This is exclusive
        with both L{NPN} and L{ALPN}.
    @cvar NPN: The implementation supports Next Protocol Negotiation.
    @cvar ALPN: The implementation supports Application Layer Protocol
        Negotiation.
    r    rO   N)r#   r$   r%   r&   r   NPNALPNr,   r,   r,   r-   rg      s    rg   c               	   C   s   t j} ttj}z	|dd  W n ttfy   Y nw | t jO } z	|	dd  W n ttfy8   Y | S w | t j
O } | S )ay  
    Checks whether your versions of PyOpenSSL and OpenSSL are recent enough to
    support protocol negotiation, and if they are, what kind of protocol
    negotiation is supported.

    @return: A combination of flags from L{ProtocolNegotiationSupport} that
        indicate which mechanisms for protocol negotiation are supported.
    @rtype: L{constantly.FlagConstant}
    c                 S      d S rI   r,   cr,   r,   r-   <lambda>       z/protocolNegotiationMechanisms.<locals>.<lambda>c                 S   rj   rI   r,   rk   r,   r,   r-   rm      rn   )rg   	NOSUPPORTr   ContextSSLv23_METHODset_npn_advertise_callbackAttributeErrorNotImplementedErrorrh   set_alpn_select_callbackri   )supportctxr,   r,   r-   protocolNegotiationMechanisms   s    


rx   rA   organizationNameorganizationalUnitNamelocalityNamestateOrProvinceNamecountryNameemailAddress)CNrA   Ory   OUrz   Lr{   STr|   Cr}   r~   c                   @   sR   e Zd ZdZdZdd Zdd Zdd Zd	efd
dZ	dd Z
dd Zdd ZdS )DistinguishedNameag  
    Identify and describe an entity.

    Distinguished names are used to provide a minimal amount of identifying
    information about a certificate issuer or subject.  They are commonly
    created with one or more of the following fields::

        commonName (CN)
        organizationName (O)
        organizationalUnitName (OU)
        localityName (L)
        stateOrProvinceName (ST)
        countryName (C)
        emailAddress

    A L{DistinguishedName} should be constructed using keyword arguments whose
    keys can be any of the field names above (as a native string), and the
    values are either Unicode text which is encodable to ASCII, or L{bytes}
    limited to the ASCII subset. Any fields passed to the constructor will be
    set as attributes, accessible using both their extended name and their
    shortened acronym. The attribute values will be the ASCII-encoded
    bytes. For example::

        >>> dn = DistinguishedName(commonName=b'www.example.com',
        ...                        C='US')
        >>> dn.C
        b'US'
        >>> dn.countryName
        b'US'
        >>> hasattr(dn, "organizationName")
        False

    L{DistinguishedName} instances can also be used as dictionaries; the keys
    are extended name of the fields::

        >>> dn.keys()
        ['countryName', 'commonName']
        >>> dn['countryName']
        b'US'

    r,   c                 K   s"   |  D ]
\}}t| || qd S rI   )itemssetattr)selfkwkvr,   r,   r-   __init__1  s   zDistinguishedName.__init__c                 C   s.   t D ]}t||d }|d urt| || qd S rI   )
_x509namesgetattrr   )r   x509namenamevaluer,   r,   r-   	_copyFrom5  s   zDistinguishedName._copyFromc                 C   s&   |   D ]\}}t||t| qd S rI   )r   r   r   )r   r   r   r   r,   r,   r-   	_copyInto;  s   zDistinguishedName._copyIntoreturnc                 C   s   dt | dd  S )Nz<DN %s>r    )dict__repr__r   r,   r,   r-   r   ?  s   zDistinguishedName.__repr__c                 C   s&   z| t |  W S  ty   t|w rI   )r   KeyErrorrs   )r   attrr,   r,   r-   __getattr__B  s
   zDistinguishedName.__getattr__c                 C   s>   |t vrt| dt | }t|ts|d}|| |< d S )Nz' is not a valid OpenSSL X509 name fieldascii)r   rs   
isinstancebytesencode)r   r   r   realAttrr,   r,   r-   __setattr__H  s   

zDistinguishedName.__setattr__c           	      C   s   g }d}dd }t |tD ]!}t|}tt||}t| |d}|dur/||t|f q|d7 }t	|D ]\}\}}|
|d | ||< q8d|S )zh
        Return a multi-line, human-readable representation of this DN.

        @rtype: L{str}
        r   c                 S   s   t |  S rI   )setvalues)mappingr,   r,   r-   uniqueValuesY     z/DistinguishedName.inspect.<locals>.uniqueValuesNrO   z: 
)sortedr   r   nameToLabelmaxlenr   appendr   	enumeraterjustjoin)	r   llablenr   r   labelr   nattribr,   r,   r-   inspectP  s   

zDistinguishedName.inspectN)r#   r$   r%   r&   	__slots__r   r   r   rb   r   r   r   r   r,   r,   r,   r-   r     s    *r   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )CertBasez
    Base class for public (certificate only) and private (certificate + key
    pair) certificates.

    @ivar original: The underlying OpenSSL certificate object.
    @type original: L{OpenSSL.crypto.X509}
    c                 C   
   || _ d S rI   original)r   r   r,   r,   r-   r   t     
zCertBase.__init__c                 C   s"   t  }|t| jd|   |S )Nget_)r   r   r   r   )r   suffixdnr,   r,   r-   	_copyNamew  s   zCertBase._copyNamec                 C   
   |  dS )z
        Retrieve the subject of this certificate.

        @return: A copy of the subject of this certificate.
        @rtype: L{DistinguishedName}
        subjectr   r   r,   r,   r-   
getSubject|     
zCertBase.getSubjectc                 C   s   |t u r
t| jgS tS )aM  
        Convert this L{CertBase} into a provider of the given interface.

        @param interface: The interface to conform to.
        @type interface: L{zope.interface.interfaces.IInterface}

        @return: an L{IOpenSSLTrustRoot} provider or L{NotImplemented}
        @rtype: L{IOpenSSLTrustRoot} or L{NotImplemented}
        )IOpenSSLTrustRootOpenSSLCertificateAuthoritiesr   NotImplemented)r   	interfacer,   r,   r-   __conform__  s   
zCertBase.__conform__N)r#   r$   r%   r&   r   r   r   r   r,   r,   r,   r-   r   k  s    	r   c                 C   sV   t | d| dd}|du rtd||| }|du r'td||| |S )a  
    (private) Helper for L{Certificate.peerFromTransport} and
    L{Certificate.hostFromTransport} which checks for incompatible handle types
    and null certificates and raises the appropriate exception or returns the
    appropriate certificate object.
    r   _certificateNz2non-TLS transport {!r} did not have {} certificatez.TLS transport {!r} did not have {} certificate)r   	getHandler   format)Class	transport
methodNamemethodcertr,   r,   r-   _handleattrhelper  s   r   c                   @   s   e Zd ZdZdefddZdedefddZe	e
jdfd	d
ZeZdd Ze	dd Ze	dd Ze	dd Zdd Ze
jfddZdd Zd%ddZdd Zdd Zd d! Zd"d# Zd$S )&Certificatez
    An x509 certificate.
    r   c                 C   s   d | jj|  j|  jS )Nz<{} Subject={} Issuer={}>)r   	__class__r#   r   rA   	getIssuerr   r,   r,   r-   r     s
   zCertificate.__repr__otherc                 C   s   t |tr|  | kS tS rI   )r   r   dumpr   )r   r   r,   r,   r-   __eq__  s   
zCertificate.__eq__r,   c                 C   s   | t ||g|R  S )zc
        Load a certificate from an ASN.1- or PEM-format string.

        @rtype: C{Class}
        )r	   load_certificate)r   requestDatar   argsr,   r,   r-   load  s   zCertificate.loadc                 C   s   |  tjS )z\
        Dump this certificate to a PEM-format data string.

        @rtype: L{str}
        )r   r	   FILETYPE_PEMr   r,   r,   r-   dumpPEM  s   zCertificate.dumpPEMc                 C   s   |  |tjS )z]
        Load a certificate from a PEM-format data string.

        @rtype: C{Class}
        )r   r	   r   r   datar,   r,   r-   loadPEM  s   zCertificate.loadPEMc                 C      t | |dS )a	  
        Get the certificate for the remote end of the given transport.

        @param transport: an L{ISystemHandle} provider

        @rtype: C{Class}

        @raise CertificateError: if the given transport does not have a peer
            certificate.
        peerr   r   r   r,   r,   r-   peerFromTransport     zCertificate.peerFromTransportc                 C   r   )a  
        Get the certificate for the local end of the given transport.

        @param transport: an L{ISystemHandle} provider; the transport we will

        @rtype: C{Class}

        @raise CertificateError: if the given transport does not have a host
            certificate.
        hostr   r   r,   r,   r-   hostFromTransport  r   zCertificate.hostFromTransportc                 C   s   t | j S )zX
        Get the public key for this certificate.

        @rtype: L{PublicKey}
        )	PublicKeyr   
get_pubkeyr   r,   r,   r-   getPublicKey  s   zCertificate.getPublicKeyc                 C      t || jS rI   )r	   dump_certificater   r   r   r,   r,   r-   r        zCertificate.dumpc                 C   s
   | j  S )zY
        Retrieve the serial number of this certificate.

        @rtype: L{int}
        )r   get_serial_numberr   r,   r,   r-   serialNumber     
zCertificate.serialNumberr   c                 C   s   | j |S )a  
        Return a digest hash of this certificate using the specified hash
        algorithm.

        @param method: One of C{'md5'} or C{'sha'}.

        @return: The digest of the object, formatted as b":"-delimited hex
            pairs
        @rtype: L{bytes}
        )r   digest)r   r   r,   r,   r-   r   
  s   zCertificate.digestc                 C   s:   d d|   d|   d|   dt|   gS )Nr   zCertificate For Subject:z
Issuer:z
Serial Number: %dz
Digest: %s)r   r   r   r   r   r   r   r   r,   r,   r-   _inspect  s   


zCertificate._inspectc                 C   s   d |  |   fS )z
        Return a multi-line, human-readable representation of this
        Certificate, including information about the subject, issuer, and
        public key.
        r   )r   r   r   r   r   r,   r,   r-   r   #  s   zCertificate.inspectc                 C   r   )z
        Retrieve the issuer of this certificate.

        @rtype: L{DistinguishedName}
        @return: A copy of the issuer of this certificate.
        issuerr   r   r,   r,   r-   r   +  r   zCertificate.getIssuerc                 G   rF   )Nz'Possible, but doubtful we need this yet)rt   )r   authoritiesr,   r,   r-   options4  s   zCertificate.optionsNr   )r#   r$   r%   r&   rb   r   objectboolr   classmethodr	   FILETYPE_ASN1r   _loadr   r   r   r   r   r   r   r   r   r   r   r   r,   r,   r,   r-   r     s,    




	r   c                   @   s0   e Zd ZdZeejfddZejfddZdS )CertificateRequestz
    An x509 certificate request.

    Certificate requests are given to certificate authorities to be signed and
    returned resulting in an actual certificate.
    c                 C   sF   t ||}t }||  || std|d| |S )NzCan't verify that request for z is self-signed.)r	   load_certificate_requestr   r   r@   verifyr   r   )r   r   requestFormatreqr   r,   r,   r-   r   @  s   zCertificateRequest.loadc                 C   r   rI   )r	   dump_certificate_requestr   r   r,   r,   r-   r   I  r   zCertificateRequest.dumpN)	r#   r$   r%   r&   r   r	   r   r   r   r,   r,   r,   r-   r   8  s
    r   c                   @   s   e Zd ZdZdefddZdd ZejfddZ	e
ejfd	d
Zdd Zdd Ze
dd Ze
dd Zdd ZejdfddZejejfddZ		dddZdS )PrivateCertificatez.
    An x509 certificate and private key.
    r   c                 C   s   t | d t| j S )Nz with )r   r   rB   
privateKeyr   r,   r,   r-   r   R  s   zPrivateCertificate.__repr__c                 C   s    | |  std|| _| S )Nz1Certificate public and private keys do not match.)matchesr   r   r  )r   r  r,   r,   r-   _setPrivateKeyU  s   z!PrivateCertificate._setPrivateKeyc                 C   s   |  || j|S )z}
        Create a new L{PrivateCertificate} from the given certificate data and
        this instance's private key.
        )r   r  r   newCertDatar   r,   r,   r-   newCertificate[  s   z!PrivateCertificate.newCertificatec                 C      |  |||S rI   )r   r  )r   r   r  r   r,   r,   r-   r   b  s   zPrivateCertificate.loadc                 C   s   d t| | j gS )Nr   )r   r   r   r  r   r   r,   r,   r-   r   f     zPrivateCertificate.inspectc                 C   s   |  tj| j tj S )zi
        Dump both public and private parts of a private certificate to
        PEM-format data.
        )r   r	   r   r  r   r,   r,   r-   r   i  s   zPrivateCertificate.dumpPEMc                 C   s   |  |t |tjtjS )zv
        Load both private and public parts of a private certificate from a
        chunk of PEM-format data.
        )r   KeyPairr	   r   r   r,   r,   r-   r   r  s   zPrivateCertificate.loadPEMc                 C   s   | |j }||S rI   )r   r  )r   certificateInstancer  privcertr,   r,   r-   fromCertificateAndKeyPair|  s   

z,PrivateCertificate.fromCertificateAndKeyPairc                 G   sB   t | jj| jd}|r|t tdd |D d tdi |S )a$  
        Create a context factory using this L{PrivateCertificate}'s certificate
        and private key.

        @param authorities: A list of L{Certificate} object

        @return: A context factory.
        @rtype: L{CertificateOptions <twisted.internet.ssl.CertificateOptions>}
        r  certificatec                 S   s   g | ]}|j qS r,   r   )r1   authr,   r,   r-   r3     s    z.PrivateCertificate.options.<locals>.<listcomp>)	trustRootNr,   )r   r  r   updater   OpenSSLCertificateOptions)r   r   r   r,   r,   r-   r     s   
zPrivateCertificate.optionssha256c                 C   s   | j |  ||S rI   )r  certificateRequestr   )r   r   digestAlgorithmr,   r,   r-   r    s   
z%PrivateCertificate.certificateRequestc                 C   s   |   }| j||||||S rI   )r   r  signCertificateRequest)r   r   verifyDNCallbackr   r  certificateFormatr   r,   r,   r-   r    s   z)PrivateCertificate.signCertificateRequest3c                 C   s   | j |  ||||S rI   )r  signRequestObjectr   )r   r  r   secondsToExpiryr  r,   r,   r-   r    s   z$PrivateCertificate.signRequestObjectNr  r  )r#   r$   r%   r&   rb   r   r  r	   r   r
  r   r   r   r   r   r  r   r  r  r  r,   r,   r,   r-   r  M  s*    	
	


r  c                   @   s>   e Zd ZdZdd Zdd ZdefddZd	d
 Zdd Z	dS )r   an  
    A L{PublicKey} is a representation of the public part of a key pair.

    You can't do a whole lot with it aside from comparing it to other
    L{PublicKey} objects.

    @note: If constructing a L{PublicKey} manually, be sure to pass only a
        L{OpenSSL.crypto.PKey} that does not contain a private key!

    @ivar original: The original private key.
    c                 C   
   || _ dS )zv
        @param osslpkey: The underlying pyOpenSSL key object.
        @type osslpkey: L{OpenSSL.crypto.PKey}
        Nr   )r   osslpkeyr,   r,   r-   r     s   
zPublicKey.__init__c                 C   s   |   |  kS )a  
        Does this L{PublicKey} contain the same value as another L{PublicKey}?

        @param otherKey: The key to compare C{self} to.
        @type otherKey: L{PublicKey}

        @return: L{True} if these keys match, L{False} if not.
        @rtype: L{bool}
        keyHash)r   otherKeyr,   r,   r-   r    s   
zPublicKey.matchesr   c                 C   s   d| j j d|   dS )N< >)r   r#   r$  r   r,   r,   r-   r     r  zPublicKey.__repr__c                 C   s(   t t j| j}t }|| | S )at  
        Compute a hash of the underlying PKey object.

        The purpose of this method is to allow you to determine if two
        certificates share the same public key; it is not really useful for
        anything else.

        In versions of Twisted prior to 15.0, C{keyHash} used a technique
        involving certificate requests for computing the hash that was not
        stable in the face of changes to the underlying OpenSSL library.

        @return: Return a 32-character hexadecimal string uniquely identifying
            this public key, I{for this version of Twisted}.
        @rtype: native L{str}
        )r	   dump_publickeyr   r   r   r  	hexdigest)r   rawhr,   r,   r-   r$    s   
zPublicKey.keyHashc                 C   s   d|    S )NzPublic Key with Hash: r#  r   r,   r,   r-   r     r   zPublicKey.inspectN)
r#   r$   r%   r&   r   r  rb   r   r$  r   r,   r,   r,   r-   r     s    r   c                   @   s   e Zd ZeejfddZejfddZee	dddddd	d
 Z
ee	ddddddd Zdd ZeejdfddZejfddZd!ddZejdfddZejejddfddZ		d"ddZdd Zd S )#r  c                 C   s   | t ||S rI   )r	   load_privatekey)r   r   r   r,   r,   r-   r     s   zKeyPair.loadc                 C   r   rI   )r	   dump_privatekeyr   r   r,   r,   r-   r     r   zKeyPair.dumpTwisted   r   a real persistence systemc                 C   s   |   S rI   )r   r   r,   r,   r-   __getstate__  s   zKeyPair.__getstate__c                 C   s   |  ttj| d S rI   )r   r	   r-  r   r   stater,   r,   r-   __setstate__  s   zKeyPair.__setstate__c                 C   sJ   | j  }|tjkrd}n
|tjkrd}nd}| j  ||  f}d| S )NRSADSAz(Unknown Type!)z %s-bit %s Key Pair with Hash: %s)r   typer	   TYPE_RSATYPE_DSAbitsr$  )r   ttsr   r,   r,   r-   r   	  s   


zKeyPair.inspecti   c                 C   s   t  }||| | |S rI   )r	   PKeygenerate_key)r   kindsizepkeyr,   r,   r-   generate  s   zKeyPair.generatec                 C   s   t || |S rI   )r  r   r  r,   r,   r-   r
    r   zKeyPair.newCertificater  c                 C   s8   t  }|| j ||  || j| t|S rI   )r	   X509Req
set_pubkeyr   r   r@   signr   )r   distinguishedNamer  r  r,   r,   r-   requestObject  s
   zKeyPair.requestObjectc                 C   r  )z
        Create a certificate request signed with this key.

        @return: a string, formatted according to the 'format' argument.
        )rH  r   )r   rG  r   r  r,   r,   r-   r  $  s   zKeyPair.certificateRequestr  c	              	      sT   t || }	 f	dd}
t|	tr&|	|
S |
|	S )a&  
        Given a blob of certificate request data and a certificate authority's
        DistinguishedName, return a blob of signed certificate data.

        If verifyDNCallback returns a Deferred, I will return a Deferred which
        fires the data when that Deferred has completed.
        c                    s,   | s
t d S )Nz)DN callback {!r} rejected request DN {!r})r   r   r  r   )r   	r  r  r   hlreqissuerDistinguishedNamer  r   r   r  r,   r-   verifiedE  s   z0KeyPair.signCertificateRequest.<locals>.verified)r   r   r   r   r   addCallback)r   rK  r   r  r   r  r  r  r  vvalrL  r,   rI  r-   r  .  s   

zKeyPair.signCertificateRequestc                 C   sl   |j }t }||  ||  ||  |	d |
| || || j | t|S )zW
        Sign a CertificateRequest instance, returning a Certificate instance.
        r   )r   r	   X509r   
get_issuerset_subjectr@   rE  r   gmtime_adj_notBeforegmtime_adj_notAfterset_serial_numberrF  r   )r   rK  rH  r   r  r  r  r   r,   r,   r-   r  Y  s   


zKeyPair.signRequestObjectc                 K   s*   t di |}t| || ||| S )Nr,   )DNr  r  r  rH  )r   r   r   r   r,   r,   r-   selfSignedCerto  s   zKeyPair.selfSignedCertN)r  r   )r#   r$   r%   r   r	   r   r   r   r   r   r2  r5  r   r9  rC  r
  rH  r  r  r  rV  r,   r,   r,   r-   r    s0    




0
r  c                   @      e Zd ZdZdd ZdS )r   z
    Trust settings for an OpenSSL context.

    Note that this interface's methods are private, so things outside of
    Twisted shouldn't implement it.
    c                 C      dS )aI  
        Add certificate-authority certificates to an SSL context whose
        connections should trust those authorities.

        @param context: An SSL context for a connection which should be
            verified by some certificate authority.
        @type context: L{OpenSSL.SSL.Context}

        @return: L{None}
        Nr,   )contextr,   r,   r-   _addCACertsToContext~  rn   z&IOpenSSLTrustRoot._addCACertsToContextNr#   r$   r%   r&   rZ  r,   r,   r,   r-   r   v  s    r   c                   @   s    e Zd ZdZdd Zdd ZdS )r   zy
    Trust an explicitly specified set of certificates, represented by a list of
    L{OpenSSL.crypto.X509} objects.
    c                 C   r!  )z
        @param caCerts: The certificate authorities to trust when using this
            object as a C{trustRoot} for L{OpenSSLCertificateOptions}.
        @type caCerts: L{list} of L{OpenSSL.crypto.X509}
        N)_caCerts)r   caCertsr,   r,   r-   r     r   z&OpenSSLCertificateAuthorities.__init__c                 C   s"   |  }| jD ]}|| qd S rI   )get_cert_storer\  add_cert)r   rY  storer   r,   r,   r-   rZ    s   
z2OpenSSLCertificateAuthorities._addCACertsToContextN)r#   r$   r%   r&   r   rZ  r,   r,   r,   r-   r     s    r   c                 C   s:   g }| D ]}t |tr|j}ntd|| qt|S )a  
    Builds an object that trusts multiple root L{Certificate}s.

    When passed to L{optionsForClientTLS}, connections using those options will
    reject any server certificate not signed by at least one of the
    certificates in the `certificates` list.

    @since: 16.0

    @param certificates: All certificates which will be trusted.
    @type certificates: C{iterable} of L{CertBase}

    @rtype: L{IOpenSSLTrustRoot}
    @return: an object suitable for use as the trustRoot= keyword argument to
        L{optionsForClientTLS}
    zBcertificates items must be twisted.internet.ssl.CertBase instances)r   r   r   	TypeErrorr   r   )certificatescertsr   r,   r,   r-   trustRootFromCertificates  s   
rd  c                   @   rW  )OpenSSLDefaultPathsz
    Trust the set of default verify paths that OpenSSL was built with, as
    specified by U{SSL_CTX_set_default_verify_paths
    <https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_load_verify_locations.html>}.
    c                 C   s   |   d S rI   )set_default_verify_paths)r   rY  r,   r,   r-   rZ    r   z(OpenSSLDefaultPaths._addCACertsToContextNr[  r,   r,   r,   r-   re    s    re  c                   C   s   t  S )aD  
    Attempt to discover a set of trusted certificate authority certificates
    (or, in other words: trust roots, or root certificates) whose trust is
    managed and updated by tools outside of Twisted.

    If you are writing any client-side TLS code with Twisted, you should use
    this as the C{trustRoot} argument to L{CertificateOptions
    <twisted.internet.ssl.CertificateOptions>}.

    The result of this function should be like the up-to-date list of
    certificates in a web browser.  When developing code that uses
    C{platformTrust}, you can think of it that way.  However, the choice of
    which certificate authorities to trust is never Twisted's responsibility.
    Unless you're writing a very unusual application or library, it's not your
    code's responsibility either.  The user may use platform-specific tools for
    defining which server certificates should be trusted by programs using TLS.
    The purpose of using this API is to respect that decision as much as
    possible.

    This should be a set of trust settings most appropriate for I{client} TLS
    connections; i.e. those which need to verify a server's authenticity.  You
    should probably use this by default for any client TLS connection that you
    create.  For servers, however, client certificates are typically not
    verified; or, if they are, their verification will depend on a custom,
    application-specific certificate authority.

    @since: 14.0

    @note: Currently, L{platformTrust} depends entirely upon your OpenSSL build
        supporting a set of "L{default verify paths <OpenSSLDefaultPaths>}"
        which correspond to certificate authority trust roots.  Unfortunately,
        whether this is true of your system is both outside of Twisted's
        control and difficult (if not impossible) for Twisted to detect
        automatically.

        Nevertheless, this ought to work as desired by default on:

            - Ubuntu Linux machines with the U{ca-certificates
              <https://launchpad.net/ubuntu/+source/ca-certificates>} package
              installed,

            - macOS when using the system-installed version of OpenSSL (i.e.
              I{not} one installed via MacPorts or Homebrew),

            - any build of OpenSSL which has had certificate authority
              certificates installed into its default verify paths (by default,
              C{/usr/local/ssl/certs} if you've built your own OpenSSL), or

            - any process where the C{SSL_CERT_FILE} environment variable is
              set to the path of a file containing your desired CA certificates
              bundle.

        Hopefully soon, this API will be updated to use more sophisticated
        trust-root discovery mechanisms.  Until then, you can follow tickets in
        the Twisted tracker for progress on this implementation on U{Microsoft
        Windows <https://twistedmatrix.com/trac/ticket/6371>}, U{macOS
        <https://twistedmatrix.com/trac/ticket/6372>}, and U{a fallback for
        other platforms which do not have native trust management tools
        <https://twistedmatrix.com/trac/ticket/6934>}.

    @return: an appropriate trust settings object for your platform.
    @rtype: L{IOpenSSLTrustRoot}

    @raise NotImplementedError: if this platform is not yet supported by
        Twisted.  At present, only OpenSSL is supported.
    )re  r,   r,   r,   r-   platformTrust  s   Crg  c                    s    fdd}|S )a-  
    Wrap up an C{info_callback} for pyOpenSSL so that if something goes wrong
    the error is immediately logged and the connection is dropped if possible.

    This wrapper exists because some versions of pyOpenSSL don't handle errors
    from callbacks at I{all}, and those which do write tracebacks directly to
    stderr rather than to a supplied logging system.  This reports unexpected
    errors to the Twisted logging system.

    Also, this terminates the connection immediately if possible because if
    you've got bugs in your verification logic it's much safer to just give up.

    @param wrapped: A valid C{info_callback} for pyOpenSSL.
    @type wrapped: L{callable}

    @return: A valid C{info_callback} for pyOpenSSL that handles any errors in
        C{wrapped}.
    @rtype: L{callable}
    c                    sD   z | ||W S  t y!   t }t|d |  | Y d S w )NzError during info_callback)BaseExceptionr   r   errget_app_datafailVerification)rC   whereretfwrappedr,   r-   infoCallback&  s   z%_tolerateErrors.<locals>.infoCallbackr,   )rp  rq  r,   ro  r-   _tolerateErrors  s   rr  c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	ClientTLSOptionsa  
    Client creator for TLS.

    Private implementation type (not exposed to applications) for public
    L{optionsForClientTLS} API.

    @ivar _ctx: The context to use for new connections.
    @type _ctx: L{OpenSSL.SSL.Context}

    @ivar _hostname: The hostname to verify, as specified by the application,
        as some human-readable text.
    @type _hostname: L{unicode}

    @ivar _hostnameBytes: The hostname to verify, decoded into IDNA-encoded
        bytes.  This is passed to APIs which think that hostnames are bytes,
        such as OpenSSL's SNI implementation.
    @type _hostnameBytes: L{bytes}

    @ivar _hostnameASCII: The hostname, as transcoded into IDNA ASCII-range
        unicode code points.  This is pre-transcoded because the
        C{service_identity} package is rather strict about requiring the
        C{idna} package from PyPI for internationalized domain names, rather
        than working with Python's built-in (but sometimes broken) IDNA
        encoding.  ASCII values, however, will always work.
    @type _hostnameASCII: L{unicode}

    @ivar _hostnameIsDnsName: Whether or not the C{_hostname} is a DNSName.
        Will be L{False} if C{_hostname} is an IP address or L{True} if
        C{_hostname} is a DNSName
    @type _hostnameIsDnsName: L{bool}
    c                 C   sb   || _ || _t|st|r|d| _d| _nt|| _d| _| jd| _	|
t| j dS )a  
        Initialize L{ClientTLSOptions}.

        @param hostname: The hostname to verify as input by a human.
        @type hostname: L{unicode}

        @param ctx: an L{OpenSSL.SSL.Context} to use for new connections.
        @type ctx: L{OpenSSL.SSL.Context}.
        r   FTN)_ctx	_hostnamer   r   r   _hostnameBytes_hostnameIsDnsNamer!   decode_hostnameASCIIset_info_callbackrr  _identityVerifyingInfoCallback)r   rD   rw   r,   r,   r-   r   S  s   

zClientTLSOptions.__init__c                 C   s    | j }t|d}|| |S )ap  
        Create a TLS connection for a client.

        @note: This will call C{set_app_data} on its connection.  If you're
            delegating to this implementation of this method, don't ever call
            C{set_app_data} or C{set_info_callback} on the returned connection,
            or you'll break the implementation of various features of this
            class.

        @param tlsProtocol: the TLS protocol initiating the connection.
        @type tlsProtocol: L{twisted.protocols.tls.TLSMemoryBIOProtocol}

        @return: the configured client connection.
        @rtype: L{OpenSSL.SSL.Connection}
        N)rt  r   
Connectionset_app_data)r   tlsProtocolrY  rC   r,   r,   r-   clientConnectionForTLSj  s   
z'ClientTLSOptions.clientConnectionForTLSc                 C   s   |t j@ r| jr|| j dS |t j@ rAz| jr"t|| j W dS t|| j W dS  t	y@   t
 }| }|| Y dS w dS )a  
        U{info_callback
        <http://pythonhosted.org/pyOpenSSL/api/ssl.html#OpenSSL.SSL.Context.set_info_callback>
        } for pyOpenSSL that verifies the hostname in the presented certificate
        matches the one passed to this L{ClientTLSOptions}.

        @param connection: the connection which is handshaking.
        @type connection: L{OpenSSL.SSL.Connection}

        @param where: flags indicating progress through a TLS handshake.
        @type where: L{int}

        @param ret: ignored
        @type ret: ignored
        N)r   SSL_CB_HANDSHAKE_STARTrw  set_tlsext_host_namerv  SSL_CB_HANDSHAKE_DONEverifyHostnamery  verifyIPAddressrV   r   rj  rk  )r   rC   rl  rm  rn  r   r,   r,   r-   r{    s   
z/ClientTLSOptions._identityVerifyingInfoCallbackN)r#   r$   r%   r&   r   r  r{  r,   r,   r,   r-   rs  1  s
     rs  )extraCertificateOptionsc                C   sn   |du ri }|du rt  }t| tstd| jj |r&|j|jj|jd t	d||d|}t
| | S )a	  
    Create a L{client connection creator <IOpenSSLClientConnectionCreator>} for
    use with APIs such as L{SSL4ClientEndpoint
    <twisted.internet.endpoints.SSL4ClientEndpoint>}, L{connectSSL
    <twisted.internet.interfaces.IReactorSSL.connectSSL>}, and L{startTLS
    <twisted.internet.interfaces.ITLSTransport.startTLS>}.

    @since: 14.0

    @param hostname: The expected name of the remote host. This serves two
        purposes: first, and most importantly, it verifies that the certificate
        received from the server correctly identifies the specified hostname.
        The second purpose is to use the U{Server Name Indication extension
        <https://en.wikipedia.org/wiki/Server_Name_Indication>} to indicate to
        the server which certificate should be used.
    @type hostname: L{unicode}

    @param trustRoot: Specification of trust requirements of peers. This may be
        a L{Certificate} or the result of L{platformTrust}. By default it is
        L{platformTrust} and you probably shouldn't adjust it unless you really
        know what you're doing. Be aware that clients using this interface
        I{must} verify the server; you cannot explicitly pass L{None} since
        that just means to use L{platformTrust}.
    @type trustRoot: L{IOpenSSLTrustRoot}

    @param clientCertificate: The certificate and private key that the client
        will use to authenticate to the server. If unspecified, the client will
        not authenticate.
    @type clientCertificate: L{PrivateCertificate}

    @param acceptableProtocols: The protocols this peer is willing to speak
        after the TLS negotiation has completed, advertised over both ALPN and
        NPN. If this argument is specified, and no overlap can be found with
        the other peer, the connection will fail to be established. If the
        remote peer does not offer NPN or ALPN, the connection will be
        established, but no protocol wil be negotiated. Protocols earlier in
        the list are preferred over those later in the list.
    @type acceptableProtocols: L{list} of L{bytes}

    @param extraCertificateOptions: A dictionary of additional keyword arguments
        to be presented to L{CertificateOptions}. Please avoid using this unless
        you absolutely need to; any time you need to pass an option here that is
        a bug in this interface.
    @type extraCertificateOptions: L{dict}

    @return: A client connection creator.
    @rtype: L{IOpenSSLClientConnectionCreator}
    Nz6optionsForClientTLS requires text for host names, not r  )r  acceptableProtocolsr,   )rg  r   rb   ra  r   r#   r  r  r   r  rs  
getContext)rD   r  clientCertificater  r  certificateOptionsr,   r,   r-   optionsForClientTLS  s,   8
r  c                	   @   s   e Zd ZdZejZdZee	j
 Ze	jZeddgddgddgddgdd	gd	dgdd
gg																				dddZdd Zdd Zdd Zdd ZdS )r  a  
    A L{CertificateOptions <twisted.internet.ssl.CertificateOptions>} specifies
    the security properties for a client or server TLS connection used with
    OpenSSL.

    @ivar _options: Any option flags to set on the L{OpenSSL.SSL.Context}
        object that will be created.
    @type _options: L{int}

    @ivar _cipherString: An OpenSSL-specific cipher string.
    @type _cipherString: L{unicode}

    @ivar _defaultMinimumTLSVersion: The default TLS version that will be
        negotiated. This should be a "safe default", with wide client and
        server support, vs an optimally secure one that excludes a large number
        of users. As of late 2016, TLSv1.0 is that safe default.
    @type _defaultMinimumTLSVersion: L{TLSVersion} constant
    Nr  requireCertificater   r]  r   insecurelyLowerMinimumToraiseMinimumTolowerMaximumSecurityToF	   Tc              	   C   sX  |du |du krt d|| _|| _tjtjB tjB | _tj| _	|du rhtj
| _|r;|r4||kr4t d|| jkr;|}|du rJ| j}|rJ||krJ|}|rT||krTt dt||}|D ]}|  jt| O  _q[ntjdtdd || _|r{|s{t d|| _|durd||fv rt d	|dur|| _ng | _|| _|| _|| _|| _|	| _|	r|  jtjtjB O  _|
| _|| _|r|  jtjO  _|| _|s|  jtjO  _|| _ t!tj"t#t$d
| _%|du rt&}d'dd |(t)d| j| jD | _*| j*dkrt d|du r| jrt+|}n
d| _d| _t,|}|| _-|dur't. s't/d|| _0dS )a  
        Create an OpenSSL context SSL connection context factory.

        @param privateKey: A PKey object holding the private key.

        @param certificate: An X509 object holding the certificate.

        @param method: Deprecated, use a combination of
            C{insecurelyLowerMinimumTo}, C{raiseMinimumTo}, or
            C{lowerMaximumSecurityTo} instead.  The SSL protocol to use, one of
            C{SSLv23_METHOD}, C{SSLv2_METHOD}, C{SSLv3_METHOD}, C{TLSv1_METHOD}
            (or any other method constants provided by pyOpenSSL).  By default,
            a setting will be used which allows TLSv1.0, TLSv1.1, and TLSv1.2.
            Can not be used with C{insecurelyLowerMinimumTo},
            C{raiseMinimumTo}, or C{lowerMaximumSecurityTo}

        @param verify: Please use a C{trustRoot} keyword argument instead,
            since it provides the same functionality in a less error-prone way.
            By default this is L{False}.

            If L{True}, verify certificates received from the peer and fail the
            handshake if verification fails.  Otherwise, allow anonymous
            sessions and sessions with certificates which fail validation.

        @param caCerts: Please use a C{trustRoot} keyword argument instead,
            since it provides the same functionality in a less error-prone way.

            List of certificate authority certificate objects to use to verify
            the peer's certificate.  Only used if verify is L{True} and will be
            ignored otherwise.  Since verify is L{False} by default, this is
            L{None} by default.

        @type caCerts: L{list} of L{OpenSSL.crypto.X509}

        @param verifyDepth: Depth in certificate chain down to which to verify.
            If unspecified, use the underlying default (9).

        @param requireCertificate: Please use a C{trustRoot} keyword argument
            instead, since it provides the same functionality in a less
            error-prone way.

            If L{True}, do not allow anonymous sessions; defaults to L{True}.

        @param verifyOnce: If True, do not re-verify the certificate on session
            resumption.

        @param enableSingleUseKeys: If L{True}, generate a new key whenever
            ephemeral DH and ECDH parameters are used to prevent small subgroup
            attacks and to ensure perfect forward secrecy.

        @param enableSessions: This allows a shortened handshake to be used
            when a known client reconnects to the same process.  If True,
            enable OpenSSL's session caching.  Note that session caching only
            works on a single Twisted node at once.  Also, it is currently
            somewhat risky due to U{a crashing bug when using OpenSSL 1.1.1
            <https://twistedmatrix.com/trac/ticket/9764>}.

        @param fixBrokenPeers: If True, enable various non-spec protocol fixes
            for broken SSL implementations.  This should be entirely safe,
            according to the OpenSSL documentation, but YMMV.  This option is
            now off by default, because it causes problems with connections
            between peers using OpenSSL 0.9.8a.

        @param enableSessionTickets: If L{True}, enable session ticket
            extension for session resumption per RFC 5077.  Note there is no
            support for controlling session tickets.  This option is off by
            default, as some server implementations don't correctly process
            incoming empty session ticket extensions in the hello.

        @param extraCertChain: List of certificates that I{complete} your
            verification chain if the certificate authority that signed your
            C{certificate} isn't widely supported.  Do I{not} add
            C{certificate} to it.
        @type extraCertChain: C{list} of L{OpenSSL.crypto.X509}

        @param acceptableCiphers: Ciphers that are acceptable for connections.
            Uses a secure default if left L{None}.
        @type acceptableCiphers: L{IAcceptableCiphers}

        @param dhParameters: Key generation parameters that are required for
            Diffie-Hellman key exchange.  If this argument is left L{None},
            C{EDH} ciphers are I{disabled} regardless of C{acceptableCiphers}.
        @type dhParameters: L{DiffieHellmanParameters
            <twisted.internet.ssl.DiffieHellmanParameters>}

        @param trustRoot: Specification of trust requirements of peers.  If
            this argument is specified, the peer is verified.  It requires a
            certificate, and that certificate must be signed by one of the
            certificate authorities specified by this object.

            Note that since this option specifies the same information as
            C{caCerts}, C{verify}, and C{requireCertificate}, specifying any of
            those options in combination with this one will raise a
            L{TypeError}.

        @type trustRoot: L{IOpenSSLTrustRoot}

        @param acceptableProtocols: The protocols this peer is willing to speak
            after the TLS negotiation has completed, advertised over both ALPN
            and NPN.  If this argument is specified, and no overlap can be
            found with the other peer, the connection will fail to be
            established.  If the remote peer does not offer NPN or ALPN, the
            connection will be established, but no protocol wil be negotiated.
            Protocols earlier in the list are preferred over those later in the
            list.
        @type acceptableProtocols: L{list} of L{bytes}

        @param raiseMinimumTo: The minimum TLS version that you want to use, or
            Twisted's default if it is higher.  Use this if you want to make
            your client/server more secure than Twisted's default, but will
            accept Twisted's default instead if it moves higher than this
            value.  You probably want to use this over
            C{insecurelyLowerMinimumTo}.
        @type raiseMinimumTo: L{TLSVersion} constant

        @param insecurelyLowerMinimumTo: The minimum TLS version to use,
            possibly lower than Twisted's default.  If not specified, it is a
            generally considered safe default (TLSv1.0).  If you want to raise
            your minimum TLS version to above that of this default, use
            C{raiseMinimumTo}.  DO NOT use this argument unless you are
            absolutely sure this is what you want.
        @type insecurelyLowerMinimumTo: L{TLSVersion} constant

        @param lowerMaximumSecurityTo: The maximum TLS version to use.  If not
            specified, it is the most recent your OpenSSL supports.  You only
            want to set this if the peer that you are communicating with has
            problems with more recent TLS versions, it lowers your security
            when communicating with newer peers.  DO NOT use this argument
            unless you are absolutely sure this is what you want.
        @type lowerMaximumSecurityTo: L{TLSVersion} constant

        @raise ValueError: when C{privateKey} or C{certificate} are set without
            setting the respective other.
        @raise ValueError: when C{verify} is L{True} but C{caCerts} doesn't
            specify any CA certificates.
        @raise ValueError: when C{extraCertChain} is passed without specifying
            C{privateKey} or C{certificate}.
        @raise ValueError: when C{acceptableCiphers} doesn't yield any usable
            ciphers for the current platform.

        @raise TypeError: if C{trustRoot} is passed in combination with
            C{caCert}, C{verify}, or C{requireCertificate}.  Please prefer
            C{trustRoot} in new code, as its semantics are less tricky.
        @raise TypeError: if C{method} is passed in combination with
            C{tlsProtocols}.  Please prefer the more explicit C{tlsProtocols}
            in new code.

        @raises NotImplementedError: If acceptableProtocols were provided but
            no negotiation mechanism is available.
        Nz5Specify neither or both of privateKey and certificatez<raiseMinimumTo needs to be lower than lowerMaximumSecurityTozFinsecurelyLowerMinimumTo needs to be lower than lowerMaximumSecurityTozPassing method to twisted.internet.ssl.CertificateOptions was deprecated in Twisted 17.1.0. Please use a combination of insecurelyLowerMinimumTo, raiseMinimumTo, and lowerMaximumSecurityTo instead, as Twisted will correctly configure the method.   )
stacklevelzZSpecify client CA certificate information if and only if enabling certificate verificationzZA private key and a certificate are required when adding a supplemental certificate chain.)
openSSLlibopenSSLcrypto:c                 s   s    | ]}|j V  qd S rI   )fullName)r1   rl   r,   r,   r-   rL   4  s
    
z5OpenSSLCertificateOptions.__init__.<locals>.<genexpr>ALLrY   zGSupplied IAcceptableCiphers yielded no usable ciphers on this platform.Tz5No support for protocol negotiation on this platform.)1
ValueErrorr  r  r   OP_NO_SSLv2OP_NO_COMPRESSIONOP_CIPHER_SERVER_PREFERENCE_optionsMODE_RELEASE_BUFFERS_moderq   r   _defaultMinimumTLSVersionr=   _tlsDisableFlagsr`   warnDeprecationWarningr   extraCertChainr]  verifyDepthr  
verifyOnceenableSingleUseKeysOP_SINGLE_DH_USEOP_SINGLE_ECDH_USEenableSessionsfixBrokenPeersOP_ALLenableSessionTicketsOP_NO_TICKETdhParameters!_ChooseDiffieHellmanEllipticCurveOPENSSL_VERSION_NUMBERpyOpenSSLlibr	   
_ecChooserdefaultCiphersr   selectCiphers_expandCipherString_cipherStringr   r   r  rx   rt   _acceptableProtocols)r   r  r  r   r   r]  r  r  r  r  r  r  r  r  acceptableCiphersr  r  r  r  r  r  r<   rR   r,   r,   r-   r   
  s    :





z"OpenSSLCertificateOptions.__init__c                 C   s,   | j  }z|d= W |S  ty   Y |S w )N_context)__dict__copyr   )r   dr,   r,   r-   r2  P  s   
z&OpenSSLCertificateOptions.__getstate__c                 C   r   rI   )r  r3  r,   r,   r-   r5  X  r   z&OpenSSLCertificateOptions.__setstate__c                 C   s   | j du r
|  | _ | j S )z:
        Return an L{OpenSSL.SSL.Context} object.
        N)r  _makeContextr   r,   r,   r-   r  [  s   

z$OpenSSLCertificateOptions.getContextc                 C   sV  |  | j}|| j || j | jd ur7| jd ur7|| j |	| j | j
D ]}|| q+|  tj}| jrVtj}| jrH|tjO }| jrP|tjO }| j| dd }||| | jd urk|| j ttd}|| | jr|tj n|tj  | j!r|"| j!j#j$ |%| j&'d | j()| | j*rt+|| j* |S )Nc                 S   s   |S rI   r,   )connr   errnodepthpreverify_okr,   r,   r-   _verifyCallback|     z?OpenSSLCertificateOptions._makeContext.<locals>._verifyCallback   r   ),_contextFactoryr   set_optionsr  set_moder  r  r  use_certificateuse_privatekeyr  add_extra_chain_certcheck_privatekeyr   VERIFY_NONEr   VERIFY_PEERr  VERIFY_FAIL_IF_NO_PEER_CERTr  VERIFY_CLIENT_ONCEr  rZ  
set_verifyr  set_verify_depthr   r   set_session_idr  set_session_cache_modeSESS_CACHE_SERVERSESS_CACHE_OFFr  load_tmp_dh_dhFilepathset_cipher_listr  r   r  configureECDHCurver  _setAcceptableProtocols)r   rw   	extraCertverifyFlagsr  sessionIDContextr,   r,   r-   r  c  sB   




z&OpenSSLCertificateOptions._makeContext)NNNFNr  TTTFFFNNNNNNNN)r#   r$   r%   r&   r   rp   r  r  r  r"   r+   _OP_NO_TLSv1_3r(   r  r   r   r2  r5  r  r  r,   r,   r,   r-   r    sV    
  =r  r/  r0  r1  T)frozenauto_attribsc                   @   s   e Zd ZU dZeed< dS )OpenSSLCipherz
    A representation of an OpenSSL cipher.

    @ivar fullName: The full name of the cipher. For example
        C{u"ECDHE-RSA-AES256-GCM-SHA384"}.
    @type fullName: L{unicode}
    r  N)r#   r$   r%   r&   rb   __annotations__r,   r,   r,   r-   r    s   
 r      )maxsizec              
   C   s   t |}|| z
|| d W n0 t jyD } z#|jd s+t W  Y d}~S |jd d d dkr?t W  Y d}~S  d}~ww t |d}|	 }t
|d tr_tdd |D S tdd |D S )	ah  
    Expand C{cipherString} according to C{method} and C{options} to a tuple
    of explicit ciphers that are supported by the current platform.

    @param cipherString: An OpenSSL cipher string to expand.
    @type cipherString: L{unicode}

    @param method: An OpenSSL method like C{SSL.TLSv1_METHOD} used for
        determining the effective ciphers.

    @param options: OpenSSL options like C{SSL.OP_NO_SSLv3} ORed together.
    @type options: L{int}

    @return: The effective list of explicit ciphers that results from the
        arguments on the current platform.
    @rtype: L{tuple} of L{ICipher}
    r   r   NrO   zno cipher matchc                 s   rH   rI   )r  r1   cipherr,   r,   r-   rL     rM   z&_expandCipherString.<locals>.<genexpr>c                 s   s    | ]
}t |d V  qdS )r   N)r  rx  r  r,   r,   r-   rL     s    )r   rp   r  r  r   Errorr   tupler|  get_cipher_listr   rb   )cipherStringr   r   rw   re   r  ciphersr,   r,   r-   r    s"   


r     c                    s   t  fdd| D S )a  
    Caclulate the acceptable list of ciphers from the ciphers we want and the
    ciphers we have support for.

    @param wantedCiphers: The ciphers we want to use.
    @type wantedCiphers: L{tuple} of L{OpenSSLCipher}

    @param availableCiphers: The ciphers we have available to use.
    @type availableCiphers: L{tuple} of L{OpenSSLCipher}

    @rtype: L{tuple} of L{OpenSSLCipher}
    c                 3   s    | ]	}| v r|V  qd S rI   r,   r  availableCiphersr,   r-   rL     s    z!_selectCiphers.<locals>.<genexpr>)r  )wantedCiphersr  r,   r  r-   _selectCiphers  s   r  c                   @   s,   e Zd ZdZdd Zdd Zedd ZdS )	OpenSSLAcceptableCipherszN
    A representation of ciphers that are acceptable for TLS connections.
    c                 C   s   t || _d S rI   )r  _ciphers)r   r  r,   r,   r-   r     r   z!OpenSSLAcceptableCiphers.__init__c                 C   s   t | jt|S rI   )r  r  r  )r   r  r,   r,   r-   r    s   z&OpenSSLAcceptableCiphers.selectCiphersc                 C   s   | t t|tjtjtjB S )aR  
        Create a new instance using an OpenSSL cipher string.

        @param cipherString: An OpenSSL cipher string that describes what
            cipher suites are acceptable.
            See the documentation of U{OpenSSL
            <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_STRINGS>} or
            U{Apache
            <http://httpd.apache.org/docs/2.4/mod/mod_ssl.html#sslciphersuite>}
            for details.
        @type cipherString: L{unicode}

        @return: Instance representing C{cipherString}.
        @rtype: L{twisted.internet.ssl.AcceptableCiphers}
        )r  r   r   rq   r  OP_NO_SSLv3)clsr  r,   r,   r-   fromOpenSSLCipherString  s   
z0OpenSSLAcceptableCiphers.fromOpenSSLCipherStringN)r#   r$   r%   r&   r   r  r   r  r,   r,   r,   r-   r    s    r  zTLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-128-GCM-SHA256:ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS
prime256v1c                   @   s8   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdS )r  a  
    Chooses the best elliptic curve for Elliptic Curve Diffie-Hellman
    key exchange, and provides a C{configureECDHCurve} method to set
    the curve, when appropriate, on a new L{OpenSSL.SSL.Context}.

    The C{configureECDHCurve} method will be set to one of the
    following based on the provided OpenSSL version and configuration:

        - L{_configureOpenSSL110}

        - L{_configureOpenSSL102}

        - L{_configureOpenSSL101}

        - L{_configureOpenSSL101NoCurves}.

    @param openSSLVersion: The OpenSSL version number.
    @type openSSLVersion: L{int}

    @see: L{OpenSSL.SSL.OPENSSL_VERSION_NUMBER}

    @param openSSLlib: The OpenSSL C{cffi} library module.
    @param openSSLcrypto: The OpenSSL L{crypto} module.

    @see: L{crypto}
    c                 C   sn   || _ || _|dkr| j| _d S |dkr| j| _d S z|t| _W n ty0   | j	| _Y d S w | j
| _d S )Ni  i   )_openSSLlib_openSSLcrypto_configureOpenSSL110r  _configureOpenSSL102get_elliptic_curve_defaultCurveName_ecCurver  _configureOpenSSL101NoCurves_configureOpenSSL101)r   openSSLVersionr  r  r,   r,   r-   r   P  s   z*_ChooseDiffieHellmanEllipticCurve.__init__c                 C   rX  )z
        OpenSSL 1.1.0 Contexts are preconfigured with an optimal set
        of ECDH curves.  This method does nothing.

        @param ctx: L{OpenSSL.SSL.Context}
        Nr,   r   rw   r,   r,   r-   r  a  rn   z6_ChooseDiffieHellmanEllipticCurve._configureOpenSSL110c                 C   s0   |j }z
| j|d W dS  ty   Y dS w )a  
        Have the context automatically choose elliptic curves for
        ECDH.  Run on OpenSSL 1.0.2 and OpenSSL 1.1.0+, but only has
        an effect on OpenSSL 1.0.2.

        @param ctx: The context which .
        @type ctx: L{OpenSSL.SSL.Context}
        TN)r  r  SSL_CTX_set_ecdh_autorh  )r   rw   ctxPtrr,   r,   r-   r  i  s   	z6_ChooseDiffieHellmanEllipticCurve._configureOpenSSL102c                 C   s(   z	| | j W dS  ty   Y dS w )z
        Set the default elliptic curve for ECDH on the context.  Only
        run on OpenSSL 1.0.1.

        @param ctx: The context on which to set the ECDH curve.
        @type ctx: L{OpenSSL.SSL.Context}
        N)set_tmp_ecdhr  rh  r  r,   r,   r-   r  x  s
   z6_ChooseDiffieHellmanEllipticCurve._configureOpenSSL101c                 C   rX  )z
        No elliptic curves are available on OpenSSL 1.0.1. We can't
        set anything, so do nothing.

        @param ctx: The context on which to set the ECDH curve.
        @type ctx: L{OpenSSL.SSL.Context}
        Nr,   r  r,   r,   r-   r    rn   z>_ChooseDiffieHellmanEllipticCurve._configureOpenSSL101NoCurvesN)	r#   r$   r%   r&   r   r  r  r  r  r,   r,   r,   r-   r  4  s    r  c                   @   s$   e Zd ZdZdd Zedd ZdS )OpenSSLDiffieHellmanParameterszn
    A representation of key generation parameters that are required for
    Diffie-Hellman key exchange.
    c                 C   r   rI   )r  )r   
parametersr,   r,   r-   r     r   z'OpenSSLDiffieHellmanParameters.__init__c                 C   s   | |S )a  
        Load parameters from a file.

        Such a file can be generated using the C{openssl} command line tool as
        following:

        C{openssl dhparam -out dh_param_2048.pem -2 2048}

        Please refer to U{OpenSSL's C{dhparam} documentation
        <http://www.openssl.org/docs/apps/dhparam.html>} for further details.

        @param filePath: A file containing parameters for Diffie-Hellman key
            exchange.
        @type filePath: L{FilePath <twisted.python.filepath.FilePath>}

        @return: An instance that loads its parameters from C{filePath}.
        @rtype: L{DiffieHellmanParameters
            <twisted.internet.ssl.DiffieHellmanParameters>}
        r,   )r  filePathr,   r,   r-   fromFile  s   z'OpenSSLDiffieHellmanParameters.fromFileN)r#   r$   r%   r&   r   r   r  r,   r,   r,   r-   r    s
    r  c                    sj    fdd} s
dS t  }|tj@ r" fdd}| | | | |tj@ r3| | |   dS dS )a  
    Called to set up the L{OpenSSL.SSL.Context} for doing NPN and/or ALPN
    negotiation.

    @param context: The context which is set up.
    @type context: L{OpenSSL.SSL.Context}

    @param acceptableProtocols: The protocols this peer is willing to speak
        after the TLS negotiation has completed, advertised over both ALPN and
        NPN. If this argument is specified, and no overlap can be found with
        the other peer, the connection will fail to be established. If the
        remote peer does not offer NPN or ALPN, the connection will be
        established, but no protocol wil be negotiated. Protocols earlier in
        the list are preferred over those later in the list.
    @type acceptableProtocols: L{list} of L{bytes}
    c                    s.   t |t  @ } D ]
}||v r|  S q
dS )at  
        NPN client-side and ALPN server-side callback used to select
        the next protocol. Prefers protocols found earlier in
        C{_acceptableProtocols}.

        @param conn: The context which is set up.
        @type conn: L{OpenSSL.SSL.Connection}

        @param conn: Protocols advertised by the other side.
        @type conn: L{list} of L{bytes}
            )r   )r  	protocolsoverlappr  r,   r-   protoSelectCallback  s   z4_setAcceptableProtocols.<locals>.protoSelectCallbackNc                    s    S rI   r,   )r  r  r,   r-   npnAdvertiseCallback  r  z5_setAcceptableProtocols.<locals>.npnAdvertiseCallback)rx   rg   rh   rr   set_npn_select_callbackri   ru   set_alpn_protos)rY  r  r  	supportedr  r,   r  r-   r    s   




r  )NNN)nr`   binasciir   	functoolsr   hashlibr   zope.interfacer   r   OpenSSLr   r	   OpenSSL._utilr
   r  r   
constantlyr   r   r   r   incrementalr   twisted.internet.abstractr   r   twisted.internet.deferr   twisted.internet.errorr   r   twisted.internet.interfacesr   r   r   r   twisted.pythonr   r   twisted.python.compatr   twisted.python.deprecater   r   twisted.python.failurer   twisted.python.randbytesr   _idnar!   r"   r'   r  r(   OP_NO_TLSv1r)   OP_NO_TLSv1_1r*   OP_NO_TLSv1_2r+   r   r  r=   	Exceptionr>   rE   rG   rU   rf   r  r  rV   rg   rh   ro   rx   r   r   r   rU  r   r   r   r   r  r   r  r   r   rd  re  rg  rr  rs  r  r  r2  r5  sr  r  r  r  r  r  r  r  r  r  r,   r,   r,   r-   <module>   s   (
d) p<}F oN   9
)
4[!