
    F2j                      U d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
mZ d dlmZ d dlmZmZ d dlmZ d dlmZ d dlmZ d d	lmZmZmZmZmZmZmZ d
dlm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8 d
dlm9Z:  ej;        d          Z<	 d dl=Z>n# e?$ r 	 d dl@Z>n# e?$ r dZ>Y nw xY wY nw xY wdZAdZBdZCdZDddZEddZF ed          ZGd dD             ZHdddZI G d d e          ZJ G d! d"eK          ZL G d# d$eL          ZM G d% d&eL          ZN G d' d(eL          ZO G d) d*eL          ZP G d+ d,eL          ZQ G d- d.eL          ZR G d/ d0eL          ZS G d1 d2eL          ZT G d3 d4eL          ZU G d5 d6eL          ZV G d7 d8eL          ZW G d9 d:e          ZX G d; d<e          ZY G d= d>e          ZZeZj[        eYj\        eZj]        eYj^        eZj_        eYj^        eZj`        eYj^        eZja        eYj^        eZjb        eYj^        eZjc        eYjd        eZje        eYj\        eZjf        eYj^        eZjg        eYjd        i
Zhd?eid@<    G dA dB          ZjddGZkddJZlddMZm	 dddRZnddTZoddVZpddYZq	 	 	 d dd^Zr	 	 	 	 	 	 	 dddfZs G dg dhe          Zt G di dje          Zu G dk dle          Zv G dm dne          Zw G do dpe          Zx G dq dre          Zy G ds dte          Zz G du dve          Z{edd{            Z|edd|            Z}ddZ~ddZddZddZed	d            Zd
dZddZeeef         ZddZddZd
dZddZeeef         ZddZddZddZddZe G d d                      Ze G d d                      ZddZdZd
Zh dZddZeeef         Ze G d d                      Ze G d d                      ZddZddZddZe G d d                      ZddZddZe G d d                      ZddZddZe G d d                      ZddZddZeeef         Ze G d d                      Z9e G d d                      ZddZddZd dZe G d dæ                      Zd!dĄZd"dƄZe G dǄ dȦ                      Zd#dɄZd$d˄Z G d̄ dͦ          Z G d΄ dϦ          Zetj        detj        detj        diZe{j        de{j        de{j        de{j        de{j        de{j        de{j        de{j        de{j        di	Zdeid<   d%dބZ	 	 	 d d&dZÐd'dZed(d            Ze G d d                      Zeegdf         Zeegee         f         Zeegdf         Zʐd)dZ G d d          ZdS (*      )annotationsN)	unhexlify)contextmanager)	dataclassfield)IntEnum)partial)HMAC)AnyCallable	GeneratorOptionalSequenceTupleTypeVar   )BufferBufferReadErrorCryptoErrorDsaPrivateKeyECDHP256KeyExchangeECDHP384KeyExchangeECDHP521KeyExchangeEcPrivateKeyEd25519PrivateKeyExpiredCertificateErrorHpkeContextInvalidNameCertificateErrorKeyTypePrivateKeyInfoRsaPrivateKeySelfSignedCertificateErrorServerVerifierSignatureErrorUnacceptableCertificateErrorX25519KeyExchangeX25519ML768KeyExchangeclassify_certificates_deridna_encoderebuild_chainverify_with_public_key)Certificatez^[0-9a-fA-F]{8}\.[0-9]$   i  i    returnintc                 V    t          j        d          d         } | dz  dz  }|dz  |z  S )zGenerate a random GREASE value of the form 0xNaNa (RFC 8701).

    GREASE values are: 0x0A0A, 0x1A1A, 0x2A2A, ..., 0xFAFA (16 possible).
    This matches BoringSSL/Chrome's grease_index_to_value().
    r   r      
      )osurandom)seedlos     O/home/thesage/.hermes/hermes-agent/venv/lib/python3.11/site-packages/qh3/tls.py_generate_grease_valuer:   I   s2     :a==D
+	B!Gr>    vboolc                ,    | dz	  | dz  k    o| dz  dk    S )zCheck if a value is a GREASE value (0xNaNa form per RFC 8701).

    A GREASE value has both bytes equal and of the form 0xNa,
    i.e. low nibble is 0x0A: 0x0A0A, 0x1A1A, ..., 0xFAFA.
    r4         r3    )r<   s    r9   _is_grease_valuerB   T   s%     FD!8q4xD&88r;   Tc                B    i | ]\  }}|t          t          |d           S N)getattrhashlib).0length	algorithms      r9   
<dictcomp>rK   `   s:       	 GGY--  r;   ))    md5)(   sha1)@   sha256T	remove_tzdatetime.datetimec                    t           j                             t           j        j                  }| r|                    d           n|S )N)tzinfo)datetimenowtimezoneutcreplace)rR   dts     r9   utcnowr\   k   s<    				x04	5	5B&/72::T:"""R7r;   c                  ~    e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdS )AlertDescriptionr   r3         rN   *   +   ,   -   .   /   0   1   2   3   F   G   P   V   Z   m   n   p   q   s   t   x   y   N)__name__
__module____qualname__close_notifyunexpected_messagebad_record_macrecord_overflowhandshake_failurebad_certificateunsupported_certificatecertificate_revokedcertificate_expiredcertificate_unknownillegal_parameter
unknown_caaccess_denieddecode_errordecrypt_errorprotocol_versioninsufficient_securityinternal_errorinappropriate_fallbackuser_canceledmissing_extensionunsupported_extensionunrecognized_namebad_certificate_status_responseunknown_psk_identitycertificate_requiredno_application_protocolech_requiredrA   r;   r9   r^   r^   p   s        LNOO JMLMNM&)#!LLLr;   r^   c                      e Zd ZU ded<   dS )Alertr^   descriptionNrx   ry   rz   __annotations__rA   r;   r9   r   r      s         !!!!!!r;   r   c                      e Zd Zej        ZdS )AlertBadCertificateN)rx   ry   rz   r^   r   r   rA   r;   r9   r   r      s        "2KKKr;   r   c                      e Zd Zej        ZdS )AlertCertificateExpiredN)rx   ry   rz   r^   r   r   rA   r;   r9   r   r      s        "6KKKr;   r   c                      e Zd Zej        ZdS )AlertDecodeErrorN)rx   ry   rz   r^   r   r   rA   r;   r9   r   r              "/KKKr;   r   c                      e Zd Zej        ZdS )AlertDecryptErrorN)rx   ry   rz   r^   r   r   rA   r;   r9   r   r      s        "0KKKr;   r   c                      e Zd Zej        ZdS )AlertHandshakeFailureN)rx   ry   rz   r^   r   r   rA   r;   r9   r   r              "4KKKr;   r   c                      e Zd Zej        ZdS )AlertIllegalParameterN)rx   ry   rz   r^   r   r   rA   r;   r9   r   r      r   r;   r   c                      e Zd Zej        ZdS )AlertInternalErrorN)rx   ry   rz   r^   r   r   rA   r;   r9   r   r      s        "1KKKr;   r   c                      e Zd Zej        ZdS )AlertProtocolVersionN)rx   ry   rz   r^   r   r   rA   r;   r9   r   r      s        "3KKKr;   r   c                      e Zd Zej        ZdS )AlertUnexpectedMessageN)rx   ry   rz   r^   r|   r   rA   r;   r9   r   r      s        "5KKKr;   r   c                      e Zd Zej        ZdS )AlertUnsupportedExtensionN)rx   ry   rz   r^   r   r   rA   r;   r9   r   r      s        "8KKKr;   r   c                      e Zd Zej        ZdS )AlertECHRequiredN)rx   ry   rz   r^   r   r   rA   r;   r9   r   r      r   r;   r   c                      e Zd ZdZdZdS )	Directionr   r   N)rx   ry   rz   DECRYPTENCRYPTrA   r;   r9   r   r      s        GGGGr;   r   c                      e Zd ZdZdZdZdZdS )Epochr   r   r-      N)rx   ry   rz   INITIALZERO_RTT	HANDSHAKEONE_RTTrA   r;   r9   r   r      s"        GHIGGGr;   r   c                  :    e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdS )Stater   r   r-   r               r4   	   r3   N)rx   ry   rz   CLIENT_HANDSHAKE_STARTCLIENT_EXPECT_SERVER_HELLO"CLIENT_EXPECT_ENCRYPTED_EXTENSIONS0CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE%CLIENT_EXPECT_CERTIFICATE_CERTIFICATE CLIENT_EXPECT_CERTIFICATE_VERIFYCLIENT_EXPECT_FINISHEDCLIENT_POST_HANDSHAKESERVER_EXPECT_CLIENT_HELLOSERVER_EXPECT_FINISHEDSERVER_POST_HANDSHAKErA   r;   r9   r   r      sR        !")*&784,-)'($!"r;   r   zdict[int, int]_STATE_EXPECTED_EPOCHc                  &    e Zd ZddZdd
ZddZdS )
HKDFExpandrJ   r0   rI   infobytes | Nonec                    || _         t          |dz            | _        d| j        z  }||k    rt          d| d          || _        |d}|| _        d| _        d S )Nr4   r?   zCannot derive keys larger than z octets.r;   F)
_algorithmr0   _digest_size
ValueError_length_info_used)selfrJ   rI   r   
max_lengths        r9   __init__zHKDFExpand.__init__   st     $	A..4,,
JSzSSSTTT<D



r;   key_materialbytesr/   c                   dg}d}| j         t          |          dz
  z  | j        k     rt          |d| j                   }|                    |d                    |                    | j                   |                    t          |g                     |                    |	                                           |dz  }| j         t          |          dz
  z  | j        k     d
                    |          d | j                 S )Nr;   r   sha	digestmod)r   lenr   r
   r   updater   r   appenddigestjoin)r   r   outputcounterhs        r9   _expandzHKDFExpand._expand   s    3v;;?3dlBB\-D4?-D-DEEEAHHVBZ   HHTZ   HHUG9%%&&&MM!((**%%%qLG 3v;;?3dlBB xx$,//r;   c                V    | j         rt          d| _         |                     |          S )NT)r   r   r   r   r   s     r9   derivezHKDFExpand.derive  s+    : 	
||L)))r;   N)rJ   r0   rI   r0   r   r   )r   r   r/   r   )rx   ry   rz   r   r   r   rA   r;   r9   r   r      sP           ,0 0 0 0* * * * * *r;   r   labelr   
hash_valuerI   c                    d| z   }t          j        d|t          |                    |z   t          j        dt          |                    z   |z   S )Ns   tls13 z!HBz!B)structpackr   )r   r   rI   
full_labels       r9   
hkdf_labelr     sT    U"JE63z??33
	
+dC
OO
,
,	- 	r;   rJ   secretc           	     j    t          | |t          |||                                        |          S )N)rJ   rI   r   )r   r   r   rJ   r   r   r   rI   s        r9   hkdf_expand_labelr      s=     z622   fVnn	r;   saltr   c                |    t          |d|            }|                    |           |                                S )Nr   r   )r
   r   r   )rJ   r   r   r   s       r9   hkdf_extractr   .  s=    T.9..///AHH\88::r;   datapasswordr   @EcPrivateKey | DsaPrivateKey | RsaPrivateKey | Ed25519PrivateKeyc                |   t          | |          }|                                t          j        t          j        t          j        fv rd}|                                t          j        k    rd}nI|                                t          j        k    rd}n$|                                t          j        k    rd}|J t          |                                |d| v          S |                                t          j        k    r!t          |                                          S |                                t          j
        k    r!t          |                                          S |                                t          j        k    r!t          |                                          S t          j        d          )z)
    Load a PEM-encoded private key.
    N     	  s   BEGIN EC PRIVATE KEYzUnsupported private key format)r    get_typer   
ECDSA_P256
ECDSA_P384
ECDSA_P521r   public_bytesDSAr   RSAr!   ED25519r   sslSSLError)r  r  	pkey_info
curve_types       r9   load_pem_private_keyr  4  s    tX..I   
 
7#555JJ!!W%777JJ!!W%777J%%%""$$j2IQU2U
 
 	
 
					,	,Y3355666						,	,Y3355666						0	0 !7!7!9!9:::
,7
8
88r;   list[X509Certificate]c                4    d t          |           D             S )z8
    Load a chain of PEM-encoded X509 certificates.
    c                ,    g | ]}t          |          S rA   )X509Certificate)rH   ds     r9   
<listcomp>z.load_pem_x509_certificates.<locals>.<listcomp>\  s     EEE1OAEEEr;   )_load_pem_certs_as_derr  s    r9   load_pem_x509_certificatesr  X  s"     FE(>t(D(DEEEEr;   list[bytes]c                J   d| vrdnd}d|z   }g }|                      |          D ]}}|ry|                    d|z             }|dk    r nZd                    ||d         |g                              d	          }|                    t          j        |                     ~|S )
z
    Decode a PEM bundle into a list of DER byte strings, without instantiating
    the (relatively expensive) ``X509Certificate`` Python wrapper.  Used by
    ``load_store_and_sort`` to feed the bulk classifier.
    s   -----
   
s   
s   -----END CERTIFICATE-----s   -----BEGIN CERTIFICATE-----r   r;   Nascii)splitfindr   decoder   r  PEM_cert_to_DER_cert)r  line_endingboundaryoutchunkstart_markerpem_reconstructeds          r9   r  r  _  s     (t33%%K+k9HCH%% D D 	D ::&D{&RSSLr!! #%*>)I J J Q Q! ! JJs/0ABBCCCJr;   capathstrc                    t           j                            |           sdS t          j        |           D ]}t                              |          r dS  dS )zFCheck whether capath exists and contains certs in the expected format.FT)r5   pathisdirlistdir_HASHED_CERT_FILENAME_REmatch)r,  names     r9   _capath_contains_certsr5  t  s]    7==   u
6""  #))$// 	44	5r;   cadatacafile
str | None,tuple[list[bytes], list[bytes], list[bytes]]c                   g }| "|                     t          |                      |||r\t          |d          5 }|                     t          |                                                     ddd           n# 1 swxY w Y   |rt	          |          rvt          j        | d          D ]^}t          |d          5 }|                     t          |                                                     ddd           n# 1 swxY w Y   _| T|R|Pt          j                    }|                                 |                     |	                    d                     t          |          S )a{  
    Given cadata, cafile and capath load X509 certificates and sort
    them into three distinct lists of DER-encoded byte strings:
        - Trust anchors (self-issued CAs with no TLS-purpose EKU)
        - Intermediates (CAs signed by another CA)
        - Others        (self-issued but flagged with TLS-purpose EKU;
                         excluded from trust anchors)
    Nrbz/*T)binary_form)extendr  openreadr5  globr  create_default_contextload_default_certsget_ca_certsr(   )r6  r7  r,  raw_dersfpr/  default_ctxs          r9   load_store_and_sortrG  ~  s    H.v66777V/ 	Cfd## Cr 6rwwyy A ABBBC C C C C C C C C C C C C C C 	G,V44 	G	V---00 G G$%% GOO$:27799$E$EFFFG G G G G G G G G G G G G G G ~&.V^022&&(((00T0BBCCC$X...s#   5A>>BB5DD	D	certificater  chainserver_nameassert_server_nameocsp_responseNonec                r   |g }t          |||          \  }}	}
||du r|                                 D ]}|                                }||                    d          dz   |                    d                   }|                    dd           d|v rGt          |          d	k    r3d
                    d |                    d          D                       }n|} |t          d          |st          d          |si|	rgt          | 
                                |	          }t          |          dk    r0|dd          D ]$}|                    t          |                     %ng }	 t          |          }n"# t          $ r}t          d          |d }~ww xY w	 |                    | 
                                d |D             ||pd           d S # t           t"          t$          t&          f$ r>}t)          |t"                    r
|du rY d }~d S t          |j        d                   d }~ww xY w)N)r6  r7  r,  F(r   )z*.zunverified.:   .c              3  N   K   | ] }t          t          |                    V  !d S rE   )r-  r0   )rH   ps     r9   	<genexpr>z%verify_certificate.<locals>.<genexpr>  s?       + +()CFF+ + + + + +r;   z&unable to determine server name targetz7unable to get local issuer certificate (empty CA store)r-   z(unable to create the verifier x509 storec                6    g | ]}|                                 S rA   r  )rH   cs     r9   r  z&verify_certificate.<locals>.<listcomp>  s"    ---!Q^^---r;   r;   r   )rG  get_subject_alt_namesr$  r#  rZ   r   r   r"  r   r*   r  r   r  r#   r   verifyr"   r   r   r%   
isinstanceargs)rH  rI  r6  r7  r,  rJ  rK  rL  trust_anchorsintermediaries_alt_nameserver_name_candidate	raw_chainistoreeexcs                     r9   verify_certificaterh    s    }':( ( ($M>1 0E99
 $99;; 	 	H$,OO$5$5!$9%**3//!36K6P6PQT6U6UU%! "))$>>>+++,--33"%(( + +-B-H-H-M-M+ + + # #KK  4!"JKKK 
!E
 
 	
  
^ 
!$$&&
 
	
 y>>Qqrr] 1 1_Q//00001 EU}-- U U U!"LMMSTTU/$$&&--u--- S		
 	
 	
 	
 	
 	##$	 / / / c677 	<NRW<W<WFFFFF!#(1+.../s6   0F   
F
FF#6G H68H1H11H6c                  "    e Zd ZdZdZdZdZdZdS )CipherSuitei  i  i  r?   i  N)rx   ry   rz   AES_128_GCM_SHA256AES_256_GCM_SHA384CHACHA20_POLY1305_SHA256EMPTY_RENEGOTIATION_INFO_SCSVGREASErA   r;   r9   rj  rj    s+        %$*!FFFr;   rj  c                      e Zd ZdZdS )CompressionMethodr   N)rx   ry   rz   NULLrA   r;   r9   rq  rq    s        DDDr;   rq  c                  V    e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdZdZdZdZdZdS )ExtensionTyper   r   r3            )   ra   rb   rc   rd   rj   9   iD  i  i   r.   i

  N)rx   ry   rz   SERVER_NAMESTATUS_REQUESTSUPPORTED_GROUPSSIGNATURE_ALGORITHMSALPNCOMPRESS_CERTIFICATEPRE_SHARED_KEY
EARLY_DATASUPPORTED_VERSIONSCOOKIEPSK_KEY_EXCHANGE_MODES	KEY_SHAREQUIC_TRANSPORT_PARAMETERSAPPLICATION_SETTINGSENCRYPTED_SERVER_NAMEECH_OUTER_EXTENSIONSENCRYPTED_CLIENT_HELLOro  rA   r;   r9   rt  rt    sr        KNDNJFI & !!#FFFr;   rt  c                  .    e Zd ZdZdZdZdZdZdZdZ	dZ
d	S )
Group         ic  i        i  N)rx   ry   rz   	SECP256R1	SECP384R1	SECP521R1X25519KYBER768DRAFT00X25519ML768X25519X448ro  rA   r;   r9   r  r    s7        III"KFDFFFr;   r  c                  >    e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdS )HandshakeTyper   r-   r   r   r4   rR  ru  r@   r_   r  r     N)rx   ry   rz   CLIENT_HELLOSERVER_HELLONEW_SESSION_TICKETEND_OF_EARLY_DATAENCRYPTED_EXTENSIONSCERTIFICATECERTIFICATE_REQUESTCERTIFICATE_VERIFYFINISHED
KEY_UPDATECOMPRESSED_CERTIFICATEMESSAGE_HASHrA   r;   r9   r  r  (  sP        LLKHJLLLr;   r  c                      e Zd ZdZdS )NameTyper   N)rx   ry   rz   	HOST_NAMErA   r;   r9   r  r  7  s        IIIr;   r  c                      e Zd ZdZdZdS )PskKeyExchangeModer   r   N)rx   ry   rz   PSK_KE
PSK_DHE_KErA   r;   r9   r  r  ;  s        FJJJr;   r  c                  R    e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdZdZdZdZdS )SignatureAlgorithmi  i  i  i  i  i  i  i  i	  i
  i  i  i  i  i  i  i  N)rx   ry   rz   ECDSA_SECP256R1_SHA256ECDSA_SECP384R1_SHA384ECDSA_SECP521R1_SHA512r  ED448RSA_PKCS1_SHA256RSA_PKCS1_SHA384RSA_PKCS1_SHA512RSA_PSS_PSS_SHA256RSA_PSS_PSS_SHA384RSA_PSS_PSS_SHA512RSA_PSS_RSAE_SHA256RSA_PSS_RSAE_SHA384RSA_PSS_RSAE_SHA512RSA_PKCS1_SHA1SHA1_DSA
ECDSA_SHA1rA   r;   r9   r  r  @  sq        ###GE    NHJJJr;   r  bufr   capacityr   c              #     K   t                               |                     |          d          }|                                 |z   }|V  |                                 |k    rt	          d          d S )Nbig	byteorderz!extra bytes at the end of a block)r0   
from_bytes
pull_bytestellr   )r  r  rI   ends       r9   
pull_blockr  Y  sl      ^^CNN844^FFF
((**v
C
LLL
xxzzSBCCC r;   c              #  J  K   |                                  |z   }|                     |           dV  |                                  }||z
  }|                     ||z
             |                     |                    |d                     |                     |           dS )zi
    Context manager to push a variable-length block, with `capacity` bytes
    to write the length.
    Nr  r  )r  seek
push_bytesto_bytes)r  r  startr  rI   s        r9   
push_blockr  c  s       HHJJ!EHHUOOO	EEE
((**C5[FHHUXNN6??8u?==>>>HHSMMMMMr;   funcCallable[[], T]list[T]c                "   g }t          | |          5 }|                                 |z   }|                                 |k     r5|                     |                       |                                 |k     5ddd           n# 1 swxY w Y   |S )z
    Pull a list of items.
    N)r  r  r   )r  r  r  itemsrI   r  s         r9   	pull_listr  v  s     E	C	"	" !fhhjj6!hhjj3LL    hhjj3! ! ! ! ! ! ! ! ! ! ! ! ! ! ! Ls   A%BBBCallable[[T], None]valuesSequence[T]c                z    t          | |          5  |D ]} ||           	 ddd           dS # 1 swxY w Y   dS )z
    Push a list of items.
    N)r  )r  r  r  r  values        r9   	push_listr    s     
C	"	"   	 	EDKKKK	                 s   044c                    t          | |          5 }|                     |          cddd           S # 1 swxY w Y   dS )z4
    Pull an opaque value prefixed by a length.
    N)r  r  )r  r  rI   s      r9   pull_opaquer    s     
C	"	" &f~~f%%& & & & & & & & & & & & & & & & & &s   377r  c                    t          | |          5  |                     |           ddd           dS # 1 swxY w Y   dS )z2
    Push an opaque value prefix by a length.
    N)r  r  )r  r  r  s      r9   push_opaquer    s     
C	"	"  u                 s   488extension_typec              #     K   |                      |           t          | d          5  d V  d d d            d S # 1 swxY w Y   d S Nr-   )push_uint16r  )r  r  s     r9   push_extensionr    s      OON###	C		                   s   :>>c                   t          | d          5  |                                 }|t          j        k    rt	          d|           t          | d                              d          cd d d            S # 1 swxY w Y   d S )Nr-   z$ServerName has an unknown name type r!  )r  
pull_uint8r  r  r   r  r$  )r  	name_types     r9   pull_server_namer    s    	C		 3 3NN$$	***'ByBB   3""))'223 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3s   AA77A;>A;c                    t          | d          5  |                     t          j                   t	          | d|                    d                     d d d            d S # 1 swxY w Y   d S )Nr-   r!  )r  
push_uint8r  r  r  encode)r  rJ  s     r9   push_server_namer    s    	C		 9 9x)***CK..w778889 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9s   AA""A&)A&KeyShareEntryc                R    |                                  }t          | d          }||fS r  )pull_uint16r  )r  groupr  s      r9   pull_key_sharer    s*    OOEsAD4=r;   c                j    |                      |d                    t          | d|d                    d S )Nr   r-   r   )r  r  )r  r  s     r9   push_key_sharer    s4    OOE!HQa!!!!!r;   c                H    t          | d                              d          S Nr   r!  )r  r$  r  s    r9   pull_alpn_protocolr    s     sA%%g...r;   protocolc                N    t          | d|                    d                     d S r  )r  r  )r  r  s     r9   push_alpn_protocolr    s&    Q0011111r;   PskIdentityc                R    t          | d          }|                                 }||fS r  )r  pull_uint32)r  identityobfuscated_ticket_ages      r9   pull_psk_identityr    s-    3""HOO--+,,r;   entryc                j    t          | d|d                    |                     |d                    d S )Nr-   r   r   )r  push_uint32r  r  s     r9   push_psk_identityr    s4    Qa!!!OOE!Hr;   c                "    t          | d          S Nr   r  r  s    r9   pull_psk_binderr    s    sAr;   binderc                (    t          | d|           d S r	  r  )r  r  s     r9   push_psk_binderr    s    Qr;   c                  (    e Zd ZU dZded<   ded<   dS )ECHCipherSuitez*HPKE cipher suite: KDF + AEAD identifiers.r0   kdf_idaead_idNrx   ry   rz   __doc__r   rA   r;   r9   r  r    s(         44KKKLLLLLr;   r  c                  n    e Zd ZU dZded<   ded<   ded<   ded<   ded	<   ded
<   ded<   ded<   ded<   dS )	ECHConfiga  
    Parsed ECHConfig structure (RFC 9849 Section 4).

    version: Must be 0xFE0D
    config_id: 1-byte config identifier
    kem_id: HPKE KEM identifier (e.g. 0x0020 for DHKEM(X25519, HKDF-SHA256))
    public_key: KEM public key bytes
    cipher_suites: List of supported HPKE cipher suites
    maximum_name_length: Max length of the SNI name
    public_name: Public-facing server name (used in outer ClientHello)
    extensions: Raw extension bytes
    raw: The raw bytes of this single ECHConfig (version + length + contents)
    r0   version	config_idkem_idr   
public_keyzlist[ECHCipherSuite]cipher_suitesmaximum_name_lengthr-  public_name
extensionsrawNr  rA   r;   r9   r  r    s|           LLLNNNKKK''''JJJJJr;   r  list[ECHConfig]c                   g }t          |           }t          |d          5 }|                                |z   }|                                |k     rY|                                }|                                }t          |d          5 }|                                |z   }|t          k    r"|                    |           	 ddd           |                                }	|                                }
t          |d          }g }t          |d          5 }|                                |z   }|                                |k     rd|                                }|                                }|                    t          ||                     |                                |k     dddd           n# 1 swxY w Y   |                                }t          |d          
                    d          }t          |d          }|                                |k    rt          d          |                                }| ||         }|                    t          ||	|
||||||	  	                   ddd           n# 1 swxY w Y   |                                |k     Yddd           n# 1 swxY w Y   |S )	a9  
    Parse an ECHConfigList (RFC 9849 Section 4).

    Format:
        ECHConfigList = uint16 length || ECHConfig...
        ECHConfig = uint16 version || uint16 length || contents

    For version 0xFE0D:
        contents = uint8 config_id || uint16 kem_id ||
                   HpkePublicKey(uint16 len || bytes) ||
                   cipher_suites(uint16 len || (uint16 kdf_id, uint16 aead_id)...) ||
                   uint8 maximum_name_length ||
                   opaque public_name(uint16 len || bytes) ||
                   extensions(uint16 len || bytes)
    r  r-   N)r  r  r   r!  z/extra bytes at the end of an ECHConfig contents)	r  r  r  r  r  r  r  r  r   )r   r  r  r  ECH_VERSIONr  r  r  r   r  r$  r   r  )r  configsr  list_lengthlist_endconfig_startr  contents_lengthcontents_endr  r  r  r  	cs_lengthcs_endr  r  r  r  r  
config_endr   s                         r9   parse_ech_config_listr-    sp      "G
d


C	C		 4{88::+hhjj8##88::Loo''GC## /"xxzzO;k))NN?333/ / / / / / /  NN,,	**(a00
 79Q'' 9 XXZZ)3F((**v--!$!2!2"%//"3"3%,,*&'JJJ   ((**v--               '*nn&6&6#)#q1188AA(a00
88::--*I  
 !XXZZ
<
23 '"+%#-&3,?$/#-
 
 
  G/ / / / / / / / / / / / / / / hhjj8##4 4 4 4 4 4 4 4 4 4 4 4 4 4 4l Nsi   A)J99J	J9A
J	BF;/J	;F??J	F?B:J	=J9	J	J9J	J99J= J=rL   >   r   r-   r   r$  'tuple[ECHConfig, ECHCipherSuite] | Nonec                   | D ]}|j         t          k    r|j        t          k    r$|j        rt          |j                  }d}	 |                                s@|                                }t          |d           |dz  rd}n|                                @n# t          $ r Y w xY w|r|j
        D ](}|j        t          k    r|j        t          v r||fc c S )dS )a  
    Select the first usable ECHConfig from a list.

    Returns (config, cipher_suite) or None if no config is usable.

    Selection criteria (RFC 9849 Section 6.1):
    - Version must be 0xFE0D
    - KEM must be DHKEM(X25519, HKDF-SHA256) (0x0020)
    - At least one cipher suite must use HKDF-SHA256 (0x0001)
      with a supported AEAD
    - No mandatory extensions (we don't support any)
    r  Fr-   i   TN)r  r#  r  _ECH_SUPPORTED_KEMr  r   eofr  r  r   r  r  _ECH_SUPPORTED_KDFr  _ECH_SUPPORTED_AEADS)r$  configext_bufhas_mandatoryext_typecss         r9   select_ech_configr9  e  s6     " ">[((=...  	&"3444G!M	!++-- &2244H+++&( (, "++--  #     & 	" 	"By...2:AU3U3Urz!!!!!	" 4s   AB
B('B(c                  $    e Zd ZU ded<   ded<   dS )OfferedPskszlist[PskIdentity]
identitiesr  bindersNr   rA   r;   r9   r;  r;    s*         !!!!r;   r;  c                     e Zd ZU ded<   ded<   ded<   ded<   dZded	<   d
Zded<   dZded<   dZded<   dZded<   dZ	ded<   dZ
ded<   dZded<   dZded<   dZded<   dZded<   d
Zded<    ee          Zded<   dZded<   dZded <   dS )!ClientHellor   randomlegacy_session_id	list[int]r  legacy_compression_methodsNlist[str] | Nonealpn_protocolsFr=   
early_datazlist[KeyShareEntry] | None	key_sharezOfferedPsks | Nonepre_shared_keylist[int] | Nonepsk_key_exchange_modesr8  rJ  signature_algorithmssupported_groupssupported_versionsalps_protocolscompress_certificate_algorithmscertificate_status_requestdefault_factorylist[Extension]other_extensions
int | Nonegrease_extension1grease_extension2)rx   ry   rz   r   rE  rF  rG  rH  rJ  rJ  rK  rL  rM  rN  rO  rP  r   listrT  rV  rW  rA   r;   r9   r?  r?    sZ        MMM)))) (,N++++J,0I0000)-N----/33333"K""""-11111)-----+/////'+N++++8<#<<<< (-,,,,(-d(C(C(CCCCC %)(((($(((((((r;   r?  expected_typec                d    |                                  }||k    rt          d| d|           dS )a  
    Pull the message type and check it is the expected one.

    The message type is always pulled (even when running under `python -O`)
    so that framing is preserved. If it is not the expected type, we have a
    programming error in the dispatch logic.
    zunexpected handshake type z, expected N)r  r   )r  rY  message_types      r9   pull_handshake_typer\    sK     >>##L}$$QQQ-QQ
 
 	
 %$r;   c                    t           t          j                   t           d          5                                   t
          k    rt          d          t                               d          t           d          t           d j                  t           d j                            dd fd
}t           d|           d d d            n# 1 swxY w Y   S )Nr   zClientHello version is not 1.2rL   r   r-   )r@  rA  r  rC  Fr/   rM  c                     rt          d                                          }                                 }| t          j        k    r+t	          dt          t                              _        d S | t          j        k    rt	          dj                  _	        d S | t          j
        k    rt	          dj                  _        d S | t          j        k    rt	          dj                  _        d S | t          j        k    rt	          dj                  _        d S | t          j        k    rt%                    _        d S | t          j        k    r+t	          dt          t*                              _        d S | t          j        k    r	d_        d S | t          j        k    r^t5          t	          dt          t6                              t	          dt          t8                                        _        dd S | t          j        k    r                    |           d S tA          |           r                    |           d S j!        "                    |                     |          f           d S )Nz&PreSharedKey is not the last extensionr-   r   Tr<  r=  )#r   r  rt  r  r  r	   r  rG  r  rM  r}  rK  r|  rL  r  r  rJ  rz  r  rJ  r~  r  rE  r  rF  r  r;  r  r  rH  r{  r  rB   rT  r   )r  extension_length	after_pskr  hellos     r9   pull_extensionz)pull_client_hello.<locals>.pull_extension  s     V+,TUUU __..N"00!888"+CGNC4P4P"Q"Q=#CCC+4S!S_+M+M(((=#EEE-6sAs-O-O***=#AAA)233?)K)K&&&=#GGG/8a/P/P,,,=#<<<$4S$9$9!!!=#555'0G$6<<( ($$$  =#;;;#'   =#???'2(a9JC1P1PQQ%c1gos.K.KLL( ( ($ !			=#???$     ".11 /00000&--#S^^4D%E%EF    r;   r/   rM  )r\  r  r  r  r  TLS_VERSION_1_2r   r?  r  r  r  r  )r  rc  ra  rb  s   ` @@r9   pull_client_hellorf    s@   ]7888	C		 :* :*??//"#CDDD>>"%%)#q11#CCO<<'0a'H'H	
 
 
 	*	 *	 *	 *	 *	 *	 *	 *	X 	#q.)))u:* :* :* :* :* :* :* :* :* :* :* :* :* :* :*x Ls   B$CC"%C"rb  c                   |                      t          j                   t          | d          5  |                     t
                     |                     |j                   t          | d|j	                   t          | d| j        |j                   t          | d| j         |j                   t          | d          5  d }d }g }|j        D ]F\  }}|t          j        k    r||f}|t          j        k    r||f}/|                    ||f           G|j        .t'          | |j                  5  	 d d d            n# 1 swxY w Y   t'          | t          j                  5  t          | d| j        |j                   d d d            n# 1 swxY w Y   |j        \t'          | t          j                  5  t          | dt1          t2          |           |j                   d d d            n# 1 swxY w Y   t'          | t          j                  5  t          | dt1          t6          |           |j                   d d d            n# 1 swxY w Y   |j        Nt'          | t          j                  5  t          | d| j        |j                   d d d            n# 1 swxY w Y   |j        rqt'          | t          j                   5  |                      d           |                     d           |                     d           d d d            n# 1 swxY w Y   |j!        \t'          | t          j"                  5  t          | dt1          t2          |           |j!                   d d d            n# 1 swxY w Y   |It'          | |d                   5  |                     |d                    d d d            n# 1 swxY w Y   |j#        Nt'          | t          j$                  5  t          | d| j         |j#                   d d d            n# 1 swxY w Y   |j%        Gt'          | t          j&                  5  tO          | |j%                   d d d            n# 1 swxY w Y   t'          | t          j(                  5  t          | d| j        |j)                   d d d            n# 1 swxY w Y   t'          | t          j*                  5  t          | d| j        |j+                   d d d            n# 1 swxY w Y   |It'          | |d                   5  |                     |d                    d d d            n# 1 swxY w Y   |D ]B\  }}t'          | |          5  |                     |           d d d            n# 1 swxY w Y   C|j,        r3t'          | t          j-                  5  	 d d d            n# 1 swxY w Y   |j.        Bt'          | |j.                  5  |                      d           d d d            n# 1 swxY w Y   |j/        t'          | t          j0                  5  t          | dt1          tb          |           |j/        j2                   t          | dt1          tf          |           |j/        j4                   d d d            n# 1 swxY w Y   d d d            n# 1 swxY w Y   d d d            d S # 1 swxY w Y   d S )Nr   r   r-   r   )5r  r  r  r  r  re  r  r@  r  rA  r  r  rC  rT  rt  r  r  r   rV  r  r}  rK  rN  r  r	   r  r  r  rG  rO  r  rP  r{  rE  r~  rJ  r  rJ  rz  r  r  rM  r|  rL  rF  r  rW  rH  r  r  r<  r  r=  )r  rb  ech_extensionquic_tp_extensionremaining_extensionsr  extension_values          r9   push_client_hellorl    s   NN=-...	C		 y y(((u|$$$CE3444#q#/5+>???#q#.%*JKKK Q q	 q	 7;M:><> 383I S S/!]%III%3_$EMM#}'NNN)7(I%%(//0QRRRR &2#C)@AA                  ]%GHH O O#q#/53MNNNO O O O O O O O O O O O O O O #/#C)KLL  Q(:C @ @%BV                  ]%<== Q Q#q'.#">">PPPQ Q Q Q Q Q Q Q Q Q Q Q Q Q Q 4@#C)KLL  Q1V                 / '#C)EFF ' 'NN1%%%OOA&&&OOA&&&' ' ' ' ' ' ' ' ' ' ' ' ' ' ' #/#C);<<  Q(:C @ @%BV                 (#Cq)9:: 5 5NN=#34445 5 5 5 5 5 5 5 5 5 5 5 5 5 5 +7#C)MNN T Tc1cne6RSSST T T T T T T T T T T T T T T  ,#C)BCC = =$S%*;<<<= = = = = = = = = = = = = = =  ]%EFF M M#q#/53KLLLM M M M M M M M M M M M M M M  ]%CDD K K#q#/53IJJJK K K K K K K K K K K K K K K !,#C):1)=>> 9 9NN#4Q#78889 9 9 9 9 9 9 9 9 9 9 9 9 9 9 4H 4 4/#C88 4 4NN?3334 4 4 4 4 4 4 4 4 4 4 4 4 4 4  #C)ABB                 &2#C)@AA & &NN1%%%& & & & & & & & & & & & & & & #/#C)EFF   1377,7	   55,4	                Kq	 q	 q	 q	 q	 q	 q	 q	 q	 q	 q	 q	 q	 q	 q	y y y y y y y y y y y y y y y y y ys  B["A1[
4E6[
E[
	E
[
'F[
F[
F$[
<+G3'[
3G77[
:G7;[
+I[
I[
I$[
;J$[
$J(([
+J(,$[
A L[
L  [
#L $$[
+M?3[
?N[
N[
"O
>[

O[
O$[
6P[
P##[
&P#'$[
Q-![
-Q11[
4Q15[
R;/[
;R??[
R?[
 T	=[
	T[
T[
,U[
U[
U[
6V	[
V[
V %[
W[
W[
W[
:X[
X  [
#X $$[
AZ3'[
3Z77[
:Z7;[
>["
[	["[	[""[&)[&c                      e Zd ZU ded<   ded<   ded<   ded<   dZded	<   dZd
ed<   dZd
ed<    ee          Z	ded<   dS )ServerHellor   r@  rA  r0   cipher_suitecompression_methodNzKeyShareEntry | NonerG  rU  rH  supported_versionrQ  list[tuple[int, bytes]]rT  )
rx   ry   rz   r   rG  rH  rq  r   rX  rT  rA   r;   r9   rn  rn    s         MMM '+I****!%N%%%%$(((((05d0K0K0KKKKKKKr;   rn  c                    t           t          j                   t           d          5                                   t
          k    rt          d          t                               d          t           d                                            
                                          d
 fd}t           d	|           d d d            n# 1 swxY w Y   S )Nr   zServerHello version is not 1.2rL   r   )r@  rA  ro  rp  r/   rM  c                                                     }                                  }| t          j        k    r                                 _        d S | t          j        k    rt                    _        d S | t          j        k    r                                 _        d S j	        
                    |                     |          f           d S rE   )r  rt  r  rq  r  r  rG  r  rH  rT  r   r  )r  r`  r  rb  s     r9   rc  z)pull_server_hello.<locals>.pull_extension  s     __..N"00!AAA*-//*;*;'''=#:::"0"5"5=#???'*'8'8$$$&--#S^^4D%E%EF    r;   r-   rd  )r\  r  r  r  r  re  r   rn  r  r  r  r  )r  rc  rb  s   ` @r9   pull_server_helloru    s(   ]7888	C		 * *??//"#CDDD>>"%%)#q11**"~~//	
 
 
	 	 	 	 	 	 	 	#q.)))5* * * * * * * * * * * * * * *8 Ls   BCCCc           	     `   |                      t          j                   t          | d          5  |                     t
                     |                     |j                   t          | d|j	                   |                     |j
                   |                      |j                   t          | d          5  |j        Lt          | t          j                  5  |                     |j                   d d d            n# 1 swxY w Y   |j        Gt          | t          j                  5  t%          | |j                   d d d            n# 1 swxY w Y   |j        Lt          | t          j                  5  |                     |j                   d d d            n# 1 swxY w Y   |j        D ]B\  }}t          | |          5  |                     |           d d d            n# 1 swxY w Y   C	 d d d            n# 1 swxY w Y   d d d            d S # 1 swxY w Y   d S Nr   r   r-   )r  r  r  r  r  re  r  r@  r  rA  ro  rp  rq  r  rt  r  rG  r  r  rH  r  rT  )r  rb  r  rk  s       r9   push_server_hellorx    s   NN=-...	C		 4 4(((u|$$$CE3444*+++u/000 Q 	4 	4&2#C)IJJ = =OOE$;<<<= = = = = = = = = = = = = = = *#C)@AA 9 9"38889 9 9 9 9 9 9 9 9 9 9 9 9 9 9 #/#C)EFF : :OOE$8999: : : : : : : : : : : : : : : 493I 4 4/#C88 4 4NN?3334 4 4 4 4 4 4 4 4 4 4 4 4 4 44	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	44 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4s   BH#?"H!D<HDHD$H4E
HEHE$HF)H)F--H0F-1HG2	&H2G66H9G6:H?H#H	H#H	H##H'*H'c                  x    e Zd ZU dZded<   dZded<   dZded<   dZded<   d	Zd
ed<    e	e
          Zded<   d	S )NewSessionTicketr   r0   ticket_lifetimeticket_age_addr;   r   ticket_nonceticketNrU  max_early_data_sizerQ  rr  rT  )rx   ry   rz   r{  r   r|  r}  r~  r  r   rX  rT  rA   r;   r9   rz  rz    s         ONLF '+****05d0K0K0KKKKKKKr;   rz  c                    t                      t           t          j                   t	           d          5                                   _                                         _        t           d          _	        t           d          _
        d fd}t           d|           d d d            n# 1 swxY w Y   S )Nr   r   r-   r/   rM  c                                                     }                                  }| t          j        k    r                                _        d S j                            |                     |          f           d S rE   )r  rt  r  r  r  rT  r   r  )r  r`  r  new_session_tickets     r9   rc  z/pull_new_session_ticket.<locals>.pull_extension  s     __..N"00!9999<9J9J"666"3::#S^^4D%E%EF    r;   rd  )rz  r\  r  r  r  r  r{  r|  r  r}  r~  r  )r  rc  r  s   ` @r9   pull_new_session_ticketr    s   )++]=>>>	C		 * *-0__->->*,/OO,=,=)*5c1*=*='$/Q$7$7!	 	 	 	 	 	 	 	#q.)))!* * * * * * * * * * * * * * *$ s   A5B<<C C r  c           	        |                      t          j                   t          | d          5  |                     |j                   |                     |j                   t          | d|j                   t          | d|j	                   t          | d          5  |j
        Lt          | t          j                  5  |                     |j
                   d d d            n# 1 swxY w Y   |j        D ]B\  }}t          | |          5  |                     |           d d d            n# 1 swxY w Y   C	 d d d            n# 1 swxY w Y   d d d            d S # 1 swxY w Y   d S rw  )r  r  r  r  r  r{  r|  r  r}  r~  r  r  rt  r  rT  r  )r  r  r  rk  s       r9   push_new_session_ticketr    sw   NN=3444	C		 4 4*:;;;*9:::C.;<<<C.5666Q 	4 	4!5A#C)ABB L LOO$6$JKKKL L L L L L L L L L L L L L L 4F3V 4 4/#C88 4 4NN?3334 4 4 4 4 4 4 4 4 4 4 4 4 4 44	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	44 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4s~   A1E$!"EC*E*C..E1C.2ED3	'E3D77E:D7;E E$E	E$E	E$$E(+E(c                  \    e Zd ZU dZded<   dZded<   dZded<    ee	          Z	d
ed<   dS )EncryptedExtensionsNr8  alpn_protocolFr=   rF  r   retry_configsrQ  rr  rT  )
rx   ry   rz   r  r   rF  r  r   rX  rT  rA   r;   r9   r  r    sd          $M$$$$J"&M&&&&05d0K0K0KKKKKKKr;   r  c                     t                      t           t          j                   t	           d          5  d fd}t           d|           d d d            n# 1 swxY w Y   S )Nr   r/   rM  c                                                     }                                  }| t          j        k    r1t          dt	          t
                              d         _        d S | t          j        k    r	d_        d S | t          j	        k    r
                    |          _        d S j                            | 
                    |          f           d S )Nr-   r   T)r  rt  r~  r  r	   r  r  r  rF  r  r  r  rT  r   )r  r`  r  r  s     r9   rc  z1pull_encrypted_extensions.<locals>.pull_extension   s     __..N"00!333+4G$6<<, ,,
(((  =#;;;(,
%%%=#GGG+.>>:J+K+K
(((+22#S^^4D%E%EF    r;   r-   rd  )r  r\  r  r  r  r  )r  rc  r  s   ` @r9   pull_encrypted_extensionsr    s    $&&J]?@@@	C		 * *	 	 	 	 	 	 	" 	#q.)))'* * * * * * * * * * * * * * ** s   A  A$'A$r  c                   |                      t          j                   t          | d          5  t          | d          5  |j        ]t          | t          j                  5  t          | dt          t          |           |j        g           d d d            n# 1 swxY w Y   |j        r3t          | t          j                  5  	 d d d            n# 1 swxY w Y   |j        D ]B\  }}t          | |          5  |                     |           d d d            n# 1 swxY w Y   C	 d d d            n# 1 swxY w Y   d d d            d S # 1 swxY w Y   d S Nr   r-   )r  r  r  r  r  r  rt  r~  r  r	   r  rF  r  rT  r  )r  r  r  rk  s       r9   push_encrypted_extensionsr  6  s   NN=5666	C		 4 4Q 	4 	4'3#C);<<   2C88#12	                 $ #C)ABB                 4>3N 4 4/#C88 4 4NN?3334 4 4 4 4 4 4 4 4 4 4 4 4 4 44	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	44 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4s   E"D7#,BD7BD7"B#$D7C	D7CD7CD7<D	D7D""D7%D"&D7+E7D;	;E>D;	?EEEc                  @    e Zd ZU dZded<    ee          Zded<   dS )r,   r;   r   request_contextrQ  zlist[CertificateEntry]certificatesN)rx   ry   rz   r  r   r   rX  r  rA   r;   r9   r,   r,   O  sA          O    +05+F+F+FLFFFFFFr;   r,   c                  N    e Zd ZU dZded<   dZded<    ee          Zded	<   dS )
CertificateRequestr;   r   r  NrI  rK  rQ  rr  rT  )	rx   ry   rz   r  r   rK  r   rX  rT  rA   r;   r9   r  r  U  sT          O    -1111105d0K0K0KKKKKKKr;   r  c           	         t                      }t          | t          j                   t	          | d          5  t          | d          |_        dd}t          | dt          ||                     |_	        d d d            n# 1 swxY w Y   |S )	Nr   r   r  r   r/   CertificateEntryc                J    t          | d          }t          | d          }||fS r  r
  )r  r  r  s      r9   pull_certificate_entryz0pull_certificate.<locals>.pull_certificate_entryc  s+    sA&&D$S!,,J*%%r;   )r  r   r/   r  )
r,   r\  r  r  r  r  r  r  r	   r  )r  rH  r  s      r9   pull_certificater  \  s    --K]6777	C		 

 

&1#q&9&9#	& 	& 	& 	&
 $-G2C88$
 $
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 s   >BB
Bc                    t                      t           t          j                   t	           d          5  t           d          _        d fd}t           d|           d d d            n# 1 swxY w Y   S )Nr   r   r/   rM  c                                                     }                                  }| t          j        k    rt          dj                   _        d S j                            |                     |          f           d S r  )r  rt  r}  r  rK  rT  r   r  )r  r`  r  certificate_requests     r9   rc  z0pull_certificate_request.<locals>.pull_extensionv  s     __..N"00!CCC;DCO< <#888 $4;;#S^^4D%E%EF    r;   r-   rd  )r  r\  r  r  r  r  r  r  )r  rc  r  s   ` @r9   pull_certificate_requestr  o  s    ,..]>???	C		 * *.9#q.A.A+
	 
	 
	 
	 
	 
	 
	 	#q.)))* * * * * * * * * * * * * * *" s   .A55A9<A9c           	        |                      t          j                   t          | d          5  t	          | d|j                   d
d	}t          | dt          ||           |j                   d d d            d S # 1 swxY w Y   d S )Nr   r   r  r   r  r  r/   rM  c                b    t          | d|d                    t          | d|d                    d S )Nr   r   r-   r   r  r  s     r9   push_certificate_entryz0push_certificate.<locals>.push_certificate_entry  s4    Qa)))Qa)))))r;   )r  r   r  r  r/   rM  )	r  r  r  r  r  r  r  r	   r  )r  rH  r  s      r9   push_certificater    s    NN=,---	C		 	
 	
CK7888	* 	* 	* 	* 	G2C88+:R	
 	
 	
	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
s   A A==BBc                  $    e Zd ZU ded<   ded<   dS )CertificateVerifyr0   rJ   r   	signatureNr   rA   r;   r9   r  r    s'         NNNr;   r  c                    t          | t          j                   t          | d          5  |                                 }t          | d          }d d d            n# 1 swxY w Y   t          ||          S )Nr   r-   rJ   r  )r\  r  r  r  r  r  r  )r  rJ   r  s      r9   pull_certificate_verifyr    s    ]=>>>	C		 ( (OO%%	Q''	( ( ( ( ( ( ( ( ( ( ( ( ( ( ( yIFFFFs   %AA #A r[  c                    |                      t          j                   t          | d          5  |                     |j                   t          | d|j                   d d d            d S # 1 swxY w Y   d S r  )r  r  r  r  r  rJ   r  r  )r  r[  s     r9   push_certificate_verifyr    s    NN=3444	C		 . .()))CF,---. . . . . . . . . . . . . . . . . .s   1A..A25A2c                      e Zd ZU dZded<   dS )Finishedr;   r   verify_dataN)rx   ry   rz   r  r   rA   r;   r9   r  r    s#         Kr;   r  c                    t                      }t          | t          j                   t	          | d          |_        |S Nr   )r  r\  r  r  r  r  r  finisheds     r9   pull_finishedr    s5    zzH]3444&sA..HOr;   r  c                p    |                      t          j                   t          | d|j                   d S r  )r  r  r  r  r  r  s     r9   push_finishedr    s2    NN=)***Q,-----r;   c                  @    e Zd ZddZddZdd	ZddZdddZddZdS )KeySchedulero  rj  c                V   t          |          | _        t          | j        dz            | _        || _        d| _        t          j        d| j                   | _        | j        	                                
                                | _        t          | j                  | _        d S )Nr4   r   r   )cipher_suite_hashrJ   r0   digest_sizero  
generationrG   newhashcopyr   hash_empty_valuer   r   r   ro  s     r9   r   zKeySchedule.__init__  s    *<88t~122(K 6dn 6 677	 $	 0 0 7 7 9 9D,--r;   context_stringr   r/   c                j    d|z   dz   | j                                                                         z   S )Ns@                                                                       )r  r  r   )r   r  s     r9   certificate_verify_dataz#KeySchedule.certificate_verify_data  s/    >)G3dinn6F6F6M6M6O6OOOr;   r   c                   t          | j        |dd| j                  }t          |d| j                   }|                    | j                                                                                   |                                S )Ns   finishedr;   r   r   r   )r   rJ   r  r
   r   r  r  r   )r   r   hmac_keyr   s       r9   finished_verify_dataz KeySchedule.finished_verify_data  s    $n#
 
 
 %;4>%;%;<<<	!!((**+++xxzzr;   r   c                    t          | j        | j        || j                                                                        | j                  S )Nr   )r   rJ   r   r  r  r   r  )r   r   s     r9   derive_secretzKeySchedule.derive_secret  sG     n;y~~''..00#
 
 
 	
r;   Nr   r   rM  c                    |t          | j                  }| j        r-t          | j        | j        d| j        | j                  | _        | xj        dz  c_        t          | j        | j        |          | _        d S )Ns   derivedr   r   rJ   r   r   )r   r  r  r   rJ   r   r  r   r   s     r9   extractzKeySchedule.extract  s     !122L? 	+.{ 0'  DK 	1"n4;\
 
 
r;   r  c                :    | j                             |           d S rE   )r  r   )r   r  s     r9   update_hashzKeySchedule.update_hash  s    	r;   )ro  rj  )r  r   r/   r   )r   r   r/   r   )r   r   r/   r   rE   r   r   r/   rM  r  r   r/   rM  )	rx   ry   rz   r   r  r  r  r  r  rA   r;   r9   r  r    s        . . . .P P P P   
 
 
 

 
 
 
 
$     r;   r  c                  0    e Zd ZddZddd	ZddZddZdS )KeyScheduleProxyr  list[CipherSuite]c                L    t          t          d |                    | _        d S )Nc                $    | t          |           fS rE   )r  )rY  s    r9   <lambda>z+KeyScheduleProxy.__init__.<locals>.<lambda>  s    q+a...A r;   )dictmap_KeyScheduleProxy__schedules)r   r  s     r9   r   zKeyScheduleProxy.__init__  s&    $A$A= Q QRRr;   Nr   r   r/   rM  c                h    | j                                         D ]}|                    |           d S rE   )r  r  r  )r   r   ks      r9   r  zKeyScheduleProxy.extract  s?    !((** 	$ 	$AIIl####	$ 	$r;   ro  rj  r  c                    | j         |         S rE   )r  r  s     r9   selectzKeyScheduleProxy.select  s    --r;   r  r   c                h    | j                                         D ]}|                    |           d S rE   )r  r  r  )r   r  r  s      r9   r  zKeyScheduleProxy.update_hash  s?    !((** 	  	 AMM$	  	 r;   )r  r  rE   r  )ro  rj  r/   r  r  )rx   ry   rz   r   r  r  r  rA   r;   r9   r  r    sm        S S S S$ $ $ $ $. . . .           r;   r  r  r  )Nr  )Nr  )N   )Fr  )Fr  )Fr  )Tr  )Tr  )Tr  z1dict[SignatureAlgorithm, tuple[bool | None, int]]r}  ro  c                    t           |          S rE   )CIPHER_SUITES)ro  s    r9   r  r    s    &&r;   	supportedofferedlist[Any] | Nonerg  Alert | NoneexclT | Noneexcl_fnCallable[[Any], bool] | Nonec                Z    |$| D ]!}||v r|||k    r| ||          r|c S "||d S rE   rA   )r  r  rg  r  r  rY  s         r9   	negotiater    sh      	 	AG||#		&771::&  	4r;   signature_algorithmtuple[Any, ...]c                    | t           j        t           j        fv rdS t          t          |                    \  }}|dS ||fS )NrA   )r  r  r  r}  )r  is_pss	hash_sizes      r9   signature_algorithm_paramsr  3  sT    19;M;STTTr,-?@S-T-TUFI~r 	 r;   key_scheduleKeySchedule | KeyScheduleProxyc              #     K   |                                 }d V  |                     |                    ||                                                      d S rE   )r  r  
data_slice)r  r  
hash_starts      r9   push_messager  B  sN       J	EEES^^J

CCDDDDDr;   c                      e Zd ZU dZded<   ded<   ded<   ded<   d	ed
<   ded<   d	ed<   dZded<    ee          Zded<   e	dd            Z
e	dd            ZdS )SessionTicketz6
    A TLS session ticket for session resumption.
    r0   age_addrj  ro  rS   not_valid_afternot_valid_beforer   resumption_secretr-  rJ  r~  NrU  r  rQ  rr  rT  r/   r=   c                J    t                      }|| j        k    o
|| j        k    S rE   )r\   r  r  )r   rW   s     r9   is_validzSessionTicket.is_valid_  s&    hhd++Kt7K0KKr;   c                    t          t                      | j        z
                                  dz            }|| j        z   dz  S )Ni  l        )r0   r\   r  total_secondsr  )r   ages     r9   obfuscated_agezSessionTicket.obfuscated_aged  s>    688d33BBDDtKLLdl"w//r;   r/   r=   r/   r0   )rx   ry   rz   r  r   r  r   rX  rT  propertyr  r  rA   r;   r9   r  r  N  s           LLL&&&&''''MMM&*****05d0K0K0KKKKKL L L XL 0 0 0 X0 0 0r;   r  c                 r   t                      } |                                 }t          j        d          d         }d}d}d}t          j        |          }t	          dt          |          z   dz   |z             }|                    d           |                    |           |                    |           |                    |           |                    t          |                     |                    |           |                    |           |                    |           |j	        S )a  
    Build a GREASE ECH extension payload for the outer ClientHello.

    RFC 9849 Section 6.2: When ECH is not being offered, the client
    SHOULD include a GREASE ECH extension to make ECH usage indistinguishable.

    Format (ECHClientHello outer):
        type(1) = 0x00
        cipher_suite(4) = kdf_id(2) + aead_id(2)
        config_id(1) = random
        enc_len(2) + enc(32) = valid X25519 KEM output
        payload_len(2) + payload = random (sized to be realistic)
    r   r      r4   r-   r  )
r&   r  r5   r6   r   r   r  r  r  r  )kxencr  r  r  payload_lenpayloadr  s           r9   _build_grease_ech_extensionr  o  s     
		B
--//C
1a I FG
 Kj%%G
-#c((2Q6D
E
E
ECNN1OOFOOGNN9OOCHHNN3OOK   NN78Or;   c                  |   e Zd Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d^d_dZed`d             Zedad"            Zedbd#            Zedbd$            Zedcd%            Z	edbd&            Z
edcd'            Z	 ddded0Zdfd6Zdgd8Zdhd=ZdidCZdjdEZdkdFZdkdGZdkdHZdldKZdkdLZdkdMZdjdNZdkdOZdmdSZdkdTZdjdUZdndZZdod]ZdS )pContextNFT	is_clientr=   rE  rD  r6  r   r7  r8  r,  r  list[CipherSuite] | Nonelogger-logging.Logger | logging.LoggerAdapter | Nonemax_early_datarU  rJ  verify_modehostname_checks_common_nameassert_fingerprintverify_hostnameech_config_listrK  rI  offer_ec_key_shares offer_certificate_status_requestc           	        || _         || _        || _        || _        || _        || _        || _        d | _        g | _        d | _	        g | _
        || _        d | _        |	5|	                                s!t          |	                                          }	|	| _        |
|
| _        n|rt$          j        nt$          j        | _        d | _        d | _        d | _        d | _        t3                      | _        t3                      | _        | j        | j        k    r| xj        dz  c_        t3                      | _        t3                      | _        t3                      | _        ||| _        n.| j        t@          j!        t@          j"        t@          j#        g| _        tH          j%        g| _&        tN          j(        g| _)        tT          j+        tT          j,        tT          j-        tT          j.        tT          j/        tT          j0        tT          j1        tT          j2        tT          j3        g	| _4        |tk          |          | _4        || _6        || _7        | j        tp          j9        tp          j:        tp          j;        tp          j<        g| _=        | j        t|          g| _?        t          t          g| _B        nd | _B        d | _C        d| _D        d | _E        d | _F        d | _G        d | _H        d | _I        d | _J        g | _K        d | _L        d| _M        d | _N        d| _O        d| _P        d| _Q        d| _R        d | _S        d | _T        d | _U        || _V        d | _W        d | _X        d | _Y        d | _Z        d | _[        || _\        d | _]        d | _^        d | __        d| _`        d| _a        d | _b        d | _c        d | _d        d | _e        |r3t          jg        d          | _h        d| _i        t          jk        | _l        d S d | _h        d | _i        t          jm        | _l        d S )Nc                    d S rE   rA   )r  rf  rY  ss       r9   r  z"Context.__init__.<locals>.<lambda>  s    t r;   i  Fr;   rL   )n_alpn_protocols_cadata_cafile_capath_hostname_checks_common_name_assert_fingerprint_verify_hostnamerH  certificate_chaincertificate_private_keyhandshake_extensions_max_early_datasession_ticketisasciir)   r$  _server_name_verify_moder  CERT_REQUIRED	CERT_NONEalpn_cbget_session_ticket_cbnew_session_ticket_cbupdate_traffic_key_cbr:   _grease_extension1_grease_extension2_grease_group_grease_cipher_grease_version_cipher_suitesrj  rk  rl  rm  rq  rr  _legacy_compression_methodsr  r  _psk_key_exchange_modesr  r  r  r  r  r  r  r  r  r  _signature_algorithmsrX  _offer_ec_key_shares!_offer_certificate_status_requestr  r  r  r  r  _supported_groupsTLS_VERSION_1_3_supported_versions_brotliCERTIFICATE_COMPRESSION_BROTLI _compress_certificate_algorithmsalpn_negotiatedearly_data_acceptedr  received_extensions_key_schedule_psk_key_schedule_proxy_new_session_ticket_peer_certificate_peer_certificate_chain_ocsp_response_alps_negotiated_peer_alps_settings_local_alps_settings_alps_supported_receive_buffer_session_resumed_enc_key_dec_key_certificate_request_Context__logger_ec_p256_private_key_ec_p384_private_key_ec_p521_private_key_x25519_private_key_x25519_kyber_768_private_key_ech_config_list_ech_config_ech_cipher_suite_ech_hpke_context_ech_offered_ech_accepted_ech_inner_random_ech_retry_configs_ech_inner_ch_hash_ech_inner_ch_bytesr5   r6   client_randomrA  r   r   stater   )r   r  rE  r6  r7  r,  r  r  r  rJ  r  r  r  r  r  rK  r  r  s                     r9   r   zContext.__init__  s   *  .,G)#5  /378:  	$ 68!-48 ";+>+>+@+@"%k2299;;K'" +D5> Q 1 1CMD ,0BF"BF" $# 	" #9":":"8":":"d&===##v-##355466577 $"/D #..4	#D 8I7M6N(3E3P2Q$52/52/2/-
1
"   +)-.B)C)CD& %8! 2R. LOO"
 %)$8/#J  .GD11 59D1 ,0). 04;? 59<@ <@ 9=>@$,0 ',15 +.! &+" %&*&*?C! AE!@D!@D!=A LP* !0-18<59"'#(/3048< 	   	:!#BD%(D"5DJJJ!%D%)D"9DJJJr;   r/   X509Certificate | Nonec                    | j         S rE   )rJ  r   s    r9   peer_certificatezContext.peer_certificateW  s    %%r;   r  c                    | j         S rE   )rK  rj  s    r9   peer_certificate_chainzContext.peer_certificate_chain[  s    ++r;   c                    | j         S )zK
        Returns True if session resumption was successfully used.
        )rR  rj  s    r9   session_resumedzContext.session_resumed_  s    
 $$r;   c                    | j         S )zM
        Returns True if ECH was offered and accepted by the server.
        )ra  rj  s    r9   ech_acceptedzContext.ech_acceptedf  s    
 !!r;   c                    | j         S )z
        Returns retry_configs from server's EncryptedExtensions if ECH
        was rejected. Can be used to retry with updated configs.
        )rc  rj  s    r9   ech_retry_configszContext.ech_retry_configsm  s     &&r;   c                    | j         S )z~
        Whether application_settings (draft-vvv-tls-alps) was negotiated with
        the peer during the handshake.
        )rM  rj  s    r9   alps_negotiatedzContext.alps_negotiatedu  s     $$r;   c                    | j         S )z|
        The application_settings value received from the peer when ALPS was
        negotiated, or None otherwise.
        )rN  rj  s    r9   peer_alps_settingszContext.peer_alps_settings}  s     ''r;   r   
input_datar   
output_bufdict[Epoch, Buffer]epochr0   rM  c                   | j         t          j        k    r'|                     |t          j                            d S | xj        |z  c_        t          | j                  dk    r| j        d         }dt          	                    | j        dd         d          z   }t          | j                  |k     rd S | j        d |         }| j        |d          | _        t          |          }|dk    r.t                              | j                   }|||k    rt          | j         t          j        k    r?|t          j        k    r(|                     ||t          j                            nt          | j         t          j        k    r.|t          j        k    r|                     |           nt          | j         t          j        k    r||t          j        k    r|                     |           n@|t          j        k    r|                     |           n|t          j        k    r|                     |           nt          | j         t          j        k    r.|t          j        k    r|                     |           nt          | j         t          j        k    r?|t          j         k    r(| !                    ||t          j"                            n[t          | j         t          j#        k    r.|t          j$        k    r| %                    |           nt          | j         t          j&        k    r`|t          j'        k    rI| (                    ||t          j                 |t          j"                 |t          j)                            nt          | j         t          j*        k    rk|t          j         k    r'| +                    ||t          j)                            nP|t          j        k    r| j,        r| -                    |           n#t          | j         t          j.        k    rt          |/                                sta          d          t          | j                  dk    	d S d S )Nr   r   r   r  r  r  z-extra bytes at the end of a handshake message)1rg  r   r   _client_send_hellor   r   rQ  r   r0   r  r   r   getr   r   r  r  _client_handle_hellor   r  #_client_handle_encrypted_extensionsr   r  _client_handle_certificater  %_client_handle_compressed_certificater  "_client_handle_certificate_requestr   r  !_client_handle_certificate_verifyr   r  _client_handle_finishedr   r   r  !_client_handle_new_session_ticketr   r  _server_handle_hellor   r   _server_handle_finishedrM  *_server_handle_client_encrypted_extensionsr   r1  r   )	r   rx  ry  r{  r[  message_lengthmessage	input_bufexpected_epochs	            r9   handle_messagezContext.handle_message  s    :555##Ju}$=>>>F
*$&''1,,/2L$QqS)U "0 " " N
 4'((>99*?N?;G#'#7#HD G,,,I zz!6!:!:4:!F!F!-%>2I2I00 zU====#===--iEM9RSSSS00uGGG=#EEE<<YGGGG00uUUU=#<<<33I>>>>!]%III>>yIIII!]%FFF;;IFFFF00uEEE=#CCC::9EEEE00u;;;=#99900Ju<WXXXX00u:::=#CCC::9EEEE00 u???=#===--!"5=1"5?3"5=1	    10u;;;=#99900Ju}<UVVVV M$FFF- G CCINNNN00u:::,,
 ==?? X&'VWWWq $&''1,,,,,,r;   r  rz  rT  rS  r  c                N   | j                             d          }t          | j         j        |d|j        | j         j                  }t                      }t          |j        | j         j	        |j
        |t          j        |j                  z   |||| j        |j        	  	        S )Ns
   res masters
   resumptionr   )seconds)	r  ro  r  r  r  rT  r  rJ  r~  )r  r  r   rJ   r}  r  r\   r  r|  ro  r  rV   	timedeltar{  r+  r~  )r   r  rT  resumption_master_secretr  	timestamps         r9   _build_session_ticketzContext._build_session_ticket  s     $(#4#B#B=#Q#Q -'1+)6$0
 
 
 HH	&5*7 2 F% );)KLLLM&-/)%,
 
 
 	
r;   r   c                j   g }g }| j         D ]}|t          j        k    rr| j        rKt	                      | _        |                    t          j        | j                                        f           |                    t          j                   |t          j        k    rs| j        rKt                      | _
        |                    t          j        | j
                                        f           |                    t          j                   |t          j        k    rs| j        rKt                      | _        |                    t          j        | j                                        f           |                    t          j                   |t          j        k    rlt                      | _        |                    t          j        | j                                        f           |                    t          j                   |t          j        k    rt%                      | _        |                    t          j        | j                                        f           |                    t          j                   | j        | j                            d           t-          |          r,|                    |df           |                    |           t/          |          s
J d            d}| j        	 t3          | j                  }t5          |          }|j|\  | _        | _        d}| j        Q| j                            d| j        j        | j        j        | j        j        | j        j         | j        j!                   n!| j        | j                            d           n1# tD          $ r$ | j        | j                            d           Y nw xY wtG          | j$                  }|rLd| _%        | &                    ||	          }	|                    tN          j(        |	f           | j        j!        }
nWtS                      }	|                    tN          j(        |	f           | j*        }
| j        | j                            d
           tW          d%i d| j,        d| j-        dd | j.        D             d| j/        d| j0        d|d| j1        d|
d| j2        d|d| j3        d| j0        d| j4        d| j5        d|d| j6        d| j7        }| j8        r| j8        j9        rtu          | j8        j;                  | _<        | j<        =                    | j8        j>                   | j<        ?                    d          }| j<        j@        }| j8        jA        d|_B        t          | j8        jD        | j8        jE        fgt          |          g          |_G        t          d           }t          ||           |J                                |z
  d!z
  }| j<        K                    |L                    d"|                     | j<        M                    |          }||jG        jN        d"<   | j<        K                    |L                    ||d!z             |z              |jB        rP| j<        ?                    d#          }| O                    t          jQ        t          jS        | j<        j;        |           t          d$ | j.        D                       | _U        | jU        =                    d            t          | jU        |          5  t          ||           d d d            n# 1 swxY w Y   | W                    t          jY                   d S )&NzJTLS: Advertising to peer post-quantum algorithm using X25519ML768 (0x11EC)r  zno key share entriesFTzOECH: Selected config_id=%d, KEM=0x%04X, KDF=0x%04X, AEAD=0x%04X, public_name=%sz3ECH: No usable config found, falling back to GREASEz:ECH: Failed to parse ECHConfigList, falling back to GREASE)rG  rL  z*ECH: GREASE extension added to ClientHellor@  rA  r  c                ,    g | ]}t          |          S rA   r0   rH   xs     r9   r  z.Context._client_send_hello.<locals>.<listcomp>m      ???a3q66???r;   rC  rE  rG  rJ  rJ  rK  rL  rM  rN  rO  rP  rT  rV  rW  
   res binderr_  i   r  r   r      c e trafficc                0    g | ]}t          |          |S rA   )rB   )rH   r8  s     r9   r  z.Context._client_send_hello.<locals>.<listcomp>  s&    JJJB5Eb5I5IJRJJJr;   rA   )Zr>  r  r  r<  r   rW  r   r  r  r   rX  r  r   rY  r  r&   rZ  r  r'   r[  rV  debugrB   r   r\  r-  r9  r]  r^  r  r  r  r  r  	ExceptionrX  r'  r`  _build_ech_extensionrt  r  r  r+  r?  rf  rA  r8  r9  r  r:  r;  r@  rC  r=  r3  r4  r)  r  r  ro  rG  r  r  r  r  r  rF  r;  r~  r  r   rH  r   rl  r  r  r  r  r=  r2  r   r   r   r   r  rH  r  
_set_stater   r   )r   ry  rG  rL  r  ech_config_selectedr$  resultr  ech_extension_dataouter_server_namerb  
binder_keybinder_lengthtmp_bufhash_offsetr  	early_keys                     r9   r}  zContext._client_send_hello  ss   )+	&(+ *	/ *	/E'', 0C0E0ED-$$$*C*N*N*P*PQ   !''8888%/)), 0C0E0ED-$$$*C*N*N*P*PQ   !''8888%/)), 0C0E0ED-$$$*C*N*N*P*PQ   !''8888%,&&+<+>+>(  %,0H0S0S0U0U!VWWW ''5555%+++5K5M5M2  ):EEGG   !''(9:::=,M''5   "%(( /  %!1222 ''...9~~55555~ $ ,/0EFF*733%?E<D$d&<*.'}0++F ,6 ,3 29 2: ,8   }0++Q      =,M''T   $344
 	R $D!%!:!:#!1 "; " " 57IJ   !% 0 < "=!>!>57IJ   !% 1}(##$PQQQ 
 
 
%%
"44
 @?4+>????
 (,'G'G	

  //
  i
 $(#?#?
 *)
 "&!;!;
 .-
  $77
  //
 -1,Q,Q
 (,'M'M
 (Z
  #55!
" #55#
*  %	4#6#? %	%01D1Q%R%RD""**4+>+PQQQ/==mLLJ 2>M "6B#' #.(/1D1ST }--.	$ $ $E  d+++Ggu--- ",,..=81<K"..w/A/A![/Q/QRRR+@@LLF.4E (+".."";a@@6I  
   2@@PP	**%N*7	   $4JJ$-JJJ$
 $
  	 ((...$2J?? 	1 	1j%000	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	899999s%   B0O +O/.O/,^		^^rG  list[KeyShareEntry]rL  rB  c                     j         J  j        J t          j        d           _        d j         j        z   }t           j         j         j        j         j        j	         j         j
        |           _         j                                        g }|                     j                   |                    t          j                    j        |                    t          j                   |                    t          j                    j        |                    t          j                    j        |                    t          j                   |                    t          j                   |                    t          j                   |                    t          j                    j        D ]*\  }}|t          j        k    r|                    |           + j        D ]*\  }}|t          j        k    r|                    |           +|                     j                   t;          dt=          |          dz  z             }t?          |d          5  |D ]}|                     |           	 ddd           n# 1 swxY w Y   t;          d          }|                     tB                     |"                     j                   tG          |dd	           tI          |d|j         d
  j%        D                        tI          |d|j&         j'                   t?          |d          5   j(        tS          |t          j*                  5  t?          |d          5  |&                    d           tG          |d j(        +                    d                     ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   tS          |t          j,                  5  |&                    d           ddd           n# 1 swxY w Y   tS          |t          j-                  5  |"                    |j.                   ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   |j.        }	 j(        r't=           j(        +                    d                    nd}
t_          d j         j0        |
z
            }t=          |	          |z   }|dz  }|dk    r|d|z
  z  }|dk    r|	d|z  z  }	d}t=          |	          |z   }d* fd} |d|z            }tc           j                  }|                    t          j,        |f           te          d+i d j3        d j4        dd  j%        D             d j'        d j        d|d j5        d j         j6        d j7        d|d j8        d j        d  j        d!|d" j        d# j        }t;          d$          }ts          ||           |j.        d%d         } j        :                    ||	&          } ||          }t;          d$          }|&                    tv          j<                   t?          |d'          5  |                     tB                     |"                     j                   tG          |d j4                   tI          |d|j         d(  j%        D                        tI          |d|j&         j'                   t?          |d          5   j(        tS          |t          j*                  5  t?          |d          5  |&                    d           tG          |d j(        +                    d                     ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   tS          |t          j,                  5  |&                    d           ddd           n# 1 swxY w Y   tS          | j                  5  	 ddd           n# 1 swxY w Y   tS          |t          j                  5  tI          |d|j          j7                   ddd           n# 1 swxY w Y    j        \tS          |t          j                  5  tI          |dt{          t|          |           j                   ddd           n# 1 swxY w Y   tS          |t          j                  5  tI          |dt{          t~          |          |           ddd           n# 1 swxY w Y    j        NtS          |t          j                  5  tI          |d|j          j                   ddd           n# 1 swxY w Y    j        \tS          |t          j                  5  tI          |dt{          t|          |           j                   ddd           n# 1 swxY w Y   tS          |t          j                  5  tI          |d|j&         j5                   ddd           n# 1 swxY w Y   tS          |t          j                  5  tI          |d|j          j8                   ddd           n# 1 swxY w Y   tS          |t          j                  5  tI          |d|j         |           ddd           n# 1 swxY w Y    j        D ]R\  }}|t          j        k    r=tS          ||          5  |"                    |           ddd           n# 1 swxY w Y   S j        D ]R\  }}|t          j        k    r=tS          ||          5  |"                    |           ddd           n# 1 swxY w Y   StS          | j                  5  |&                    d           ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   |j.         _@         jA        O jA        B                    d) j         jC        t=                    t=          |          t=          |	                     |S ),a  
        Build a real ECH extension for the outer ClientHello.

        This constructs the inner ClientHello (EncodedClientHelloInner),
        encrypts it with HPKE, and returns the outer ECH extension payload.

        The inner CH contains the real SNI (server_name), while the outer
        CH will have its SNI replaced with the ECH config's public_name.

        RFC 9849 Section 5.1:
        EncodedClientHelloInner = inner CH without Handshake header,
          with legacy_session_id = empty, padded to hide true SNI length.

        The AAD is the complete outer ClientHello (serialized with Handshake
        header) with the ECH payload field replaced by zeros.
        NrL   s   tls ech )r  r  r  r  r   r   r-   r  i   r;   c                ,    g | ]}t          |          S rA   r  r  s     r9   r  z0Context._build_ech_extension.<locals>.<listcomp>	  s    111SVV111r;   r   r!  r  rv  r  r   r/   c                8   t          dt                    z   dz   t          |           z             }|                    d           |                    j        j                   |                    j        j                   |                    j        j                   |                    t                               |	                               |                    t          |                      |	                    |            |j
        S )z1Build ECH extension structure with given payload.r4   r-   r  r   )r   r   r  r  r^  r  r  r]  r  r  r  )r  r  r	  r   s     r9   _build_ech_headerz7Context._build_ech_extension.<locals>._build_ech_header*	  s    -#c((":Q">W"MNNNCNN1OOD29:::OOD2:;;;NN4+5666OOCHH%%%NN3OOCLL)))NN7###8Or;   r@  rA  r  c                ,    g | ]}t          |          S rA   r  r  s     r9   r  z0Context._build_ech_extension.<locals>.<listcomp>A	  r  r;   rC  rE  rG  rJ  rJ  rK  rL  rM  rN  rO  rT  rV  rW  i    r   )aad	plaintextr   c                ,    g | ]}t          |          S rA   r  r  s     r9   r  z0Context._build_ech_extension.<locals>.<listcomp>	  s    555AQ555r;   z_ECH: Built real ECH extension (config_id=%d, enc=%d bytes, payload=%d bytes, inner_ch=%d bytes))r  r   r/   r   rA   )Dr]  r^  r5   r6   rb  r   r   r  r  r  r  r_  r	  r   r3  rt  r}  r  r  r  rC  r  r~  r  r  r|  r'  r  r4  r   r   r  r  re  r  r  r  r8  r  r9  r+  r  rz  r  r  r  r  maxr  rX  r?  rf  rA  r:  r  r;  r@  rl  sealr  r  r	   r  r  re  rV  r  r  )r   rG  rL  r   compressed_typesr7  r`  outer_ext_buf	inner_bufencoded_innerserver_name_lenpadding_needed	total_len	remainderaead_tag_lenr
  r  ech_placeholderaad_extensions	aad_helloaad_bufr  
ciphertextr  inner_ch_buf	ext_valuer	  s   `                         @r9   r  zContext._build_ech_extension  s   * +++%111 "$B  0 44!,#*)0*2'2"
 "
 "
 $((** ') 7888 BCCC+##M$FGGG 78880<##M$FGGG+##M$6777 DEEE @AAA >???  4 	2 	2KHa=BBB ''1114 	2 	2KHa=BBB ''111 7888 C0@,A,AA,E(EFFFq)) 	4 	4, 4 4))(33334	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4
 D)))	o...T3444Iq#&&&!11T0111		
 	
 	
 	)Q	 4d6VWWW 	1%% 	9 	9 ,#I}/HII U U#Iq11 U U!,,Q///#Iq$2C2J2J72S2STTTU U U U U U U U U U U U U U UU U U U U U U U U U U U U U U  	=+OPP ( ($$Q'''( ( ( ( ( ( ( ( ( ( ( ( ( ( (  	=+MNN 9 9$$]%78889 9 9 9 9 9 9 9 9 9 9 9 9 9 9	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9  " 7;6GNC!((11222Q 	 Q 0 D VWW&&7	N	>>b9n,NAW~55M -((<7	 	 	 	 	 	 	 ,+Gk,ABB d788}C_UVVV 
 
 
%%
"44
 @?4+>????
 (,'G'G	

  //
  i
 $(#?#?
 (44
 "&!;!;
 .-
  $77
  //
 -1,Q,Q
 ,^
 #55
  #55!
	0 $''''9---l122 +00SM0RR
 #":..4 t,,, :;;;a(( G	/ G	/$$_555##D$:;;;a)?@@@(55!4555	   '0	   L!,, u/ u/ $0'm6OPP  'a88  (33A666' , ! $ 1 8 8 A A                               $L-2VWW / / ++A.../ / / / / / / / / / / / / / / $L$2IJJ                 $L-2TUU  $$02	                 '3'$m&H    "(#$6EE 0	                 $L-2IJJ  $==!	                 8D'$m&H    "((4 A	                 '3'm6HII  !(#$6EE 0	                 $L-2VWW  $$/4	                 $L-2RSS  $$00	                 $L-2PQQ  $$0(	                 ,0+D ? ?'Hi=#JJJ+L(CC ? ?(33I>>>? ? ? ? ? ? ? ? ? ? ? ? ? ? ?+/+D ? ?'Hi=#JJJ+L(CC ? ?(33I>>>? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
 $L$2IJJ / / ++A.../ / / / / / / / / / / / / / /iu/ u/ u/ u/ u/ u/ u/ u/ u/ u/ u/ u/ u/ u/ u/%G	/ G	/ G	/ G	/ G	/ G	/ G	/ G	/ G	/ G	/ G	/ G	/ G	/ G	/ G	/R $0#4 =$M7 *CJM""   s  1JJ J"R
-O >?O	=O 	OO OO R
 O$	$R
'O$	(R
P'R
'P+	+R
.P+	/R
Q3'R
3Q7	7R
:Q7	;R

RRBp	6"o2_)?^4	(_4^88_;^8<_?o2_o2_o20`o2`o2`o22a 4o2 ao2ao2%bo2bo2b$o2:+c1%o21c55o28c59o2&e<o2eo2e$o24fo2f!!o2$f!%$o2	+h 4o2 ho2ho2%io2io2io23jo2j  o2#j $o2k%o2%k))o2,k)-/o2l>	2o2>mo2m0o26n	o2no2n o29oo2oo2"o#o2&p	2o6	6p	9o6	:p		pp
peer_hellorn  ro  rj  raw_server_helloc                H   | j         J | j        J |j        dd         }t          |          }d|dd<   t	          |          }t          j        d|           }|                    | j                   |                    t          |                     |	                                }t          |dz            }	t          |t          |	          | j         	          }
t          ||
d
|d          }| j        | j                            d||k               ||k    S )ax  
        Check ECH acceptance confirmation per RFC 9849 Section 7.2.

        The server signals ECH acceptance by embedding a confirmation value
        in the last 8 bytes of ServerHello.random. To verify:
        1. Zero the last 8 bytes of ServerHello.random in the raw wire bytes
        2. Compute transcript hash over inner_CH + modified_ServerHello
        3. Compute accept_confirmation = HKDF-Expand-Label(
               HKDF-Extract(0, inner_random),
               "ech accept confirmation",
               transcript_hash, 8)
        4. Compare with original last 8 bytes of ServerHello.random

        IMPORTANT: We must use the original wire bytes (raw_server_hello) and
        modify them directly, rather than re-serializing with push_server_hello(),
        because push_server_hello() may reorder extensions differently from the
        original wire format.
        Nr  rL   s           r  &   r   r4   r  s   ech accept confirmationr   zECH acceptance check: match=%s)rb  re  r@  	bytearrayr  rG   r  r   r   r   r0   r   r   rV  r  )r   r  ro  r  	candidatemodified_shrJ   transcript_hashtranscript_ech_confr  prkaccept_confirmations               r9   _check_ech_acceptancezContext._check_ech_acceptance
  s\   0 %111'333 %be,	   011(BrE &l33	!+&7I&7&788t7888u[11222-4466 )a-(({##/
 
 

 0,*
 
 
 =$M0#y0  
 #i//r;   r  c                ,   t          |          }|j        }t          | j        |j        gt          d          t                    }|j        | j        vrt          d          |j
        | j        vrt          d          | j        rN| j        G|                     |||          | _        | j        $| j                            d| j        rdnd           |j        =| j        |j        dk    s|| j        j        k    rt          | j        | _        d	| _        n| j                            |          | _        d | _        d | _        |j        d
         }d }|j        d         t2          j        k    r#| j        | j                            |          }n|j        d         t2          j        k    r<| j                            |          }| j        | j                            d           n|j        d         t2          j        k    r"| j         | j                             |          }ny|j        d         t2          j!        k    r"| j"        | j"                            |          }n<|j        d         t2          j#        k    r!| j$        | j$                            |          }|t          d          | j        rX| j%        J tM          j'        d| j        j(                   | j        _)        | j        j)        *                    | j%                   | j        +                    |j                   | j        ,                    |           | -                    t\          j/        t`          j1        d           | 2                    tf          j4                   d S )NzUnsupported cipher suiter  z9ServerHello has a compression method we did not advertisez.ServerHello has a version we did not advertisezECH: Server %s ECHacceptedrejectedr   Tr   zBTLS: Post-quantum safety achieved using X25519ML768 (key-exchange)z7ServerHello selected a key share group we did not offerr      s hs traffic)5ru  r  r  r8  ro  r   rB   rp  r9  r   rq  r@  r`  rb  r  ra  rV  r  rH  rG  r  rR  rH  r  rG  r  r  rZ  exchanger  r[  r  rW  r  rX  r  rY  re  rG   r  rJ   r  r   r  r  _setup_traffic_protectionr   r   r   r   r  r   r   )r   r  ry  r  r  ro  peer_public_key
shared_keys           r9   r  zContext._client_handle_hello[
  s   &y11
 %> $%!"<==$	
 
 
 (0PPP'K   't/GGG'@    	!7!C!%!;!;L*:" "D }(##("&"4DJJ*   $0&.,114#9#FFF++ $ 6D$(D!! $ 8 ? ? M MD!%#'  %.q1#'
  #u|33(41::?KKJJ!!$(999;DD_UUJ}(##X    #u66)52;;OLLJJ #u66)52;;OLLJJ #u66)52;;OLLJ (I    	D +777%,[1Tt7H7R1T1T%U%UD""))$*BCCC%%in555!!*---&&u	
 	
 	
 	@AAAAAr;   c                   t          |          }|j        | _        |j        | _        |j        | _        | j        r|                     | j                   |j        D ]%\  }}|t          j	        k    rd| _
        || _         n&|j        U| j        rt          | j        r@|j        | _        | j        -| j                            dt'          |j                             |                     t*          j        t.          j        d           | j                            |j                   | j        r!|                     t<          j                   d S |                     t<          j                    d S )NTz<ECH: Server rejected ECH, provided %d bytes of retry_configs   c hs traffic)!r  r  rD  rF  rE  rT  rF  r/  rt  r  rM  rN  r  ra  r   r`  rc  rV  r  r   r  r   r   r   r   r  r  r  rR  r  r   r   r   r   r  encrypted_extensionsr7  r  s        r9   r  z+Context._client_handle_encrypted_extensions
  s   8CC3A#7#B #7#H < 	/LL-...
 $8#H 	 	Hi====(,%+4( >  -9! 0 0/   +?*L'=,M''V0>??  
 	&&u	
 	
 	
 	%%in555   	TOOE899999OOERSSSSSr;   c                    |                      t          |                     | j                            |j                   |                     t          j                   d S rE   )_process_certificater  r  r  r  r  r   r   r   r  s     r9   r  z"Context._client_handle_certificate
  sS    !!"29"="=>>>%%in555>?????r;   c                D   t          |t          j                   t          |d          5  |                                }|                                }t          |d          }d d d            n# 1 swxY w Y   |t          k    st          t          d          	 t          j
        |          }n# t          $ r t          d          w xY wt          |          |k    rt          d          t          t          j        g          t          |                              dd          z   |z   }|                     t#          t%          |                               | j                            |j                   |                     t.          j                   d S )Nr   z-unsupported certificate compression algorithmz certificate decompression failedz(certificate decompressed length mismatchr  r  )r\  r  r  r  r  pull_uint24r  rB  rA  r   
decompressr  r   r   r  r  r  r  r   r  r  r  r  r   r   )r   r  rJ   uncompressed_length
compressedcertificate_bodycertificate_messages          r9   r  z-Context._client_handle_compressed_certificate
  s    	I}'KLLL	1%% 	3 	3!--//I"+"7"7"9"9$Y22J	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3
 666'/%&UVVV	J&1*== 	J 	J 	J%&HIII	J   $777%&PQQQ
 =,-.."##,,Q667 	
 	!!"26?R3S3S3S"T"TUUU 	%%in555>?????s   9A00A47A4B2 2CrH  r,   c                   t          j        d         d                   }	 |                                s|                                }|                                }|t          j        k    rb|                                }|dk    r/|                                }|                    |          | _	        n.|                    |dz
             nn|                                n# t          $ r Y nw xY wt          j        d         d                   | _        fdt          dt          j                            D             | _        d S )Nr   r   r  c                P    g | ]"}t          j        |         d                    #S )r   )r  r  )rH   rd  rH  s     r9   r  z0Context._process_certificate.<locals>.<listcomp>2  s>     (
 (
 (
 K4Q7:;;(
 (
 (
r;   )r   r  r1  r  rt  r{  r  r  r  rL  r   r  rJ  ranger   rK  )r   rH  r5  r7  ext_lenstatus_typeresp_lens    `     r9   r  zContext._process_certificate  sg    k6q9!<===	 kkmm "..00!--//};;;")"4"4"6"6K"a''#*#6#6#8#8.5.@.@.J.J+**7Q;7777 kkmm   	 	 	D	 "11I!1LQ1O!P!P(
 (
 (
 (
1c+":;;<<(
 (
 (
$$$s   CC( (
C54C5c                    t          |          | _        | j                            |j                   |                     t          j                   d S rE   )r  rU  r  r  r  r  r   r   r  s     r9   r  z*Context._client_handle_certificate_request7  sF    $<Y$G$G!%%in555NOOOOOr;   c           
        t          |          }|j        | j        vrt          d          	 t	          | j                                        |j        | j                            d          |j	                   n.# t          $ r!}t          t          |                    d }~ww xY w| j        t          j        k    rc| j        r| j        s| j        | j        j        }n| j        }t)          | j        | j        | j        | j        | j        || j        | j                   | j        | j                            dd                                          }t=          |          }t>                               |          }|stC          d|           tE          |#                                          } || j        $                                          %                                }	|	|k    r:tC          d|&                                 d|	&                                 d	          | j        '                    |j(                   | )                    tT          j+                   d S )
Nz@CertificateVerify has a signature algorithm we did not advertise!   TLS 1.3, server CertificateVerify)r6  r7  r,  rH  rI  rJ  rK  rL  rQ   zFingerprint of invalid length: z&Fingerprints did not match. Expected "z", got ""),r  rJ   r;  r   r+   rJ  r  r  r  r  r$   r-  r,  r  r.  r`  ra  r]  r  r+  rh  r  r   r!  rK  r$  rL  r#  rZ   lowerr   HASHFUNC_MAPr~  r   r   r  r  r   hexr  r  r  r   r   )
r   r  r[  rf  cert_server_namefingerprintdigest_lengthhashfuncexpect_fingerprintpeer_fingerprints
             r9   r  z)Context._client_handle_certificate_verify<  s   (334#===#R  

	,"&1133 !998        	, 	, 	,#CFF+++	, --
 !5*5 $0#'#3#?  #'#4 ||| 22,#'#8"1	 	 	 	 #/2::3CCIIKKK,,M#''66H )CkCC   "+;+=+=+?+?!@!@'x(>(K(K(M(MNNUUWW#555)6!3!7!7!9!96 6,00226 6 6   	%%in555455555s   AA: :
B%B  B%c           
        t          |          }| j                            | j                  }|j        |k    rt
          | j                            |j                   | j        j        dk    sJ | j        	                    d            | 
                    t          j        t          j        d           | j                            d          }| j        r]t#          | j        |          5  t%          |t'          t(          j        | j        fg                     d d d            n# 1 swxY w Y   | j        t#          | j        |          5  t1          |t3          | j        j        d | j        g| j        z   D                                  d d d            n# 1 swxY w Y   d | j        | j        fvr|g }t=          | j        t>                    rt@          j!        t@          j"        g}nt=          | j        tF                    rZ| j        j$        dk    rt@          j%        g}nc| j        j$        dk    rt@          j&        g}nE| j        j$        d	k    rt@          j'        g}n't=          | j        tP                    rt@          j)        g}tU          || j        j+        tY          d
                    } | j        j-        | j        .                    d          gt_          |          R  }t#          | j        |          5  ta          |tc          ||                     d d d            n# 1 swxY w Y   t#          | j        |          5  te          |tg          | j                            | j4                                       d d d            n# 1 swxY w Y   || _4        | 5                    t          j6        t          j        | j        j7        | j4                   | 8                    tr          j:                   | j;        r7| j<        s2| j=        | j=        >                    d           t          d          d S d S )Nr-      s ap traffic   c ap traffic)rT  c                >    g | ]}||                                 dfS )Nr;   rX  )rH   certs     r9   r  z3Context._client_handle_finished.<locals>.<listcomp>  s9     & & & $#/ "..00#6///r;   r  r  r  r  r   No supported signature algorithms!   TLS 1.3, client CertificateVerifyr  r  zLECH: Handshake completed for outer (public_name), raising ech_required alertz*ECH was offered but rejected by the server)@r  r  r  rT  r  r   r  r  r  r  r  r   r   r   r   r  rM  r  r  r  rt  r  rO  rU  r  r,   r  rH  r%  r&  r\  r!   r  r  r  r   r  r  r  r  r   r  r  rK  r   signr  r  r  r  r  r  rS  r2  r   ro  r  r   r   r`  ra  rV  r  r   )	r   r  ry  r  expected_verify_datanext_enc_keyrK  r  r  s	            r9   r  zContext._client_handle_finished  s    ++  $0EEdmTT#777##%%in555  +q0000!!$'''&&u}o	
 	
 	
 (66GG   	d/<<  )' !. B $ 9*  
 
 
               $0d/<<   (,(A(Q& &)-)9(:T=S(S& & &  
 
 
               D,d.JKKKAC$d:MJJ H*>*;,((   <lKK H3>#EE.E0,, 5@CGG.E0,, 5@CGG.E0,   <>OPP H,>,F+G(&/(-B)*LMM' '# >D8=%==<  00CDD	  	 "$"3Z@@  +")&9Y                   $+Z88 	 	 $ 1 F Ft} U U    	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 %""M*M		
 	
 	
 	3444  	QT%7 	Q}(##1   ##OPPP	Q 	Q 	Q 	QsI   -1D**D.1D.AF  F$'F$ L--L14L1<NNNc                    t          |          }| j        2|                     || j                  }|                     |           d S d S rE   )r  r1  r  rF  )r   r  r  r~  s       r9   r  z)Context._client_handle_new_session_ticket  s\    4Y?? %1//"D$< F &&v.....	 21r;   initial_bufhandshake_buf
onertt_bufc           
        t          |          }g }t          | j        t                    rt          j        t          j        g}nt          | j        t                    rZ| j        j        dk    rt          j	        g}nc| j        j        dk    rt          j
        g}nE| j        j        dk    rt          j        g}n't          | j        t                    rt          j        g}t          | j        |j        t#          d          t$                    }t          | j        |j        t#          d                    }t          | j        |j                  }	t          ||j        t#          d                    }
t          | j        |j        t5          d                    }| j        -t          | j        |j        t#          d	                    | _        |j        | _        tA          j!        d
          | _"        |j#        | _#        |j$        | _%        | j&        r| &                    | j                   | j'        rQ|j$        D ]I\  }}|tP          j)        k    r4d| _*        | j+        ,                    tP          j)        | j-        f            nJd }| j.        |	|j/        
ta          |j/        j1                  dk    rta          |j/        j2                  dk    r|j/        j1        d         }| .                    |d                   }||j3        r|j4        |k    rtk          |          | _6        | j6        7                    |j8                   | j6        9                    d          }| j6        j:        }|;                                |z
  dz
  }|<                    |dz   |dz   |z             }| j6        =                    |<                    d|                     | j6        >                    |          }||k    rt#          d          | j6        =                    |<                    ||dz   |z                        d| _?        |j@        rW| j6        9                    d          }d| _A        | B                    t          jD        t          jF        | j6        j4        |           d}|Mtk          |          | _6        | j6        7                    d            | j6        =                    |jG                   d }d }d }|jH        D ]}|d         }|d         t          jJ        k    rUt                      | _L        | jL        M                                }| jL        N                    |          }t          jJ        } n|d         t          jO        k    rUt                      | _Q        | jQ        N                    |          }| jQ        R                                }t          jO        } n@|d         t          jS        k    rTt                      | _U        | jU        M                                }| jU        N                    |          }t          jS        } n|d         t          jV        k    rTt                      | _X        | jX        M                                }| jX        N                    |          }t          jV        } nl|d         t          jY        k    rTt                      | _[        | j[        M                                }| j[        N                    |          }t          jY        } n!|t#          d          t          | j"        | j#        ||||f||          }t          | j6        |          5  t          ||           d d d            n# 1 swxY w Y   | j6        7                    |           | _                    t          j`        t          ja        d           | _                    t          jD        t          ja        d           t          | j6        |          5  t          |t          | j        | jA        | j+                             d d d            n# 1 swxY w Y   |t          | j6        |          5  t          |t          dd | jf        g| jg        z   D                                  d d d            n# 1 swxY w Y    | j        jh        | j6        i                    d          gt          |
          R  }t          | j6        |          5  t          |t          |
|                     d d d            n# 1 swxY w Y   t          | j6        |          5  t          |t          | j6        >                    | jo                                       d d d            n# 1 swxY w Y   | j6        jp        dk    sJ | j6        7                    d            | _                    t          j`        t          jq        d           | j6        9                    d          | _r        | j*        sv| j6        >                    | js                  | _t        t          d !          }t          |t          | jt                             | j6        =                    |jG                   | jv        |	t          d"t          jy        d#tA          j!        d$                    d         dtA          j!        d           | jz        %          | _{        t          || j{                   | }                    | j{        | j+                  }| v                    |           | ~                    t          j                   d S )&Nr  r  r  zNo supported cipher suiter  zNo supported compression methodr  zNo supported protocol versionzNo common ALPN protocolsrL   Tr   r   r  r   zPSK validation failedr  z+No supported key share group in ClientHello)r@  rA  ro  rp  rG  rH  rq  r  r  )r  rF  rT  r;   c                :    g | ]}|                                 d fS )r;   rX  r  s     r9   r  z0Context._server_handle_hello.<locals>.<listcomp>  s7     & & & ! ^^--s3& & &r;   r  r  r  r  r-   r  r  rP   r  iQ Ir   )r{  r|  r}  r~  r  )rf  r\  r&  r!   r  r  r  r   r  r  r  r  r   r  r  r8  r  r   rB   r9  rC  r:  rJ  rK  r@  rM  r   r  rE  rD  r@  rf  r5   r6   server_randomrA  rT  rF  r/  rP  rt  r  rM  r'  r   rO  r0  rH  r   r<  r=  r  ro  r  r  r  r  r  r  r  r  r  r  rR  rF  rE  r2  r   r   r   r   r  rG  r  r  r&   rZ  r  r  r  r'   r[  shared_ciphertextr  r   rW  r  r   rX  r  r   rY  rn  r  rx  r  r   r   r  r  r  r,   rH  r%  r  r  r  r  r  r  r  rS  r  r   _next_dec_keyrT  _expected_verify_datar   r1  rz  r   unpackr(  rI  r  r  r  r   r   ) r   r  r	  r
  r  r  rK  ro  rp  psk_key_exchange_moder  rq  r7  r`  rH  r   r)  r  r  r  r  expected_binderr  r  group_kxr  rG  r  rb  r  r  r~  s                                    r9   r  zContext._server_handle_hello  s    'y11
 :<d2MBB 	@"6"3$   4lCC 	@+6#==(:(Q'R$$-8C??(:(Q'R$$-8C??(:(Q'R$46GHH 	@$6$>#?  !$!"=>>$	
 
 
 ',1!"CDD
 

 !*(**K!
 !
 ( +!"DEE
 

 &$) !@AA
 
 +#,$)%&@AA$ $D  (.Z^^!+!=#-#> < 	/LL-...  
	): 	 	!}AAA,0D)-44)> 5   E B &2%1)5J-899Q>>J-566!;; "0;A>H!77DDN *"+ +"/<??$/$=$=!!)).*JKKK!.<<]KK
 $ 1 ='nn..>B"--!O[1_}%D  !--i.B.B1k.R.RSSS"&"3"H"H"T"T_,,/0GHHH!--((kAo6UVV   )-% (  $ 1 ? ? O OI/3D,..!))6!	   "# ! +L 9 9D%%d+++))).999 $(
!%#'
#- "	 "	I'lO|u|+++<+>+>(!5@@BB
!5>>OO
 <1!2225K5M5M2!?HH# 
 "?QQSS
 ,100,?,A,A)!6AACC
!6??PP
 ?100,?,A,A)!6AACC
!6??PP
 ?100,?,A,A)!6AACC
!6??PP
 ? 1  ((UVVV %"4%1,)/
 
 
 $+[99 	2 	2k5111	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2!!*---&&u	
 	
 	
 	&&u	
 	
 	

 $+];; 	 	%#"&"6#7%)%>    	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 !d/?? 
 
 !(+& &&*&6%7$:P%P& & &  	 	 	
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 :49!998  ,,?@@	  I d/??  '!%"5                   $+];; 	 	 $ 1 F Ft} U U    	 	 	 	 	 	 	 	 	 	 	 	 	 	 	  +q0000!!$'''&&u}o	
 	
 	
 ".<<_MM $ 	4)-):)O)O* *D& "%%%C#xD4NOOOPPP))#(333 %16K6W'7 %%}S"*Q--@@C z"~~$($8( ( (D$ $J0HIII //($*C F &&v...455555sZ   *^^^0aaa58b99b= b= d==ee<f%%f),f)c                    t          |          }|j        D ]\  }}|t          j        k    r	|| _         n| j                            |j                   d S rE   )r  rT  rt  r  rN  r  r  r  r  s        r9   r  z2Context._server_handle_client_encrypted_extensions>  sh    8CC#7#H 	 	Hi====+4( > 	%%in55555r;   c                   t          |          }| j        r$| j                            | j                  | _        |j        | j        k    rt          | j        r| j                            |j	                   | j
        | _        d | _
        |                     t          j        t          j        | j        j        | j                   |                     t$          j                   d S rE   )r  rM  r  r  rT  r  r  r   r  r  r  r2  r   r   r   r   ro  r  r   r   )r   r  ry  r  s       r9   r  zContext._server_handle_finishedI  s     ++
   	)-):)O)O* *D&
 4#===##  	:))).999 *!""M*M		
 	
 	
 	344444r;   	directionr   r   r   c                    | j                             |          }|t          j        k    r|| _        n|| _        |                     ||| j         j        |           d S rE   )r  r  r   r   rS  rT  r2  ro  )r   r  r{  r   keys        r9   r  z!Context._setup_traffic_protectiong  si     --e44	)))DMMDM""ud/<c	
 	
 	
 	
 	
r;   rg  r   c                x    | j         r+| j                             d| j        j        |j                   || _        d S )NzTLS %s -> %s)rV  r  rg  r4  )r   rg  s     r9   r  zContext._set_stateu  s8    = 	MM
LLL


r;   )NNNNNNNNNFNTNNFF)"r  r=   rE  rD  r6  r   r7  r8  r,  r8  r  r  r  r  r  rU  rJ  r8  r  rU  r  r=   r  r8  r  r=   r  r   rK  rI  r  r=   r  r=   )r/   rh  )r/   r  r  )r/   r   )r   )rx  r   ry  rz  r{  r0   r/   rM  )r  rz  rT  rS  r/   r  )ry  r   r/   rM  )rG  r  rL  rB  r/   r   )r  rn  ro  rj  r  r   r/   r=   )r  r   ry  r   r/   rM  )r  r   r/   rM  )rH  r,   r/   rM  )
r  r   r	  r   r
  r   r  r   r/   rM  )r  r   r{  r   r   r   r/   rM  )rg  r   r/   rM  )rx   ry   rz   r   r  rk  rm  ro  rq  rs  ru  rw  r  r  r}  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rA   r;   r9   r  r    s        ,0#!!26@D%)"&"&,1)- $(,15$)16%y: y: y: y: y:v & & & X& , , , X, % % % X% " " " X" ' ' ' X' % % % X% ( ( ( X( PR`X `X `X `X `XD
 
 
 
4m: m: m: m:^_ _ _ _BH0 H0 H0 H0TgB gB gB gBR+T +T +T +TZ@ @ @ @
 @  @  @  @D
 
 
 
>P P P P
C6 C6 C6 C6J~Q ~Q ~Q ~Q@/ / / /q6 q6 q6 q6f		6 	6 	6 	65 5 5 5<
 
 
 
     r;   r  r  )r<   r0   r/   r=   )T)rR   r=   r/   rS   )r   r   r   r   rI   r0   r/   r   )rJ   r0   r   r   r   r   r   r   rI   r0   r/   r   )rJ   r0   r   r   r   r   r/   r   rE   )r  r   r  r   r/   r  )r  r   r/   r  )r  r   r/   r  )r,  r-  r/   r=   )NNN)r6  r   r7  r8  r,  r8  r/   r9  )NNNNNTN)rH  r  rI  r  r6  r   r7  r8  r,  r8  rJ  r8  rK  r=   rL  r   r/   rM  )r  r   r  r0   r/   r   )r  r   r  r0   r  r  r/   r  )
r  r   r  r0   r  r  r  r  r/   rM  )r  r   r  r0   r/   r   )r  r   r  r0   r  r   r/   rM  )r  r   r  r0   r/   r   )r  r   r/   r-  )r  r   rJ  r-  r/   rM  )r  r   r/   r  )r  r   r  r  r/   rM  )r  r   r  r-  r/   rM  )r  r   r/   r  )r  r   r  r  r/   rM  )r  r   r/   r   )r  r   r  r   r/   rM  )r  r   r/   r!  )r$  r!  r/   r.  )r  r   rY  r  r/   rM  )r  r   r/   r?  )r  r   rb  r?  r/   rM  )r  r   r/   rn  )r  r   rb  rn  r/   rM  )r  r   r/   rz  )r  r   r  rz  r/   rM  )r  r   r/   r  )r  r   r  r  r/   rM  )r  r   r/   r,   )r  r   r/   r  )r  r   rH  r,   r/   rM  )r  r   r/   r  )r  r   r[  r  r/   rM  )r  r   r/   r  )r  r   r  r  r/   rM  )ro  rj  r/   r0   )r  r  r  r  rg  r  r  r  r  r  r/   rC   )r  r0   r/   r  )r  r  r  r   r/   r   )r/   r   )
__future__r   rV   r@  rG   loggingr5   rer  r   binasciir   
contextlibr   dataclassesr   r   enumr   	functoolsr	   hmacr
   typingr   r   r   r   r   r   r   _hazmatr   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r  compiler2  brotlirA  ImportError
brotlicffirB  re  r?  r#  r:   rB   rC   r  r\   r^   r  r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r5  rG  rh  rj  rq  rt  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r0   r   r  r  r  r  r  r  r  r  r  r  r  r  r-  r0  r2  r3  r9  	Extensionr;  r?  r\  rf  rl  rn  ru  rx  rz  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rk  rl  rm  r  r  r  r  r  r  r  r  r  r  r}  r  r  r  r  r  r-  AlpnHandlerSessionTicketFetcherSessionTicketHandlerr  r  rA   r;   r9   <module>r0     s   " " " " " " "     				 				 



        % % % % % % ( ( ( ( ( ( ( (                   O O O O O O O O O O O O O O O O O O                                                     6      &2:&@AA    $$$$$    "#    9 9 9 9 GCLL   8 8 8 8 8
    w   >" " " " "I " " "3 3 3 3 3% 3 3 37 7 7 7 7e 7 7 70 0 0 0 0u 0 0 01 1 1 1 1 1 1 15 5 5 5 5E 5 5 55 5 5 5 5E 5 5 52 2 2 2 2 2 2 24 4 4 4 45 4 4 46 6 6 6 6U 6 6 69 9 9 9 9 9 9 90 0 0 0 0u 0 0 0       
    G       G   " 
$em	,eo	:EO	/	*EO	 %/		$em	 %/	)     ** ** ** ** ** ** ** **Z          +/!9 !9 !9 !9 !9HF F F F   *      /  /  /  /  /J $("#"&X/ X/ X/ X/ X/v    '              G   *    G       G       w          
       2 D D D D    $	 	 	 	   & & & &       3 3 3 39 9 9 9 c5j!   " " " "/ / / /2 2 2 2 E3J- - - -   
                          4I I I IZ      , , , ,b #u*	        
 ) ) ) ) ) ) ) )@
 
 
 
> > > >B{ { { {| 
L 
L 
L 
L 
L 
L 
L 
L   B4 4 4 4: L L L L L L L L   24 4 4 4$ L L L L L L L L   84 4 4 4, &  G G G G G G G G
 L L L L L L L L   &   0
 
 
 
        
G G G G. . . .           . . . .
6 6 6 6 6 6 6 6r               " "C"C(# -{-{-{'''*K*K*K
K  
 
 
 
' ' ' ' ,0    *    E E E E 0 0 0 0 0 0 0 06 ud{#-)@ @A  56 ) ) ) )X] ] ] ] ] ] ] ] ] ]s6   -B2 2C8B=<C=CCCCC