
    @OOfL                    F   d dl mZ d dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlZd dlZ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Zd dlmZ d d	lmZ d
ZdZ ej8                  e      Zd;dZd<dZ  G d d      Z! G d dejD                        Z# G d dejH                  ejJ                        Z&dZ'ejP                  dz  Z)ejP                  dz  Z* G d dejV                        Z,d Z- G d dejV                        Z.d Z/dZ0 G d dejb                  jd                        Z3 G d d ejh                        Z5 G d! d"e5      Z6e7e8e9f   Z: G d# d$      Z; G d% d&      Z<ed'k(  rd dl=Z= e=j|                         d(        Z?e?j                          e=j                  d)d*d+,       e=j                  d-d*d.,       e=j                  d/e8d0d12       e=j                  d3d4e9d5d6d78      d9                                    ZBe?j                         d:        ZC e?        yy)=    )annotationsN)Callable)Any)cast)ClassVar)IO)get_local_ip)get_local_ip6z	127.0.0.1i  c                n    | j                         j                         }|sy t        j                  |      S N)readlinestripjsonloads)rfilexs     [/var/www/premiumrankchecker/venv/lib/python3.12/site-packages/mitmproxy/platform/windows.pyreadr   $   s+     A::a=    c                    |j                  t        j                  |       j                         dz          |j	                          y )N   
)writer   dumpsencodeflush)datawfiles     r   r   r   +   s.    	KK

4 '')E12	KKMr   c                  <    e Zd ZU ded<   ded<   d Zd Zd Zd
dZy	)Resolverzsocket.socket | Nonesockzthreading.RLocklockc                D    d | _         t        j                         | _        y r   )r    	threadingRLockr!   selfs    r   __init__zResolver.__init__4   s    	OO%	r   c                    | j                   5  t        j                          | j                          d d d        y # 1 sw Y   y xY wr   )r!   TransparentProxysetup_connectr%   s    r   r*   zResolver.setup8   s3    YY 	""$MMO	 	 	s	   %;Ac                   | j                   r| j                   j                          t        j                  t        j                  t        j                        | _         | j                   j                  t        t        f       | j                   j                  d      | _	        | j                   j                  d      | _
        t        t        j                         | j                         y )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._connect=   s    99IIOOMM&..&2D2DE			,.?@AYY''-
YY''-
biik4::&r   c                   |j                         d d \  }}t        j                  dd|      }|j                  dd      d   }| j                  5  	 t        ||f| j                         t        | j                        }|t        d      t        |      cd d d        S # t        t        t        f$ r- | j                          | j                  |      cY cd d d        S w xY w# 1 sw Y   y xY w)N   z^::ffff:(?=\d+.\d+.\d+.\d+$) %   r   z$Cannot resolve original destination.)getpeernameresubsplitr!   r   r   r   r   RuntimeErrortupleEOFErrorOSErrorAttributeErrorr+   original_addr)r&   csockipportaddrs        r   rG   zResolver.original_addrG   s    $$&r*DVV3R<XXc1a YY 		11r4j$**-DJJ'<&'MNNT{		1 		1 g~6 1))%00		1 		11		1 		1s+   C#AB5C C#C  C##C,N)rH   zsocket.socket)__name__
__module____qualname____annotations__r'   r*   r+   rG    r   r   r   r   0   s"    

&
'1r   r   c                  $    e Zd ZU dZded<   ddZy)APIRequestHandlerz
    TransparentProxy API: Returns the pickled server address, port tuple
    for each received pickled client address, port tuple.
    	APIServerserverc                   | j                   j                  }	 t        | j                        }|y |j	                  |      5  	 t        | j                        }|
	 d d d        y 	 |j
                  t        t        t        t        f   t        |               }t        || j                         l# t        $ r d }Y $w xY w# 1 sw Y   y xY w# t        t        f$ r Y y w xY wr   )rT   	proxifierr   r   exemptclient_server_mapr   rC   strintKeyErrorr   r   rD   rE   )r&   rV   pidcrT   s        r   handlezAPIRequestHandler.handle_   s    &*kk&;&;		DJJ'C{!!#& .TZZ(Ay	. .
&!*!<!< sCx%(;"
 &$**-  $ &!%&. . '" 		sX   C C C C %3B/C /B=:C <B==C  C	C 	C CCN)returnNone)rL   rM   rN   __doc__rO   r^   rP   r   r   rR   rR   W   s    
 r   rR   c                       e Zd Z fdZ xZS )rS   c                @    t        |   |i | || _        d| _        y )NT)superr'   rV   daemon_threads)r&   rV   argskwargs	__class__s       r   r'   zAPIServer.__init__v   s$    $)&)""r   )rL   rM   rN   r'   __classcell__rh   s   @r   rS   rS   u   s    # #r   rS   z         c            	      0   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y	)
MIB_TCP6ROW_OWNER_PIDucLocalAddrdwLocalScopeIddwLocalPortucRemoteAddrdwRemoteScopeIddwRemotePortdwStatedwOwningPidN)rL   rM   rN   IN6_ADDRctypeswintypesDWORD_fields_rP   r   r   ro   ro      s    	!	6??001	--.	"	FOO112	../	FOO))*	--.	Hr   ro   c                H      G  fddt         j                        } |       S )Nc                  N    e Zd Zdej                  j
                  fdeW  z  fgZy)9MIB_TCP6TABLE_OWNER_PID.<locals>._MIB_TCP6TABLE_OWNER_PIDdwNumEntriestableN)rL   rM   rN   ry   rz   r{   ro   r|   sizes   r   _MIB_TCP6TABLE_OWNER_PIDr      s*    V__223+d23
r   r   ry   	Structure)r   r   s   ` r   MIB_TCP6TABLE_OWNER_PIDr      s     
6#3#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y)MIB_TCPROW_OWNER_PIDrv   rp   rr   rs   ru   rw   N)rL   rM   rN   ry   rz   r{   IN4_ADDRr|   rP   r   r   r   r      sa    	FOO))*	!	--.	"	../	--.Hr   r   c                H      G  fddt         j                        } |       S )Nc                  N    e Zd Zdej                  j
                  fdeW  z  fgZy)7MIB_TCPTABLE_OWNER_PID.<locals>._MIB_TCPTABLE_OWNER_PIDr   r   N)rL   rM   rN   ry   rz   r{   r   r|   r   s   r   _MIB_TCPTABLE_OWNER_PIDr      s*    V__223*T12
r   r   r   )r   r   s   ` r   MIB_TCPTABLE_OWNER_PIDr      s     
&"2"2 
 #$$r   c                  :    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
y	)
TcpConnectionTablei   c                2   t        | j                        | _        t        j                  j                  | j                        | _        t        | j                        | _        t        j                  j                  | j                        | _	        i | _
        y r   )r   DEFAULT_TABLE_SIZE_tcpry   rz   r{   	_tcp_sizer   _tcp6
_tcp6_size_mapr%   s    r   r'   zTcpConnectionTable.__init__   se    *4+B+BC	..t/F/FG,T-D-DE
 ////0G0GH	r   c                     | j                   |   S r   )r   r&   items     r   __getitem__zTcpConnectionTable.__getitem__   s    yyr   c                6    | j                   j                         S r   )r   __iter__r%   s    r   r   zTcpConnectionTable.__iter__   s    yy!!##r   c                6    | j                   j                         S r   )r   __len__r%   s    r   r   zTcpConnectionTable.__len__   s    yy  ""r   c                R    i | _         | j                          | j                          y r   )r   _refresh_ipv4_refresh_ipv6r%   s    r   refreshzTcpConnectionTable.refresh   s!    	r   c                   t         j                  j                  j                  t        j                  | j
                        t        j                  | j                        dt        j                  t        d      }|dk(  r| j
                  j                  d | j
                  j                   D ]s  }t        j                  t        j                  t        |j                              }t        j                  |j                         }|j"                  | j$                  ||f<   u y |t&        k(  r5t)        | j                  j*                        | _        | j-                          y t/        d|z        )NFr   z2[IPv4] Unknown GetExtendedTcpTable return code: %s)ry   windlliphlpapiGetExtendedTcpTablebyrefr   r   r0   r1   TCP_TABLE_OWNER_PID_CONNECTIONSr   r   	inet_ntopbytesrp   htonsrr   rw   r   ERROR_INSUFFICIENT_BUFFERr   valuer   rB   r&   retrowlocal_ip
local_ports        r   r   z TcpConnectionTable._refresh_ipv4   s
   mm$$88LL#LL(NN+
 !8yy'?)?)?@ D!++FNNE#//<RS#\\#//:
47OO		8Z01D --.t~~/C/CDDI DsJ r   c                   t         j                  j                  j                  t        j                  | j
                        t        j                  | j                        dt        j                  t        d      }|dk(  r| j
                  j                  d | j
                  j                   D ]s  }t        j                  t        j                  t        |j                              }t        j                  |j                         }|j"                  | j$                  ||f<   u y |t&        k(  r5t)        | j                  j*                        | _        | j-                          y t/        d|z        )NFr   z2[IPv6] Unknown GetExtendedTcpTable return code: %s)ry   r   r   r   r   r   r   r0   AF_INET6r   r   r   r   r   rp   r   rr   rw   r   r   r   r   r   rB   r   s        r   r   z TcpConnectionTable._refresh_ipv6   s   mm$$88LL$LL)OO+
 !8zz''(A$***A*AB D!++FOOU3??=ST#\\#//:
47OO		8Z01D --01F1FGDJ DsJ r   N)rL   rM   rN   r   r'   r   r   r   r   r   r   rP   r   r   r   r      s+    $#
.r   r   c                       e Zd ZU dZded<   ej                  j                  df	 	 	 	 	 	 	 	 	 d
 fdZ fdZ	d Z
d Zdd	Z xZS )RedirectTzpydivert.WinDivert	windivertr   c                j    || _         t        j                  |||      | _        t        |           y )Nflags)r^   pydivert	WinDivertr   rd   r'   )r&   r^   filterlayerr   rh   s        r   r'   zRedirect.__init__  s-     !++FEGr   c                V    | j                   j                          t        |           y r   )r   openrd   start)r&   rh   s    r   r   zRedirect.start  s    r   c                    	 	 | j                   j                         }| j                  |       -# t        $ r}t	        |dd       dk(  rY d }~y  d }~ww xY w)Nwinerror  )r   recvr^   rE   getattr)r&   packetes      r   runzRedirect.run  sX    $,,. F#   1j$/36	s   / 	AAAAc                8    | j                   j                          y r   )r   r/   r%   s    r   shutdownzRedirect.shutdown)  s    r   c                    	 | j                   j                         S # t        $ r}|j                  dk(  rY d}~y 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   rE   r   )r&   r   s     r   r   zRedirect.recv,  s<    
	>>&&(( 	zzS 		s    	?::?)
r^   !Callable[[pydivert.Packet], None]r   rY   r   zpydivert.Layerr   zpydivert.Flagr_   r`   )r_   zpydivert.Packet | None)rL   rM   rN   daemonrO   r   LayerNETWORKr'   r   r   r   r   ri   rj   s   @r   r   r   
  si    F!! !) 6 6 	1	 	 		
 	 
	
$r   r   c                  >     e Zd ZU ded<   	 	 	 	 	 	 d fdZd Z xZS )RedirectLocalzset[int]trusted_pidsc                    t               | _        t               | _        || _        t
        |   | j                  |       y r   )r   tcp_connectionssetr   redirect_requestrd   r'   r^   )r&   r   r   rh   s      r   r'   zRedirectLocal.__init__=  s5      23E 0f-r   c                6   |j                   |j                  f}|| j                  vr| j                  j                          | j                  j	                  |d       }|| j
                  vr| j                  |       y | j                  j                  |d       y )NTrecalculate_checksum)	src_addrsrc_portr   r   getr   r   r   send)r&   r   clientr\   s       r   r^   zRedirectLocal.handleE  s    //6??3---  ((* ""&&vt4d'''!!&) NNTBr   )r   r   r   rY   r_   r`   )rL   rM   rN   rO   r'   r^   ri   rj   s   @r   r   r   :  s,    . A.KN.	.Cr   r   c                  6    e Zd ZU dZdZded<   d Zd	dZd
dZy)ClientServerMapzA thread-safe LRU dict.i   zClassVar[int]connection_cache_sizec                h    t        j                         | _        t        j                         | _        y r   )r#   Lock_lockcollectionsOrderedDictr   r%   s    r   r'   zClientServerMap.__init___  s     ^^%
++-	r   c                d    | j                   5  | j                  |   cd d d        S # 1 sw Y   y xY wr   )r   r   r   s     r   r   zClientServerMap.__getitem__c  s)    ZZ 	#99T?	# 	# 	#s   &/c                Z   | j                   5  || j                  |<   | j                  j                  |       t        | j                        | j                  kD  r>| j                  j                  d       t        | j                        | j                  kD  r>d d d        y # 1 sw Y   y xY w)NF)r   r   move_to_endlenr   popitem)r&   keyr   s      r   __setitem__zClientServerMap.__setitem__g  s}    ZZ 	)"DIIcNII!!#&dii.4#=#==		!!%( dii.4#=#==	) 	) 	)s   B
B!!B*N)r   TConnectionr_   r   )r   r   r   r   r_   r`   )	rL   rM   rN   ra   r   rO   r'   r   r   rP   r   r   r   r   Z  s    !+0=0.#)r   r   c                      e Zd ZU dZdZded<   dZded<   ded<   ded	<   d
ed<   ded<   ded<   	 	 	 	 d	 	 	 	 	 	 	 	 	 ddZed        Z	d Z
d ZddZddZej                  dd       Zy)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 proxy 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 proxy.

    (2) Next, the proxy receives the forwarded packet, but does not know the real destination yet
    (which we overwrote with the proxy'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 proxy now establishes the upstream connection as usual.

    (4) Finally, the proxy 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 proxy 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.
    NzRedirectLocal | NonelocalzRedirect | Noneforwardr   responseicmprZ   
proxy_portrY   r   r   rX   c                   || _         |xs d| dt         d| _        t               | _        t               | _        t               | _        t        | t        t        ft              | _        t        j                  | j                  j                        | _        d| j                   _        |r>t%        | j&                  | j                  t(        j*                  j,                        | _        |r%t1        | j&                  | j                        | _        t%        | j4                  d|       | _        t%        d dt(        j8                  j:                  	      | _        y )
Nztcp.DstPort != z and tcp.DstPort != z and tcp.DstPort < 49152)targetTzoutbound and tcp.SrcPort == c                     y r   rP   )_s    r   <lambda>z+TransparentProxy.__init__.<locals>.<lambda>  s    r   r   r   )r   r5   r   r	   ipv4_addressr
   ipv6_addressr   rX   rS   r4   rR   apir#   Threadserve_forever
api_threadr   r   r   r   r   NETWORK_FORWARDr   r   r   redirect_responser   FlagDROPr   )r&   r   r   r   r   s        r   r'   zTransparentProxy.__init__  s    % m ,@AR@SSkl 	
 )N)O!0!2$&78:K
 $**$((2H2HI!%#%%t{{HNN4R4RDL &t'<'<dkkJDJ !""*:,7
 ^V8==;M;MN	r   c                   t         j                  d       t        j                  t        j                  t        j                        }|j                  t        t        f      }|rt               }|j                          y y )NzsTransparent mode on Windows is unsupported and flaky. Consider using local redirect mode or WireGuard mode instead.)
loggerwarningr0   r1   r2   
connect_exr4   r5   r)   r   )clssserver_unavailablerV   s       r   r*   zTransparentProxy.setup  sb     	 B	
 MM&..&*<*<=\\+<>O*PQ(*IOO r   c                :   | j                   j                          | j                  j                          | j                  j                          | j                  r| j                  j                          | j
                  r| j
                  j                          y y r   )r  r   r   r   r   r   r%   s    r   r   zTransparentProxy.start  sc    		<<LL ::JJ r   c                8   | j                   r| j                   j                          | j                  r| j                  j                          | j                  j                          | j                  j                          | j
                  j                          y r   )r   r   r   r   r   r   r%   s    r   r   zTransparentProxy.shutdown  s`    ::JJ!<<LL!!# 		r   c                   |j                   |j                  f}|j                  |j                  f| j                  |<   |j
                  t        j                  k(  r | j                  sJ | j                  |_        nn|j
                  t        j                  k(  rF| j                  st        |j                         | _
        | j                  sJ | j                  |_        nt        d      | j                  |_        t        j                  j                   j"                  |_        | j&                  j(                  j+                  |       y )NzUnknown address family)r   r   dst_addrdst_portrX   address_familyr0   r1   r   r   r   r
   rB   r   r   consts	DirectionINBOUND	directionr   r   r   r&   r   r   s      r   r   z!TransparentProxy.redirect_request  s     //6??3*0//6??)Kv&   FNN2$$$$"//FO""foo5$$$1&//$B!$$$$"//FO788//#??44<< 	$$V,r   c                   |j                   |j                  f}	 | j                  |   \  |_        |_        |j                          | j                  j                  j                  |d       y# t        $ r t        d|        Y Aw xY w)zy
        If the proxy responds to the client, let the client believe the target server sent the
        packets.
        z4Warning: Previously unseen connection from proxy to Fr   N)r  r  rX   r   r   recalculate_checksumsr[   printr   r   r   r  s      r   r  z"TransparentProxy.redirect_response  s     //6??3	+/3/E/Ef/M,FOV_ ((*$$V%$H  	SHQR	Ss   A. .BBc              #  J  K   | j                   r%| j                   j                  j                  |       	 d  | j                   r&| j                   j                  j                  |       y y # | j                   r&| j                   j                  j                  |       w w xY wwr   )r   r   addremove)r&   r\   s     r   rW   zTransparentProxy.exempt  su     ::JJ##'',	4zz

''..s3 tzz

''..s3 s   2B#A, 3B#,4B  B#)TT  z'tcp.DstPort == 80 or tcp.DstPort == 443)
r   boolr   r   r   rZ   r   z
str | Noner_   r`   )r   zpydivert.Packet)r\   rZ   )rL   rM   rN   ra   r   rO   r   r'   classmethodr*   r   r   r   r  
contextlibcontextmanagerrW   rP   r   r   r)   r)   o  s    &P #'E&#G_#
NOK&& F*O*O *O 	*O
 *O 
*OX 
 
-2I  4 4r   r)   __main__c                      y r   rP   rP   r   r   clir&  %  s    r   z--local/--no-localTz Redirect the host's own traffic.)defaulthelpz--forward/--no-forwardz.Redirect traffic that's forwarded by the host.z--filterWINDIVERT_FILTERz#Custom WinDivert interception rule.)typemetavarr(  z-pz--proxy-port8080r  z#The port mitmproxy is listening on.)r*  r+  r'  r(  c                    t        di | }|j                          t        d       t        d|j                          	 	 t	        j
                  d       # t        $ r) t        d       |j                          t        d       Y yw xY w)zRedirect flows to mitmproxy.z * Redirection active.z   Filter: r=   z * Shutting down...z * Shut down.NrP   )r)   r   r  r   timesleepKeyboardInterruptr   )optionsproxys     r   redirectr3  )  sx    2 !+7+&(ELL>*+	#

1   	#'(NN/"	#s    A /B	B	c                     t               } | j                          | j                         D ]  \  \  }}}t        | d| d|         y)z1List all TCP connections and the associated PIDs.:z -> N)r   r   itemsr  )connectionsrI   rJ   r\   s       r   r7  r7  N  sQ     )**002 	+OJRRD$tC5)*	+r   )r   	IO[bytes]r_   r   )r   r8  r_   r`   )D
__future__r   collections.abcr   r"  ctypes.wintypesry   r   loggingr7   r?   r0   socketserverr#   r.  r   typingr   r   r   r   pydivert.constsr   mitmproxy.net.local_ipr	   r
   r4   r5   	getLoggerrL   r  r   r   r   StreamRequestHandlerrR   ThreadingMixIn	TCPServerrS   r   c_ubyterx   r   r   ro   r   r   r   r   abcMappingr   r   r   r   rC   rY   rZ   r   r   r)   clickgroupr&  commandoptionr3  r7  rP   r   r   <module>rL     sE   "      	 	     $      / 0   
		8	$
$1 $1N99 <#++\-C-C # ! >>B>>A
F,, 
& 6++ % #$ D00 DN-y -`CH C: CHo) )*p4 p4f zU[[]  	[[]U\\d1S U\\ =
 U\\"2	 U\\2# .# 	[[]+ + Ei r   