
    @OOf+c                        d dl Z d dl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 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 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 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 dlm Z  d dlm!Z! d dl"m#Z# de$dee$   fdZ%de$de$dz  fdZ&de$dedz  fdZ'de$dee$   fdZ(de$de$dz  fdZ)de$dedz  fd Z*d!Z+d"e+z   Z,e G d# d$e             Z-e G d% d&e             Z.e G d' d(e             Z/e G d) d*e             Z0e G d+ d,e             Z1e G d- d.e             Z2e G d/ d0e             Z3 G d1 d2ejh                        Z5 G d3 d4e5      Z6 G d5 d6e5      Z7 G d7 d8e5      Z8y)9    N)Iterator)	dataclass)DEBUG)ERROR)INFO)WARNING)SSL)certs)
connection)starts_like_dtls_record)starts_like_tls_record)commands)context)events)layer)tunnel)	StartHook)tcp)udp)ClientHello)ClientHelloData)TlsData)humandatareturnc              #   "  K   d}	 t        |       |dz   k  ry| ||dz    }t        |      st        d|d      t        j                  d|dd       d   }|dk(  rt        d      |dz  }t        |       ||z   k  ry| |||z    }| ||z  }w)	
    Returns a generator that yields the bytes contained in each handshake record.
    This will raise an error on the first non-handshake record, so fully exhausting this
    generator is a bad idea.
    r      NzExpected TLS record, got 	 instead.!H   Record must not be empty.)lenr   
ValueErrorstructunpackr   offsetrecord_headerrecord_sizerecord_bodys        [/var/www/premiumrankchecker/venv/lib/python3.12/site-packages/mitmproxy/proxy/layers/tls.pyhandshake_record_contentsr-      s      F
t9vz!Vfqj1%m488ISTTmmD-*;<Q?!899!t9v++6F[$89+    BBc                     d}t        |       D ]M  }||z  }t        |      dk\  st        j                  dd|dd z         d   dz   }t        |      |k\  sH|d| c S  y)z
    Read all TLS records that contain the initial ClientHello.
    Returns the raw handshake packet bytes, without TLS record headers.
           !I       r   N)r-   r#   r%   r&   r   client_hellodclient_hello_sizes       r,   get_client_hellor9   7   s    
 L&t, 8|! &dGl1Q>O4O PQR SVW W< $55#$6%6778 r0   c                 v    t        |       }|r	 t        |dd       S y# t        $ r}t        d      |d}~ww xY w)  
    Check if the supplied bytes contain a full ClientHello message,
    and if so, parse it.

    Returns:
        - A ClientHello object on success
        - None, if the TLS record is not complete

    Raises:
        - A ValueError, if the passed ClientHello is invalid
    r1   NInvalid ClientHello)r9   r   EOFErrorr$   r   r6   es      r,   parse_client_hellor@   F   sM     $D)L	;|AB/00   	;23:	;s    	838c              #   "  K   d}	 t        |       |dz   k  ry| ||dz    }t        |      st        d|d      t        j                  d|dd       d   }|dk(  rt        d      |dz  }t        |       ||z   k  ry| |||z    }| ||z  }w)	r   r      NzExpected DTLS record, got r   r       r"   )r#   r   r$   r%   r&   r'   s        r,   dtls_handshake_record_contentsrD   \   s      F
t9v{"Vfrk2&}59-9J)TUUmmD-*<=a@!899"t9v++6F[$89+# r.   c                     d}t        |       D ]M  }||z  }t        |      dk\  st        j                  dd|dd z         d   dz   }t        |      |k\  sH|d| c S  y)	z
    Read all DTLS records that contain the initial ClientHello.
    Returns the raw handshake packet bytes, without TLS record headers.
    r0   rB   r2   r3   	      r   N)rD   r#   r%   r&   r5   s       r,   get_dtls_client_hellorH   w   s    
 L+D1 8|" dGl1R.@$@A!DrI  < $55#$6%6778 r0   c                 z    t        |       }|r	 t        |dd d      S y# t        $ r}t        d      |d}~ww xY w)r;   rG   NT)dtlsr<   )rH   r   r=   r$   r>   s      r,   dtls_parse_client_hellorK      sO     ).L	;|BC0t<<   	;23:	;s     	:5:)s   http/1.1s   http/1.0s   http/0.9)s   h2c                       e Zd ZU dZeed<   y)TlsClienthelloHookz
    Mitmproxy has received a TLS ClientHello message.

    This hook decides whether a server connection is needed
    to negotiate TLS with the client (data.establish_server_tls_first)
    r   N)__name__
__module____qualname____doc__r   __annotations__ r0   r,   rM   rM      s     r0   rM   c                       e Zd ZU dZeed<   y)TlsStartClientHookz
    TLS negotation between mitmproxy and a client is about to start.

    An addon is expected to initialize data.ssl_conn.
    (by default, this is done by `mitmproxy.addons.tlsconfig`)
    r   NrN   rO   rP   rQ   r   rR   rS   r0   r,   rU   rU           Mr0   rU   c                       e Zd ZU dZeed<   y)TlsStartServerHookz
    TLS negotation between mitmproxy and a server is about to start.

    An addon is expected to initialize data.ssl_conn.
    (by default, this is done by `mitmproxy.addons.tlsconfig`)
    r   NrV   rS   r0   r,   rY   rY      rW   r0   rY   c                       e Zd ZU dZeed<   y)TlsEstablishedClientHookzL
    The TLS handshake with the client has been completed successfully.
    r   NrV   rS   r0   r,   r[   r[           Mr0   r[   c                       e Zd ZU dZeed<   y)TlsEstablishedServerHookzL
    The TLS handshake with the server has been completed successfully.
    r   NrV   rS   r0   r,   r^   r^      r\   r0   r^   c                       e Zd ZU dZeed<   y)TlsFailedClientHookz7
    The TLS handshake with the client has failed.
    r   NrV   rS   r0   r,   r`   r`      r\   r0   r`   c                       e Zd ZU dZeed<   y)TlsFailedServerHookz7
    The TLS handshake with the server has failed.
    r   NrV   rS   r0   r,   rb   rb      r\   r0   rb   c                       e Zd ZU dZej
                  ed<   	 dej                  de	j
                  f fdZ
 fdZed        Zed        Zd	ej                   d   fd
Zd	ej                   d   fdZded	ej                   eeedz  f      fdZded	ej                   d   f fdZded	ej                   d   fdZd	ej                   d   f fdZded	ej                   d   fdZdej:                  d	ej                   d   f fdZ xZS )TLSLayerNtlsr   connc                 8    t         |   |||       d|_        y )N)tunnel_connectionrf   T)super__init__re   selfr   rf   	__class__s      r,   rj   zTLSLayer.__init__   s'    " 	 	
 r0   c                     t         |          j                  dd| j                  j                  d| j                  j
                  d      S )N) )ri   __repr__replacerf   snialpnrl   rm   s    r,   rq   zTLSLayer.__repr__   sB    G&&sa		/@$))..ASST,UV	
r0   c                 4    | j                   j                  dk(  S )Nr   )rf   transport_protocolrl   s    r,   is_dtlszTLSLayer.is_dtls   s    yy++u44r0   c                 "    | j                   rdS dS )NDTLSTLSry   rx   s    r,   
proto_namezTLSLayer.proto_name  s    v050r0   r   c              #     K   | j                   rJ t        | j                  | j                  | j                        }| j                  | j                  j
                  k(  rt        |       nt        |       |j                  sLt        j                  d| j                   dt               t        j                  | j                         y |j                  sJ |j                  | _         y w)Nr}   zNo z* context was provided, failing connection.)re   r   rf   r   ry   clientrU   rY   ssl_connr   Logr~   r   CloseConnection)rl   	tls_starts     r,   	start_tlszTLSLayer.start_tls  s     88|DIIt||T\\J	99+++$Y//$Y//!!,,doo&&PQSX  **49955!!!!%%s   C1C3c              #      K   	 	 | j                   j                  d      }t        j                  | j                  |       ?# t
        j                  $ r Y y w xY ww)N  )re   bio_readr   SendDatarf   r	   WantReadErrorrl   r   s     r,   tls_interactzTLSLayer.tls_interact  sY     9xx((/ ''		488  $$ s'   AA #AAAAAr   c              #     K   |r| j                   j                  |       	 | j                   j                          | j                   j                         xs g }| j                  | j
                  j                  k(  r.| j                   j                         }|r|j                  d|       t        j                         | j                  _
        | j                   j                         | j                  _        |D cg c]!  }t        j                  j                  |      # c}| j                  _        | j                   j#                         | j                  _        | j                   j'                         | j                  _        | j*                  r5t-        j.                  | j*                   d| j                   t0               | j                  | j
                  j                  k(  r7t3        t5        | j                  | j
                  | j                                n6t7        t5        | j                  | j
                  | j                                | j9                  d      E d {    yc c}w 7 
# t:        j<                  $ r | j?                         E d {  7   Y yt:        j@                  $ r'}|jB                  xrB tE        |jB                  d   tF              xr# |jB                  d   xr |jB                  d   d   }|dv rt:        jH                  jK                  | j                   jL                        }t:        jN                  jQ                  t:        jH                  jS                  |            jU                         }d| }	nB|d	v rtE        |tV              sJ |d
   }	n&|dv r|d d jY                         rd}	n|dv rd}	nd|}	d|	fcY d }~S d }~ww xY ww)Nr   z[tls] tls established: r0   TNFN))SSL routinestls_process_server_certificatecertificate verify failed)r    r   zCertificate verify failed: ))r   ssl3_read_bytestlsv1 alert unknown ca)r   r   sslv3 alert bad certificate)r   r   ssl/tls alert bad certificate)r   r   r   )r   r   r   )r   r   r      ))r   ssl3_get_recordwrong version number)r   r   r   )r   r   zpacket length too long)r   r   zrecord layer failurer1   z%The remote server does not speak TLS.))r   r   tlsv1 alert protocol version)r   r   r   zThe remote server and mitmproxy cannot agree on a TLS version to use. You may need to adjust mitmproxy's tls_version_server_min option.zOpenSSL F)-re   	bio_writedo_handshakeget_peer_cert_chainrf   r   r   get_peer_certificateinserttimetimestamp_tls_setupget_alpn_proto_negotiatedrt   r
   Certfrom_pyopensslcertificate_listget_cipher_namecipherget_protocol_version_nametls_versiondebugr   r   r   r[   r   r^   receive_datar	   r   r   Errorargs
isinstancelist_libSSL_get_verify_result_ssl_ffistringX509_verify_cert_error_stringdecodetupleisascii)
rl   r   	all_certscertxr?   last_errverify_resulterrorerrs
             r,   receive_handshake_datazTLSLayer.receive_handshake_data"  s,     HHt$X	HH!!#z 446<"IyyDLL///xx446$$Q-,0IIKDII)!XX??ADIIN6?*12

))!,*DII&  $xx779DII$(HH$F$F$HDII!zzllzzl"9$))Eu  yyDLL///.DIIt||TXX>  /DIIt||TXX>  ((---%*" .k    	((***yy 1	 V:affQi6V166!9VPQSU     !$ > >txx}} MHH::=I&(  4E7;   "(E222qk !H$$&=  
X 
 !&#:c1	sf   O!I6 B?O!:&I/ E	O!)I4*O!6&OJO"O!$O7DOOO!OO!r   c              #     K   || j                   _        | j                   | j                  j                  k(  r7t	        t        | j                   | j                  | j                               n6t        t        | j                   | j                  | j                               t        | %  |      E d {    y 7 wN)
rf   r   r   r   r`   r   re   rb   ri   on_handshake_errorrl   r   rm   s     r,   r   zTLSLayer.on_handshake_error  s{     		99+++%gdiitxx&PQQ%gdiitxx&PQQ7-c222s   B4B?7B=8B?c              #     K   |r| j                   j                  |       | j                         E d {    t               }d}	 	 |j	                  | j                   j                  d             ,7 =# t        j                  $ r Y nTt        j                  $ r d}Y n>t        j                  $ r)}t        j                  d| t               Y d }~nd }~ww xY w|rA| j                  t        j                  | j                   t#        |                  E d {  7   |r| j                   xj$                  t&        j(                  j*                   z  c_        | j,                  r5t        j                  | j,                   d| j                    t.               | j                  t        j0                  | j                               E d {  7   y y w)NFTr   zTLS Error: z[tls] close_notify )re   r   r   	bytearrayextendrecvr	   r   ZeroReturnErrorr   r   r   r   event_to_childr   DataReceivedrf   bytesstater   ConnectionStateCAN_READr   r   ConnectionClosed)rl   r   	plaintextcloser?   s        r,   r   zTLSLayer.receive_data  sq    HHt$$$&&&K	  u!56 	 	' $$ && 99  ll[#4g>> **##DIIuY/?@   IIOO
 : : C CCCOzzlldjj\1DTYYK#PRWXX**6+B+B499+MNNN	 sk   1GA1G*A3 0G3CGCGC0CGCA GDB1GGGc              #      K   | j                   j                         t        j                  z  ry t        |          E d {    y 7 wr   )re   get_shutdownr	   RECEIVED_SHUTDOWNri   receive_closeru   s    r,   r   zTLSLayer.receive_close  s6     88  "S%:%::w,...s   >A	AA	c              #      K   	 | j                   j                  |       | j                         E d {    y # t        j                  t        j                  f$ r Y >w xY w7 .wr   )re   sendallr	   r   SysCallErrorr   r   s     r,   	send_datazTLSLayer.send_data  s[     	HHT" $$&&& ##S%5%56 		 	's/   A#8 A#A!A##AA#AA#commandc              #   @   K   t         |   |      E d {    y 7 wr   )ri   
send_close)rl   r   rm   s     r,   r   zTLSLayer.send_close  s      7%g...s   ) rN   rO   rP   re   r	   
ConnectionrR   r   Contextr   rj   rq   propertyry   r~   r   CommandGeneratorr   r   r   r   boolstrr   r   r   r   r   r   r   r   __classcell__rm   s   @r,   rd   rd      s^   C' z7L7L 

 5 5 1 1&511$7 &"9e44T: 9^^			dC$J&6 7	8^@3c 3e.D.DT.J 3O O5+A+A$+G OB/u55d; /'e '(>(>t(D '////				%/ /r0   rd   c                       e Zd ZU dZdZeed<   ddej                  de	j                  dz  f fdZdej                  d   fd	Zd
ej                   dej                  d   f fdZdedej                  d   f fdZ xZS )ServerTLSLayerzD
    This layer establishes TLS for a single server connection.
    Fwait_for_clienthelloNr   rf   c                 B    t         |   ||xs |j                         y r   )ri   rj   serverrk   s      r,   rj   zServerTLSLayer.__init__  s    $"8'..9r0   r   c              #   4  K   | j                    xr t        | j                  t              }|r'd| _        t
        j                  j                  | _        y | j                         E d {    | j                  r| j                  d      E d {    y y 7 +7 w)NTr0   )command_to_reply_tor   child_layerClientTLSLayerr   r   TunnelStateCLOSEDtunnel_stater   re   r   )rl   r   s     r,   start_handshakezServerTLSLayer.start_handshake  s      ((( =
 4++^< 	  (,D% & 2 2 9 9D~~'''xx66s;;;  (;s$   A&B(B)$BBBBeventc              #      K   | j                   rTt        | 	  |      D ]A  }t        |t        j
                        r!|j                  | j                  k(  rd| _         >| C y t        | 	  |      E d {    y 7 w)NF)r   ri   r   r   r   OpenConnectionr   rf   )rl   r   r   rm   s      r,   r   zServerTLSLayer.event_to_child  so     $$ 71%8 "w(?(?@**dii705D- "M" w-e444s   A3A>6A<7A>r   c              #      K   t        j                  d| t               t        |   |      E d {    y 7 w)NzServer TLS handshake failed. level)r   r   r   ri   r   r   s     r,   r   z!ServerTLSLayer.on_handshake_error  s3     ll:3%@PP7-c222s   3><>r   )rN   rO   rP   rQ   r   r   rR   r   r   r   Serverrj   r   r   r   r   Eventr   r   r   r   r   s   @r,   r   r     s     "'$&: :z7H7H47O :<!7!7!= <&5FLL 5U5K5KD5Q 53c 3e.D.DT.J 3 3r0   r   c                   \    e Zd ZU dZeed<   eed<   dZeed<   dej                  f fdZ
dej                  d	   fd
Zdedej                  eeed	z  f      f fdZdej                  ed	z     fdZdedej                  d	   f fdZdej*                  dej                  d	   fdZ xZS )r   u  
    This layer establishes TLS on a single client connection.

    ┌─────┐
    │Start│
    └┬────┘
     ↓
    ┌────────────────────┐
    │Wait for ClientHello│
    └┬───────────────────┘
     ↓
    ┌────────────────┐
    │Process messages│
    └────────────────┘

    recv_bufferserver_tls_availableFclient_hello_parsedr   c                    |j                   j                  rd |j                   _        d |j                   _        d |j                   _        d |j                   _        d |j                   _        g |j                   _        d |j                   _        g |j                   _	        g |j                   _
        t        | 1  ||j                          t        | j                  j                  d   t               | _        t%               | _        y )N)r   re   rt   r   rs   r   r   r   mitmcertalpn_offerscipher_listri   rj   r   r   layersr   r   r   r   )rl   r   rm   s     r,   rj   zClientTLSLayer.__init__  s    >> #'GNN$(GNN!!%GNN15GNN.)-GNN&.0GNN+&*GNN#)+GNN&)+GNN&'..1$.t||/B/B2/F$W!$;r0   r   Nc              #   $   K   dE d {    y 7 w)NrS   rS   rx   s    r,   r   zClientTLSLayer.start_handshake  s     s   r   c           	   #     K   | j                   rt        | 	  |      E d {   S | j                  j	                  |       	 | j
                  rt        | j                        }nt        | j                        }|rd| _         ny|j                  | j                  _
        |j                  | j                  _        t        | j                  |      }t!        |       |j"                  r\t%        j&                  dd      x| _        | _        | j                  j*                  | j                  j*                  j-                  |       dz
     }t/        |t0              r"t%        j2                  d       x|_        |_        | j
                  r't5        j6                  | j                  d	      | _        n&t;        j<                  | j                  d	      | _        | j?                  tA        jB                  | j                  jD                  tG        | j                                    E d {    | j                  jI                          y
|jJ                  ro| j                  jL                  jN                  sO| jQ                         E d {   }|r5tS        jT                  d| jV                   d| d| jV                   d       | jY                         E d {    | j                  jZ                  syt        | 	  tG        | j                              E d {   }| j                  jI                          |S 7 # t        $ r" dd| j                  j                          fcY S w xY w7 A7 7 7 Xw)NFzCannot parse ClientHello: Tr   )zignore-connr   )peernamesocknamer4   address)ignorer   zUnable to establish z connection with server (z). Trying to establish z with client anyway. If you plan to redirect requests away from this server, consider setting `connection_strategy` to `lazy` to suppress early connections.)Fconnection closed early).r   ri   r   r   r   ry   rK   r@   r$   hexrs   rf   alpn_protocolsr  r   r   rM   ignore_connectionr   Clientrh   r  indexr   r   r   r   UDPLayerr   r   TCPLayerr   r   r   r   r   clearestablish_server_tls_firstr   tls_establishedstart_server_tlsr   r   r~   r   	connected)rl   r   r6   tls_clienthelloparent_layerr   retrm   s          r,   r   z%ClientTLSLayer.receive_handshake_data  s     ##$w=dCCD%	P||6t7G7GH1$2B2BC '+D$$((		 , ; ;		)$,,E 11,, 2<1B1B+6H2 DI.  <<..t||/B/B/H/H/NQR/RSL,7EOEVEV F !L$B ||#&<<T#J #&<<T#J **##DLL$7$7t?O?O9PQ   ""$66LL''77!2244Cll*4??*;;TUXTY Z++/??*; <fg  >>###yy""37d>N>N8OPP 
w D  	P6t7G7G7K7K7M6NOOO	P8 5 	$ Qsy   M1L7M17L: :F-M1'M((AM1M+AM1M-A M1M/!M1:(M%"M1$M%%M1+M1-M1/M1c              #      K   | j                   sd| j                   dS t        j                  | j                  j
                        }|S w)z
        We often need information from the upstream connection to establish TLS with the client.
        For example, we need to check if the client does ALPN or not.
        z
No server z available.)r   r~   r   r   r   r   )rl   r   s     r,   r  zClientTLSLayer.start_server_tls`  sG     
 ((0<<++DLL,?,?@@
s   A
Ar   c              #     K   | j                   j                  r| j                   j                  }n3t        j                  | j                  j
                  j                        }t        }|j                  d      rnBd|v sd|v rd}n7d|v sd|v sd|v r
d| d	| d
}n!|dk(  rd| d}t        }n|dk(  rn	d| d	| d
}|dk7  rt        j                  d| |       t        | 5  |      E d {    | j                  | _        y 7 w)NzCannot parse ClientHellozO('SSL routines', 'tls_early_post_process_client_hello', 'unsupported protocol')z,('SSL routines', '', 'unsupported protocol')z|Client and mitmproxy cannot agree on a TLS version to use. You may need to adjust mitmproxy's tls_version_client_min option.z
unknown cazbad certificatezcertificate unknownz6The client does not trust the proxy's certificate for z (ro   zconnection closedzOThe client disconnected during the handshake. If this happens consistently for zK, this may indicate that the client does not trust the proxy's certificate.r  z5The client may not trust the proxy's certificate for zClient TLS handshake failed. r   )rf   rs   r   format_addressr   r   r  r   
startswithr   r   r   ri   r   erroredr   )rl   r   destr   rm   s       r,   r   z!ClientTLSLayer.on_handshake_errorj  s?    99==99==D''(;(;(C(CDD>>45]=DT 
 C C'$+ IbQTPUUVW  ''abfag h\ ]  E--I$rRUQVVWXC++,,!>seDERR7-c222"ll 	3s   C.D
1D2D
r   c              #   ~   K   | j                   -t        j                  | j                    d| dt               y y w)Nz[tls] Swallowing z as handshake failed.)r   r   r   r   )rl   r   s     r,   r"  zClientTLSLayer.errored  s>     ::!,,::,/w6KLe  "s   ;=)rN   rO   rP   rQ   r   rR   r   r   r   r   rj   r   r   r   r   r   r   r   r  r   r   r   r"  r   r   s   @r,   r   r     s    "  %%' ',!7!7!= ??			dC$J&6 7	8?B%"8"8t"D &+c &+e.D.DT.J &+PV\\ e.D.DT.J r0   r   c                   <     e Zd ZdZdej
                  f fdZ xZS )MockTLSLayerzMock layer to disable actual TLS and use cleartext in tests.

    Use like so:
        monkeypatch.setattr(tls, "ServerTLSLayer", tls.MockTLSLayer)
    ctxc                 N    t         |   |t        j                  d              y )Nr  )ri   rj   r   r   )rl   r'  rm   s     r,   rj   zMockTLSLayer.__init__  s    j//=>r0   )rN   rO   rP   rQ   r   r   rj   r   r   s   @r,   r&  r&    s    ?GOO ? ?r0   r&  )9r%   r   collections.abcr   dataclassesr   loggingr   r   r   r   OpenSSLr	   	mitmproxyr
   r   mitmproxy.net.tlsr   r   mitmproxy.proxyr   r   r   r   r   mitmproxy.proxy.commandsr   mitmproxy.proxy.layersr   r   mitmproxy.tlsr   r   r   mitmproxy.utilsr   r   r-   r9   r@   rD   rH   rK   HTTP1_ALPNS
HTTP_ALPNSrM   rU   rY   r[   r^   r`   rb   TunnelLayerrd   r   r   r&  rS   r0   r,   <module>r7     s     $ !         5 4 $ # " ! " . & & % ) ! !E huo 25 UT\ U {T'9 , 8E? 6 %$, $% K$,> , 6#
          y   y   )   )  O/v!! O/d-3X -3`fX fR?8 ?r0   