
    h:                     d   d Z ddlZddlmZ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mZ ddlmZ ddlmZ ddlmZ ddlmZmZmZ dd	lmZ dd
lmZ ddlmZmZmZmZm Z m!Z! ddl"m#Z#m$Z$m%Z% ddlm&Z&m'Z'm(Z( ddl)m*Z*m+Z+ ddl,m-Z- ddl.m/Z/m0Z0 ddl1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z; ddlm<Z< ddl"m=Z= ej>        ddl?Z@ G d d          ZAdZBe:e9e-         e-f         ZC G d deD          ZEd ZF	 	 	 	 	 	 dDdZG	 	 	 	 	 	 	 	 dEdZHejI        jJ        d             ZKejI        jJ        	 	 	 dFd            ZLejI        jJ        	 	 	 	 	 	 	 	 	 dGde=d e7eM         d!e7eM         d"eNd#e7eO         d$eOd%eNd&e7e<         d'e7e6eP                  d(eNfd)            ZQd* ZRd+e=d,e8eeNf         fd-ZSejI        jJ        	 	 	 dHd.            ZTejI        jJ        d/             ZUejI        jJ        dddddefd0            ZVejI        jJ        d1             ZWeVeWeTeUfD ]ZXeXj         eXxj         eBz  c_         d2 d3 d4dddd4fd5ZYejI        jJ        d6             ZZejI        jJ        d7             Z[ G d8 d9eD          Z\	 	 	 	 	 dId:Z]ejI        jJ        	 	 	 	 dJd;            Z^ejI        jJ        	 	 	 dHd<            Z_ejI        jJ        	 	 	 	 	 dKd=            Z`ejI        jJ        	 	 	 	 dLd>            Za G d? d@eD          ZbejI        jJ        dA             Zcebj         ec_         ejI        jJ        	 	 	 	 dJdB            ZdejI        jJ        dC             ZedS )Mz(
Functions to send and receive packets.
    N)ThreadEvent)	plain_str	ETH_P_ALL)conf)warning)network_nameresolve_ifaceNetworkInterface)Packet)	inet_pton)get_temp_filetcpdumpwrpcapContextManagerSubprocess
PcapReaderEDecimal)
PacketListQueryAnswer
SndRcvList)log_runtimelog_interactiveScapy_Exception)GenSetGen)DefaultSession)SuperSocket
IterSocket)
AnyCallableDictIteratorListOptionalTupleTypeUnioncast)_GlobInterfaceType)_PacketIterablec                   Z    e Zd Z eg d          Z eg d          Z eg d          ZdZdS )debugReceivedSentMatchedN)	__name__
__module____qualname__r   recvsentr   match
crashed_on     R/mounts/lovelace/software/anaconda3/lib/python3.11/site-packages/scapy/sendrecv.pyr-   r-   C   sF        :b*%%D:b&!!DJr9%%EJJJr9   r-   a  
    :param pks: SuperSocket instance to send/receive packets
    :param pkt: the packet to send
    :param timeout: how much time to wait after the last packet has been sent
    :param inter: delay between two packets during sending
    :param verbose: set verbosity level
    :param chainCC: if True, KeyboardInterrupts will be forwarded
    :param retry: if positive, how many times to resend unanswered packets
        if negative, how many times to retry when no more packets
        are answered
    :param multi: whether to accept multiple answers for the same stimulus
    :param rcv_pks: if set, will be used instead of pks to receive packets.
        packets will still be sent through pks
    :param prebuild: pre-build the packets before starting to send them.
        Automatically enabled when a generator is passed as the packet
    :param _flood:
    :param threaded: if True, packets are sent in a thread and received in another.
        Defaults to True.
    :param session: a flow decoder used to handle stream of packets
    :param chainEX: if True, exceptions during send will be forwarded
    :param stop_filter: Python function applied to each packet to determine if
        we have to stop the capture after this packet.
    c                   T    e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 	 	 ddZd Zdd	Zd
 Zd Zd Z	dS )SndRcvHandlera  
    Util to send/receive packets, used by sr*().
    Do not use directly.

    This matches the requests and answers.

    Notes::
      - threaded: if you're planning to send/receive many packets, it's likely
        a good idea to use threaded mode.
      - DEVS: store the outgoing timestamp right BEFORE sending the packet
        to avoid races that could result in negative latency. We aren't Stadia
    Nr   FTc           
      ,   |t           j        }t           j        rNt          g d          t          _        t          g d          t          _        t          g d          t          _        d| _	        g | _
        || _        |	p|| _        || _        || _        || _        || _        || _        || _        || _        || _        d| _        d| _        d| _        || _        || _        t5                      | _        |
r| j        st9          |          | _        n|| _        |dk     r| x}}nd}||dk     rd | _        |dk    r| j                                         i | _        |s| j        rtA          | j!                  }d|_"        d }	 | #                    |j$                   n# tJ          $ r}|}Y d }~nd }~ww xY w| j        &                                 | j        r| j        '                                 |(                                 |r	| j        r|n4	 | #                    | j!                   n# tJ          $ r | j        r Y nw xY w|r0d tS          j*        | j        +                                 D             }n2t9          tS          j*        | j        +                                           }|r:tY          |          dk    r'tY          |          tY          | j                  k    r|}|| _        tY          | j                  dk    rn|d	z  }|dk    t           j        rHt          |d d          d          t          _        t          | j
        d d                    t          _        |r| j
        D ]\  }}t[          |d
          r|`.|r\t_          d| j	        tY          | j
                  z   tY          | j
                  ta          d| j        | j        z
            fz             t          | j
                  | _1        t          |d          | _2        d S )Nr.   r/   r0   r   F)targetTc                 2    g | ]}t          |d           |S )	_answered)hasattr).0ps     r:   
<listcomp>z*SndRcvHandler.__init__.<locals>.<listcomp>   s8       "1k22  r9      r@   z:
Received %i packets, got %i answers, remaining %i packets
Unanswered)3r   verbdebug_matchr   r-   r4   r5   r   r6   nbrecvanspksrcv_pksinterverbosechainCCmultitimeoutsessionchainEXstop_filter
_send_donenotansnoans_floodthreadedr   breakoutlisttobesentclearhsentr   _sndrcv_snddaemon_sndrcv_rcvstartKeyboardInterruptsetstopjoin	itertoolschainvalueslenrA   r@   printmax
ans_resultunans_result)selfrK   pktrQ   rM   rN   rO   retryrP   rL   prebuildrX   rY   rR   rS   rT   autostop
snd_threadinterruptedexremainsnd_s                          r:   __init__zSndRcvHandler.__init__w   sT   & ?iG 	4#B
33EJ#B//EJ$R33EK~#

&
  	 DK 	  IIDMMDM199 %v%HuuH7Q;;DLqjjM!!!DJ 4; #+  
 %)
! #%$$Z%56666( % % %"$KKKKKK% !!### ; 'K$$&&&!!! &4< &%%$$T%56666(   |    E (
0A0A0C0CD  
 iotz/@/@/B/BCDD !CKK!OO6{{c$-0000 "DM4=!!Q&&QJEg qjjj  	2#F111Iv66EJ$TXaaa[11EK  	&( & &Q3,, & 	'K#dh--/TX4;344*   %TX..&v|<<s*   F! !
F7+F22F7H/ /IIc                     | j         | j        fS N)rm   rn   ro   s    r:   resultszSndRcvHandler.results   s     111r9   returnc                     | j         rG| j        | j        k    r9| j        s4| j        r/| j        j        r%| j                            d           dS dS dS dS dS dS )z<Close the sniffer if all expected answers have been receivedF)rf   N)rU   rW   rV   rP   snifferrunningre   r}   s    r:   _stop_sniffer_if_donez#SndRcvHandler._stop_sniffer_if_done   s    ? 	.tzT[888| . 4 .!!u!-----	. 	.8888. . . .r9   c                 :   d}d}	 | j         rt          j        dd           | j        D ]}| j                            |                                g                               |           | j        	                    |           t          j        | j                   | j                                        r n|dz  }| j         rt          j        dd|z             n7# t          $ r Y n+t           $ r | j        r t%          j        d           Y nw xY w	 t)          t*          |          j        t)          t*          | j                  _        n# t.          $ r Y nw xY w| j        r| j        j        | _        n| j        s|| _        d| _        n|# 	 t)          t*          |          j        t)          t*          | j                  _        n# t.          $ r Y nw xY w| j        r| j        j        | _        n| j        s|| _        d| _        w xY w|                                  | j        rn| j        i| j                                        sR| j                            | j                   | j         r-| j         j!        r#| j         "                                 dS dS dS dS dS dS )	z/Function used in the sending thread of sndrcv()r   NrE   s   Begin emission
s   
Finished sending %i packets
z--- Error sending packetsT)rQ   )#rN   oswriter\   r^   
setdefaulthashretappendrK   sendtimesleeprM   rZ   is_set
SystemExit	ExceptionrS   r   	exceptionr)   r   	sent_timeAttributeErrorrX   iterlenrV   rU   r   rY   rQ   waitr   r   re   )ro   irC   s      r:   r_   zSndRcvHandler._sndrcv_snd  s    !	#| 1/000] 
 
 
%%aiikk266==a@@@a   
4:&&&='')) EQ| D>BCCC 	 	 	D 	C 	C 	C| C%&ABBBBB		COO- VT]++55!   {  "k1_  "DOOOO- VT]++55!   {  "k1_  "DO""""""$$$= 	$T\5dm>R>R>T>T5Mt|444| $ 4 $!!#####	$ 	$5555$ $ $ $sl   CC F 
D)F +%DF DF 7E 
EEH7GH
GHG2Hc                    |dS d}|                                 }|| j        v r| j        |         }t          |          D ]\  }}|                    |          r| j                            t          ||                     | j        dk    rt          j	        dd           d}| j
        s||= | xj        dz  c_        n't          |d          s| xj        dz  c_        d|_         n|                                  |s]| j        dk    rt          j	        dd           | xj        dz  c_        t           j        r#t$          j                            |           dS dS dS )z.Internal function used to process each packet.NFrE      *Tr@      .)r   r^   	enumerateanswersrJ   r   r   rN   r   r   rP   rW   rA   r@   r   rI   r   rH   r-   r4   )ro   rokhhlstr   sentpkts          r:   _process_packetzSndRcvHandler._process_packet3  s    9FIIKK
??:a=D'oo  
799W%% HOOK$;$;<<<|a''D)))B: . G

a


&w<< , JJ!OJJ,-)E 	""$$$ 	%|aD!!!KK1KK %
!!!$$$$$	% 	%% %r9   c           
          d| _         t                      | _         | j                             | j        | j        r	| j        sdn| j        d| j        | j        | j	        |d           dS )z8Function used to receive packets and check their hashretNFT)prnrQ   storeopened_socketrR   rT   started_callbackrO   )
r   AsyncSniffer_runr   rY   rX   rQ   rL   rR   rT   )ro   callbacks     r:   ra   zSndRcvHandler._sndrcv_rcvR  su     #~~$ MO$+ODD4<,L(% 	 		
 		
 		
 		
 		
r9   )Nr   NFr   FNFNTNFN)r   N)
r1   r2   r3   __doc__rz   r~   r   r_   r   ra   r8   r9   r:   r<   r<   j   s          !B= B= B= B=H2 2 2. . . .,$ ,$ ,$\% % %>
 
 
 
 
r9   r<   c                  B    t          | i |}|                                S )zScapy raw function to send a packet and receive its answer.
    WARNING: This is an internal function. Using sr/srp/sr1/srp is
    more appropriate in many cases.
    )r<   r~   )argskwargssndrcvers      r:   sndrcvr   d  s(     d-f--Hr9   Fc                    t          |t                    rt          j        |          }t          |t                    st          |          }|t          j        }d}
|| }n|sd}|rt                      nd}d}	 |rd}|D ]}|rat          j                    }|r5|t          |j                  z   |z
  }|dk    rt          j
        |           n|t          |j                  z
  }|                     |           ||                    |           |
dz  }
|rt          j        dd           t          j
        |           |dk     r|dz  }|n# t          $ r Y nw xY w	 t!          t"          |          j        t!          t"          |          _        nX# t&          $ r Y nLw xY w# 	 t!          t"          |          j        t!          t"          |          _        w # t&          $ r Y w w xY wxY w|rt)          d|
z             |S )z
    An internal function used by send/sendp to actually send the packets,
    implement the send logic...

    It will take care of iterating through the different packets
    )loadNr   rE   r   z
Sent %i packets.)
isinstancestrr   	raw_layerr   r   rG   r   r   floatr   r   r   r   r   rc   r)   r   r   r   rk   )sxrM   loopcountrN   realtimereturn_packetsr   kargsnsent_packetsrC   dt0ctsts                   r:   
__gen_sendr   n  sO   $ !S #N"""a 1II)	Av #1;:<<<tLA 	C " " 1B 1 5==02566 JrNNN 5==0q			+ ''***Q &HQ%%%
5!!!!axx	'  	(    	(,VQ(ADOO%% 	 	 	D		(,VQ(ADOO%% 	 	 	D	 ("Q&'''sa   >CE F( 
E!F(  E!!F( %2F 
F%$F%(G-*2GG-
G*'G-)G**G-c
           
          |	du }t          |pt          j                  }|	p  ||          dd|i|
}	t          |	| ||||||          }|r |	j                     |S )z(Internal function used by send and sendpNiface)rM   r   r   rN   r   r   r8   )r   r   r   r   close)r   _funcrM   r   r   r   rN   r   r   socketr   need_closingr~   s                r:   _sendr     s     T>L%-4:..E9|uuU||99%9599F%d$g"*>K K KG  Nr9   c                     d|v rt          j        dt                     |d= t          |           \  }t	          | fdfd|i|S )a  
    Send packets at layer 3

    This determines the interface (or L2 source to use) based on the routing
    table: conf.route / conf.route6

    :param x: the packets
    :param inter: time (in s) between two packets (default 0)
    :param loop: send packet indefinitely (default 0)
    :param count: number of packets to send (default None=1)
    :param verbose: verbose mode (default None=conf.verb)
    :param realtime: check that a packet was sent before sending the next one
    :param return_packets: return the sent packets
    :param socket: the socket to use (default is conf.L3socket(kargs))
    :param monitor: (not on linux) send in monitor mode
    :returns: None
    r   z'iface' has no effect on L3 I/O send(). For multicast/link-local see https://scapy.readthedocs.io/en/latest/usage.html#multicastc                 .    |                                S r|   )l3socket)r   ipv6s    r:   <lambda>zsend.<locals>.<lambda>  s    ennT** r9   )warningswarnSyntaxWarning_interface_selectionr   )r   r   r   r   s      @r:   r   r     s    , %N	
 	
 	

 'N&q))KE4	****   	  r9   c                 |    |)|'|%t           j                            |          d         }t          | d f||d|S )aq  
    Send packets at layer 2

    :param x: the packets
    :param inter: time (in s) between two packets (default 0)
    :param loop: send packet indefinitely (default 0)
    :param count: number of packets to send (default None=1)
    :param verbose: verbose mode (default None=conf.verb)
    :param realtime: check that a packet was sent before sending the next one
    :param return_packets: return the sent packets
    :param socket: the socket to use (default is conf.L3socket(kargs))
    :param iface: the interface to send the packets on
    :param monitor: (not on linux) send in monitor mode
    :returns: None
    Nr   c                 *    |                                  S r|   )l2socketr   s    r:   r   zsendp.<locals>.<lambda>	  s    enn&& r9   )r   r   )r   router   )r   r   
iface_hintr   r   s        r:   sendpr     sc    . }/FN
  ,,Q/	&& 	 
   r9   r   ppsmbpsr   r   r   
file_cacher   replay_argsparse_resultsc
                 8   |t           j        }t           j        j        dt	          |          z  g}
||
                    d|z             nK||
                    d|z             n0||
                    d|z             n|
                    d           |r%|r
J d            |
                    d|z             n|r|
                    d	           |r|
                    d
           ||
                    |           t                      }|
                    |           t          ||            d}t          t           j        j                  5  	 t          j        |
t          j        t          j                  }|                                \  }}|r&t          j        |                                           |	rt#          |||
          }nyt           j        dk    r&t          j        |                                           nB# t(          $ r t+          j        d           Y n"t,          $ r t/          j        |            w xY wddd           n# 1 swxY w Y   t.          j                            |          rt/          j        |           |S )a  Send packets at layer 2 using tcpreplay for performance

    :param pps:  packets per second
    :param mbps: MBits per second
    :param realtime: use packet's timestamp, bending time with real-time value
    :param loop: send the packet indefinitely (default 0)
    :param count: number of packets to send (default None=1)
    :param file_cache: cache packets in RAM instead of reading from
        disk at each iteration
    :param iface: output interface
    :param replay_args: List of additional tcpreplay args (List[str])
    :param parse_results: Return a dictionary of information
        outputted by tcpreplay (default=False)
    :returns: stdout, stderr, command used
    Nz
--intf1=%sz--pps=%fz	--mbps=%fz--multiplier=%fz
--topspeedz6Can't use loop and count at the same time in sendpfastz	--loop=%iz--loop=0z--preload-pcap)stdoutstderr   zInterrupted by user)r   r   prog	tcpreplayr
   r   extendr   r   r   
subprocessPopenPIPEcommunicater   r	   decode_parse_tcpreplay_resultrG   inforc   r   r   r   unlinkpathexists)r   r   r   r   r   r   r   r   r   r   argvfr~   cmdr   r   s                   r:   	sendpfastr     s   8 }
IU0C0C!CDD
J$%%%%		K$&''''		%01111L!!!  QQQQQQK%'((((	  J &$%%% K   AKKNNN
1aLLLG	!$)"5	6	6 2 2	2"4
*4/; ; ;C !__..NFF 5#FMMOO444 21&&$GGQ 111 ! 	8 	8 	8 !677777 	 	 	IaLLL	2 2 2 2 2 2 2 2 2 2 2 2 2 2 2" 
w~~a 
	!Ns7   I+HB
II,I.III #I c           
      ^   	 i }t          |                                           }t          |                                                              d          }t          t          t
          ft
          t
          t
          ft          t
          t          t          ft          ft          ft          ft          ft          ft          fd	}dddddd}d	}d
}	d}
t          |	t
          |i|                    d          D ]}|                                }|                                D ]\  }}|                    |          r|
                    fd|D                       }t          j
        ||          }t          |          D ]H\  }}|                    ||g          |         }|r$ ||                    |dz                       ||<   Id                    |          |d<   |dd         |d<   |S # t          $ r.}t          j        s t#          j        d|           i cY d}~S d}~ww xY w)a  
    Parse the output of tcpreplay and modify the results_dict to populate output information.  # noqa: E501
    Tested with tcpreplay v3.4.4
    Tested with tcpreplay v4.1.2
    :param stdout: stdout of tcpreplay subprocess call
    :param stderr: stderr of tcpreplay subprocess call
    :param argv: the command used in the subprocess call
    :return: dictionary containing the results
    
)	actualratedflows	attempted
successfulfailed	truncatedretried packets (enoretried packets (eag)packetsbytesr   )bpsr   r   )r   fpsflow_packetsnon_flow)retried_enobufs)retried_eagain)r   r   r   r   r   z([0-9]*\.[0-9]+|[0-9]+)z([0-9]+)z[^0-9]*c                      g | ]
}|         S r8   r8   )rB   r   r_typess     r:   rD   z+_parse_tcpreplay_result.<locals>.<listcomp>  s    )E)E)E'!*)E)E)Er9   rE    commandNr   r   zError parsing output: %s)r   lowerstripsplitintr   items
startswithrf   researchr   getgroupr   r   interactiver   error)stdout_bstderr_br   r~   r   r   elementsrP   	float_regint_regany_reglineelt_typesregexmatchesr   typnameparse_exceptionr  s                       @r:   r   r   ^  sP   +8$$**,,8$$**,,22488C'UE*5#s+&f%(F%(F

 

 3+A$8$7
 
 /		2LL&& 		F 		FD::<<D'~~// F FV??3'' F#LL)E)E)E)Ef)E)E)EFFE it44G"+F"3"3 F F3$yyse44Q7" F,/Ca!e0D0D,E,EGDMF !XXd^^	$SbSk
    	4oFFF							s   G0G4 4
H,>#H'!H,'H,packetr   c                 `   t          |                                                                           \  }}}d}|r5	 t          t          j        |           d}n# t          t          f$ r Y nw xY w	 t          |pt          j
                  }n# t          $ r d}Y nw xY w|pt          j
        |fS )zK
    Select the network interface according to the layer 3 destination
    FTN)next__iter__r   r   r   AF_INET6
ValueErrorOSErrorr   r   r   r   )r%  _iffsrcry   r   iffs         r:   r   r     s     ))**0022LD#qD
 	fos+++DDG$ 	 	 	D	D.DJ//   $*d""s#   A A.-A.2B BBc                     d|v rt          j        dt                     |d= t          |           \  }} |                    |          ||||          }t          || g|R i |}	|                                 |	S )z
    Send and receive packets at layer 3

    This determines the interface (or L2 source to use) based on the routing
    table: conf.route / conf.route6
    r   z~'iface' has no effect on L3 I/O sr(). For multicast/link-local see https://scapy.readthedocs.io/en/latest/usage.html#multicastpromiscfilterr   nofilter)r   r   r   r   r   r   r   )
r   r1  r2  r3  r   r   r   r   r   results
             r:   srr5    s     %N	
 	
 	

 'N&q))KE4th	 	 	A Aq)4)))5))FGGIIIMr9   c                      d|v rt          j        dt                     |d= t          | i |\  }}|r!t	          t
          |d         d                   S dS )z
    Send packets at layer 3 and return only the first answer

    This determines the interface (or L2 source to use) based on the routing
    table: conf.route / conf.route6
    r   z'iface' has no effect on L3 I/O sr1(). For multicast/link-local see https://scapy.readthedocs.io/en/latest/usage.html#multicastr   rE   N)r   r   r   r5  r)   r   r   r   rJ   ry   s       r:   sr1r8    sp     %N	
 	
 	

 'NFC
 'FCF1I&&&4r9   c                    |'|%t           j                            |          d         }t          |pt           j                  } |                                |||||          }	t          |	| g|R i |}
|	                                 |
S )z-
    Send and receive packets at layer 2
    Nr   )r1  r   r2  r3  type)r   r   r   r   r   r   r   )r   r1  r   r   r2  r3  r:  r   r   r   r4  s              r:   srpr;    s     }/
  ,,Q/%-4:..E &	F 	F 	FAAq)4)))5))FGGIIIMr9   c                      t          | i |\  }}t          |          dk    r!t          t          |d         d                   S dS )zN
    Send and receive packets at layer 2 and return only the first answer
    r   rE   N)r;  rj   r)   r   r7  s       r:   srp1r=    sF     $ %  FC
3xx!||FCF1I&&&4r9   c                 6    | d                                          S )NrE   summaryr   s    r:   r   r     s    AaDLLNN r9   c                 *    |                                  S r|   r?  rA  s    r:   r   r     s    		 r9   rE   c	                    d}d}t           j        }|t           j        }d}g }g }|t          d|z  d          }	 	 |dz  }|j        |j        g|         }||dk    rn|dz  }t          j                    }|dk    rt          dd            | |g|	R |ddd	|
}|t          |d                   t          |d                   z   z  }|t          |d                   z  }|dk    r|rt          |d                   dk    rd
t          |d                   z  }t          d|
                    |          z   d           |d         D ]D}t           | ||                               t          dt          |          z  d           E|dk    r|rt          |d                   dk    rdt          |d                   z  }t          d|                    |          z   d           |d         D ]D}t           | ||                               t          dt          |          z  d           E|dk    r>|s<|s:t          dt          t          t          |d d                             z             |dk    r:|d         rt          j        dd           |d         rt          j        dd           |r||d         z  }||d         z  }t          j                    }||z
  |k     rt          j        ||z   |z
             n# t"          $ r Y nw xY w|r4|dk    r.t          |                    d||d|z  |z  fz                       t'          |          t)          |          fS )Nr   r      TrE   z	send...r	  )end)rQ   rN   rO   zRECV %i:zfail %i:zrecv:%i  fail:%ir   r   z4
Sent %i packets, received %i packets. %3.1f%% hits.g      Y@)r   color_themerG   minevenoddr   	monotonicrk   rj   successfailtuplemapr   r   r   rc   normalr   r   )srfuncpktsr   prnfailrM   rQ   r   rN   r   r   r   r   r   r   parityrJ   unanscolrb   resmsgrcvrM  rE  s                           r:   	__sr_looprZ    s    	
A	A		B)F
CEa%i##*'	0aKF7BF#F+C A::
N$$E{{m----&X$XXw4XXRWXXCSVs3q6{{**ASVA{{s{s3q6{{Q 3s1v;;.dRZZ__,#6666q6 3 3C##cc#hh--(((#C.c22222{{w{3s1v;;?? 3s1v;;.dRWWS\\)s3333F 3 3D##ggdmm,,---#C.c22222{{C{7{(5S!W%%, ,     !||q6 &HQ%%%q6 &HQ%%%  s1vQ.""CU{U""
55=3.///O'	0
 F      j1q55biiOSTVWY^abYbefYfRgghhiiic??Ju----s   KL 
L L c                 .    t          t          | g|R i |S )z
    Send a packet at layer 3 in loop and print the answer each time
    srloop(pkts, [prn], [inter], [count], ...) --> None
    )rZ  r5  rR  r   r   s      r:   srloopr]  X  s$     R.......r9   c                 .    t          t          | g|R i |S )z
    Send a packet at layer 2 in loop and print the answer each time
    srloop(pkts, [prn], [inter], [count], ...) --> None
    )rZ  r;  r\  s      r:   srploopr_  e  s$     S$///////r9   c                   V    e Zd Zd Zd Zed             Zej        d             Zd ZdS )_FloodGeneratorc                 V    || _         || _        t                      | _        d| _        d S )Nr   )r\   
maxretriesr   	stopeventr   )ro   r\   rc  s      r:   rz   z_FloodGenerator.__init__u  s&     $r9   c              #      K   d}	 |dz  }d}| j         r|| j         k    rd S | j        D ]'}| j                                        r d S |dz  }|V  (| j        dk    r|| _        ])Nr   TrE   )rc  r\   rd  r   r   )ro   r   jrC   s       r:   r(  z_FloodGenerator.__iter__|  s      	!FAA 1#7#7]  >((** FFQ|q   	!r9   c                 @    t          t          | j                  j        S r|   r)   r   r\   r   r}   s    r:   r   z_FloodGenerator.sent_time  s     FDM**44r9   c                 D    |t          t          | j                  _        d S r|   rh  )ro   vals     r:   r   z_FloodGenerator.sent_time  s     14VT]##---r9   c                 8    | j                                          d S r|   )rd  rd   r}   s    r:   re   z_FloodGenerator.stop  s    r9   N)	r1   r2   r3   rz   r(  propertyr   setterre   r8   r9   r:   ra  ra  t  s{          ! ! !  5 5 X5 4 4 4    r9   ra  c           	      N    t          ||          }t          | ||||||          S )zsndrcv equivalent for flooding.)rM   rN   rO   rQ   rX   )ra  r   )rK   rp   rM   rc  rN   rO   rQ   	flood_gens           r:   sndrcvfloodrp    s<      Z00IYW	   r9   c                     d|v rt          j        dt                     |d= t          |           \  }} |                    |          ||||          }t          || g|R i |}	|                                 |	S )an  Flood and receive packets at layer 3

    This determines the interface (or L2 source to use) based on the routing
    table: conf.route / conf.route6

    :param prn:      function applied to packets received
    :param unique:   only consider packets whose print
    :param nofilter: put 1 to avoid use of BPF filters
    :param filter:   provide a BPF filter
    r   z'iface' has no effect on L3 I/O srflood(). For multicast/link-local see https://scapy.readthedocs.io/en/latest/usage.html#multicastr0  )r   r   r   r   r   rp  r   )
r   r1  r2  r   r3  r   r   r   r   r   s
             r:   srfloodrr    s    ( %N	
 	
 	

 'N&q))KE4th	 	 	A 	Aq)4)))5))AGGIIIHr9   c                 h   d|v rt          j        dt                     |d= t          |           \  }} |                    |          ||||          }t          || g|R i |\  }	}
|                                 t          |	          dk    r!t          t          |	d         d                   S dS )a  Flood and receive packets at layer 3 and return only the first answer

    This determines the interface (or L2 source to use) based on the routing
    table: conf.route / conf.route6

    :param prn:      function applied to packets received
    :param verbose:  set verbosity level
    :param nofilter: put 1 to avoid use of BPF filters
    :param filter:   provide a BPF filter
    :param iface:    listen answers only on the given interface
    r   z'iface' has no effect on L3 I/O sr1flood(). For multicast/link-local see https://scapy.readthedocs.io/en/latest/usage.html#multicastr1  r2  r3  r   r   rE   N)
r   r   r   r   r   rp  r   rj   r)   r   )r   r1  r2  r3  r   r   r   r   r   rJ   ry   s              r:   sr1floodru    s    ( %N	
 	
 	

 'N&q))KE4t	 	 	A A......FCGGIII
3xx!||FCF1I&&&4r9   c                    |'|%t           j                            |          d         }t          |pt           j                  } |                                ||||          }t          || g|R i |}	|                                 |	S )a<  Flood and receive packets at layer 2

    :param prn:      function applied to packets received
    :param unique:   only consider packets whose print
    :param nofilter: put 1 to avoid use of BPF filters
    :param filter:   provide a BPF filter
    :param iface:    listen answers only on the given interface
    Nr   r0  )r   r   r   r   r   rp  r   )
r   r1  r2  r   r   r3  r   r   r   r   s
             r:   srpfloodrw    s    & }/
  ,,Q/%-4:..EuxXXXAAq)4)))5))AGGIIIHr9   c                 6   t          |pt          j                  } |                                ||||          }t	          || g|R i |\  }}	|                                 t          |          dk    r!t          t          |d         d                   S dS )aO  Flood and receive packets at layer 2 and return only the first answer

    :param prn:      function applied to packets received
    :param verbose:  set verbosity level
    :param nofilter: put 1 to avoid use of BPF filters
    :param filter:   provide a BPF filter
    :param iface:    listen answers only on the given interface
    rt  r   rE   N)	r   r   r   r   rp  r   rj   r)   r   )
r   r1  r2  r   r3  r   r   r   rJ   ry   s
             r:   	srp1floodry    s    $ %-4:..E(RWXXXAA......FCGGIII
3xx!||FCF1I&&&4r9   c                   V    e Zd ZdZd Zd Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZd	 Zdd
Zd Z	dS )r   a  
    Sniff packets and return a list of packets.

    Args:
        count: number of packets to capture. 0 means infinity.
        store: whether to store sniffed packets or discard them
        prn: function to apply to each packet. If something is returned, it
             is displayed.
             --Ex: prn = lambda x: x.summary()
        session: a session = a flow decoder used to handle stream of packets.
                 --Ex: session=TCPSession
                 See below for more details.
        filter: BPF filter to apply.
        lfilter: Python function applied to each packet to determine if
                 further action may be done.
                 --Ex: lfilter = lambda x: x.haslayer(Padding)
        offline: PCAP file (or list of PCAP files) to read packets from,
                 instead of sniffing them
        quiet:   when set to True, the process stderr is discarded
                 (default: False).
        timeout: stop sniffing after a given time (default: None).
        L2socket: use the provided L2socket (default: use conf.L2listen).
        opened_socket: provide an object (or a list of objects) ready to use
                      .recv() on.
        stop_filter: Python function applied to each packet to determine if
                     we have to stop the capture after this packet.
                     --Ex: stop_filter = lambda x: x.haslayer(TCP)
        iface: interface or list of interfaces (default: None for sniffing
               on the default interface).
        monitor: use monitor mode. May not be available on all OS
        started_callback: called as soon as the sniffer starts sniffing
                          (default: None).

    The iface, offline and opened_socket parameters can be either an
    element, a list of elements, or a dict object mapping an element to a
    label (see examples below).

    For more information about the session argument, see
    https://scapy.rtfd.io/en/latest/usage.html#advanced-sniffing-sniffing-sessions

    Examples: synchronous
      >>> sniff(filter="arp")
      >>> sniff(filter="tcp",
      ...       session=IPSession,  # defragment on-the-flow
      ...       prn=lambda x: x.summary())
      >>> sniff(lfilter=lambda pkt: ARP in pkt)
      >>> sniff(iface="eth0", prn=Packet.summary)
      >>> sniff(iface=["eth0", "mon0"],
      ...       prn=lambda pkt: "%s: %s" % (pkt.sniffed_on,
      ...                                   pkt.summary()))
      >>> sniff(iface={"eth0": "Ethernet", "mon0": "Wifi"},
      ...       prn=lambda pkt: "%s: %s" % (pkt.sniffed_on,
      ...                                   pkt.summary()))

    Examples: asynchronous
      >>> t = AsyncSniffer(iface="enp0s3")
      >>> t.start()
      >>> time.sleep(1)
      >>> print("nice weather today")
      >>> t.stop()
    c                 Z    || _         || _        d| _        d | _        d | _        d | _        d S NF)r   r   r   threadr~   r   ro   r   r   s      r:   rz   zAsyncSniffer.__init__u  s2     	r9   c                 l    | fd}t          || j        | j        d          | _        d| j        _        d S )Nc                 `    	  | j         |i | d S # t          $ r}|| _        Y d }~d S d }~ww xY wr|   )r   r   r   )ro   r   r   rv   s       r:   
_run_catchz.AsyncSniffer._setup_thread.<locals>._run_catch  sV    $	4*6***** $ $ $!#$s    
-(-r   )r>   r   r   r#  T)r   r   r   r}  r`   )ro   r  s     r:   _setup_threadzAsyncSniffer._setup_thread  sS      	$ 	$ 	$ 	$ ;	
 
 
 "r9   r   TNFc                 4   !"#$ d _         d _        g }t          |t                    s|pt          } |            }i }|	t          |	t                    r-|                    d t          |	          D                        nLt          |	t                    r2|                    d |	                                D                        nd||	<   |N	                    d          #t          |t                    r|g}t          |t                    r<t          d |D                       r#|                    #fd|D                        nt          |t                    r5|                    #fd	|                                D                        nt          |t          t          t          f          r:t          |          }||#|n"t          t!          |d
dg#d                    <   n*||t          #|nt!          |d
dg#d                    <   |r|fd!t          |t                    r#|                    !fd|D                        ntt          |t                    r5|                    !fd|                                D                        n*|pt"          j        }||  !|          d!t&          |d<   t)          t+          |                    }|j        $t/          |dd          }t          $fd|D                       st1          d           d "|s*ddlm}  |d          d          "d|"<   " fd}| _        n fd}| _        	 |r
 |             d _        |t;          j                    |z   }d }|r j        r||t;          j                    z
  }|dk    rn $t	          |                                          |          }g }|D ]}|"u r n	 |                     |          }|D ]}|r ||          s|	                    |d           |_!         xj        dz  c_        |r|"                    |           |r ||          }|tG          |           |
r |
|          sd|cxk     r j        k    rn d _         n# tH          $ r? 	 |%                                 n# tL          $ r Y nw xY w|"                    |           Y tL          $ r~}d}	 |%                                 n# tL          $ r} d| z  }Y d } ~ nd } ~ ww xY wt1          d|d|d|z              |"                    |           t"          j'        dk    r Y d }~d }~ww xY w|D ]}||= tQ          |          dk    r"|v r|"=  |r j        n# tR          $ r |r Y nw xY wd _         |	|D ]}|%                                 n"r"%                                 t          |d            _*        d S )"NTr   c              3   *   K   | ]\  }}|d |z  fV  dS )zsocket%dNr8   )rB   r   r   s      r:   	<genexpr>z$AsyncSniffer._run.<locals>.<genexpr>  sC       % %1 
Q'% % % % % %r9   c              3   $   K   | ]\  }}||fV  d S r|   r8   )rB   r   labels      r:   r  z$AsyncSniffer._run.<locals>.<genexpr>  s>       % % 5 J% % % % % %r9   socket0r2  c              3   @   K   | ]}t          |t                    V  d S r|   )r   r   )rB   r  s     r:   r  z$AsyncSniffer._run.<locals>.<genexpr>  s,      @@
3,,@@@@@@r9   c           
   3   j   K   | ]-}t          |nt          |ddgd                    |fV  .d S N-w-Tr   fltgetfdquietr   r   )rB   fnamer  r  s     r:   r  z$AsyncSniffer._run.<locals>.<genexpr>  sz       %0 %0 $ '1 [EEE"& #"&"'	) ) )' ' & %0 %0 %0 %0 %0 %0r9   c           
   3   p   K   | ]0\  }}t          |nt          |ddgd                    |fV  1d S r  r  )rB   r  r  r  r  s      r:   r  z$AsyncSniffer._run.<locals>.<genexpr>  s~       %? %? +eU '1 [EEE"& #"&"'	) ) )' ' & %? %? %? %? %? %?r9   r  r  r  c                 J    p t          |                                           S r|   )r   l2listen)r   L2sockets    r:   r   z#AsyncSniffer._run.<locals>.<lambda>  s     XDq)9)9)B)B)D)D r9   c              3   N   K   | ]}  |          dt           |d |fV   dS r:  r   Nr8   r   )rB   ifname_RL2kargs     r:   r  z$AsyncSniffer._run.<locals>.<genexpr>  s`       % %  "TT&\\GyGG$GG% % % % % %r9   c              3   T   K   | ]"\  }}  |          dt           |d |fV  #dS r  r   )rB   r  iflabelr  r  s      r:   r  z$AsyncSniffer._run.<locals>.<genexpr>  sd       % % ( "TT&\\GyGG$GG% % % % % %r9   r  nonblocking_socketFc              3   .   K   | ]}|j         k    V  d S r|   )select)rB   sockselect_funcs     r:   r  z$AsyncSniffer._run.<locals>.<genexpr>  s*      HH$;$+-HHHHHHr9   zaWarning: inconsistent socket types ! The used select function will be the one of the first socket)
ObjectPipecontrol_socketc                  R    j         r r                     d            d_        d S r|  )r   r   continue_sniff)
close_pipero   s   r:   stop_cbz"AsyncSniffer._run.<locals>.stop_cb  s4    < *J *OOD)))&+###r9   c                      d _         d S r|  )r  r}   s   r:   r  z"AsyncSniffer._run.<locals>.stop_cb  s    &+###r9   rE   z It was closed.z close() failed with '%s'zSocket z failed with 'z'.r   Sniffedr8   )+r   r   r   r   r[   updater   dictr  r  r   allr   r   r   r   r   r   r   r   r'  iterr  getattrr	   scapy.automatonr  r  r  r   rK  keysr4   
sniffed_onr   rk   EOFErrorr   r   debug_dissectorrj   rc   r~   )%ro   r   r   offliner  r   lfilterr  rQ   r   rT   r   r   rR   rO   r  lstsniff_sockets_main_socketr  r  r  stoptimerw   socketsdead_socketsr   r   rC   r4  rv   rX  ex2r  r  r  r  s%   `   `  `       `                 @@@@r:   r   zAsyncSniffer._run  s   $ 
 '>22 	 /GgiiG$-.. 9$$ % % )- 8 8% % %     M400 9$$ % %$1$7$7$9$9% % %    
 09m,((8$$C'3'' $")'4(( (@@@@@@@( $$ %0 %0 %0 %0 %0 (/%0 %0 %0 0 0 0 0 GT** $$ %? %? %? %? %? /6mmoo%? %? %? ? ? ? ? Gfj$%?@@ $W--  gg*G"& #"&"'	) ) ); ;     j"{GGG"& #"&"'	) ) )    	; 1DDDDD%&& ;$$ % % % % % #(% % %    
 E4(( 	;$$ % % % % % ,1;;==% % %     +5: kdd5kk 2y 2 2,02 2 3 D//00")$\3GOOHHHH-HHHHH 	; : ; ; ; 
! 	#222222)D)*:;;J(8M*%, , , , , ,
 #DLL, , , , , #DLI	 #  """"&D ">++g5F <6D$7 <6&%(8(88F{{%+d=+=+=+?+?&@&@&II!  .! .!AJ)!"),,q//!( & &A& )wwqzz ) (+8+<+<Q+E+EAL JJ!OJJ$ . #

1" 2),Q#)#5$)&MMM + &A &%&%<%<%<%<$*%<%<%<%<%<6; 3 % &= $ ! ! !!GGIIII( ! ! ! D!$++A... $ ! ! !/DGGIIII( D D D"="CCCCCCCD=>QQCcI   %++A.../144! ! & 6 6A%a(=))Q..&-77)*5y   <6D$7 <6z ! 	 	 	  	  "  				 	!#y11s   2BV7 B3R87V7 8
VSV
S%"V$S%%V=V7  	V	VT! V!
T:+T50V5T::AV<V7 V/V7 7WWc                 r    |                                   | j        r| j                                         dS dS )z!Starts AsyncSniffer in async modeN)r  r}  rb   r}   s    r:   rb   zAsyncSniffer.startl  sD     	; 	 K	  	 r9   c                     | j         rR	 |                                  n# t          $ r t          d          w xY w|r|                                  | j        S dS t          d          )z'Stops AsyncSniffer if not in async modez+Unsupported (offline or unsupported socket)Nz#Not running ! (check .running attr))r   r  r   r   rf   r~   )ro   rf   s     r:   re   zAsyncSniffer.stops  s     < 	I!   %A    $		|#4!"GHHHs    8c                 T    | j         r | j         j        |i | | j        | j        d S r|   )r}  rf   r   r~  s      r:   rf   zAsyncSniffer.join  s>    ; 	.DKd-f--->%.  &%r9   )r   TNFNNNNNNNNNF)T)
r1   r2   r3   r   rz   r  r   rb   re   rf   r8   r9   r:   r   r   6  s        < <|  " " "$ "Z2 Z2 Z2 Z2x     I I I I"! ! ! ! !r9   r   c                  l    t                      } |j        | i | t          t          |j                  S r|   )r   r   r)   r   r~   )r   r   r   s      r:   sniffr    s6     nnGGL$!&!!!
GO,,,r9   c                 
   dD ]}||v rt          j        d|           ||= |fd}	 |	| d          \  }
}  |	|d          \  }}| |||
ii ||| <   |||<   fd|}n|fd}t          ||
| ||i|d	|S )
a  Forward traffic between interfaces if1 and if2, sniff and return
    the exchanged packets.

    :param if1: the interfaces to use (interface names or opened sockets).
    :param if2:
    :param xfrm12: a function to call when forwarding a packet from if1 to
        if2. If it returns True, the packet is forwarded as it. If it
        returns False or None, the packet is discarded. If it returns a
        packet, this packet is forwarded instead of the original packet
        one.
    :param xfrm21: same as xfrm12 for packets forwarded from if2 to if1.

    The other arguments are the same than for the function sniff(),
    except for offline, opened_socket and iface that are ignored.
    See help(sniff) for more.
    )r   r  r   z@Argument %s cannot be used in bridge_and_sniff() -- ignoring it.c                     t          | t                    r| d|z  fS |s/t          | pt          j                  } |                                 } ||           | fS )Nziface%dr   )r   r   r   r   r   r   )r   r   r  s      r:   _init_socketz&bridge_and_sniff.<locals>._init_socket  si    
 e[)) 	0)e+++ ,%e&9tz:: >>++8%(((%//r9   rE   r   Nc                    	 | j         pd         }n# t          $ r Y d S w xY w| j         v rv	  | j                  |           }t          |t                    r|sd S | }nE|}nB# t          $ r3 t          j        d|                                 | j         d           Y d S w xY w| }	 |                    |           d S # t          $ r3 t          j        d|                                 | j         d           Y d S w xY w)N zOException in transformation function for packet [%s] received on %s -- droppingT)exc_infoz)Cannot forward packet [%s] received on %s)	r  KeyErrorr   boolr   r   r	   r@  r   )rp   sendsock_newpktnewpktpeersxfrmss       r:   prn_sendz"bridge_and_sniff.<locals>.prn_send  sr   	S^1r2HH 	 	 	FF	>U""%/%/44 gt,, %"  FF$FF    #1KKMM3>D   
  F	NMM&!!!!! 	N 	N 	N K #s~N N N N N N N	Ns/    
!!A# #9B B &B= =9C:9C:c                 0     |             |           S r|   r8   )rp   prn_origr  s    r:   r   zbridge_and_sniff.<locals>.prn  s    HSMMM8C== r9   )r   r   )r   r	   r  )if1if2xfrm12xfrm21r   r  r   r   argr  sckt1sckt2r  r  r  r  s               @@@@r:   bridge_and_sniffr    sH   6 5  %<< !EFIK K Kc
 '0 0 0 0 c1%%JE3c1%%JE3%e$EEc
c
N N N N N N< {	! 	! 	! 	! 	! 	!
  !&sE37S ! !! ! !r9   c                  Z   d|v r|                     d          }n>d|v r.t          t          |                     d                    j        }nt          j        }t          d|z             dgfd}t          | |dd| t          dd         d         d	k    rd
ndfz             dS )z|Sniff packets and print them calling pkt.summary().
    This tries to replicate what text-wireshark (tshark) would look liker   r   zCapturing on '%s'r   c                     t          dd         |                                 fz             dxx         dz  cc<   d S )Nz%5d	%sr   rE   )rk   r@  )rp   r   s    r:   _cbztshark.<locals>._cb  s@    i1Q4//000	!	r9   F)r   r   z
%d packet%s capturedrE   r   r  N)r  r)   r   r   r   rk   r  )r   r   r   r  r   s       @r:   tsharkr    s     %		'""	E	!	![%))O"<"<==C
	

%&&& 
A    
 
c/////	
"ad1Q4!88CC%D
DEEEEEr9   )r   r   NNFF)r   r   NNNFFN)NNN)	NNFNr   FNNF)NNr   )r   NNFN)NNNN)NNNNN)NNNr   )fr   rg   	threadingr   r   r   r  r   r   r   r   scapy.compatr   
scapy.datar   scapy.configr   scapy.errorr	   scapy.interfacesr
   r   r   scapy.packetr   scapy.pton_ntopr   scapy.utilsr   r   r   r   r   r   scapy.plistr   r   r   r   r   r   scapy.base_classesr   r   scapy.sessionsr   scapy.supersocketr   r   typingr    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r   scapy.routescapyr-   _DOC_SNDRCV_PARAMS_GlobSessionTypeobjectr<   r   r   r   commandsregisterr   r   r   r  r  r   r   r   r   r5  r8  r;  r=  sr_funcrZ  r]  r_  ra  rp  rr  ru  rw  ry  r   r  r  r  r8   r9   r:   <module>r     s        # # # # # # # # 				 				        " " " " " "                                 
        % % % % % %3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3         
 F E E E E E E E E E * * * * * * * * ) ) ) ) ) ) 5 5 5 5 5 5 5 5                        0 / / / / / ' ' ' ' ' ':        2 n-~=> w
 w
 w
 w
 w
F w
 w
 w
t   #= = = =D    2 # # #L    B %)&*$%)!&4815$)J J JE?JUOJ J c]	J
 J J 01J $DI.J "J J J JZ6 6 6r# #U;KT;Q5R # # # #&    @   ,    0    T2s# . .G"-- +*++E. E. E. E.P 	/ 	/ 	/ 	0 	0 	0$ $ $ $ $f $ $ $R    ( 	" " " "J $ $ $ $N    6 	   8S! S! S! S! S!6 S! S! S!l
 - - - $  ! "^! ^! ^! ^!B F F F F Fr9   