
    EgG                        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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ZdZdej        dej        fdZdej        ddfdZ G d	 d
          Z G d de
j                  Z G d de
j        e
j                  ZdZej        dz  Zej        dz  Z G d dej                   Z!d Z" G d dej                   Z#d Z$dZ% G d de j&        j'                  Z(dej)        e*         fdZ+de*dej)        e*         fdZ, G d dej-                  Z. G d d e.          Z/ej0        e*e1f         Z2 G d! d"          Z3 G d# d$          Z4dS )%    Nz	127.0.0.1i  rfilereturnc                 v    |                                                                  }t          j        |          S N)readlinestripjsonloads)r   xs     g/var/www/sysmax/venv/lib/python3.11/site-packages/seleniumwire/thirdparty/mitmproxy/platform/windows.pyreadr      s+      A:a==    wfilec                     |                     t          j        |                                           dz              |                                 d S )N   
)writer	   dumpsencodeflush)datar   s     r   r   r      s@    	KK
4  ''))E1222	KKMMMMMr   c                   `    e Zd ZU ej        ed<   ej        ed<   d Zd Zd Z	dej        fdZ
dS )	Resolversocklockc                 D    d | _         t          j                    | _        d S r   )r   	threadingRLockr   selfs    r   __init__zResolver.__init__'   s    	O%%			r   c                     | j         5  t                                           |                                  d d d            d S # 1 swxY w Y   d S r   )r   TransparentProxysetup_connectr   s    r   r#   zResolver.setup+   s    Y 	 	""$$$MMOOO	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   .AA
Ac                    | j         r| j                                          t          j        t          j        t          j                  | _         | j                             t          t          f           | j                             d          | _	        | j                             d          | _
        t          t          j                    | j	                   d S )Nwbrb)r   closesocketAF_INETSOCK_STREAMconnectREDIRECT_API_HOSTREDIRECT_API_PORTmakefiler   r   r   osgetpidr   s    r   r$   zResolver._connect0   s    9 	IOOM&.&2DEE		,.?@AAAY''--
Y''--
bikk4:&&&&&r   csockc                     |                                 d d         \  }}t          j        dd|          }|                    dd          d         }| j        5  	 t          ||f| j                   t          | j                  }|t          d          t          |          cd d d            S # t          t          j        f$ r8 |                                  |                     |          cY cd d d            S w xY w# 1 swxY w Y   d S )N   z^::ffff:(?=\d+.\d+.\d+.\d+$) %   r   z$Cannot resolve original destination.)getpeernameresubsplitr   r   r   r   r   RuntimeErrortupleEOFErrorr)   errorr$   original_addr)r   r2   ipportaddrs        r   r@   zResolver.original_addr:   so   $$&&rr*DV3R<<XXc1a Y 		1 		11r4j$*---DJ''<&'MNNNT{{		1 		1 		1 		1 		1 		1 		1 		1 fl+ 1 1 1))%0000		1 		1 		1 		1 		1 		1 		1 		11		1 		1 		1 		1 		1 		1 		1 		1 		1 		1s1   DA
B22?D 1D?D  DD
DN)__name__
__module____qualname__r)   __annotations__r   r   r    r#   r$   r@    r   r   r   r   #   s|         
-
/& & &  
' ' '16= 1 1 1 1 1 1r   r   c                       e Zd ZdZd ZdS )APIRequestHandlerz
    TransparentProxy API: Returns the pickled server address, port tuple
    for each received pickled client address, port tuple.
    c                 v   | j         j        }	 t          | j                  }|                    |          5  	 t          t          | j                            }	 |j        |         }n# t          $ r d }Y nw xY wt          || j	                   X# 1 swxY w Y   d S # t          t          j        f$ r Y d S w xY wr   )server	proxifierr   r   exemptr=   client_server_mapKeyErrorr   r   r>   r)   r?   )r   rM   pidclientrL   s        r   handlezAPIRequestHandler.handleP   s   &*k&;		DJ''C!!#&& . .."4
#3#344F&!*!<V!D# & & &!%&&$*---.. . . . . . . . . . &,' 	 	 	DD	sR   )B #BA)(B)A85B7A88BBB BB B87B8N)rD   rE   rF   __doc__rS   rH   r   r   rJ   rJ   J   s-         
    r   rJ   c                        e Zd Z fdZ xZS )	APIServerc                 V     t                      j        |i | || _        d| _        d S )NT)superr    rM   daemon_threads)r   rM   argskwargs	__class__s       r   r    zAPIServer.__init__b   s4    $)&)))""r   )rD   rE   rF   r    __classcell__r\   s   @r   rV   rV   `   s8        # # # # # # # # #r   rV   z         c            	           e Zd Zdefdej        j        fdej        j        fdefdej        j        fdej        j        fdej        j        fdej        j        fgZd	S )
MIB_TCP6ROW_OWNER_PIDucLocalAddrdwLocalScopeIddwLocalPortucRemoteAddrdwRemoteScopeIddwRemotePortdwStatedwOwningPidN)rD   rE   rF   IN6_ADDRctypeswintypesDWORD_fields_rH   r   r   rc   rc   w   ss        	!	6?01	-.	"	FO12	./	FO)*	-.	HHHr   rc   c                 L      G  fddt           j                  } |            S )Nc                   :    e Zd Zdej        j        fde z  fgZdS )9MIB_TCP6TABLE_OWNER_PID.<locals>._MIB_TCP6TABLE_OWNER_PIDdwNumEntriestableN)rD   rE   rF   rm   rn   ro   rc   rp   sizes   r   _MIB_TCP6TABLE_OWNER_PIDrs      s1        V_23+d23
r   rx   rm   	Structure)rw   rx   s   ` r   MIB_TCP6TABLE_OWNER_PIDr{      sK    
 
 
 
 
 
 
6#3 
 
 
 $#%%%r   c                       e Zd Zdej        j        fdefdej        j        fdefdej        j        fdej        j        fgZdS )MIB_TCPROW_OWNER_PIDrj   rd   rf   rg   ri   rk   N)rD   rE   rF   rm   rn   ro   IN4_ADDRrp   rH   r   r   r}   r}      sY        	FO)*	!	-.	"	./	-.HHHr   r}   c                 L      G  fddt           j                  } |            S )Nc                   :    e Zd Zdej        j        fde z  fgZdS )7MIB_TCPTABLE_OWNER_PID.<locals>._MIB_TCPTABLE_OWNER_PIDrt   ru   N)rD   rE   rF   rm   rn   ro   r}   rp   rv   s   r   _MIB_TCPTABLE_OWNER_PIDr      s1        V_23*T12
r   r   ry   )rw   r   s   ` r   MIB_TCPTABLE_OWNER_PIDr      sK    
 
 
 
 
 
 
&"2 
 
 
 #"$$$r   c                   <    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	S )
TcpConnectionTablei   c                    t          | j                  | _        t          j                            | j                  | _        t          | j                  | _        t          j                            | j                  | _	        i | _
        d S r   )r   DEFAULT_TABLE_SIZE_tcprm   rn   ro   	_tcp_sizer{   _tcp6
_tcp6_size_mapr   s    r   r    zTcpConnectionTable.__init__   se    *4+BCC	..t/FGG,T-DEE
 ///0GHH			r   c                     | j         |         S r   )r   r   items     r   __getitem__zTcpConnectionTable.__getitem__   s    yr   c                 4    | j                                         S r   )r   __iter__r   s    r   r   zTcpConnectionTable.__iter__   s    y!!###r   c                 4    | j                                         S r   )r   __len__r   s    r   r   zTcpConnectionTable.__len__   s    y  """r   c                 d    i | _         |                                  |                                  d S r   )r   _refresh_ipv4_refresh_ipv6r   s    r   refreshzTcpConnectionTable.refresh   s3    	r   c                 x   t           j        j                            t          j        | j                  t          j        | j                  dt          j        t          d          }|dk    r~| j        j
        d | j        j                 D ]]}t          j        t          j        t          |j                            }t          j        |j                  }|j        | j        ||f<   ^d S |t&          k    r4t)          | j        j                  | _        |                                  d S t/          d|z            )NFr   z2[IPv4] Unknown GetExtendedTcpTable return code: %s)rm   windlliphlpapiGetExtendedTcpTablebyrefr   r   r)   r*   TCP_TABLE_OWNER_PID_CONNECTIONSru   rt   	inet_ntopbytesrd   htonsrf   rk   r   ERROR_INSUFFICIENT_BUFFERr   valuer   r<   r   retrowlocal_ip
local_ports        r   r   z TcpConnectionTable._refresh_ipv4   s   m$88L##L((N+
 
 !88y'>	(>'>? D D!+FNE#/<R<RSS#\#/::
47O	8Z011D D ---.t~/CDDDI     SVYYZZZr   c                 x   t           j        j                            t          j        | j                  t          j        | j                  dt          j        t          d          }|dk    r~| j        j
        d | j        j                 D ]]}t          j        t          j        t          |j                            }t          j        |j                  }|j        | j        ||f<   ^d S |t&          k    r4t)          | j        j                  | _        |                                  d S t/          d|z            )NFr   z2[IPv6] Unknown GetExtendedTcpTable return code: %s)rm   r   r   r   r   r   r   r)   AF_INET6r   ru   rt   r   r   rd   r   rf   rk   r   r   r{   r   r   r<   r   s        r   r   z TcpConnectionTable._refresh_ipv6   s   m$88L$$L))O+
 
 !88z'(@)@(@A D D!+FOU3?=S=STT#\#/::
47O	8Z011D D ---01FGGDJ     SVYYZZZr   N)rD   rE   rF   r   r    r   r   r   r   r   r   rH   r   r   r   r      s            $ $ $# # #  
[ [ [*[ [ [ [ [r   r   c                  X   t          j         t           j        t           j                  } 	 |                     d           |                                 d         |                                  S # t          $ r Y |                                  d S w xY w# |                                  w xY w)N)z8.8.8.8P   r   )r)   r*   
SOCK_DGRAMr,   getsocknamer(   OSError)ss    r   get_local_ipr      s     	fnf&788A			/"""}}q! 	
				    						 	
				s#   .A. .
B8B BB B)	reachablec                 \   t          j         t           j        t           j                  }	 |                    | df           |                                d         |                                 S # t          $ r Y |                                 d S w xY w# |                                 w xY w)Nr   r   )r)   r   r   r,   r   r(   r   )r   r   s     r   get_local_ip6r      s     	fov'899A			9b/"""}}q! 	
				    						 	
				s#   0A0 0
B:B BB B+c                        e Zd ZU dZej        ed<   ej        j        dfde	j
        ej        gdf         dedej        dej        d	df
 fd
Z fdZd Zd Zd	e	j        ej                 fdZ xZS )RedirectT	windivertr   rS   Nfilterlayerflagsr   c                     || _         t          j        |||          | _        t	                                                       d S )Nr   )rS   pydivert	WinDivertr   rX   r    )r   rS   r   r   r   r\   s        r   r    zRedirect.__init__  sA     !+FEGGGr   c                 z    | j                                          t                                                       d S r   )r   openrX   start)r   r\   s    r   r   zRedirect.start  s,    r   c                     	 	 | j                                         }|                     |           n$# t          $ r}|j        dk    rY d }~d S  d }~ww xY wU)NT  )r   recvrS   WindowsErrorwinerror)r   packetes      r   runzRedirect.run  sy    		$$,,.. F####     :$$FFFFF			$s   2 
AAAAc                 8    | j                                          d S r   )r   r(   r   s    r   shutdownzRedirect.shutdown)  s    r   c                 ~    	 | j                                         S # t          $ r}|j        dk    rY d}~dS  d}~ww xY w)z
        Convenience function that receives a packet from the passed handler and handles error codes.
        If the process has been shut down, None is returned.
        r   N)r   r   r   r   )r   r   s     r   r   zRedirect.recv,  sW    
	>&&((( 	 	 	zS  ttttt		s    
<77<)rD   rE   rF   daemonr   r   rG   LayerNETWORKtypingCallablePacketstrFlagr    r   r   r   Optionalr   r]   r^   s   @r   r   r   
  s        F!!!! !) 6 	 	 14 78	 	 ~		
 }	 
	 	 	 	 	 	    
$ 
$ 
$  foho6        r   r   c                   z     e Zd ZU ej        e         ed<   dej        ej	        gdf         de
ddf fdZd Z xZS )RedirectLocaltrusted_pidsredirect_requestNr   r   c                     t                      | _        t                      | _        || _        t                                          | j        |           d S r   )r   tcp_connectionssetr   r   rX   r    rS   )r   r   r   r\   s      r   r    zRedirectLocal.__init__=  sI    
  233EE 0f-----r   c                    |j         |j        f}|| j        vr| j                                         | j                            |d           }|| j        vr|                     |           d S | j                            |d           d S )NTrecalculate_checksum)	src_addrsrc_portr   r   getr   r   r   send)r   r   rR   rQ   s       r   rS   zRedirectLocal.handleG  s    /6?3--- ((*** "&&vt44d'''!!&))))) NTBBBBBr   )rD   rE   rF   r   SetintrG   r   r   r   r   r    rS   r]   r^   s   @r   r   r   :  s         *S/!!!. /8?*;T*AB. . 
	. . . . . .C C C C C C Cr   r   c                   b    e Zd ZU dZdZej        e         ed<   d Z	de
de
fdZde
d	e
dd
fdZd
S )ClientServerMapzA thread-safe LRU dict.i   connection_cache_sizec                 f    t          j                    | _        t          j                    | _        d S r   )r   Lock_lockcollectionsOrderedDictr   r   s    r   r    zClientServerMap.__init__`  s%    ^%%
+--			r   r   r   c                 ^    | j         5  | j        |         cd d d            S # 1 swxY w Y   d S r   )r   r   r   s     r   r   zClientServerMap.__getitem__d  sw    Z 	# 	#9T?	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	#s   "&&keyr   Nc                 6   | j         5  || j        |<   | j                            |           t          | j                  | j        k    r7| j                            d           t          | j                  | j        k    7d d d            d S # 1 swxY w Y   d S )NF)r   r   move_to_endlenr   popitem)r   r   r   s      r   __setitem__zClientServerMap.__setitem__h  s    Z 	) 	)"DIcNI!!#&&&di..4#===	!!%((( di..4#===	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	)s   A9BBB)rD   rE   rF   rT   r   r   ClassVarr   rG   r    TConnectionr   r   rH   r   r   r   r   \  s         !!276?3/777. . .# # # # # #){ ); )4 ) ) ) ) ) )r   r   c                   >   e Zd ZU dZdZej        e         ed<   dZ	ej        e
         ed<   e
ed<   e
ed<   eed<   eed<   eed	<   	 	 	 	 ddedededej        e         ddf
dZed             Zd Zd Zdej        fdZdej        fdZej        defd            ZdS )r"   a  
    Transparent Windows Proxy for mitmproxy based on WinDivert/PyDivert. This module can be used to
    redirect both traffic that is forwarded by the host and traffic originating from the host itself.

    Requires elevated (admin) privileges. Can be started separately by manually running the file.

    How it works:

    (1) First, we intercept all packages that match our filter.
    We both consider traffic that is forwarded by the OS (WinDivert's NETWORK_FORWARD layer) as well
    as traffic sent from the local machine (WinDivert's NETWORK layer). In the case of traffic from
    the local machine, we need to exempt packets sent from the mitmproxy to not create a redirect loop.
    To accomplish this, we use Windows' GetExtendedTcpTable syscall and determine the source
    application's PID.

    For each intercepted package, we
        1. Store the source -> destination mapping (address and port)
        2. Remove the package from the network (by not reinjecting it).
        3. Re-inject the package into the local network stack, but with the destination address
           changed to the mitmproxy.

    (2) Next, the mitmproxy receives the forwarded packet, but does not know the real destination yet
    (which we overwrote with the mitmproxy's address). On Linux, we would now call
    getsockopt(SO_ORIGINAL_DST). We now access the redirect module's API (see APIRequestHandler),
    submit the source information and get the actual destination back (which we stored in 1.1).

    (3) The mitmproxy now establishes the upstream connection as usual.

    (4) Finally, the mitmproxy sends the response back to the client. To make it work, we need to change
    the packet's source address back to the original destination (using the mapping from 1.1),
    to which the client believes it is talking to.

    Limitations:

    - We assume that ephemeral TCP ports are not re-used for multiple connections at the same time.
    The mitmproxy will fail if an application connects to example.com and example.org from
    192.168.0.42:4242 simultaneously. This could be mitigated by introducing unique "meta-addresses"
    which mitmproxy sees, but this would remove the correct client info from mitmproxy.
    Nlocalforwardresponseicmp
proxy_portr   rO   T  'tcp.DstPort == 80 or tcp.DstPort == 443r   c                    || _         |pd| dt           d| _        t                      | _        t          d          | _        t                      | _        t          | t          t          ft                    | _        t          j        | j        j                  | _        d| j        _        |r/t%          | j        | j        t(          j        j                  | _        |rt1          | j        | j                  | _        t%          | j        d|           | _        t%          d d	t(          j        j        
          | _        d S )Nztcp.DstPort != z and tcp.DstPort != z and tcp.DstPort < 49152z2001:4860:4860::8888)targetTzoutbound and tcp.SrcPort == c                     d S r   rH   )_s    r   <lambda>z+TransparentProxy.__init__.<locals>.<lambda>  s    d r   r   r   )r   r.   r   r   ipv4_addressr   ipv6_addressr   rO   rV   r-   rJ   apir   Threadserve_forever
api_threadr   r   r   r   r   NETWORK_FORWARDr   r   r   redirect_responser   r   DROPr   )r   r   r   r   r   s        r   r    zTransparentProxy.__init__  s@    % jijii>Oiii 	 )NN)*@AA!0!2!2T$57H#IK\]]#*$(2HIII!% 	#%. DL
  	&% DJ !"7:77
 
 N-$
 
 
			r   c                     t          j         t           j        t           j                  }|                    t          t
          f          }|r$t                      }|                                 d S d S r   )r)   r*   r+   
connect_exr-   r.   r"   r   )clsr   server_unavailablerM   s       r   r#   zTransparentProxy.setup  sf     M&.&*<==\\+<>O*PQQ 	(**IOO	 	r   c                     | j                                          | j                                         | j                                         | j        r| j                                         | j        r| j                                         d S d S r   )r	  r   r   r   r   r   r   s    r   r   zTransparentProxy.start  s    	< 	!L   : 	J	 	r   c                    | j         r| j                                          | j        r| j                                         | j                                         | j                                         | j                                         d S r   )r   r   r   r   r   r  r   s    r   r   zTransparentProxy.shutdown  s    : 	"J!!!< 	$L!!###   	r   r   c                    |j         |j        f}|j        |j        f| j        |<   |j        t          j        k    r| j        sJ | j        |_        nZ|j        t          j	        k    r6| j
        st          |j                   | _
        | j
        sJ | j
        |_        nt          d          | j        |_        t          j        j        j        |_        | j        j                            |           d S )NzUnknown address family)r   r   dst_addrdst_portrO   address_familyr)   r*   r  r   r  r   r<   r   r   consts	DirectionINBOUND	directionr   r   r   r   r   rR   s      r   r   z!TransparentProxy.redirect_request  s     /6?3*0/6?)Kv&  FN22$$$$"/FOO"fo55$ C$1&/$B$B!$$$$"/FOO7888/#?4< 	$$V,,,,,r   c                    |j         |j        f}	 | j        |         \  |_        |_        |                                 n"# t          $ r t          d|            Y nw xY w| j        j	        
                    |d           dS )z}
        If the mitmproxy responds to the client, let the client believe the target server sent the
        packets.
        z8Warning: Previously unseen connection from mitmproxy to Fr   N)r  r  rO   r   r   recalculate_checksumsrP   printr   r   r   r  s      r   r  z"TransparentProxy.redirect_response  s     /6?3	+/3/Ef/M,FOV_ ((****  	W 	W 	WUVUUVVVVV	W
 	$$V%$HHHHHs   ? AArQ   c              #     K   | j         r| j         j                            |           	 d V  | j         r!| j         j                            |           d S d S # | j         r | j         j                            |           w w xY wr   )r   r   addremove)r   rQ   s     r   rN   zTransparentProxy.exempt  s      : 	-J#'',,,	4EEEz 4
'..s333334 4tz 4
'..s33334s   A )B)TTr   r   )rD   rE   rF   rT   r   r   r   r   rG   r   r   r   r   r   boolr    classmethodr#   r   r   r   r   r   r  
contextlibcontextmanagerrN   rH   r   r   r"   r"   p  s        & &N -1E6?=)000)-GV_X&---
NNNOOOKKK&&&& 'P2
 2
2
 2
 	2

 $2
 
2
 2
 2
 2
h   [    -x - - - -2I I I I I  4# 4 4 4 4 4 4r   r"   )5r   collections.abcr$  rm   ctypes.wintypesior	   r0   r9   r)   socketserverr   r   r   pydivert.constsr-   r.   BufferedReaderAnyr   BufferedWriterr   r   StreamRequestHandlerrJ   ThreadingMixIn	TCPServerrV   r   c_ubyterl   r~   rz   rc   r{   r}   r   r   abcMappingr   r   r   r   r   r  r   r   Tupler   r   r   r"   rH   r   r   <module>r5     s                    				  				 				                 ! fj    
r( T    
$1 $1 $1 $1 $1 $1 $1 $1N    9   ,# # # # #+\-C # # # ! >B>A
 
 
 
 
F, 
 
 
& & &    6+   % % % #$ @[ @[ @[ @[ @[0 @[ @[ @[F
foc* 
 
 
 

S 
V_S%9 
 
 
 
- - - - -y - - -`C C C C CH C C C> l38$) ) ) ) ) ) ) )(t4 t4 t4 t4 t4 t4 t4 t4 t4 t4r   