
    hM                   ,   S SK Jr  S SKrS SKJr  S SKJr  S SKJr  S SK	J
r
  S SKJrJr  S SKJrJr  S S	KJr  S SKrS S
KJrJrJrJr  S SKJr  S SKJrJr  S SKJ r   S SK!J"r"J#r#  S SK$J%r%J&r&J'r'J(r(  S SK)J*r*  S SK+J,r,  S SK-J.r.J/r/  S SK0J1r1  S SK2J3r3  S SK4J5r5  SSK6J7r7  \*" 5       r8 " S S\5      r9\9Rt                  \Rv                  \9Rx                  \Rz                  \9R|                  \R~                  \9R                  \R                  \9R                  \C" \SS 5      0rDS rE " S S\F5      rGS rHS rIS  rJS! rK\K" 5       u  rLrMrN " S" S#\5      rO\OR                  \OR                  -  \OlQ        S$ rRS%S%S&S&S'S'S(S(S)S)S*S*S+S,.rS " S- S.\
\T\U4   5      rV\VrW " S/ S05      rXS1 rY " S2 S3\X5      rZ " S4 S5\X5      r[ " S6 S7\Z5      r\ " S8 S95      r] " S: S;\]5      r^ " S< S=\5      r_\" \_5       " S> S?5      5       r`S@ ra\" \_5       " SA SB5      5       rbSC rcSD rd\" \'5       " SE SF5      5       re   S`SSG.SH jjrf\" \(5       " SI SJ5      5       rg\/" \" SKSLS S 5      SM5      " \gR                  5      \glh        \/" \" SKSLS S 5      SM5      " \gR                  5      \gli        \" \&5      \R                  " SNSNSO9 " SP SQ5      5       5       rk\" SRSS9ST 5       rl\" SUSS9SV 5       rm\" \%5       " SW SX5      5       rn\nR                  SY5      rpSZrq " S[ S\5      rr " S] S^5      rsS_ rtg)a    )annotationsN)hexlify)	lru_cachemd5)Dict)	Interfaceimplementer)SSLcrypto)lib)FlagConstantFlagsNamedConstantNames)Version)isIPAddressisIPv6Address)Deferred)CertificateErrorVerifyError)IAcceptableCiphersICipherIOpenSSLClientConnectionCreatorIOpenSSLContextFactory)Logger)nativeString)_mutuallyExclusiveArguments
deprecated)Failure)secureRandom)nameToLabel   )
_idnaBytesc                  ^    \ rS rSrSr\" 5       r\" 5       r\" 5       r\" 5       r	\" 5       r
Srg)
TLSVersion*   z<
TLS versions that we can negotiate with the client/server.
 N)__name__
__module____qualname____firstlineno____doc__r   SSLv3TLSv1_0TLSv1_1TLSv1_2TLSv1_3__static_attributes__r(       b/root/1688_scrapy/alibaba-scraper/venv/lib/python3.13/site-packages/twisted/internet/_sslverify.pyr&   r&   *   s,     OEoGoGoGoGr4   r&   OP_NO_TLSv1_3c                   [        [        R                  5       5      nUSUR                  U 5        Vs/ s H  o3PM     nnU(       a2  UR	                  X"R                  U5      S  Vs/ s H  o3PM     sn5        U$ s  snf s  snf )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.
N)listr&   iterconstantsindexextend)oldestnewestversionsxexcludedVersionss        r5   _getExcludedTLSProtocolsrA   B   s     J,,./H#+,DhnnV.D#EF#Ea#EFH^^F5K5M,N O,Nq,N OP G !Ps   A<(Bc                      \ rS rSrSrSrg)SimpleVerificationErrorZ   z'
Not a very useful verification error.
r(   N)r)   r*   r+   r,   r-   r3   r(   r4   r5   rC   rC   Z   s    r4   rC   c                    U R                  5       R                  5       R                  nX!:w  a#  [        [	        U5      S-   [	        U5      -   5      eg)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
commonNamerC   repr)
connectionhostnamerH   s      r5   simpleVerifyHostnamerL   `   sJ    ( 002>>@KKJ%d:&6&=X&NOO r4   c                    [        S5      e)a  
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)rC   )rJ   rK   s     r5   simpleVerifyIPAddressrN   y   s     ""J
KKr4   c                H    S U R                  S5      SS  5       u  pX4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              3  8   #    U  H  n[        U5      v   M     g 7fN)int).0parts     r5   	<genexpr>#_usablePyOpenSSL.<locals>.<genexpr>   s     A*@$CII*@   .N   )r      )split)versionmajorminors      r5   _usablePyOpenSSLr_      s.     B'--*<Ra*@ALE>W$$r4   c                     Sn  SSK Jn  SSKJnJn  X#U4$ ! [
         a7  n[        R                  " S[        U5      -   S-   U -   [        SSS9   S	nAOS	nAff = f[        [        [        4$ )
z
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_identityra   service_identity.pyopensslrb   rc   ImportErrorwarningswarn_explicitstrUserWarningrL   rN   rC   )
whatsWrongra   rb   rc   es        r5   _selectVerifyImplementationrq      s    	9 
6Q3DDD 
)+.q625<< ?I	I !
	

  !68OOOs    
A-AAc                  8    \ rS rSrSr\" S5      r\" S5      rSrg)ProtocolNegotiationSupport   a  
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#   rY   r(   N)	r)   r*   r+   r,   r-   r   NPNALPNr3   r(   r4   r5   rs   rs      s    	 v
CDr4   rs   c                 `   [         R                  n [        R                  " [        R                  5      n UR                  S 5        U [         R                  -  n  UR                  S 5        U [         R                  -  n U $ ! [        [        4 a     N:f = f! [        [        4 a     U $ f = f)a]  
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                    g rQ   r(   cs    r5   <lambda>/protocolNegotiationMechanisms.<locals>.<lambda>   s    r4   c                    g rQ   r(   ry   s    r5   r{   r|      s    tr4   )rs   	NOSUPPORTr   ContextSSLv23_METHODset_npn_advertise_callbackru   AttributeErrorNotImplementedErrorset_alpn_select_callbackrv   )supportctxs     r5   protocolNegotiationMechanismsr      s     )22G
++c''
(C2&&~6 	-1113$$^4 	-222N /0  /0  Ns#   B B BBB-,B-rH   organizationNameorganizationalUnitNamelocalityNamestateOrProvinceNamecountryNameemailAddress)CNrH   Or   OUr   Lr   STr   Cr   r   c                  J    \ rS rSrSrSrS rS rS rSS jr	S r
S	 rS
 rSrg)DistinguishedNamei  a  
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                N    UR                  5        H  u  p#[        XU5        M     g rQ   )itemssetattr)selfkwkvs       r5   __init__DistinguishedName.__init__2  s    HHJDADQ r4   c                X    [          H   n[        XS 5      nUc  M  [        XU5        M"     g rQ   )
_x509namesgetattrr   )r   x509namenamevalues       r5   	_copyFromDistinguishedName._copyFrom6  s(    DHD1E E* r4   c                `    U R                  5        H  u  p#[        X[        U5      5        M     g rQ   )r   r   r   )r   r   r   r   s       r5   	_copyIntoDistinguishedName._copyInto<  s"    JJLDAHa1 !r4   c                8    S[         R                  U 5      SS -  $ )Nz<DN %s>r#   )dict__repr__r   s    r5   r   DistinguishedName.__repr__@  s    DMM$/"566r4   c                N     U [         U      $ ! [         a    [        U5      ef = frQ   )r   KeyErrorr   )r   attrs     r5   __getattr__DistinguishedName.__getattr__C  s1    	'
4()) 	' &&	's    $c                    U[         ;  a  [        U S35      e[         U   n[        U[        5      (       d  UR	                  S5      nX U'   g )Nz' is not a valid OpenSSL X509 name fieldascii)r   r   
isinstancebytesencode)r   r   r   realAttrs       r5   __setattr__DistinguishedName.__setattr__I  sI    z! D6)P!QRRd#%''LL)EXr4   c                n   / nSnS n[        U" [        5      5       HP  n[        U5      n[        [	        U5      U5      n[        XS5      nUc  M4  UR                  U[        U5      45        MR     US-  n[        U5       H!  u  nu  pXUR                  U5      S-   U-   X'   M#     SR                  U5      $ )zP
Return a multi-line, human-readable representation of this DN.

@rtype: L{str}
r   c                4    [        U R                  5       5      $ rQ   )setvalues)mappings    r5   uniqueValues/DistinguishedName.inspect.<locals>.uniqueValuesZ  s    w~~'((r4   NrY   z: 
)sortedr   r"   maxlenr   appendr   	enumeraterjustjoin)	r   llablenr   r   labelr   nattribs	            r5   inspectDistinguishedName.inspectQ  s     	) Z01ANEUV,F&A}%a12 2 	!"+A,A;;v&-6AD #/yy|r4   Nreturnrm   )r)   r*   r+   r,   r-   	__slots__r   r   r   r   r   r   r   r3   r(   r4   r5   r   r     s2    (T I +27'r4   r   c                  0    \ rS rSrSrS rS rS rS rSr	g)	CertBaseil  z
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                    Xl         g rQ   original)r   r   s     r5   r   CertBase.__init__u  s     r4   c                t    [        5       nUR                  [        U R                  SU-   5      " 5       5        U$ )Nget_)r   r   r   r   )r   suffixdns      r5   	_copyNameCertBase._copyNamex  s-     
WT]]FVO<>?	r4   c                $    U R                  S5      $ )z}
Retrieve the subject of this certificate.

@return: A copy of the subject of this certificate.
@rtype: L{DistinguishedName}
subjectr   r   s    r5   
getSubjectCertBase.getSubject}  s     ~~i((r4   c                L    U[         L a  [        U R                  /5      $ [        $ )a  
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   	interfaces     r5   __conform__CertBase.__conform__  s$     ))0$--AAr4   r   N)
r)   r*   r+   r,   r-   r   r   r   r   r3   r(   r4   r5   r   r   l  s    !
)r4   r   c                    [        UR                  5       SU S3S5      nUc  [        SR                  X5      5      eU" 5       nUc  [        SR                  X5      5      eU " U5      $ )z
(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certs        r5   _handleattrhelperr     s     Y((*d:,l,KTRF~@GG
 	

 8D|<CC
 	

 ;r4   c                      \ rS rSrSrSS jrSS jr\\R                  S4S j5       r
\
rS r\S 5       r\S	 5       r\S
 5       rS r\R                  4SS jjrS rSS jrS rS rS rS rSrg)Certificatei  z
An x509 certificate.
c                    SR                  U R                  R                  U R                  5       R	                  SS5      U R                  5       R	                  SS5      5      $ )Nz<{} Subject={} Issuer={}>rH   rd   )r   	__class__r)   r   get	getIssuerr   s    r5   r   Certificate.__repr__  sP    *11NN##OO!!,3NN  r2
 	
r4   c                z    [        U[        5      (       a!  U R                  5       UR                  5       :H  $ [        $ rQ   )r   r   dumpr   )r   others     r5   __eq__Certificate.__eq__  s,    e[))99;%**,..r4   r(   c                <    U " [         R                  " X!5      /UQ76 $ )zK
Load a certificate from an ASN.1- or PEM-format string.

@rtype: C{Class}
)r   load_certificate)r   requestDatar   argss       r5   loadCertificate.load  s     V,,VAIDIIr4   c                @    U R                  [        R                  5      $ )zD
Dump this certificate to a PEM-format data string.

@rtype: L{str}
)r   r   FILETYPE_PEMr   s    r5   dumpPEMCertificate.dumpPEM  s     yy,,--r4   c                B    U R                  U[        R                  5      $ )zE
Load a certificate from a PEM-format data string.

@rtype: C{Class}
)r  r   r  r   datas     r5   loadPEMCertificate.loadPEM  s     zz$ 3 344r4   c                    [        XS5      $ )z
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   s     r5   peerFromTransportCertificate.peerFromTransport       !6::r4   c                    [        XS5      $ )z
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  s     r5   hostFromTransportCertificate.hostFromTransport  r  r4   c                H    [        U R                  R                  5       5      $ )z@
Get the public key for this certificate.

@rtype: L{PublicKey}
)	PublicKeyr   
get_pubkeyr   s    r5   getPublicKeyCertificate.getPublicKey  s     11344r4   c                B    [         R                  " XR                  5      $ rQ   )r   dump_certificater   r   r   s     r5   r   Certificate.dump   s    &&v}}==r4   c                6    U R                   R                  5       $ )zA
Retrieve the serial number of this certificate.

@rtype: L{int}
)r   get_serial_numberr   s    r5   serialNumberCertificate.serialNumber  s     }}..00r4   c                8    U R                   R                  U5      $ )z
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   s     r5   r,  Certificate.digest  s     }}##F++r4   c                    SR                  SU R                  5       R                  5       SU R                  5       R                  5       SU R	                  5       -  S[        U R                  5       5      -  /5      $ )Nr   zCertificate For Subject:z
Issuer:z
Serial Number: %dz
Digest: %s)r   r   r   r   r)  r   r,  r   s    r5   _inspectCertificate._inspect  sh    yy*!))+ ((*%(9(9(;;|DKKM::	
 		
r4   c                |    SR                  U R                  5       U R                  5       R                  5       45      $ )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   s    r5   r   Certificate.inspect$  s0     yy$--/4+<+<+>+F+F+HIJJr4   c                $    U R                  S5      $ )z{
Retrieve the issuer of this certificate.

@rtype: L{DistinguishedName}
@return: A copy of the issuer of this certificate.
issuerr   r   s    r5   r   Certificate.getIssuer,  s     ~~h''r4   c                    [        S5      e)Nz'Possible, but doubtful we need this yet)r   )r   authoritiess     r5   optionsCertificate.options5  s    !"KLLr4   Nr   )r  objectr   bool)r   rR   r   r   r   )r)   r*   r+   r,   r-   r   r  classmethodr   FILETYPE_ASN1r  _loadr  r  r  r  r!  r   r)  r,  r/  r   r   r8  r3   r(   r4   r5   r   r     s    

 (.(<(<2 J J E. 5 5 ; ; ; ;5 "(!5!5 >1,

K(Mr4   r   c                  b    \ rS rSrSr\\R                  4S j5       r\R                  4S jr	Sr
g)CertificateRequesti9  z
An x509 certificate request.

Certificate requests are given to certificate authorities to be signed and
returned resulting in an actual certificate.
c                    [         R                  " X!5      n[        5       nUR                  UR	                  5       5        UR                  UR                  5       5      (       d  [        SU< S35      eU " U5      $ )NzCan't verify that request for z is self-signed.)r   load_certificate_requestr   r   rG   verifyr   r   )r   r  requestFormatreqr   s        r5   r  CertificateRequest.loadA  sc    --mI 
S__&'zz#..*++ >rfDTUVVSzr4   c                B    [         R                  " XR                  5      $ rQ   )r   dump_certificate_requestr   r%  s     r5   r   CertificateRequest.dumpJ  s    ..v}}EEr4   r(   N)r)   r*   r+   r,   r-   r<  r   r=  r  r   r3   r(   r4   r5   r@  r@  9  s5     /5/C/C   !.. Fr4   r@  c                  
   \ rS rSrSrSS jrS r\R                  4S jr	\
\R                  4S j5       rS rS r\
S	 5       r\
S
 5       rS r\R                  S4S jr\R                  \R                  4S jr  SS jrSrg)PrivateCertificateiN  z&
An x509 certificate and private key.
c                ^    [         R                  U 5      S-   [        U R                  5      -   $ )Nz with )r   r   rI   
privateKeyr   s    r5   r   PrivateCertificate.__repr__S  s&    ##D)H4tDOO7LLLr4   c                p    UR                  U R                  5       5      (       d  [        S5      eXl        U $ )Nz1Certificate public and private keys do not match.)matchesr!  r   rM  )r   rM  s     r5   _setPrivateKey!PrivateCertificate._setPrivateKeyV  s2    !!$"3"3"566QRR$r4   c                :    U R                  XR                  U5      $ )ze
Create a new L{PrivateCertificate} from the given certificate data and
this instance's private key.
)r  rM  r   newCertDatar   s      r5   newCertificate!PrivateCertificate.newCertificate\  s    
 yyoov>>r4   c                B    U R                  X5      R                  U5      $ rQ   )r>  rQ  )r   r  rM  r   s       r5   r  PrivateCertificate.loadc  s    {{4(77
CCr4   c                ~    SR                  [        R                  U 5      U R                  R	                  5       /5      $ )Nr   )r   r   r/  rM  r   r   s    r5   r   PrivateCertificate.inspectg  s.    yy+..t4doo6M6M6OPQQr4   c                    U R                  [        R                  5      U R                  R                  [        R                  5      -   $ )zQ
Dump both public and private parts of a private certificate to
PEM-format data.
)r   r   r  rM  r   s    r5   r  PrivateCertificate.dumpPEMj  s:    
 yy,,-0D0D1
 
 	
r4   c                    U R                  U[        R                  U[        R                  5      [        R                  5      $ )z^
Load both private and public parts of a private certificate from a
chunk of PEM-format data.
)r  KeyPairr   r  r  s     r5   r  PrivateCertificate.loadPEMs  s3     zz',,tV%8%896;N;N
 	
r4   c                H    U " UR                   5      nUR                  U5      $ rQ   )r   rQ  )r   certificateInstancerM  privcerts       r5   fromCertificateAndKeyPair,PrivateCertificate.fromCertificateAndKeyPair}  s$    ,556&&z22r4   c           
         [        U R                  R                  U R                  S9nU(       a;  UR                  [        [	        U Vs/ s H  o3R                  PM     sn5      S95        [        S0 UD6$ s  snf )z
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>}
rM  certificate)	trustRootr(   )r   rM  r   updater   OpenSSLCertificateOptions)r   r7  r8  auths       r5   r8  PrivateCertificate.options  sg     $//":":VNN;3>?;4;? )3733	 @s   	A6sha256c                V    U R                   R                  U R                  5       X5      $ rQ   )rM  certificateRequestr   )r   r   digestAlgorithms      r5   rp  %PrivateCertificate.certificateRequest  s%    11OOv
 	
r4   c                b    U R                  5       nU R                  R                  UUUUUU5      $ rQ   )r   rM  signCertificateRequest)r   r  verifyDNCallbackr)  rD  certificateFormatr4  s          r5   rt  )PrivateCertificate.signCertificateRequest  s9     "55
 	
r4   c                \    U R                   R                  U R                  5       UUUU5      $ rQ   )rM  signRequestObjectr   )r   rp  r)  secondsToExpiryrq  s        r5   ry  $PrivateCertificate.signRequestObject  s1     00OO
 	
r4   )rM  Nr   3rn  )r)   r*   r+   r,   r-   r   rQ  r   r=  rV  r<  r  r   r  r  rd  r8  rp  rt  ry  r3   r(   r4   r5   rK  rK  N  s    M 281E1E ? -3-A-A D DR
 
 
 3 34* )/(<(<h 
 ** ..
, + 
r4   rK  c                  :    \ rS rSrSrS rS rS
S jrS rS r	Sr
g	)r  i  aR  
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                    Xl         g)z^
@param osslpkey: The underlying pyOpenSSL key object.
@type osslpkey: L{OpenSSL.crypto.PKey}
Nr   )r   osslpkeys     r5   r   PublicKey.__init__  s	    
 !r4   c                D    U R                  5       UR                  5       :H  $ )z
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   otherKeys     r5   rP  PublicKey.matches  s     ||~!1!1!333r4   c                X    SU R                   R                   SU R                  5        S3$ )N< >)r   r)   r  r   s    r5   r   PublicKey.__repr__  s)    4>>**+1T\\^,<A>>r4   c                    [         R                  " [         R                  U R                  5      n[	        5       nUR                  U5        UR                  5       $ )a  
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   rj  	hexdigest)r   rawhs      r5   r  PublicKey.keyHash  s>      ##F$8$8$--HE	{{}r4   c                (    SU R                  5        3$ )NzPublic Key with Hash: r  r   s    r5   r   PublicKey.inspect  s    ''788r4   r   Nr   )r)   r*   r+   r,   r-   r   rP  r   r  r   r3   r(   r4   r5   r  r    s     
!
4?*9r4   r  c                     \ rS rSr\\R                  4S j5       r\R                  4S jr\	" \
" SSSS5      S5      S 5       r\	" \
" SSSS5      S5      S	 5       rS
 r\\R                  S4S j5       r\R                  4S jrSS jr\R                  S4S jr\R                  \R                  SS4S jr  SS jrS rSrg)r_  i  c                :    U " [         R                  " X!5      5      $ rQ   )r   load_privatekey)r   r  r   s      r5   r  KeyPair.load  s    V++F9::r4   c                B    [         R                  " XR                  5      $ rQ   )r   dump_privatekeyr   r%  s     r5   r   KeyPair.dump  s    %%fmm<<r4   Twisted   r   a real persistence systemc                "    U R                  5       $ rQ   )r   r   s    r5   __getstate__KeyPair.__getstate__  s    yy{r4   c                l    U R                  [        R                  " [        R                  U5      5        g rQ   )r   r   r  r=  r   states     r5   __setstate__KeyPair.__setstate__  s!    f,,V-A-A5IJr4   c                    U R                   R                  5       nU[        R                  :X  a  SnOU[        R                  :X  a  SnOSnU R                   R                  5       X R                  5       4nSU-  $ )NRSADSAz(Unknown Type!)z %s-bit %s Key Pair with Hash: %s)r   typer   TYPE_RSATYPE_DSAbitsr  )r   ttsr   s       r5   r   KeyPair.inspect
  sc    MM B&//!B"B]]!2||~61A55r4   i   c                ^    [         R                  " 5       nUR                  X5        U " U5      $ rQ   )r   PKeygenerate_key)r   kindsizepkeys       r5   generateKeyPair.generate  s%    {{}$%T{r4   c                .    [         R                  XU5      $ rQ   )rK  r  rT  s      r5   rV  KeyPair.newCertificate  s    !&&{&AAr4   rn  c                    [         R                  " 5       nUR                  U R                  5        UR	                  UR                  5       5        UR                  U R                  U5        [        U5      $ rQ   )r   X509Req
set_pubkeyr   r   rG   signr@  )r   distinguishedNamerq  rE  s       r5   requestObjectKeyPair.requestObject  sP    nnt}}%##COO$560!#&&r4   c                B    U R                  X5      R                  U5      $ )zv
Create a certificate request signed with this key.

@return: a string, formatted according to the 'format' argument.
)r  r   )r   r  r   rq  s       r5   rp  KeyPair.certificateRequest%  s!     !!"3EJJ6RRr4   r}  c	           	        ^ ^^^^^^^^ [         R                  X%5      mTR                  5       mT" T5      n	UUUUUUU UU4	S jn
[        U	[        5      (       a  U	R                  U
5      $ U
" U	5      $ )z
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                   >	 U (       d  [        SR                  T	T5      5      eTR                  TTTTT5      R                  T5      $ )Nz)DN callback {!r} rejected request DN {!r})r   r   ry  r   )
r   rv  rq  r   hlreqissuerDistinguishedNamerz  r   r)  ru  s
    r5   verified0KeyPair.signCertificateRequest.<locals>.verifiedF  sW    !?FF(" 
 ))' d$%&r4   )r@  r  r   r   r   addCallback)r   r  r  ru  r)  rD  rv  rz  rq  vvalr  r   r  s   `` `` ```  @@r5   rt  KeyPair.signCertificateRequest/  sb    $ #''C#	& 	& dH%%##H--D>!r4   c                   UR                   n[        R                  " 5       nUR                  UR	                  5       5        UR                  UR                  5       5        UR                  UR                  5       5        UR                  S5        UR                  U5        UR                  U5        UR                  U R                   U5        [        U5      $ )zG
Sign a CertificateRequest instance, returning a Certificate instance.
r   )r   r   X509r   
get_issuerset_subjectrG   r  r   gmtime_adj_notBeforegmtime_adj_notAfterset_serial_numberr  r   )r   r  r  r)  rz  rq  rE  r   s           r5   ry  KeyPair.signRequestObjectZ  s     $${{}))$//*;<*+()!!!$  1|,		$--14  r4   c                    [        S0 UD6n[        R                  U R                  X0R	                  U5      U5      U 5      $ )Nr(   )DNrK  rd  ry  r  )r   r)  r   r   s       r5   selfSignedCertKeyPair.selfSignedCertp  s=    X"X!;;""2'9'9"'=|Ld
 	
r4   r(   N)rn  r|  )r)   r*   r+   r,   r<  r   r=  r  r   r   r   r  r  r   r  r  rV  r  rp  rt  ry  r  r3   r(   r4   r5   r_  r_    s    !'!5!5 ; ; !.. = 	2q!,.IJ K 	2q!,.IJK KK	6 #__4  
 281E1E B' )/(<(<hS  ** ..* )"` + !,
r4   r_  c                      \ rS rSrSrS rSrg)r   iw  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                    g)a  
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(   )contexts    r5   _addCACertsToContext&IOpenSSLTrustRoot._addCACertsToContext      r4   r(   Nr)   r*   r+   r,   r-   r  r3   r(   r4   r5   r   r   w  s    
r4   r   c                  $    \ rS rSrSrS rS rSrg)r   i  zm
Trust an explicitly specified set of certificates, represented by a list of
L{OpenSSL.crypto.X509} objects.
c                    Xl         g)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   caCertss     r5   r   &OpenSSLCertificateAuthorities.__init__  s	      r4   c                l    UR                  5       nU R                   H  nUR                  U5        M     g rQ   )get_cert_storer  add_cert)r   r  storer   s       r5   r  2OpenSSLCertificateAuthorities._addCACertsToContext  s*    &&(MMDNN4  "r4   r  N)r)   r*   r+   r,   r-   r   r  r3   r(   r4   r5   r   r     s    
 !r4   r   c                    / nU  HA  n[        U[        5      (       a  UR                  nO[        S5      eUR	                  U5        MC     [        U5      $ )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   s      r5   trustRootFromCertificatesr    sT    $ EdH%%==DW  	T  )//r4   c                      \ rS rSrSrS rSrg)OpenSSLDefaultPathsi  z
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                $    UR                  5         g rQ   )set_default_verify_paths)r   r  s     r5   r  (OpenSSLDefaultPaths._addCACertsToContext  s    ((*r4   r(   Nr  r(   r4   r5   r  r    s    +r4   r  c                     [        5       $ )at  
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.
)r  r(   r4   r5   platformTrustr    s    F   r4   c                   ^  SU 4S jjnU$ )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                   > S n[         R                  S5       nT" XU5      nS S S 5        WR                  =nb  U R                  5       R	                  U5        U$ ! , (       d  f       N>= f)NzError during info_callback)_logfailuresHandledfailureget_app_datafailVerification)rJ   whereretresultopfwrappeds         r5   infoCallback%_tolerateErrors.<locals>.infoCallback'  s_    !!">?2Z4F @OA(##%66q9	 @?s   
A
A))rJ   zSSL.Connectionr  rR   r  rR   r   r:  r(   )r  r  s   ` r5   _tolerateErrorsr    s    * r4   c                  *    \ rS rSrSrS rS rS rSrg)ClientTLSOptionsi2  a  
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                N   X l         Xl        [        U5      (       d  [        U5      (       a  UR	                  S5      U l        SU l        O[        U5      U l        SU l        U R
                  R                  S5      U l	        UR                  [        U R                  5      5        g)z
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_callbackr  _identityVerifyingInfoCallback)r   rK   r   s      r5   r   ClientTLSOptions.__init__T  s     	!x  M($;$;"*//'":D&+D#",X"6D&*D#"1188Aod.Q.QRSr4   c                n    U R                   n[        R                  " US5      nUR                  U5        U$ )a  
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)r	  r   
Connectionset_app_data)r   tlsProtocolr  rJ   s       r5   clientConnectionForTLS'ClientTLSOptions.clientConnectionForTLSk  s1      ))^^GT2
,r4   c                   U[         R                  -  (       a-  U R                  (       a  UR                  U R                  5        gU[         R
                  -  (       a>   U R                  (       a  [        XR                  5        g[        XR                  5        gg! [         a.    [        5       nUR                  5       nUR                  U5         gf = f)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_STARTr  set_tlsext_host_namer  SSL_CB_HANDSHAKE_DONEverifyHostnamer  verifyIPAddressra   r    r  r  )r   rJ   r  r  r  r   s         r5   r  /ClientTLSOptions._identityVerifyingInfoCallback  s    $ 3---$2I2I++D,?,?@S....**":/B/BC#J0C0CD / % .I&335	**1-.s   &B B 5CC)r	  r
  r  r  r  N)	r)   r*   r+   r,   r-   r   r  r  r3   r(   r4   r5   r  r  2  s    @T.*.r4   r  )extraCertificateOptionsc               L   Uc  0 nUc
  [        5       n[        U [        5      (       d"  [        SU R                  R
                  -   5      eU(       a.  UR                  UR                  R                  UR                  S9  [        SUUS.UD6n[        XR                  5       5      $ )a5	  
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}
z6optionsForClientTLS requires text for host names, not rg  )ri  acceptableProtocolsr(   )r  r   rm   r  r   r)   rj  rM  r   rk  r  
getContext)rK   ri  clientCertificater!  r  certificateOptionss         r5   optionsForClientTLSr%    s    p &"$!O	h$$D  ))*
 	
 &&(33<<)22 	' 	
 3 / "
 H&C&C&EFFr4   c            
          \ rS rSrSr\R                  rSr\	\
R                     r\
R                  r\" SS/SS/SS/SS	/SS
/S
S	/SS//5                          SS j5       rS rS rS rS rSrg)rk  i  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 May 2022, TLSv1.2 is that safe default.
@type _defaultMinimumTLSVersion: L{TLSVersion} constant
Nri  requireCertificaterC  r  r   insecurelyLowerMinimumToraiseMinimumTolowerMaximumSecurityToc           
        USL USL :w  a  [        S5      eXl        X l        [        R                  [        R
                  -  [        R                  -  U l        [        R                  U l	        Uc  [        R                  U l        U(       a*  U(       a  UU:  a  [        S5      eUU R                  :  a  UnUc  U R                  nU(       a  UU:  a  UnU(       a  UU:  a  [        S5      e[        UU5      nU H  nU =R                  [        U   -  sl        M!     O [        R                   " S["        SS9  X0l        U(       a  U(       d  [        S5      eX@l        Ub  SX4;   a  [        S	5      eUb  Xl        O/ U l        XPl        X`l        Xpl        Xl        Xl        U	(       a4  U =R                  [        R2                  [        R4                  -  -  sl        Xl        Xl        U(       a#  U =R                  [        R:                  -  sl        Xl        U(       d#  U =R                  [        R>                  -  sl        Xl         [C        [        RD                  [F        [H        S
9U l%        Uc  [L        nSRO                  S URQ                  [S        SU R                  U R                  5      5       5       5      U l*        U RT                  S:X  a  [        S5      eUc  U R$                  (       a  [W        U5      nOSU l        SU l        [Y        U5      nUU l-        Ub  []        5       (       d  [_        S5      eUU l0        g)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{TLS_METHOD}, C{TLSv1_2_METHOD}, or C{TLSv1_2_METHOD} (or any
    future method constants provided by pyOpenSSL).  By default, a
    setting will be used which allows TLSv1.2 and TLSv1.3.  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              3  :   #    U  H  nUR                   v   M     g 7frQ   )fullName)rS   rz   s     r5   rU   5OpenSSLCertificateOptions.__init__.<locals>.<genexpr>5  s      &
 JJs   ALLrd   zGSupplied IAcceptableCiphers yielded no usable ciphers on this platform.Tz5No support for protocol negotiation on this platform.)1
ValueErrorrM  rh  r   OP_NO_SSLv2OP_NO_COMPRESSIONOP_CIPHER_SERVER_PREFERENCE_optionsMODE_RELEASE_BUFFERS_mode
TLS_METHODr   _defaultMinimumTLSVersionrA   _tlsDisableFlagsrk   warnDeprecationWarningrC  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   ri  r   r   _acceptableProtocols)r   rM  rh  r   rC  r  rB  r'  rC  rD  rG  rH  rJ  rA  acceptableCiphersrL  ri  r!  r)  r(  r*  r@   r\   s                          r5   r   "OpenSSLCertificateOptions.__init__  s   r $K4$78TUU$& OOc333c6U6UU 	 --
>..DK)n?U.U$1 
 "D$B$BB/=,'/+/+I+I(
 +03II/E, ',/EE - 
  8(*@  ,!1'!:: , MM, #
 !K'=  %$:2K*K@  %"0"$D&"4$#6 MMS11C4J4JJJM,,MMSZZ'M$8!#MMS---M(;&&# 
 $ . XX &
&44#E4;;F&
 
 #$ 
 {{9'B	DK&*D#))4I"*3P3R3R%G  %8!r4   c                d    U R                   R                  5       n US	 U$ ! [         a     U$ f = f)N_context)__dict__copyr   )r   ds     r5   r  &OpenSSLCertificateOptions.__getstate__Q  s@    MM 	*   		s   ! 
//c                    Xl         g rQ   )rZ  r  s     r5   r  &OpenSSLCertificateOptions.__setstate__Y  s    r4   c                ^    U R                   c  U R                  5       U l         U R                   $ )z*
Return an L{OpenSSL.SSL.Context} object.
)rY  _makeContextr   s    r5   r"  $OpenSSLCertificateOptions.getContext\  s(     ==  --/DM}}r4   c                   U R                  U R                  5      nUR                  U R                  5        UR	                  U R
                  5        U R                  bw  U R                  bj  UR                  U R                  5        UR                  U R                  5        U R                   H  nUR                  U5        M     UR                  5         [        R                  nU R                  (       as  [        R                   nU R"                  (       a  U[        R$                  -  nU R&                  (       a  U[        R(                  -  nU R*                  R-                  U5        UR/                  U5        U R0                  b  UR3                  U R0                  5        [5        [7        S5      5      nUR9                  U5        U R:                  (       a   UR=                  [        R>                  5        OUR=                  [        R@                  5        U RB                  (       a/  URE                  U RB                  RF                  RH                  5        URK                  U RL                  RO                  S5      5        U RP                  RS                  U5        U RT                  (       a  [W        XRT                  5        U$ )N   r   ),_contextFactoryr   set_optionsr9  set_moder;  rh  rM  use_certificateuse_privatekeyrA  add_extra_chain_certcheck_privatekeyr   VERIFY_NONErC  VERIFY_PEERr'  VERIFY_FAIL_IF_NO_PEER_CERTrC  VERIFY_CLIENT_ONCEri  r  
set_verifyrB  set_verify_depthr   r!   set_session_idrG  set_session_cache_modeSESS_CACHE_SERVERSESS_CACHE_OFFrL  load_tmp_dh_dhFilepathset_cipher_listrT  r   rP  configureECDHCurverU  _setAcceptableProtocols)r   r   	extraCertverifyFlagssessionIDContexts        r5   ra  &OpenSSLCertificateOptions._makeContextd  s   ""4;;/&TZZ 'DOO,G 0 01t/!00	((3 1   "oo;;//K&&s>>>s555NN//4{#'  !1!12 #<?3 	+,&&s'<'<=&&s'9'9:OOD--55::;D..55g>?**3/$$ $C)B)BC
r4   )rZ  rU  rT  rY  rP  r;  r9  r  rh  rL  rJ  rG  rD  rA  rH  r   rM  r'  ri  rC  rB  rC  )NNNFN	   TTTFFFNNNNNNNN)r)   r*   r+   r,   r-   r   r   re  rY  r>  r&   r2   _OP_NO_TLSv1_3r1   r=  r   r   r  r  r"  ra  r3   r(   r4   r5   rk  rk    s    ( kkOH%j&8&89N * 2 2 ./(#)$12'(9:/0	

  " !%#+y8
y8v	8r4   rk  r  r  r  T)frozenauto_attribsc                  $    \ rS rSr% SrS\S'   Srg)OpenSSLCipheri  z
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}
rm   r2  r(   N)r)   r*   r+   r,   r-   __annotations__r3   r(   r4   r5   r  r    s     Mr4   r      )maxsizec                (   [         R                  " U5      nUR                  U5         UR                  U R	                  S5      5        [         R                  " US5      nUR                  5       n[        US   [        5      (       a  [        S U 5       5      $ [        S U 5       5      $ ! [         R
                   aQ  nUR                  S   (       d  [        5       s SnA$ UR                  S   S   S   S:X  a  [        5       s SnA$ e SnAff = f)a6  
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.TLS_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   NrY   zno cipher matchc              3  8   #    U  H  n[        U5      v   M     g 7frQ   )r  rS   ciphers     r5   rU   &_expandCipherString.<locals>.<genexpr>  s     Av]6**rW   c              3  V   #    U  H  n[        UR                  S 5      5      v   M!     g7f)r   N)r  r  r  s     r5   rU   r    s!     Qv]6==#9::s   '))r   r   rf  ry  r   Errorr  tupler  get_cipher_listr   rm   )cipherStringr   r8  r   rp   conncipherss          r5   rS  rS    s    & ++f
COOGL//89 >>#t$D""$G'!*c""AAAAQQQQ! 99 

 vvay7N66!9Q<?//7N
s/    B, ,D DD#"DDDD   c                .   ^ [        U4S jU  5       5      $ )ah  
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  6   >#    U  H  oT;   d  M
  Uv   M     g 7frQ   r(   )rS   r  availableCipherss     r5   rU   !_selectCiphers.<locals>.<genexpr>  s     RmFAQ7Qms   		)r  )wantedCiphersr  s    `r5   _selectCiphersr    s     RmRRRr4   c                  4    \ rS rSrSrS rS r\S 5       rSr	g)OpenSSLAcceptableCiphersi  zF
A representation of ciphers that are acceptable for TLS connections.
c                $    [        U5      U l        g rQ   )r  _ciphers)r   r  s     r5   r   !OpenSSLAcceptableCiphers.__init__  s    gr4   c                @    [        U R                  [        U5      5      $ rQ   )r  r  r  )r   r  s     r5   rR  &OpenSSLAcceptableCiphers.selectCiphers  s    dmmU3C-DEEr4   c                    U " [        [        U5      [        R                  [        R                  [        R
                  -  5      5      $ )a  
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}
)rS  r   r   r<  r6  OP_NO_SSLv3)clsr  s     r5   fromOpenSSLCipherString0OpenSSLAcceptableCiphers.fromOpenSSLCipherString  s8    " \*#//1
 	
r4   )r  N)
r)   r*   r+   r,   r-   r   rR  r<  r  r3   r(   r4   r5   r  r    s&    'F 
 
r4   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                  6    \ rS rSrSrS rS rS rS rS r	Sr
g	)
rM  i/  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                   X l         X0l        US:  a  U R                  U l        g US:  a  U R                  U l        g  UR                  [        5      U l        U R                  U l        g ! [         a    U R                  U l         g f = f)Ni  i   )_openSSLlib_openSSLcrypto_configureOpenSSL110rz  _configureOpenSSL102get_elliptic_curve_defaultCurveName_ecCurve_configureOpenSSL101r5  _configureOpenSSL101NoCurves)r   openSSLVersionr.  r/  s       r5   r   *_ChooseDiffieHellmanEllipticCurve.__init__K  s    %+Z'&*&?&?D#z)&*&?&?D#D - @ @AR S +/*C*C'  L +/*K*K'Ls   A* *BBc                    g)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   r   s     r5   r  6_ChooseDiffieHellmanEllipticCurve._configureOpenSSL110\  r  r4   c                v    UR                   n U R                  R                  US5        g! [         a     gf = f)z
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)rY  r  SSL_CTX_set_ecdh_autoBaseException)r   r   ctxPtrs      r5   r  6_ChooseDiffieHellmanEllipticCurve._configureOpenSSL102d  s:     	2264@ 		s   + 
88c                \     UR                  U R                  5        g! [         a     gf = f)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  r  r  s     r5   r  6_ChooseDiffieHellmanEllipticCurve._configureOpenSSL101s  s+    	T]]+ 		s    
++c                    g)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  s     r5   r  >_ChooseDiffieHellmanEllipticCurve._configureOpenSSL101NoCurves  r  r4   )r  r  r  rz  N)r)   r*   r+   r,   r-   r   r  r  r  r  r3   r(   r4   r5   rM  rM  /  s!    6D"r4   rM  c                  .    \ rS rSrSrS r\S 5       rSrg)OpenSSLDiffieHellmanParametersi  zb
A representation of key generation parameters that are required for
Diffie-Hellman key exchange.
c                    Xl         g rQ   rw  )r   
parameterss     r5   r   'OpenSSLDiffieHellmanParameters.__init__  s    !r4   c                    U " U5      $ )aK  
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  filePaths     r5   fromFile'OpenSSLDiffieHellmanParameters.fromFile  s    * 8}r4   r  N)	r)   r*   r+   r,   r-   r   r<  r  r3   r(   r4   r5   r  r    s     
"  r4   r  c                ,  ^ U4S jnT(       d  g[        5       nU[        R                  -  (       a(  U4S jnU R                  U5        U R	                  U5        U[        R
                  -  (       a#  U R                  U5        U R                  T5        gg)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                X   > [        U5      [        T5      -  nT H  nX2;   d  M
  Us  $    g)a4  
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}
r4   )r   )r  	protocolsoverlappr!  s       r5   protoSelectCallback4_setAcceptableProtocols.<locals>.protoSelectCallback  s2     i.3':#;;$A| % r4   Nc                   > T$ rQ   r(   )r  r!  s    r5   npnAdvertiseCallback5_setAcceptableProtocols.<locals>.npnAdvertiseCallback  s	    &&r4   )r   rs   ru   r   set_npn_select_callbackrv   r   set_alpn_protos)r  r!  r  	supportedr  s    `   r5   r{  r{    s~    $0 -/I-111	' 	**+?@''(;<-222(()<= 34 3r4   )NNN)u
__future__r   rk   binasciir   	functoolsr   hashlibr   typingr   zope.interfacer	   r
   OpenSSLr   r   OpenSSL._utilr   rO  r   
constantlyr   r   r   r   incrementalr   twisted.internet.abstractr   r   twisted.internet.deferr   twisted.internet.errorr   r   twisted.internet.interfacesr   r   r   r   twisted.loggerr   twisted.python.compatr   twisted.python.deprecater   r   twisted.python.failurer    twisted.python.randbytesr!   twisted.python.utilr"   _idnar$   r  r&   r.   r  r/   OP_NO_TLSv1r0   OP_NO_TLSv1_1r1   OP_NO_TLSv1_2r2   r   r>  rA   	ExceptionrC   rL   rN   r_   rq   r  r  ra   rs   ru   r~   r   r   rm   r   r   r  r   r   r   r@  rK  r  r_  r   r   r  r  r  r  r  r%  rk  r  r  sr  rS  r  r  r  rQ  r  rM  r  r{  r(   r4   r5   <module>r     s  
 #      1  -  @ @  @ + @  " . L * 1 + x	 	 coo)))) _d;	 0i P2L
%"PJ 6Q5R 2!2   * ""%?%C%CC  $
> 	*
"6	"
0	 "
"aS%Z( aH & &R0IM( IMXF F*m
 m
`99 99xz
i z
z	 * ! !  !(0> + +  +C!L@ ,-j. j. .j.^ 	KG !KG\ #$m m %m` *4Ir1a "=*((**  & *4Ir1a "=*((**  &
 Wt$'	 	 ( 	 2&R &RR 3S S   "
 "
 !"
h *AA ! X Xv B95r4   