
    h\                        d 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 dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ d Z G d de           Z! G d de!          Z" G d de!          Z# G d de           Z$ G d de          Z% G d de           Z& G d de          Z' e&            e_(        dS )z
TLS session handler.
    N)conf)raw)log_runtimewarning)Packet)	inet_pton)
TCPSession)repr_hexstrxor)TCP)	Comp_NULL)
TLS13_HKDF)PRF)Dictc                    t          j        t                    }	 t          |           }|                                 n"# t
          $ r t          d|            i cY S w xY w	 t          |           5 }|D ]}|                    d          r|                                	                    d          }t          |          dk    s$|d         |d                                         k    r2t          d|                                           i c cddd           S 	 t          j        |d                   }n6# t          $ r) t          d	|d                    i cY c cddd           S w xY w	 t          j        |d
                   }n6# t          $ r) t          d|d
                    i cY c cddd           S w xY w|||d                  v rt          d|d                    |||d                  |<   	 ddd           n# 1 swxY w Y   |S # t          $ r*}t          d| t!          |                     i cY d}~S d}~ww xY w)zJ
    Parses a NSS Keys log and returns unpacked keys in a dictionary.
    zCannot open NSS Key Log: %s#    r   zInvalid NSS Key Log Entry: %sN   zInvalid ClientRandom: %s   zInvalid Secret: %szDuplicated entry for %s !zCannot read NSS Key Log: %s %s)collectionsdefaultdictdictopencloseFileNotFoundErrorr   
startswithstripsplitlenupperbinascii	unhexlify
ValueErrorUnicodeDecodeErrorstr)filenamekeysfdlinedataclient_randomsecretexs           \/mounts/lovelace/software/anaconda3/lib/python3.11/site-packages/scapy/layers/tls/session.pyload_nss_keysr0   !   s    "4((D(^^




   -x888			(^^ 	6r 6 6??3'' zz||))#..t99>>T!WQ%?%?;TZZ\\JJJII	6 	6 	6 	6 	6 	6 	6 	6$,$6tAw$?$?MM!   6Q@@@IIII	6 	6 	6 	6 	6 	6 	6 	6%/Q88FF!   0$q':::IIII'	6 	6 	6 	6 	6 	6 	6 	6" !DaM117aAAA/5T!Wm,,36	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	66    0(CGGDDD						s   #? AA"H 1BHH D98H9"E,HH +E,,H0F
H"F>-H0H =F>><H;H HH HH 
II=IIc                   R    e Zd ZdZdddeddfdZd Z	 	 	 dd
Zd Zd Z	d Z
d ZdS )	connStatea  
    From RFC 5246, section 6.1:
    A TLS connection state is the operating environment of the TLS Record
    Protocol.  It specifies a compression algorithm, an encryption
    algorithm, and a MAC algorithm.  In addition, the parameters for
    these algorithms are known: the MAC key and the bulk encryption keys
    for the connection in both the read and the write directions.
    Logically, there are always four connection states outstanding: the
    current read and write states, and the pending read and write states.
    All records are processed under the current read and write states.
    The security parameters for the pending states can be set by the TLS
    Handshake Protocol, and the ChangeCipherSpec can selectively make
    either of the pending states current, in which case the appropriate
    current state is disposed of and replaced with the pending state; the
    pending state is then reinitialized to an empty state.  It is illegal
    to make a state that has not been initialized with security
    parameters a current state.  The initial current state always
    specifies that no encryption, compression, or MAC will be used.

    (For practical reasons, Scapy scraps these two last lines, through the
    implementation of dummy ciphers and MAC with TLS_NULL_WITH_NULL_NULL.)

    These attributes and behaviours are mostly mapped in this class.
    Also, note that Scapy may make a current state out of a pending state
    which has been initialized with dummy security parameters. We need
    this in order to know when the content of a TLS message is encrypted,
    whether we possess the right keys to decipher/verify it or not.
    For instance, when Scapy parses a CKE without knowledge of any secret,
    and then a CCS, it needs to know that the following Finished
    is encrypted and signed according to a new cipher suite, even though
    it cannot decipher the message nor verify its integrity.
    serverreadr   N  c                    || _         || _        || _        || _        |ddlm} |} ||          | _        | j        j        st          d           d S  |            | _	        |
                                | _        |                                | _        |                                | _        |dk    rT|j        j        dk    rd | _        | j        j        | _        nU|                                | _        | j        j        | _        n*|                                | _        | j        j        | _        |dk    r2t/          | j        j                                                  | _        d S t7          |j        j        |          | _        d S )Nr   )TLS_NULL_WITH_NULL_NULL)tls_versionzITLS cipher suite not usable. Is the cryptography Python module installed?i   aeadi  )r8   seq_numconnection_endrowscapy.layers.tls.crypto.suitesr7   ciphersuiteusabler   compressionkx_algkey_exchange
cipher_algcipherhash_alghashtypehmactag_lenmac_lenhmac_alghmac_lenhash_lenr   namelowerhkdfr   prf)selfr;   read_or_writer:   compression_algr>   r8   r7   s           r/   __init__zconnState.__init__{   s    '
 , NNNNNN1K&;;???& 	 C D D DF*?,,'..00!,,..((**	%*f44 	#{2'0022	#y1#,,..DI9-DL&  "49>#7#7#9#9::DIII;/4kBBDHHH    c           	          t           j        r3|r3t          j        d| j        | j        |t          |                     d S d S d S )NzTLS: %s %s %s: %s)r   	debug_tlsr   debugr;   r<   r
   )rR   rN   r-   s      r/   
debug_reprzconnState.debug_repr   sb    > 	0f 	01"1"h"&v..	0 0 0 0 0	0 	0 	0 	0rV   rV   c                 R   | j         }| j                            ||||j                  }d}| j        dk    r| j        dk    s| j        dk    r| j        dk    rd}d}|j        }|j        dk    s|j        d	k    rU|}	|r|	|j        j	        z  }	|	|j        j	        z   }
||	|
         }| 
                    d
|           |d|j        j	        z  z  }nd }|}	|r
|	|j	        z  }	|	|j	        z   }
||	|
         }|j        j        r0|j        }| j                            |||| j        | j        |          }| 
                    d|           |d|j	        z  z  }|}	|j        d	k    r|r
|	|j        z  }	|	|j        z   }
n!|j        dk    r|r
|	|j        z  }	|	|j        z   }
|j        d | _        |j        | _        n+|                    |          | _        | j        j        | _        |j        dk    r ||          }n|j        d	k    rh||	|
         }|j        j        r/|j        }| j                            ||| j        | j        |          } |||          }| 
                    d|           n:|j        dk    r/||	|
         }d} ||||          }| 
                    d|           || _        d S )NFclientr4   r3   writeTr   streamblock
mac_secretr   cipher_secretr9   zblock ivzaead fixed iv)r>   rQ   derive_key_blockkey_block_lenr;   r<   rC   rG   rK   key_lenrZ   rA   exportexpanded_key_lenpostprocess_key_for_export
block_sizefixed_iv_lenrH   rI   rJ   rL   generate_iv_for_exportrD   )rR   r,   server_randommaster_secretcs	key_block
skip_firstposrC   startendr`   ra   reqLenrD   ivfixed_ivnonce_explicit_inits                     r/   derive_keyszconnState.derive_keys   sE     H--m.;.;.0.>@ @	 
 H,,V1C1C$00TX5H5HJ]
 Ox''Z_-G-GE -,,"+--C"59-JOOL*5551r{***CCJ  	(Z''Ej((!%),9 	H0F H??@M@M@D@S@D@FH HM 	777q:%%% ?g%% /..*//CC_&& 100*11C ;DI%-DLLJ//DI9-DL?h&&Z..FF_'' 59%By =#.X44]5B595H59X5;	= =
  Zr22FOOJ++++_&& s+H"#  Zx9LMMFOOOX666rV   c                    d}| j         dk    r| j        dk    s| j         dk    r| j        dk    rd}| j        j        }d}|r
||j        z  }||j        z   }|||         } ||          | _        |                     d|           d	S )
z
        There is actually only one key, the CLIENT-READ-KEY or -WRITE-KEY.

        Note that skip_first is opposite from the one with SSLv3 derivation.

        Also, if needed, the IV should be set elsewhere.
        Tr\   r4   r3   r]   Fr   ra   N)r;   r<   r>   rC   rd   rD   rZ   )rR   key_materialro   rC   rq   rr   ra   s          r/   sslv2_derive_keyszconnState.sslv2_derive_keys  s     
 H,,V1C1C$00TX5H5HJ%0
 	(Z''Ej(($U3Y/ j//77777rV   c                     | j         j        }|j        }|j        }| j                            |dd|          }| j                            |dd|          } |||          | _        d S )Ns   keyrV   s   iv)r>   rC   rd   ri   rP   expand_labelrD   )rR   ry   rC   rd   iv_len	write_keywrite_ivs          r/   tls13_derive_keyszconnState.tls13_derive_keys,  sj    %0
$(I**<gNN	9)),sFKK jH55rV   c           	         t          | j        | j        | j        t	          | j                  t	          | j                  | j                  }| j        	                                |_        | j
        r| j
        j        |j
        _        |S )zX
        This is used mostly as a way to keep the cipher state and the seq_num.
        )r;   rS   r:   rT   r>   r8   )r2   r;   r<   r:   rG   r@   r>   r8   rD   snapshotrH   key)rR   snaps     r/   r   zconnState.snapshot4  s|     (;'+x!%)-d.>)?)?%)$*:%;%;%)%57 7 7 k**,,9 	* IMDIMrV   c                     d| j                                         z  }|d| j        j        | j        j        fz  z  }|d| j        j        | j        j        fz  z  }d}|                    |          S )NzConnection end : %s
zCipher suite   : %s (0x%04x)
zCompression    : %s (0x%02x)
   )r;   r!   r>   rN   valr@   
expandtabs)rR   restabsizes      r/   __repr__zconnState.__repr__C  s    %(;(A(A(C(CC/43C3H373C3G3I I 	I/43C3H373C3G3I I 	I~~g&&&rV   )rV   rV   rV   )__name__
__module____qualname____doc__r   rU   rZ   rw   rz   r   r   r    rV   r/   r2   r2   Y   s         D !)%!*!#/C /C /C /Cb0 0 0 #&"%"%_ _ _ _B8 8 8.6 6 6  ' ' ' ' 'rV   r2   c                       e Zd Zd ZdS )readConnStatec                 .    t          j        | fddi| d S )NrS   r4   r2   rU   rR   kargss     r/   rU   zreadConnState.__init__N  s&    4??v??????rV   Nr   r   r   rU   r   rV   r/   r   r   M  s(        @ @ @ @ @rV   r   c                       e Zd Zd ZdS )writeConnStatec                 .    t          j        | fddi| d S )NrS   r]   r   r   s     r/   rU   zwriteConnState.__init__S  s&    4@@w@%@@@@@rV   Nr   r   rV   r/   r   r   R  s(        A A A A ArV   r   c                        e Zd ZdZ	 	 	 	 ddZ fdZd Zd Zd Zd	e	fd
Z
d Zd Zd Zd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dZd Z xZS ) 
tlsSessiona  
    This is our TLS context, which gathers information from both sides of the
    TLS connection. These sides are represented by a readConnState instance and
    a writeConnState instance. Along with overarching network attributes, a
    tlsSession object also holds negotiated, shared information, such as the
    key exchange parameters and the master secret (when available).

    The default connection_end is "server". This corresponds to the expected
    behaviour for static exchange analysis (with a ClientHello parsed first).
    Nr3   c	                 X   d| _         || _        || _        || _        || _        || _        d | _        d | _        || _        |/t          |          | _
        | j
                                         n|| _
        |/t          |          | _        | j                                         n|| _        d | _        d| _        d | _        d| _        g | _        d | _        d | _        d | _        d | _        g | _        d | _        d | _        d | _        d | _        d | _        d | _        d | _        d | _        i | _         i | _!        i | _"        i | _#        d| _$        d | _%        d | _&        d | _'        d | _(        d | _)        g | _*        d | _+        d | _,        g | _-        d | _.        d | _/        d | _0        d | _1        d | _2        d | _3        d | _4        d | _5        d | _6        i | _7        d| _8        d| _9        d| _:        d | _;        d| _<        d| _=        g | _>        g | _?        g | _@        d| _A        d | _B        d| _C        d S )NF)r;   r5   )Dfrozenipsrcipdstsportdportsidfirsttcpsockr;   r   wcsrw   r   rcspwcstriggered_pwcs_commitprcstriggered_prcs_commitserver_certs
server_keyserver_rsa_keynss_keysserver_tmp_rsa_keyclient_certs
client_keykx_groupclient_kx_ffdh_paramsclient_kx_ecdh_paramsclient_kx_privkeyclient_kx_pubkeyserver_kx_privkeyserver_kx_pubkeytls13_client_privsharestls13_client_pubsharestls13_server_privsharetls13_server_pubshareadvertised_tls_versionr8   r,   rk   pre_master_secretrl   advertised_sig_algsselected_sig_algclient_session_ticketsslv2_common_cssslv2_connection_idsslv2_challengesslv2_challenge_clientcertsslv2_key_materialtls13_psk_secrettls13_early_secrettls13_dhe_secrettls13_handshake_secrettls13_master_secrettls13_derived_secretstls13_cert_req_ctxtpost_handshakepost_handshake_authtls13_ticket_ciphersuitetls13_retrymiddlebox_compatibilityhandshake_messageshandshake_messages_parsedpost_handshake_messagesextmssession_hashencrypt_then_mac)	rR   r   r   r   r   r   r;   r   r   s	            r/   rU   ztlsSession.__init__g  s     



  	 -;%^DDDDHH  """"DH;$NCCCDHH  """"DH 	%*"	%*"  "
  #'
 
 
 &*"%)" "& $!% $ (*$&(#&(#%'" '-#   "!!%! $&  $ &*"  "#' #*.'"& !%"& $&*##' %'"#( ##( (,% ',$ #%)+& (*$ 
  %rV   c                 ~   |dk    rt          | d          r| j        r|| j        _        t          | d          r| j        r|| j        _        t          | d          r| j        r|| j        _        t          | d          r| j        r|| j        _        t          t          |                               ||           d S )Nr;   r   r   r   r   )	hasattrr   r;   r   r   r   superr   __setattr__)rR   rN   r   	__class__s      r/   r   ztlsSession.__setattr__  s    ###tU## . .*-'tU## . .*-'tV$$ / /+.	(tV$$ / /+.	(j$++D#66666rV   c                     t          |t                    rc|}|j        | _        |j        | _        	 |j        j        | _        |j        j        | _        n# t          $ r Y nw xY w| j
        |j        | _
        d S d S d S N)
isinstancer   r   r   
underlayersrcr   dstr   AttributeErrorr   seq)rR   _underlayertcps      r/   set_underlayerztlsSession.set_underlayer(  s    k3'' 
	(CDJDJ ^/
 ^/

!   }$ #
	( 
	( %$s   "A 
A! A!c                    | j         | j        c| _        | _         | j        | j        c| _        | _        | j        | j        c| _        | _        | j        rd| j        _        | j        rd| j        _        | j        | j        c| _        | _        | j        rd| j        _        | j        rd| j        _        | j	        | j
        c| _
        | _	        | j        dk    rd| _        n| j        dk    rd| _        | S )a  
        This function takes a tlsSession object and swaps the IP addresses,
        ports, connection ends and connection states. The triggered_commit are
        also swapped (though it is probably overkill, it is cleaner this way).

        It is useful for static analysis of a series of messages from both the
        client and the server. In such a situation, it should be used every
        time the message being read comes from a different side than the one
        read right before, as the reading state becomes the writing state, and
        vice versa. For instance you could do::

            client_hello = open('client_hello.raw').read()
            <read other messages>

            m1 = TLS(client_hello)
            m2 = TLS(server_hello, tls_session=m1.tls_session.mirror())
            m3 = TLS(server_cert, tls_session=m2.tls_session)
            m4 = TLS(client_keyexchange, tls_session=m3.tls_session.mirror())
        r4   r]   r\   r3   )r   r   r   r   r   r   r<   r   r   r   r   r;   rR   s    r/   mirrorztlsSession.mirror7  s    * "&TZ
DJ!%TZ
DJ!Xtx$(8 	"!DHL8 	#"DHL#y$)	499 	#"DIM9 	$#DIM &(B 	?"D$> (**"*D H,,"*DrV   c                    | j         t          d           | j        t          d           | j        t          d           | j        r| j        t          d           | j        j                            | j         | j        | j        | j        | j                  }|| _	        t          j        r$t          j        dt          |                     d S d S )Nz8Missing pre_master_secret while computing master_secret!z4Missing client_random while computing master_secret!z4Missing server_random while computing master_secret!z3Missing session hash while computing master secret!TLS: master secret: %s)r   r   r,   rk   r   r   r   rQ   compute_master_secretrl   r   rX   r   rY   r
   )rR   mss     r/   r   z tlsSession.compute_master_secretg  s    !)NOOO%JKKK%JKKK: 	K$+3IJJJY]001G151C151C15151B	D D
  > 	F6EEEEE	F 	FrV   returnc                     | j         r	d| j         vrdS | j        | j         d         v r| j         d         | j                 | _        dS dS )NCLIENT_RANDOMFT)r   r,   rl   r   s    r/    use_nss_master_secret_if_presentz+tlsSession.use_nss_master_secret_if_presentz  sS    } 	t} D D5!???!%!?@R!SD4urV   c                     | j         s|                                  | j                            | j        | j        | j                    | j                            | j        | j        | j                    d S )N)r,   rk   rl   )rl   r   r   rw   r,   rk   r   r   s    r/   compute_ms_and_derive_keysz%tlsSession.compute_ms_and_derive_keys  s    ! 	)&&(((	D,>,0,>,0,> 	 	@ 	@ 	@ 		D,>,0,>,0,> 	 	@ 	@ 	@ 	@ 	@rV   c                    | j         t          d           | j        t          d           | j        t          d           | j        j                            | j         | j        | j        d| j        j        j        z            }|| _	        t          j        rKt          j        dt          | j                              t          j        dt          |                     d S d S )Nz3Missing master_secret while computing key_material!z/Missing challenge while computing key_material!z3Missing connection_id while computing key_material!r   r   zTLS: key material: %s)rl   r   r   r   r   rQ   rb   rD   rd   r   r   rX   r   rY   r
   )rR   kms     r/   compute_sslv2_key_materialz%tlsSession.compute_sslv2_key_material  s    %IJJJ'EFFF#+IJJJY]++D,>,0,@,0,D,-	0@0H,HJ J #%> 	E6AS8T8TUUU5x||DDDDD	E 	ErV   c                     |                                   | j                            | j                   | j                            | j                   d S )N)ry   )r   r   rz   r   r   r   s    r/    compute_sslv2_km_and_derive_keysz+tlsSession.compute_sslv2_km_and_derive_keys  sR    '')))	##1H#III	##1H#IIIIIrV   Fc                 F   | j         r| j         j        r| j         j        }n/| j        r| j        j        r| j        j        }nt          d          }| j         |                    d| j                  | _        d| j        vrE|r|                    | j        dd          }n|                    | j        dd          }|| j        d<   |                    | j        dd	                    | j
                            }|| j        d<   |                    | j        d	d	                    | j
                            }|| j        d
<   | j        dk    r%| j         r| j                             |           dS dS | j        dk    r#| j        r| j                            |           dS dS dS )a  
        This function computes the Early Secret, the binder_key,
        the client_early_traffic_secret and the
        early_exporter_master_secret (See RFC8446, section 7.1).

        The parameter external is used for the computation of the
        binder_key:

        - For external PSK provisioned outside out of TLS, the parameter
          external must be True.
        - For resumption PSK, the parameter external must be False.

        If no argument is specified, the label "res binder" will be
        used by default.

        Ciphers key and IV are updated accordingly for 0-RTT data.
        self.handshake_messages should be ClientHello only.
        sha256N
binder_keys
   ext binderrV   s
   res binders   c e trafficclient_early_traffic_secrets   e exp masterearly_exporter_secretr3   r\   )r   rP   r   r   r   extractr   r   derive_secretjoinr   r;   r   )rR   externalrP   bkcetseess         r/   compute_tls13_early_secretsz&tlsSession.compute_tls13_early_secrets  s   * 9 	( 	(9>DDY 	(49> 	(9>DDh''D"*&*ll4373H'J 'JD# t999 -''(?(5(+- - ''(?(5(+- - 8:D&|4!!$"9"0"%((4+B"C"CE E EI"#@A  !8!0!$$*A!B!BD D ?B"#:;(**y 2	++D111112 2 H,,y 2	++D11111 -,2 2rV   c                 6   | j         r| j         j        }n%| j        r| j        j        }nt          d           dS | j         |                    d| j                  | _        |                    | j        dd          }|                    || j                  | _	        |                    | j	        dd
                    | j                            }|| j        d<   |                    | j	        dd
                    | j                            }|| j        d<   dS )	z
        Ciphers key and IV are updated accordingly for Handshake data.
        self.handshake_messages should be ClientHello...ServerHello.
        No HKDF. This is abnormal.N   derivedrV   s   c hs trafficclient_handshake_traffic_secrets   s hs trafficserver_handshake_traffic_secret)r   rP   r   r   r   r  r   r  r   r   r  r   r   )rR   rP   r-   chtsshtss        r/   compute_tls13_handshake_secretsz*tlsSession.compute_tls13_handshake_secrets  s,   
 9 	9>DDY 	9>DD0111F"*&*ll4373H'J 'JD# ##D$;ZMM&*ll64;P&Q&Q#!!$"="1"%((4+B"C"CE E IM"#DE!!$"="1"%((4+B"C"CE E IM"#DEEErV   c                 *   | j         r| j         j        r| j         j        }n1| j        r| j        j        r| j        j        }nt          d           dS |                    | j        dd          }|                    |d          | _        |                    | j        dd                    | j	                            }|g| j
        d<   |                    | j        dd                    | j	                            }|g| j
        d<   |                    | j        d	d                    | j	                            }|| j
        d
<   | j        dk    r| j                            |           dS | j        dk    r| j                             |           dS dS )z
        Ciphers key and IV are updated accordingly for Application data.
        self.handshake_messages should be ClientHello...ServerFinished.
        r
  Nr  rV   s   c ap trafficclient_traffic_secretss   s ap trafficserver_traffic_secretss
   exp masterexporter_secretr3   r\   )r   rP   r   r   r  r   r  r   r  r   r   r;   r   )rR   rP   tmpcts0sts0ess         r/   compute_tls13_traffic_secretsz(tlsSession.compute_tls13_traffic_secrets  s   
 9 	 	9>DDY 	49> 	9>DD0111F  !<!+!$& & $(<<T#:#: !!$":"1"%((4+B"C"CE E AEv"#;<!!$":"1"%((4+B"C"CE E AEv"#;< 8 - #)@ A AC C 9;"#45(**I''----- H,,I''----- -,rV   c                     | j         d         d         }| j        dk    r| j                            |           d S | j        dk    r| j                            |           d S d S )Nr  r   r3   r\   )r   r;   r   r   r   )rR   r  s     r/   !compute_tls13_traffic_secrets_endz,tlsSession.compute_tls13_traffic_secrets_end+  sq    )*BCAF(**I''----- H,,I''----- -,rV   c                 v   | j         r'| j        d         d         }| j        d         d         }n| j        d         }| j        d         }|dk    r| j        j        }|dk    r|}n,|dk    r|}n#|d	k    r| j        j        }|dk    r|}n|dk    r|}|r|st          d
           d S |                    ||          S )Nr  r  r  r  r4   r\   r3   r]   z.Missing arguments for verify_data computation!)r   r   r   rP   r   r   compute_verify_data)rR   r;   rS   handshake_contextr  r  rP   basekeys           r/   compute_tls13_verify_dataz$tlsSession.compute_tls13_verify_data2  s    $  		Q
 -.FGKD-.FGKDD-.OPD-.OPDF""8=D))8++g%%8=D))8++ 	7 	DEEE4''1BCCCrV   c                     | j         dk    r| j        j        }n| j         dk    r| j        j        }|                    | j        dd                    | j                            }|| j        d<   dS )zQ
        self.handshake_messages should be ClientHello...ClientFinished.
        r3   r\   s
   res masterrV   resumption_secretN)	r;   r   rP   r   r  r   r  r   r   )rR   rP   rss      r/   compute_tls13_resumption_secretz*tlsSession.compute_tls13_resumption_secret`  s{     (**9>DD H,,9>D 8 - #)@ A AC C ;="#6777rV   c                    | j         j        r| j         j        }|j        j        }n$| j        j        r| j        j        }|j        j        }|dk    r|dk    r^| j        d         }|d         }|                    |dd|          }|                    |           | j        	                    |           d
S |dk    r^| j        d         }|d         }	|                    |	dd|          }
|                    |
           | j        	                    |
           d
S d
S |d	k    r|dk    r^| j        d         }|d         }|                    |dd|          }|                    |           | j
        	                    |           d
S |dk    r`| j        d         }|d         }	|                    |	dd|          }
|                    |
           | j
        	                    |
           d
S d
S d
S )z=
        Ciphers key and IV are updated accordingly.
        r4   r\   r  r  s   traffic updrV   r3   r  r]   N)r   rP   rF   digest_sizer   r   r|   appendr   r   r   )rR   r;   rS   rP   hlctsctsNctsN_1stsstsNstsN_1s              r/   "compute_tls13_next_traffic_secretsz-tlsSession.compute_tls13_next_traffic_secretsm  s    8= 	'8=D&BBX] 	'8=D&BF""))01IJ2w**4bII

6"""	++F333338++01IJ2w**4bII

6"""	++F33333 ,+ g%%))01IJ2w**4bII

6"""	++F333338++01IJ2w**4bII

6"""	++F33333 &% ,+rV   c                 v    | j         j        j        dk    o$d| j         j        j                                        vS )Nr_   F)r   rD   rG   readyvaluesr   s    r/   consider_read_paddingz tlsSession.consider_read_padding  s6    $/ >dho3::<<<	?rV   c                 ,    | j         j        j        dk    S )Nr_   )r   rD   rG   r   s    r/   consider_write_paddingz!tlsSession.consider_write_padding  s    x#w..rV   c                     |dk    rdS |dk    S )Nr^   Fi  r   )rR   versioncipher_types      r/   use_explicit_ivztlsSession.use_explicit_iv  s     (""5&  rV   c                 ,   t          j        d| j                  }t          j        d| j                  }t          j        }d| j        v rt          j        }|t          || j                  z  }|t          || j	                  z  }t          ||          S )N!H:)structpackr   r   socketAF_INETr   AF_INET6r   r   r   )rR   s1s2familys       r/   rF   ztlsSession.hash  s}    [tz**[tz**$*_F
i
+++
i
+++b"~~rV   c                 Z   d}| j         |j         k    r2| j        |j        k    r"| j        |j        k    r| j        |j        k    rd}|sB| j        |j         k    r2| j         |j        k    r"| j        |j        k    r| j        |j        k    rd}|r | j        r|j        r| j        |j        k    S dS dS )NFT)r   r   r   r   r   )rR   otheroks      r/   eqztlsSession.eq  s    J%+%%$**C*C
ek))djEK.G.GB 	J%+%%$**C*C
ek))djEK.G.GB 	x -EI -x59,,4urV   c           	      z   t          | j                  }t          |          dk    r|d d         dz   }|rK|j        | j        k    r;| j        dt          | j                  d| j        dt          | j                  S | j        dt          | j                  d| j        dt          | j                  S )N      ...r=  z > )reprr   r    r   r   r&   r   r   )rR   r   r   s      r/   rN  ztlsSession.repr  s    48nns88b==crc(U"C 	C;,
::&*jjj#dj////&*jjj#dj///C C"&***c$*oooo"&***c$*ooo? 	?rV   c                 *    |                                  S r   )rN  r   s    r/   r   ztlsSession.__repr__  s    yy{{rV   )NNNNNr3   NNFr   )r   r   r   r   rU   r   r   r   r   boolr   r   r   r   r  r  r  r  r!  r%  r0  r4  r6  r:  rF   rI  rN  r   __classcell__r   s   @r/   r   r   [  s       	 	 $(-1 (#	m& m& m& m&f
7 
7 
7 
7 
7( ( (, , ,`F F F&$    	@ 	@ 	@E E E"J J J;2 ;2 ;2 ;2zM M M<&. &. &.P. . .,D ,D ,D\= = ='4 '4 '4V? ? ?
/ / /! ! !    $? ? ? ?      rV   r   c                        e Zd ZdZg dZdZg Z	 	 ddZ fdZd	 Z	d
 Z
d Zd ZddZ fdZd Z fdZeZd ZddZed             Z xZS )_GenericTLSSessionInheritancea  
    Many classes inside the TLS module need to get access to session-related
    information. For instance, an encrypted TLS record cannot be parsed without
    some knowledge of the cipher suite being used and the secrets which have
    been negotiated. Passing information is also essential to the handshake.
    To this end, various TLS objects inherit from the present class.
    )tls_sessionrcs_snap_initwcs_snap_initzDummy Generic TLS Packet Nr   c                 (   	 | j         d u }n# t          $ r d}Y nw xY wd}|r|d}t                      | _         n|| _         | j         j                                        | _        | j         j                                        | _        t          |t                    r^| j         
                    |           t          j        /t          j        #t          t          j                  t          _        t          j        r|rt          j                            | j                   }	|	rTt          j        t          j        |	_        |	j        | j         j        k    r|	| _         n`|	                                | _         nFt          j        t          j        | j         _        t          j                            | j                    | j         j        dk    r+t          j        j        }
| j         j        s|
r|
| j         _        t1          j        | f||||d| d S )NTFr3   )_pktpost_transform	_internalr   )rV  	Exceptionr   r   r   rW  r   rX  r   r   r   r   tls_nss_filenametls_nss_keysr0   tls_session_enabletls_sessionsfindr   r   r   addr;   r   r   rU   )rR   r[  r\  r]  r   rV  fieldssetmenewsesssrks              r/   rU   z&_GenericTLSSessionInheritance.__init__  s   	$,EE 	 	 	EEE	  	/"#-<<  #. !-1::<<!-1::<<k3'' 	:++K888 $0$,(5d6K(L(LD%& @ @)..t/?@@A 
@,8)-):AJ7d&6&<<</0D,,/0xxzzD,,,88<8ID,5)--d.>???.(::'6'6 ::69D$3 	"4"+	" 	" 	" 	" 	" 	" 	"s   	 c                 d    |dk    rdS t          t          |                               |          S )zT
        The tls_session should be found only through the normal mechanism.
        rV  N)r   rU  __getattr__)rR   attrr   s     r/   rk  z)_GenericTLSSessionInheritance.__getattr__  s4     =  42D99EEdKKKrV   c                     dS )z
        post_{build, dissection}_tls_session_update() are used to update the
        tlsSession context. The default definitions below, along with
        tls_session_update(), may prevent code duplication in some cases.
        Nr   rR   msg_strs     r/   tls_session_updatez0_GenericTLSSessionInheritance.tls_session_update   s	     	rV   c                 0    |                      |           d S r   rp  rn  s     r/   post_build_tls_session_updatez;_GenericTLSSessionInheritance.post_build_tls_session_update(      (((((rV   c                 0    |                      |           d S r   rr  rn  s     r/   "post_dissection_tls_session_updatez@_GenericTLSSessionInheritance.post_dissection_tls_session_update+  rt  rV   c                 F    t          j        |           }| j        |_        |S r   )r   copyrV  )rR   pkts     r/   rx  z"_GenericTLSSessionInheritance.copy.  s     k$*
rV   c                 F    t          j        | fd|i|}| j        |_        |S )Npayload)r   
clone_withrV  )rR   r{  r   ry  s       r/   r|  z(_GenericTLSSessionInheritance.clone_with3  s.    ??g???*
rV   c                 R    t          t          |                                           S r   )r   rU  	__bytes__rR   r   s    r/   raw_statefulz*_GenericTLSSessionInheritance.raw_stateful8  s     2D99CCEEErV   c                 *    |                                  S r   )r  r   s    r/   str_statefulz*_GenericTLSSessionInheritance.str_stateful;  s      """rV   c                 l   | j         }|j                                        }|j                                        }| j        }| j        }| j        |_        d| _        |j        }d|_        t          t          |           
                                }||_        ||_        ||_        || _        || _        |S )a  
        The __bytes__ call has to leave the connection states unchanged.
        We also have to delete raw_packet_cache in order to access post_build.

        For performance, the pending connStates are not snapshotted.
        This should not be an issue, but maybe pay attention to this.

        The previous_freeze_state prevents issues with calling a raw() calling
        in turn another raw(), which would unfreeze the session too soon.
        NT)rV  r   r   r   raw_packet_cacheraw_packet_cache_fieldsrW  r   r   rU  r~  )	rR   rh  rcs_snapwcs_snaprpc_snap	rpcf_snapprevious_freeze_statebuilt_packetr   s	           r/   r~  z'_GenericTLSSessionInheritance.__bytes__>  s     5>>##5>>##(0	" $ !:DAAKKMM( ('0$rV   c                 8   | j         }|j                                        }|j                                        }| j        |_        t          |           }d|_        |                     ||                                           d|_        ||_        ||_        dS )a  
        Rebuild the TLS packet with the same context, and then .show() it.
        We need self.__class__ to call the subclass in a dynamic way.

        Howether we do not want the tls_session.{r,w}cs.seq_num to be updated.
        We have to bring back the init states (it's possible the cipher context
        has been updated because of parsing) but also to keep the current state
        and restore it afterwards (the raw() call may also update the states).
        T)rV  FN)	rV  r   r   r   rW  r   r   r   show)rR   rh  r  r  r  s        r/   show2z#_GenericTLSSessionInheritance.show2_  s     5>>##5>>##"4yy|3388:::rV   Tc                 T   ddl m} ddlm} | j        r1t          | j        t                    rt          | d| j                  }n_d }| j        r!t          | j        t                    r| j        }d| j
                            |          dt          | d| j                  }|||gfS )Nr   TLSTLS13_namezTLS )r   z / )scapy.layers.tls.recordr  scapy.layers.tls.record_tls13r  r   r   rU  getattrrN   r   rV  rN  )rR   firstr  r  summaryr   s         r/   	mysummaryz'_GenericTLSSessionInheritance.mysummaryw  s    //////777777O	t(EFF	 dGTY77GGK .:dos#C#C ."o %%+%>>>>gty111G e$$rV   c                    ddl m} ddlm} | ||fv r_t	          j        d|dd                   d         dz   }t          |          |k    r#d|vr | |          S |d         t                                                   }|	                                 d }t          j        rt                      }	|	                    |           t          j                            |	          }|r{|j        |j        k    r|                                }|j        |j        k    rGt)          j        dt-          |          z             t          j                            |d	
           d } | |||          S d S  | |          S )Nr   r  r  r<  r      originalzCTLS: session %s is a duplicate of a previous dissection. Discard itT)force)r   rV  )r  r  r  r  r>  unpackr    r   rx  remove_payloadr   ra  r   r   rb  rc  r   r   r   r   r   inforN  rem)
clsr+   metadatasessionr  r  lengthr   rV  rh  s
             r/   tcp_reassemblez,_GenericTLSSessionInheritance.tcp_reassemble  s    	0/////7777773,]4ac33A6:F4yyF""X--3t99$%j1#6;;==
))+++"* /"A$$Z000"&"3"8"8";";K" 	/&,
0@@@*5*<*<*>*>K&/:>AA',!9;?;L;L!M   !-11+T1JJJ*.Ks4Z[QQQQ- #"0 3t99rV   )rY  Nr   NNr   )T)r   r   r   r   	__slots__rN   fields_descrU   rk  rp  rs  rv  rx  r|  r  r  r~  __str__r  r  classmethodr  rR  rS  s   @r/   rU  rU    sU         BAAI%DK?@/31" 1" 1" 1"fL L L L L  ) ) )) ) )  
   
F F F F F# # #    > G  0% % % %$   [    rV   rU  c                   .    e Zd Zd Zd ZddZd Zd ZdS )	_tls_sessionsc                 "    i | _         d | _        d S r   )sessionsr   r   s    r/   rU   z_tls_sessions.__init__  s    "rV   c                     |                      |          }|rt          j        d           d S |                                }|| j        v r"| j        |                             |           d S |g| j        |<   d S Nz.TLS: previous session shall not be overwritten)rc  r   r  rF   r  r(  )rR   r  rh  hs       r/   rd  z_tls_sessions.add  s    IIg 	MNNNFLLNNM!##G,,,,, 'yDM!rV   Fc                     |s-|                      |          }|rt          j        d           d S |                                }| j        |                             |           d S r  )rc  r   r  rF   r  remove)rR   r  r  rh  r  s        r/   r  z_tls_sessions.rem  sh     			'""A  !QRRRLLNNa(((((rV   c                 <   	 |                                 }n# t          $ r Y d S w xY w|| j        v rJ| j        |         D ]<}|                    |          r%t          j        rt          j        d|           |c S =t          j        rt          j        d|           d S )NzTLS: found session matching %sz%TLS: did not find session matching %s)rF   r^  r  rI  r   rX   r   r  )rR   r  r  ks       r/   rc  z_tls_sessions.find  s    	AA 	 	 	44	]1%  44== ~ N#()I1MMMHHH > 	ODgNNNts    
%%c                    dg}| j                                         D ]u}|D ]p}d|j        |j        fz  }d|j        |j        fz  }t          |j                  }t          |          dk    r|d d         dz   }|	                    |||f           qvd t          | D             }d                    t          d |                    d	                    t          fd
|                    S )N)zFirst endpointzSecond endpointz
Session IDz%s[%d]rK  rL  rM  c              3   H   K   | ]}t          d  |D                       V  dS )c              3   4   K   | ]}t          |          V  d S r   )r    ).0ys     r/   	<genexpr>z3_tls_sessions.__repr__.<locals>.<genexpr>.<genexpr>  s(      **1A******rV   N)max)r  xs     r/   r  z)_tls_sessions.__repr__.<locals>.<genexpr>  s9      >>qC*******>>>>>>rV   z  c                     d| z  S )Nz%%-%dsr   )r  s    r/   <lambda>z(_tls_sessions.__repr__.<locals>.<lambda>  s
    hl rV   
c                     | z  S r   r   )r  fmts    r/   r  z(_tls_sessions.__repr__.<locals>.<lambda>  s    sQw rV   )r  r3  r   r   r   r   rN  r   r    r(  zipr  map)	rR   r   lirh  r   r   r   colwidthr  s	           @r/   r   z_tls_sessions.__repr__  s	   BC-&&(( 	, 	,B , ,!'17!33!'17!3315kks88b==crc(U*C

Cc?++++, ?>CI>>>ii22H==>>yy....44555rV   NrP  )r   r   r   rU   rd  r  rc  r   r   rV   r/   r  r    sd        # # #
) 
) 
)) ) ) )  6 6 6 6 6rV   r  c                   (     e Zd Z fdZ fdZ xZS )
TLSSessionc                     t          d           |                    dd           } t          t          |           j        |i | t
          j        | _        dt
          _        |r|t
          j        _	        d S d S )NzTLSSession is deprecated and will be removed in a future version. Please use TCPSession instead with conf.tls_session_enable=Truer   T)
r   popr   r  rU   r   ra  _old_conf_statusrb  r   )rR   argskwargsr   r   s       r/   rU   zTLSSession.__init__  s    N	
 	
 	
  $4d;;(j$($9&999 $ 7"& 	>/=D,,,	> 	>rV   c                 t    | j         t          _        t          t          |                                           S r   )r  r   ra  r   r  toPacketListr  s    r/   r  zTLSSession.toPacketList  s*    "&"7Z&&33555rV   )r   r   r   rU   r  rR  rS  s   @r/   r  r    sQ        > > > > >6 6 6 6 6 6 6 6 6rV   r  ))r   r"   r   r@  r>  scapy.configr   scapy.compatr   scapy.errorr   r   scapy.packetr   scapy.pton_ntopr   scapy.sessionsr	   scapy.utilsr
   r   scapy.layers.inetr   #scapy.layers.tls.crypto.compressionr   scapy.layers.tls.crypto.hkdfr   scapy.layers.tls.crypto.prfr   typingr   r0   objectr2   r   r   r   rU  r  r  rb  r   rV   r/   <module>r     s                       , , , , , , , ,       % % % % % % % % % % % % ( ( ( ( ( ( ( ( ! ! ! ! ! ! 9 9 9 9 9 9 3 3 3 3 3 3 + + + + + +      , , ,pq' q' q' q' q' q' q' q'h@ @ @ @ @I @ @ @
A A A A AY A A Av	 v	 v	 v	 v	 v	 v	 v	|O O O O OF O O Ol66 66 66 66 66F 66 66 66r6 6 6 6 6 6 6 6( "MOO   rV   