Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/scapy/sendrecv.py: 13%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

735 statements  

1# SPDX-License-Identifier: GPL-2.0-only 

2# This file is part of Scapy 

3# See https://scapy.net/ for more information 

4# Copyright (C) Philippe Biondi <phil@secdev.org> 

5 

6""" 

7Functions to send and receive packets. 

8""" 

9 

10import itertools 

11from threading import Thread, Event 

12import os 

13import re 

14import socket 

15import subprocess 

16import time 

17 

18from scapy.compat import plain_str 

19from scapy.data import ETH_P_ALL 

20from scapy.config import conf 

21from scapy.error import warning 

22from scapy.interfaces import ( 

23 network_name, 

24 resolve_iface, 

25 NetworkInterface, 

26) 

27from scapy.packet import Packet 

28from scapy.pton_ntop import inet_pton 

29from scapy.utils import get_temp_file, tcpdump, wrpcap, \ 

30 ContextManagerSubprocess, PcapReader, EDecimal 

31from scapy.plist import ( 

32 PacketList, 

33 QueryAnswer, 

34 SndRcvList, 

35) 

36from scapy.error import log_runtime, log_interactive, \ 

37 Scapy_Exception, ScapyNotRunningException 

38from scapy.base_classes import Gen, SetGen, ScopedIP 

39from scapy.sessions import DefaultSession 

40from scapy.supersocket import SuperSocket, IterSocket 

41 

42# Typing imports 

43from typing import ( 

44 Any, 

45 Callable, 

46 Dict, 

47 Iterator, 

48 List, 

49 Optional, 

50 Tuple, 

51 Type, 

52 Union, 

53 cast 

54) 

55from scapy.interfaces import _GlobInterfaceType 

56from scapy.plist import _PacketIterable 

57 

58if conf.route is None: 

59 # unused import, only to initialize conf.route and conf.iface* 

60 import scapy.route # noqa: F401 

61 

62################# 

63# Debug class # 

64################# 

65 

66 

67class debug: 

68 recv = PacketList([], "Received") 

69 sent = PacketList([], "Sent") 

70 match = SndRcvList([], "Matched") 

71 crashed_on = None # type: Optional[Tuple[Type[Packet], bytes]] 

72 

73 

74#################### 

75# Send / Receive # 

76#################### 

77 

78_DOC_SNDRCV_PARAMS = """ 

79 :param pks: SuperSocket instance to send/receive packets 

80 :param pkt: the packet to send 

81 :param timeout: how much time to wait after the last packet has been sent 

82 :param inter: delay between two packets during sending 

83 :param verbose: set verbosity level 

84 :param chainCC: if True, KeyboardInterrupts will be forwarded 

85 :param retry: if positive, how many times to resend unanswered packets 

86 if negative, how many times to retry when no more packets 

87 are answered 

88 :param multi: whether to accept multiple answers for the same stimulus 

89 :param first: stop after receiving the first response of any sent packet 

90 :param rcv_pks: if set, will be used instead of pks to receive packets. 

91 packets will still be sent through pks 

92 :param prebuild: pre-build the packets before starting to send them. 

93 Automatically enabled when a generator is passed as the packet 

94 :param _flood: 

95 :param threaded: if True, packets are sent in a thread and received in another. 

96 Defaults to True. 

97 :param session: a flow decoder used to handle stream of packets 

98 :param chainEX: if True, exceptions during send will be forwarded 

99 :param stop_filter: Python function applied to each packet to determine if 

100 we have to stop the capture after this packet. 

101 """ 

102 

103 

104_GlobSessionType = Union[Type[DefaultSession], DefaultSession] 

105 

106 

107class SndRcvHandler(object): 

108 """ 

109 Util to send/receive packets, used by sr*(). 

110 Do not use directly. 

111 

112 This matches the requests and answers. 

113 

114 Notes:: 

115 - threaded: if you're planning to send/receive many packets, it's likely 

116 a good idea to use threaded mode. 

117 - DEVS: store the outgoing timestamp right BEFORE sending the packet 

118 to avoid races that could result in negative latency. We aren't Stadia 

119 """ 

120 def __init__(self, 

121 pks, # type: SuperSocket 

122 pkt, # type: _PacketIterable 

123 timeout=None, # type: Optional[int] 

124 inter=0, # type: int 

125 verbose=None, # type: Optional[int] 

126 chainCC=False, # type: bool 

127 retry=0, # type: int 

128 multi=False, # type: bool 

129 first=False, # type: bool 

130 rcv_pks=None, # type: Optional[SuperSocket] 

131 prebuild=False, # type: bool 

132 _flood=None, # type: Optional[_FloodGenerator] 

133 threaded=True, # type: bool 

134 session=None, # type: Optional[_GlobSessionType] 

135 chainEX=False, # type: bool 

136 stop_filter=None, # type: Optional[Callable[[Packet], bool]] 

137 **send_kwargs, # type: Any 

138 ): 

139 # type: (...) -> None 

140 # Instantiate all arguments 

141 if verbose is None: 

142 verbose = conf.verb 

143 if conf.debug_match: 

144 debug.recv = PacketList([], "Received") 

145 debug.sent = PacketList([], "Sent") 

146 debug.match = SndRcvList([], "Matched") 

147 self.nbrecv = 0 

148 self.ans = [] # type: List[QueryAnswer] 

149 self.pks = pks 

150 self.rcv_pks = rcv_pks or pks 

151 self.inter = inter 

152 self.verbose = verbose 

153 self.chainCC = chainCC 

154 self.multi = multi 

155 self.timeout = timeout 

156 self.first = first 

157 self.session = session 

158 self.chainEX = chainEX 

159 self.stop_filter = stop_filter 

160 self._send_done = False 

161 self.notans = 0 

162 self.noans = 0 

163 self._flood = _flood 

164 self.threaded = threaded 

165 self.breakout = Event() 

166 self.send_kwargs = send_kwargs 

167 # Instantiate packet holders 

168 if prebuild and not self._flood: 

169 self.tobesent = list(pkt) # type: _PacketIterable 

170 else: 

171 self.tobesent = pkt 

172 

173 if retry < 0: 

174 autostop = retry = -retry 

175 else: 

176 autostop = 0 

177 

178 if timeout is not None and timeout < 0: 

179 self.timeout = None 

180 

181 while retry >= 0: 

182 self.breakout.clear() 

183 self.hsent = {} # type: Dict[bytes, List[Packet]] 

184 

185 if threaded or self._flood: 

186 # Send packets in thread. 

187 snd_thread = Thread( 

188 target=self._sndrcv_snd 

189 ) 

190 snd_thread.daemon = True 

191 

192 # Start routine with callback 

193 interrupted = None 

194 try: 

195 self._sndrcv_rcv(snd_thread.start) 

196 except KeyboardInterrupt as ex: 

197 interrupted = ex 

198 

199 self.breakout.set() 

200 

201 # Ended. Let's close gracefully 

202 if self._flood: 

203 # Flood: stop send thread 

204 self._flood.stop() 

205 snd_thread.join() 

206 

207 if interrupted and self.chainCC: 

208 raise interrupted 

209 else: 

210 # Send packets, then receive. 

211 try: 

212 self._sndrcv_rcv(self._sndrcv_snd) 

213 except KeyboardInterrupt: 

214 if self.chainCC: 

215 raise 

216 

217 if multi: 

218 remain = [ 

219 p for p in itertools.chain(*self.hsent.values()) 

220 if not hasattr(p, '_answered') 

221 ] 

222 else: 

223 remain = list(itertools.chain(*self.hsent.values())) 

224 

225 if autostop and len(remain) > 0 and \ 

226 len(remain) != len(self.tobesent): 

227 retry = autostop 

228 

229 self.tobesent = remain 

230 if len(self.tobesent) == 0: 

231 break 

232 retry -= 1 

233 

234 if conf.debug_match: 

235 debug.sent = PacketList(remain[:], "Sent") 

236 debug.match = SndRcvList(self.ans[:]) 

237 

238 # Clean the ans list to delete the field _answered 

239 if multi: 

240 for snd, _ in self.ans: 

241 if hasattr(snd, '_answered'): 

242 del snd._answered 

243 

244 if verbose: 

245 print( 

246 "\nReceived %i packets, got %i answers, " 

247 "remaining %i packets" % ( 

248 self.nbrecv + len(self.ans), len(self.ans), 

249 max(0, self.notans - self.noans) 

250 ) 

251 ) 

252 

253 self.ans_result = SndRcvList(self.ans) 

254 self.unans_result = PacketList(remain, "Unanswered") 

255 

256 def results(self): 

257 # type: () -> Tuple[SndRcvList, PacketList] 

258 return self.ans_result, self.unans_result 

259 

260 def _stop_sniffer_if_done(self) -> None: 

261 """Close the sniffer if all expected answers have been received""" 

262 if ( 

263 self._send_done and self.noans >= self.notans and not self.multi or 

264 self.first and self.noans 

265 ): 

266 if self.sniffer and self.sniffer.running: 

267 self.sniffer.stop(join=False) 

268 

269 def _sndrcv_snd(self): 

270 # type: () -> None 

271 """Function used in the sending thread of sndrcv()""" 

272 i = 0 

273 p = None 

274 try: 

275 if self.verbose: 

276 os.write(1, b"Begin emission\n") 

277 for p in self.tobesent: 

278 # Populate the dictionary of _sndrcv_rcv 

279 # _sndrcv_rcv won't miss the answer of a packet that 

280 # has not been sent 

281 self.hsent.setdefault(p.hashret(), []).append(p) 

282 # Send packet 

283 self.pks.send(p, **self.send_kwargs) 

284 time.sleep(self.inter) 

285 if self.breakout.is_set(): 

286 break 

287 i += 1 

288 if self.verbose: 

289 os.write(1, b"\nFinished sending %i packets\n" % i) 

290 except SystemExit: 

291 pass 

292 except Exception: 

293 if self.chainEX: 

294 raise 

295 else: 

296 log_runtime.exception("--- Error sending packets") 

297 finally: 

298 try: 

299 cast(Packet, self.tobesent).sent_time = \ 

300 cast(Packet, p).sent_time 

301 except AttributeError: 

302 pass 

303 if self._flood: 

304 self.notans = self._flood.iterlen 

305 elif not self._send_done: 

306 self.notans = i 

307 self._send_done = True 

308 self._stop_sniffer_if_done() 

309 # In threaded mode, timeout 

310 if self.threaded and self.timeout is not None and not self.breakout.is_set(): 

311 self.breakout.wait(timeout=self.timeout) 

312 if self.sniffer and self.sniffer.running: 

313 self.sniffer.stop() 

314 

315 def _process_packet(self, r): 

316 # type: (Packet) -> None 

317 """Internal function used to process each packet.""" 

318 if r is None: 

319 return 

320 ok = False 

321 h = r.hashret() 

322 if h in self.hsent: 

323 hlst = self.hsent[h] 

324 for i, sentpkt in enumerate(hlst): 

325 if r.answers(sentpkt): 

326 self.ans.append(QueryAnswer(sentpkt, r)) 

327 if self.verbose > 1: 

328 os.write(1, b"*") 

329 ok = True 

330 if not self.multi: 

331 del hlst[i] 

332 self.noans += 1 

333 else: 

334 if not hasattr(sentpkt, '_answered'): 

335 self.noans += 1 

336 sentpkt._answered = 1 

337 break 

338 self._stop_sniffer_if_done() 

339 if not ok: 

340 if self.verbose > 1: 

341 os.write(1, b".") 

342 self.nbrecv += 1 

343 if conf.debug_match: 

344 debug.recv.append(r) 

345 

346 def _sndrcv_rcv(self, callback): 

347 # type: (Callable[[], None]) -> None 

348 """Function used to receive packets and check their hashret""" 

349 # This is blocking. 

350 self.sniffer = None # type: Optional[AsyncSniffer] 

351 self.sniffer = AsyncSniffer() 

352 self.sniffer._run( 

353 prn=self._process_packet, 

354 timeout=None if self.threaded and not self._flood else self.timeout, 

355 store=False, 

356 opened_socket=self.rcv_pks, 

357 session=self.session, 

358 stop_filter=self.stop_filter, 

359 started_callback=callback, 

360 chainCC=True, 

361 ) 

362 

363 

364def sndrcv(*args, **kwargs): 

365 # type: (*Any, **Any) -> Tuple[SndRcvList, PacketList] 

366 """Scapy raw function to send a packet and receive its answer. 

367 WARNING: This is an internal function. Using sr/srp/sr1/srp is 

368 more appropriate in many cases. 

369 """ 

370 sndrcver = SndRcvHandler(*args, **kwargs) 

371 return sndrcver.results() 

372 

373 

374def __gen_send(s, # type: SuperSocket 

375 x, # type: _PacketIterable 

376 inter=0, # type: int 

377 loop=0, # type: int 

378 count=None, # type: Optional[int] 

379 verbose=None, # type: Optional[int] 

380 realtime=False, # type: bool 

381 return_packets=False, # type: bool 

382 *args, # type: Any 

383 **kargs # type: Any 

384 ): 

385 # type: (...) -> Optional[PacketList] 

386 """ 

387 An internal function used by send/sendp to actually send the packets, 

388 implement the send logic... 

389 

390 It will take care of iterating through the different packets 

391 """ 

392 if isinstance(x, str): 

393 x = conf.raw_layer(load=x) 

394 if not isinstance(x, Gen): 

395 x = SetGen(x) 

396 if verbose is None: 

397 verbose = conf.verb 

398 n = 0 

399 if count is not None: 

400 loop = -count 

401 elif not loop: 

402 loop = -1 

403 sent_packets = PacketList() if return_packets else None 

404 p = None 

405 try: 

406 while loop: 

407 dt0 = None 

408 for p in x: 

409 if realtime: 

410 ct = time.time() 

411 if dt0: 

412 st = dt0 + float(p.time) - ct 

413 if st > 0: 

414 time.sleep(st) 

415 else: 

416 dt0 = ct - float(p.time) 

417 s.send(p) 

418 if sent_packets is not None: 

419 sent_packets.append(p) 

420 n += 1 

421 if verbose: 

422 os.write(1, b".") 

423 time.sleep(inter) 

424 if loop < 0: 

425 loop += 1 

426 except KeyboardInterrupt: 

427 pass 

428 finally: 

429 try: 

430 cast(Packet, x).sent_time = cast(Packet, p).sent_time 

431 except AttributeError: 

432 pass 

433 if verbose: 

434 print("\nSent %i packets." % n) 

435 return sent_packets 

436 

437 

438def _send(x, # type: _PacketIterable 

439 _func, # type: Callable[[NetworkInterface], Type[SuperSocket]] 

440 inter=0, # type: int 

441 loop=0, # type: int 

442 iface=None, # type: Optional[_GlobInterfaceType] 

443 count=None, # type: Optional[int] 

444 verbose=None, # type: Optional[int] 

445 realtime=False, # type: bool 

446 return_packets=False, # type: bool 

447 socket=None, # type: Optional[SuperSocket] 

448 **kargs # type: Any 

449 ): 

450 # type: (...) -> Optional[PacketList] 

451 """Internal function used by send and sendp""" 

452 need_closing = socket is None 

453 iface = resolve_iface(iface or conf.iface) 

454 socket = socket or _func(iface)(iface=iface, **kargs) 

455 results = __gen_send(socket, x, inter=inter, loop=loop, 

456 count=count, verbose=verbose, 

457 realtime=realtime, return_packets=return_packets) 

458 if need_closing: 

459 socket.close() 

460 return results 

461 

462 

463@conf.commands.register 

464def send(x, # type: _PacketIterable 

465 **kargs # type: Any 

466 ): 

467 # type: (...) -> Optional[PacketList] 

468 """ 

469 Send packets at layer 3 

470 

471 This determines the interface (or L2 source to use) based on the routing 

472 table: conf.route / conf.route6 

473 

474 :param x: the packets 

475 :param inter: time (in s) between two packets (default 0) 

476 :param loop: send packet indefinitely (default 0) 

477 :param count: number of packets to send (default None=1) 

478 :param verbose: verbose mode (default None=conf.verb) 

479 :param realtime: check that a packet was sent before sending the next one 

480 :param return_packets: return the sent packets 

481 :param socket: the socket to use (default is conf.L3socket(kargs)) 

482 :param monitor: (not on linux) send in monitor mode 

483 :returns: None 

484 """ 

485 iface, ipv6 = _interface_selection(x, kargs.pop("iface", None)) 

486 return _send( 

487 x, 

488 lambda iface: iface.l3socket(ipv6), 

489 iface=iface, 

490 **kargs 

491 ) 

492 

493 

494@conf.commands.register 

495def sendp(x, # type: _PacketIterable 

496 iface=None, # type: Optional[_GlobInterfaceType] 

497 iface_hint=None, # type: Optional[str] 

498 socket=None, # type: Optional[SuperSocket] 

499 **kargs # type: Any 

500 ): 

501 # type: (...) -> Optional[PacketList] 

502 """ 

503 Send packets at layer 2 

504 

505 :param x: the packets 

506 :param inter: time (in s) between two packets (default 0) 

507 :param loop: send packet indefinitely (default 0) 

508 :param count: number of packets to send (default None=1) 

509 :param verbose: verbose mode (default None=conf.verb) 

510 :param realtime: check that a packet was sent before sending the next one 

511 :param return_packets: return the sent packets 

512 :param socket: the socket to use (default is conf.L3socket(kargs)) 

513 :param iface: the interface to send the packets on 

514 :param monitor: (not on linux) send in monitor mode 

515 :returns: None 

516 """ 

517 if iface is None and iface_hint is not None and socket is None: 

518 iface = conf.route.route(iface_hint)[0] 

519 return _send( 

520 x, 

521 lambda iface: iface.l2socket(), 

522 iface=iface, 

523 socket=socket, 

524 **kargs 

525 ) 

526 

527 

528@conf.commands.register 

529def sendpfast(x: _PacketIterable, 

530 pps: Optional[float] = None, 

531 mbps: Optional[float] = None, 

532 realtime: bool = False, 

533 count: Optional[int] = None, 

534 loop: int = 0, 

535 file_cache: bool = False, 

536 iface: Optional[_GlobInterfaceType] = None, 

537 replay_args: Optional[List[str]] = None, 

538 parse_results: bool = False, 

539 ): 

540 # type: (...) -> Optional[Dict[str, Any]] 

541 """Send packets at layer 2 using tcpreplay for performance 

542 

543 :param pps: packets per second 

544 :param mbps: MBits per second 

545 :param realtime: use packet's timestamp, bending time with real-time value 

546 :param loop: send the packet indefinitely (default 0) 

547 :param count: number of packets to send (default None=1) 

548 :param file_cache: cache packets in RAM instead of reading from 

549 disk at each iteration 

550 :param iface: output interface 

551 :param replay_args: List of additional tcpreplay args (List[str]) 

552 :param parse_results: Return a dictionary of information 

553 outputted by tcpreplay (default=False) 

554 :returns: stdout, stderr, command used 

555 """ 

556 if iface is None: 

557 iface = conf.iface 

558 argv = [conf.prog.tcpreplay, "--intf1=%s" % network_name(iface)] 

559 if pps is not None: 

560 argv.append("--pps=%f" % pps) 

561 elif mbps is not None: 

562 argv.append("--mbps=%f" % mbps) 

563 elif realtime is not None: 

564 argv.append("--multiplier=%f" % realtime) 

565 else: 

566 argv.append("--topspeed") 

567 

568 if count: 

569 assert not loop, "Can't use loop and count at the same time in sendpfast" 

570 argv.append("--loop=%i" % count) 

571 elif loop: 

572 argv.append("--loop=0") 

573 if file_cache: 

574 argv.append("--preload-pcap") 

575 

576 # Check for any additional args we didn't cover. 

577 if replay_args is not None: 

578 argv.extend(replay_args) 

579 

580 f = get_temp_file() 

581 argv.append(f) 

582 wrpcap(f, x) 

583 results = None 

584 cmd = None 

585 with ContextManagerSubprocess(conf.prog.tcpreplay): 

586 try: 

587 cmd = subprocess.Popen(argv, stdout=subprocess.PIPE, 

588 stderr=subprocess.PIPE) 

589 cmd.wait() 

590 except KeyboardInterrupt: 

591 if cmd: 

592 cmd.terminate() 

593 log_interactive.info("Interrupted by user") 

594 except Exception: 

595 os.unlink(f) 

596 raise 

597 finally: 

598 if cmd is not None: 

599 stdout, stderr = cmd.communicate() 

600 if stderr: 

601 log_runtime.warning(stderr.decode()) 

602 if parse_results: 

603 results = _parse_tcpreplay_result(stdout, stderr, argv) 

604 elif conf.verb > 2: 

605 log_runtime.info(stdout.decode()) 

606 if os.path.exists(f): 

607 os.unlink(f) 

608 return results 

609 

610 

611def _parse_tcpreplay_result(stdout_b, stderr_b, argv): 

612 # type: (bytes, bytes, List[str]) -> Dict[str, Any] 

613 """ 

614 Parse the output of tcpreplay and modify the results_dict to populate output information. # noqa: E501 

615 Tested with tcpreplay v3.4.4 

616 Tested with tcpreplay v4.1.2 

617 :param stdout: stdout of tcpreplay subprocess call 

618 :param stderr: stderr of tcpreplay subprocess call 

619 :param argv: the command used in the subprocess call 

620 :return: dictionary containing the results 

621 """ 

622 try: 

623 results = {} 

624 stdout = plain_str(stdout_b).lower() 

625 stderr = plain_str(stderr_b).strip().split("\n") 

626 elements = { 

627 "actual": (int, int, float), 

628 "rated": (float, float, float), 

629 "flows": (int, float, int, int), 

630 "attempted": (int,), 

631 "successful": (int,), 

632 "failed": (int,), 

633 "truncated": (int,), 

634 "retried packets (eno": (int,), 

635 "retried packets (eag": (int,), 

636 } 

637 multi = { 

638 "actual": ("packets", "bytes", "time"), 

639 "rated": ("bps", "mbps", "pps"), 

640 "flows": ("flows", "fps", "flow_packets", "non_flow"), 

641 "retried packets (eno": ("retried_enobufs",), 

642 "retried packets (eag": ("retried_eagain",), 

643 } 

644 float_reg = r"([0-9]*\.[0-9]+|[0-9]+)" 

645 int_reg = r"([0-9]+)" 

646 any_reg = r"[^0-9]*" 

647 r_types = {int: int_reg, float: float_reg} 

648 for line in stdout.split("\n"): 

649 line = line.strip() 

650 for elt, _types in elements.items(): 

651 if line.startswith(elt): 

652 regex = any_reg.join([r_types[x] for x in _types]) 

653 matches = re.search(regex, line) 

654 for i, typ in enumerate(_types): 

655 name = multi.get(elt, [elt])[i] 

656 if matches: 

657 results[name] = typ(matches.group(i + 1)) 

658 results["command"] = " ".join(argv) 

659 results["warnings"] = stderr[:-1] 

660 return results 

661 except Exception as parse_exception: 

662 if not conf.interactive: 

663 raise 

664 log_runtime.error("Error parsing output: %s", parse_exception) 

665 return {} 

666 

667 

668def _interface_selection( 

669 packet: _PacketIterable, 

670 iface: Optional[str] = None, 

671) -> Tuple[NetworkInterface, bool]: 

672 """ 

673 Select the network interface according to the layer 3 destination 

674 """ 

675 if iface is not None: 

676 try: 

677 packet.dst = ScopedIP(packet.dst, scope=iface) # type: ignore 

678 except AttributeError: 

679 raise AttributeError("Cannot use iface= with this packet type.") 

680 _iff, src, _ = next(packet.__iter__()).route() 

681 ipv6 = False 

682 if src: 

683 try: 

684 inet_pton(socket.AF_INET6, src) 

685 ipv6 = True 

686 except (ValueError, OSError): 

687 pass 

688 try: 

689 iff = resolve_iface(_iff or conf.iface) 

690 except AttributeError: 

691 iff = None 

692 return iff or conf.iface, ipv6 

693 

694 

695@conf.commands.register 

696def sr(x, # type: _PacketIterable 

697 promisc=None, # type: Optional[bool] 

698 filter=None, # type: Optional[str] 

699 nofilter=0, # type: int 

700 *args, # type: Any 

701 **kargs # type: Any 

702 ): 

703 # type: (...) -> Tuple[SndRcvList, PacketList] 

704 """ 

705 Send and receive packets at layer 3 

706 

707 This determines the interface (or L2 source to use) based on the routing 

708 table: conf.route / conf.route6 

709 """ 

710 iface, ipv6 = _interface_selection(x, kargs.pop("iface", None)) 

711 s = iface.l3socket(ipv6)( 

712 promisc=promisc, filter=filter, 

713 iface=iface, nofilter=nofilter, 

714 ) 

715 result = sndrcv(s, x, *args, **kargs) 

716 s.close() 

717 return result 

718 

719 

720@conf.commands.register 

721def sr1(*args, **kargs): 

722 # type: (*Any, **Any) -> Optional[Packet] 

723 """ 

724 Send packets at layer 3 and return only the first answer 

725 

726 This determines the interface (or L2 source to use) based on the routing 

727 table: conf.route / conf.route6 

728 """ 

729 ans, _ = sr(*args, **kargs) 

730 if ans: 

731 return cast(Packet, ans[0][1]) 

732 return None 

733 

734 

735@conf.commands.register 

736def srp(x, # type: _PacketIterable 

737 promisc=None, # type: Optional[bool] 

738 iface=None, # type: Optional[_GlobInterfaceType] 

739 iface_hint=None, # type: Optional[str] 

740 filter=None, # type: Optional[str] 

741 nofilter=0, # type: int 

742 type=ETH_P_ALL, # type: int 

743 *args, # type: Any 

744 **kargs # type: Any 

745 ): 

746 # type: (...) -> Tuple[SndRcvList, PacketList] 

747 """ 

748 Send and receive packets at layer 2 

749 """ 

750 if iface is None and iface_hint is not None: 

751 iface = conf.route.route(iface_hint)[0] 

752 iface = resolve_iface(iface or conf.iface) 

753 s = iface.l2socket()(promisc=promisc, iface=iface, 

754 filter=filter, nofilter=nofilter, type=type) 

755 result = sndrcv(s, x, *args, **kargs) 

756 s.close() 

757 return result 

758 

759 

760@conf.commands.register 

761def srp1(*args, **kargs): 

762 # type: (*Any, **Any) -> Optional[Packet] 

763 """ 

764 Send and receive packets at layer 2 and return only the first answer 

765 """ 

766 ans, _ = srp(*args, **kargs) 

767 if len(ans) > 0: 

768 return cast(Packet, ans[0][1]) 

769 return None 

770 

771 

772# Append doc 

773for sr_func in [srp, srp1, sr, sr1]: 

774 if sr_func.__doc__ is not None: 

775 sr_func.__doc__ += _DOC_SNDRCV_PARAMS 

776 

777 

778# SEND/RECV LOOP METHODS 

779 

780 

781def __sr_loop(srfunc, # type: Callable[..., Tuple[SndRcvList, PacketList]] 

782 pkts, # type: _PacketIterable 

783 prn=lambda x: x[1].summary(), # type: Optional[Callable[[QueryAnswer], Any]] # noqa: E501 

784 prnfail=lambda x: x.summary(), # type: Optional[Callable[[Packet], Any]] 

785 inter=1, # type: int 

786 timeout=None, # type: Optional[int] 

787 count=None, # type: Optional[int] 

788 verbose=None, # type: Optional[int] 

789 store=1, # type: int 

790 *args, # type: Any 

791 **kargs # type: Any 

792 ): 

793 # type: (...) -> Tuple[SndRcvList, PacketList] 

794 n = 0 

795 r = 0 

796 ct = conf.color_theme 

797 if verbose is None: 

798 verbose = conf.verb 

799 parity = 0 

800 ans = [] # type: List[QueryAnswer] 

801 unans = [] # type: List[Packet] 

802 if timeout is None: 

803 timeout = min(2 * inter, 5) 

804 try: 

805 while True: 

806 parity ^= 1 

807 col = [ct.even, ct.odd][parity] 

808 if count is not None: 

809 if count == 0: 

810 break 

811 count -= 1 

812 start = time.monotonic() 

813 if verbose > 1: 

814 print("\rsend...\r", end=' ') 

815 res = srfunc(pkts, timeout=timeout, verbose=0, chainCC=True, *args, **kargs) # noqa: E501 

816 n += len(res[0]) + len(res[1]) 

817 r += len(res[0]) 

818 if verbose > 1 and prn and len(res[0]) > 0: 

819 msg = "RECV %i:" % len(res[0]) 

820 print("\r" + ct.success(msg), end=' ') 

821 for rcv in res[0]: 

822 print(col(prn(rcv))) 

823 print(" " * len(msg), end=' ') 

824 if verbose > 1 and prnfail and len(res[1]) > 0: 

825 msg = "fail %i:" % len(res[1]) 

826 print("\r" + ct.fail(msg), end=' ') 

827 for fail in res[1]: 

828 print(col(prnfail(fail))) 

829 print(" " * len(msg), end=' ') 

830 if verbose > 1 and not (prn or prnfail): 

831 print("recv:%i fail:%i" % tuple( 

832 map(len, res[:2]) # type: ignore 

833 )) 

834 if verbose == 1: 

835 if res[0]: 

836 os.write(1, b"*") 

837 if res[1]: 

838 os.write(1, b".") 

839 if store: 

840 ans += res[0] 

841 unans += res[1] 

842 end = time.monotonic() 

843 if end - start < inter: 

844 time.sleep(inter + start - end) 

845 except KeyboardInterrupt: 

846 pass 

847 

848 if verbose and n > 0: 

849 print(ct.normal("\nSent %i packets, received %i packets. %3.1f%% hits." % (n, r, 100.0 * r / n))) # noqa: E501 

850 return SndRcvList(ans), PacketList(unans) 

851 

852 

853@conf.commands.register 

854def srloop(pkts, # type: _PacketIterable 

855 *args, # type: Any 

856 **kargs # type: Any 

857 ): 

858 # type: (...) -> Tuple[SndRcvList, PacketList] 

859 """ 

860 Send a packet at layer 3 in loop and print the answer each time 

861 srloop(pkts, [prn], [inter], [count], ...) --> None 

862 """ 

863 return __sr_loop(sr, pkts, *args, **kargs) 

864 

865 

866@conf.commands.register 

867def srploop(pkts, # type: _PacketIterable 

868 *args, # type: Any 

869 **kargs # type: Any 

870 ): 

871 # type: (...) -> Tuple[SndRcvList, PacketList] 

872 """ 

873 Send a packet at layer 2 in loop and print the answer each time 

874 srloop(pkts, [prn], [inter], [count], ...) --> None 

875 """ 

876 return __sr_loop(srp, pkts, *args, **kargs) 

877 

878# SEND/RECV FLOOD METHODS 

879 

880 

881class _FloodGenerator(object): 

882 def __init__(self, tobesent, maxretries): 

883 # type: (_PacketIterable, Optional[int]) -> None 

884 self.tobesent = tobesent 

885 self.maxretries = maxretries 

886 self.stopevent = Event() 

887 self.iterlen = 0 

888 

889 def __iter__(self): 

890 # type: () -> Iterator[Packet] 

891 i = 0 

892 while True: 

893 i += 1 

894 j = 0 

895 if self.maxretries and i >= self.maxretries: 

896 return 

897 for p in self.tobesent: 

898 if self.stopevent.is_set(): 

899 return 

900 j += 1 

901 yield p 

902 if self.iterlen == 0: 

903 self.iterlen = j 

904 

905 @property 

906 def sent_time(self): 

907 # type: () -> Union[EDecimal, float, None] 

908 return cast(Packet, self.tobesent).sent_time 

909 

910 @sent_time.setter 

911 def sent_time(self, val): 

912 # type: (Union[EDecimal, float, None]) -> None 

913 cast(Packet, self.tobesent).sent_time = val 

914 

915 def stop(self): 

916 # type: () -> None 

917 self.stopevent.set() 

918 

919 

920def sndrcvflood(pks, # type: SuperSocket 

921 pkt, # type: _PacketIterable 

922 inter=0, # type: int 

923 maxretries=None, # type: Optional[int] 

924 verbose=None, # type: Optional[int] 

925 chainCC=False, # type: bool 

926 timeout=None # type: Optional[int] 

927 ): 

928 # type: (...) -> Tuple[SndRcvList, PacketList] 

929 """sndrcv equivalent for flooding.""" 

930 

931 flood_gen = _FloodGenerator(pkt, maxretries) 

932 return sndrcv( 

933 pks, flood_gen, 

934 inter=inter, verbose=verbose, 

935 chainCC=chainCC, timeout=timeout, 

936 _flood=flood_gen 

937 ) 

938 

939 

940@conf.commands.register 

941def srflood(x, # type: _PacketIterable 

942 promisc=None, # type: Optional[bool] 

943 filter=None, # type: Optional[str] 

944 iface=None, # type: Optional[_GlobInterfaceType] 

945 nofilter=None, # type: Optional[bool] 

946 *args, # type: Any 

947 **kargs # type: Any 

948 ): 

949 # type: (...) -> Tuple[SndRcvList, PacketList] 

950 """Flood and receive packets at layer 3 

951 

952 This determines the interface (or L2 source to use) based on the routing 

953 table: conf.route / conf.route6 

954 

955 :param prn: function applied to packets received 

956 :param unique: only consider packets whose print 

957 :param nofilter: put 1 to avoid use of BPF filters 

958 :param filter: provide a BPF filter 

959 """ 

960 iface, ipv6 = _interface_selection(x, kargs.pop("iface", None)) 

961 s = iface.l3socket(ipv6)( 

962 promisc=promisc, filter=filter, 

963 iface=iface, nofilter=nofilter, 

964 ) 

965 r = sndrcvflood(s, x, *args, **kargs) 

966 s.close() 

967 return r 

968 

969 

970@conf.commands.register 

971def sr1flood(x, # type: _PacketIterable 

972 promisc=None, # type: Optional[bool] 

973 filter=None, # type: Optional[str] 

974 nofilter=0, # type: int 

975 *args, # type: Any 

976 **kargs # type: Any 

977 ): 

978 # type: (...) -> Optional[Packet] 

979 """Flood and receive packets at layer 3 and return only the first answer 

980 

981 This determines the interface (or L2 source to use) based on the routing 

982 table: conf.route / conf.route6 

983 

984 :param prn: function applied to packets received 

985 :param verbose: set verbosity level 

986 :param nofilter: put 1 to avoid use of BPF filters 

987 :param filter: provide a BPF filter 

988 :param iface: listen answers only on the given interface 

989 """ 

990 iface, ipv6 = _interface_selection(x, kargs.pop("iface", None)) 

991 s = iface.l3socket(ipv6)( 

992 promisc=promisc, filter=filter, 

993 nofilter=nofilter, iface=iface, 

994 ) 

995 ans, _ = sndrcvflood(s, x, *args, **kargs) 

996 s.close() 

997 if len(ans) > 0: 

998 return cast(Packet, ans[0][1]) 

999 return None 

1000 

1001 

1002@conf.commands.register 

1003def srpflood(x, # type: _PacketIterable 

1004 promisc=None, # type: Optional[bool] 

1005 filter=None, # type: Optional[str] 

1006 iface=None, # type: Optional[_GlobInterfaceType] 

1007 iface_hint=None, # type: Optional[str] 

1008 nofilter=None, # type: Optional[bool] 

1009 *args, # type: Any 

1010 **kargs # type: Any 

1011 ): 

1012 # type: (...) -> Tuple[SndRcvList, PacketList] 

1013 """Flood and receive packets at layer 2 

1014 

1015 :param prn: function applied to packets received 

1016 :param unique: only consider packets whose print 

1017 :param nofilter: put 1 to avoid use of BPF filters 

1018 :param filter: provide a BPF filter 

1019 :param iface: listen answers only on the given interface 

1020 """ 

1021 if iface is None and iface_hint is not None: 

1022 iface = conf.route.route(iface_hint)[0] 

1023 iface = resolve_iface(iface or conf.iface) 

1024 s = iface.l2socket()(promisc=promisc, filter=filter, iface=iface, nofilter=nofilter) # noqa: E501 

1025 r = sndrcvflood(s, x, *args, **kargs) 

1026 s.close() 

1027 return r 

1028 

1029 

1030@conf.commands.register 

1031def srp1flood(x, # type: _PacketIterable 

1032 promisc=None, # type: Optional[bool] 

1033 filter=None, # type: Optional[str] 

1034 iface=None, # type: Optional[_GlobInterfaceType] 

1035 nofilter=0, # type: int 

1036 *args, # type: Any 

1037 **kargs # type: Any 

1038 ): 

1039 # type: (...) -> Optional[Packet] 

1040 """Flood and receive packets at layer 2 and return only the first answer 

1041 

1042 :param prn: function applied to packets received 

1043 :param verbose: set verbosity level 

1044 :param nofilter: put 1 to avoid use of BPF filters 

1045 :param filter: provide a BPF filter 

1046 :param iface: listen answers only on the given interface 

1047 """ 

1048 iface = resolve_iface(iface or conf.iface) 

1049 s = iface.l2socket()(promisc=promisc, filter=filter, nofilter=nofilter, iface=iface) # noqa: E501 

1050 ans, _ = sndrcvflood(s, x, *args, **kargs) 

1051 s.close() 

1052 if len(ans) > 0: 

1053 return cast(Packet, ans[0][1]) 

1054 return None 

1055 

1056# SNIFF METHODS 

1057 

1058 

1059def _offline_pcap_reader(source, flt, quiet): 

1060 # type: (Any, Optional[str], bool) -> PcapReader 

1061 """Build a PcapReader for one sniff() offline source. 

1062 

1063 The source is whatever tcpdump() accepts: a filename, an IterSocket over 

1064 packets, or an open file descriptor. Without a filter it is read directly. 

1065 With a filter the packets are prefiltered through a tcpdump subprocess; 

1066 that process is attached to the reader so its close() reaps it. Reading it 

1067 through a bare file descriptor used to leak the process as a zombie 

1068 (#4512). 

1069 """ 

1070 if flt is None: 

1071 return PcapReader(source) 

1072 proc = tcpdump(source, args=["-w", "-"], flt=flt, getproc=True, quiet=quiet) 

1073 reader = PcapReader(proc.stdout) 

1074 reader.subproc = proc 

1075 return reader 

1076 

1077 

1078class AsyncSniffer(object): 

1079 """ 

1080 Sniff packets and return a list of packets. 

1081 

1082 Args: 

1083 count: number of packets to capture. 0 means infinity. 

1084 store: whether to store sniffed packets or discard them 

1085 prn: function to apply to each packet. If something is returned, it 

1086 is displayed. 

1087 --Ex: prn = lambda x: x.summary() 

1088 session: a session = a flow decoder used to handle stream of packets. 

1089 --Ex: session=TCPSession 

1090 See below for more details. 

1091 filter: BPF filter to apply. 

1092 lfilter: Python function applied to each packet to determine if 

1093 further action may be done. 

1094 --Ex: lfilter = lambda x: x.haslayer(Padding) 

1095 offline: PCAP file (or list of PCAP files) to read packets from, 

1096 instead of sniffing them 

1097 quiet: when set to True, the process stderr is discarded 

1098 (default: False). 

1099 timeout: stop sniffing after a given time (default: None). 

1100 L2socket: use the provided L2socket (default: use conf.L2listen). 

1101 opened_socket: provide an object (or a list of objects) ready to use 

1102 .recv() on. 

1103 stop_filter: Python function applied to each packet to determine if 

1104 we have to stop the capture after this packet. 

1105 --Ex: stop_filter = lambda x: x.haslayer(TCP) 

1106 iface: interface or list of interfaces (default: None for sniffing 

1107 on the default interface). 

1108 monitor: use monitor mode. May not be available on all OS 

1109 started_callback: called as soon as the sniffer starts sniffing 

1110 (default: None). 

1111 

1112 The iface, offline and opened_socket parameters can be either an 

1113 element, a list of elements, or a dict object mapping an element to a 

1114 label (see examples below). 

1115 

1116 For more information about the session argument, see 

1117 https://scapy.rtfd.io/en/latest/usage.html#advanced-sniffing-sniffing-sessions 

1118 

1119 Examples: synchronous 

1120 >>> sniff(filter="arp") 

1121 >>> sniff(filter="tcp", 

1122 ... session=IPSession, # defragment on-the-flow 

1123 ... prn=lambda x: x.summary()) 

1124 >>> sniff(lfilter=lambda pkt: ARP in pkt) 

1125 >>> sniff(iface="eth0", prn=Packet.summary) 

1126 >>> sniff(iface=["eth0", "mon0"], 

1127 ... prn=lambda pkt: "%s: %s" % (pkt.sniffed_on, 

1128 ... pkt.summary())) 

1129 >>> sniff(iface={"eth0": "Ethernet", "mon0": "Wifi"}, 

1130 ... prn=lambda pkt: "%s: %s" % (pkt.sniffed_on, 

1131 ... pkt.summary())) 

1132 

1133 Examples: asynchronous 

1134 >>> t = AsyncSniffer(iface="enp0s3") 

1135 >>> t.start() 

1136 >>> time.sleep(1) 

1137 >>> print("nice weather today") 

1138 >>> t.stop() 

1139 """ 

1140 

1141 def __init__(self, *args, **kwargs): 

1142 # type: (*Any, **Any) -> None 

1143 # Store keyword arguments 

1144 self.args = args 

1145 if "timeout" in kwargs: 

1146 raise ValueError( 

1147 "'timeout' isn't supported with AsyncSniffer. Use join(timeout=1)" 

1148 ) 

1149 self.kwargs = kwargs 

1150 self.running = False 

1151 self.thread = None # type: Optional[Thread] 

1152 self.results = None # type: Optional[PacketList] 

1153 self.exception = None # type: Optional[Exception] 

1154 self.stop_cb = lambda: None # type: Callable[[], None] 

1155 

1156 def _setup_thread(self): 

1157 # type: () -> None 

1158 def _run_catch(self=self, *args, **kwargs): 

1159 # type: (Any, *Any, **Any) -> None 

1160 try: 

1161 self._run(*args, **kwargs) 

1162 except Exception as ex: 

1163 self.exception = ex 

1164 # Prepare sniffing thread 

1165 self.thread = Thread( 

1166 target=_run_catch, 

1167 args=self.args, 

1168 kwargs=self.kwargs, 

1169 name="AsyncSniffer" 

1170 ) 

1171 self.thread.daemon = True 

1172 

1173 def _run(self, 

1174 count=0, # type: int 

1175 store=True, # type: bool 

1176 offline=None, # type: Any 

1177 quiet=False, # type: bool 

1178 prn=None, # type: Optional[Callable[[Packet], Any]] 

1179 lfilter=None, # type: Optional[Callable[[Packet], bool]] 

1180 L2socket=None, # type: Optional[Type[SuperSocket]] 

1181 timeout=None, # type: Optional[int] 

1182 opened_socket=None, # type: Optional[SuperSocket] 

1183 stop_filter=None, # type: Optional[Callable[[Packet], bool]] 

1184 iface=None, # type: Optional[_GlobInterfaceType] 

1185 started_callback=None, # type: Optional[Callable[[], Any]] 

1186 session=None, # type: Optional[_GlobSessionType] 

1187 chainCC=False, # type: bool 

1188 **karg # type: Any 

1189 ): 

1190 # type: (...) -> None 

1191 self.running = True 

1192 self.count = 0 

1193 lst = [] 

1194 # Start main thread 

1195 # instantiate session 

1196 if not isinstance(session, DefaultSession): 

1197 session = session or DefaultSession 

1198 session = session() 

1199 # sniff_sockets follows: {socket: label} 

1200 sniff_sockets = {} # type: Dict[SuperSocket, _GlobInterfaceType] 

1201 if opened_socket is not None: 

1202 if isinstance(opened_socket, list): 

1203 sniff_sockets.update( 

1204 (s, "socket%d" % i) 

1205 for i, s in enumerate(opened_socket) 

1206 ) 

1207 elif isinstance(opened_socket, dict): 

1208 sniff_sockets.update( 

1209 (s, label) 

1210 for s, label in opened_socket.items() 

1211 ) 

1212 else: 

1213 sniff_sockets[opened_socket] = "socket0" 

1214 if offline is not None: 

1215 flt = karg.get('filter') 

1216 

1217 if isinstance(offline, str): 

1218 # Single file 

1219 offline = [offline] 

1220 if isinstance(offline, list) and \ 

1221 all(isinstance(elt, str) for elt in offline): 

1222 # List of files 

1223 sniff_sockets.update( 

1224 (_offline_pcap_reader(fname, flt, quiet), fname) # type: ignore 

1225 for fname in offline 

1226 ) 

1227 elif isinstance(offline, dict): 

1228 # Dict of files 

1229 sniff_sockets.update( 

1230 (_offline_pcap_reader(fname, flt, quiet), label) # type: ignore 

1231 for fname, label in offline.items() 

1232 ) 

1233 elif isinstance(offline, (Packet, PacketList, list)): 

1234 # Iterables (list of packets, PacketList..) 

1235 offline = IterSocket(offline) 

1236 sniff_sockets[ 

1237 offline if flt is None 

1238 else _offline_pcap_reader(offline, flt, quiet) 

1239 ] = offline 

1240 else: 

1241 # Other (file descriptors...) 

1242 sniff_sockets[ 

1243 _offline_pcap_reader(offline, flt, quiet) # type: ignore 

1244 ] = offline 

1245 if not sniff_sockets or iface is not None: 

1246 # The _RL2 function resolves the L2socket of an iface 

1247 _RL2 = lambda i: L2socket or resolve_iface(i).l2listen() # type: Callable[[_GlobInterfaceType], Callable[..., SuperSocket]] # noqa: E501 

1248 if isinstance(iface, list): 

1249 sniff_sockets.update( 

1250 (_RL2(ifname)(type=ETH_P_ALL, iface=ifname, **karg), 

1251 ifname) 

1252 for ifname in iface 

1253 ) 

1254 elif isinstance(iface, dict): 

1255 sniff_sockets.update( 

1256 (_RL2(ifname)(type=ETH_P_ALL, iface=ifname, **karg), 

1257 iflabel) 

1258 for ifname, iflabel in iface.items() 

1259 ) 

1260 else: 

1261 iface = iface or conf.iface 

1262 sniff_sockets[_RL2(iface)(type=ETH_P_ALL, iface=iface, 

1263 **karg)] = iface 

1264 

1265 # Get select information from the sockets 

1266 _main_socket = next(iter(sniff_sockets)) 

1267 select_func = _main_socket.select 

1268 nonblocking_socket = getattr(_main_socket, "nonblocking_socket", False) 

1269 # We check that all sockets use the same select(), or raise a warning 

1270 if not all(select_func == sock.select for sock in sniff_sockets): 

1271 warning("Warning: inconsistent socket types ! " 

1272 "The used select function " 

1273 "will be the one of the first socket") 

1274 

1275 close_pipe = None # type: Optional[ObjectPipe[None]] 

1276 if not nonblocking_socket: 

1277 # select is blocking: Add special control socket 

1278 from scapy.automaton import ObjectPipe 

1279 close_pipe = ObjectPipe[None]("control_socket") 

1280 sniff_sockets[close_pipe] = "control_socket" # type: ignore 

1281 

1282 def stop_cb(): 

1283 # type: () -> None 

1284 if self.running and close_pipe: 

1285 close_pipe.send(None) 

1286 self.continue_sniff = False 

1287 self.stop_cb = stop_cb 

1288 else: 

1289 # select is non blocking 

1290 def stop_cb(): 

1291 # type: () -> None 

1292 self.continue_sniff = False 

1293 self.stop_cb = stop_cb 

1294 

1295 try: 

1296 self.continue_sniff = True 

1297 if started_callback: 

1298 started_callback() 

1299 

1300 # Start timeout 

1301 if timeout is not None: 

1302 stoptime = time.monotonic() + timeout 

1303 remain = None 

1304 

1305 while sniff_sockets and self.continue_sniff: 

1306 if timeout is not None: 

1307 remain = stoptime - time.monotonic() 

1308 if remain <= 0: 

1309 break 

1310 sockets = select_func(list(sniff_sockets.keys()), remain) 

1311 dead_sockets = [] 

1312 for s in sockets: 

1313 if s is close_pipe: # type: ignore 

1314 break 

1315 # The session object is passed the socket to call recv() on, 

1316 # and may perform additional processing (ip defrag, etc.) 

1317 try: 

1318 packets = session.recv(s) 

1319 # A session can return multiple objects 

1320 for p in packets: 

1321 p.sniffed_on = sniff_sockets.get(s, None) 

1322 if lfilter and not lfilter(p): 

1323 continue 

1324 # post-processing 

1325 self.count += 1 

1326 if store: 

1327 lst.append(p) 

1328 if prn: 

1329 result = prn(p) 

1330 if result is not None: 

1331 print(result) 

1332 # check 

1333 if (stop_filter and stop_filter(p)) or \ 

1334 (0 < count <= self.count): 

1335 self.continue_sniff = False 

1336 break 

1337 except EOFError: 

1338 # End of stream 

1339 try: 

1340 s.close() 

1341 except Exception: 

1342 pass 

1343 dead_sockets.append(s) 

1344 continue 

1345 except Exception as ex: 

1346 msg = " It was closed." 

1347 try: 

1348 # Make sure it's closed 

1349 s.close() 

1350 except Exception as ex2: 

1351 msg = " close() failed with '%s'" % ex2 

1352 warning( 

1353 "Socket %s failed with '%s'." % (s, ex) + msg 

1354 ) 

1355 dead_sockets.append(s) 

1356 if conf.debug_dissector >= 2: 

1357 raise 

1358 continue 

1359 # Removed dead sockets 

1360 for s in dead_sockets: 

1361 del sniff_sockets[s] 

1362 if len(sniff_sockets) == 1 and \ 

1363 close_pipe in sniff_sockets: # type: ignore 

1364 # Only the close_pipe left 

1365 del sniff_sockets[close_pipe] # type: ignore 

1366 except KeyboardInterrupt: 

1367 if chainCC: 

1368 raise 

1369 self.running = False 

1370 if opened_socket is None: 

1371 for s in sniff_sockets: 

1372 s.close() 

1373 elif close_pipe: 

1374 close_pipe.close() 

1375 self.results = PacketList(lst, "Sniffed") 

1376 

1377 def start(self): 

1378 # type: () -> None 

1379 """Starts AsyncSniffer in async mode""" 

1380 self._setup_thread() 

1381 if self.thread: 

1382 self.thread.start() 

1383 

1384 def stop(self, join=True): 

1385 # type: (bool) -> Optional[PacketList] 

1386 """Stops AsyncSniffer if not in async mode""" 

1387 if self.running: 

1388 self.stop_cb() 

1389 if not hasattr(self, "continue_sniff"): 

1390 # Never started -> is there an exception? 

1391 if self.exception is not None: 

1392 raise self.exception 

1393 return None 

1394 if self.continue_sniff: 

1395 raise Scapy_Exception( 

1396 "Unsupported (offline or unsupported socket)" 

1397 ) 

1398 if join: 

1399 self.join() 

1400 return self.results 

1401 return None 

1402 else: 

1403 raise ScapyNotRunningException("Not running ! (check .running attr)") 

1404 

1405 def join(self, *args, **kwargs): 

1406 # type: (*Any, **Any) -> None 

1407 if self.thread: 

1408 self.thread.join(*args, **kwargs) 

1409 if self.exception is not None: 

1410 raise self.exception 

1411 

1412 

1413@conf.commands.register 

1414def sniff(*args, **kwargs): 

1415 # type: (*Any, **Any) -> PacketList 

1416 sniffer = AsyncSniffer() 

1417 sniffer._run(*args, **kwargs) 

1418 return cast(PacketList, sniffer.results) 

1419 

1420 

1421sniff.__doc__ = AsyncSniffer.__doc__ 

1422 

1423 

1424@conf.commands.register 

1425def bridge_and_sniff(if1, # type: _GlobInterfaceType 

1426 if2, # type: _GlobInterfaceType 

1427 xfrm12=None, # type: Optional[Callable[[Packet], Union[Packet, bool]]] # noqa: E501 

1428 xfrm21=None, # type: Optional[Callable[[Packet], Union[Packet, bool]]] # noqa: E501 

1429 prn=None, # type: Optional[Callable[[Packet], Any]] 

1430 L2socket=None, # type: Optional[Type[SuperSocket]] 

1431 *args, # type: Any 

1432 **kargs # type: Any 

1433 ): 

1434 # type: (...) -> PacketList 

1435 """Forward traffic between interfaces if1 and if2, sniff and return 

1436 the exchanged packets. 

1437 

1438 :param if1: the interfaces to use (interface names or opened sockets). 

1439 :param if2: 

1440 :param xfrm12: a function to call when forwarding a packet from if1 to 

1441 if2. If it returns True, the packet is forwarded as it. If it 

1442 returns False or None, the packet is discarded. If it returns a 

1443 packet, this packet is forwarded instead of the original packet 

1444 one. 

1445 :param xfrm21: same as xfrm12 for packets forwarded from if2 to if1. 

1446 

1447 The other arguments are the same than for the function sniff(), 

1448 except for offline, opened_socket and iface that are ignored. 

1449 See help(sniff) for more. 

1450 """ 

1451 for arg in ['opened_socket', 'offline', 'iface']: 

1452 if arg in kargs: 

1453 log_runtime.warning("Argument %s cannot be used in " 

1454 "bridge_and_sniff() -- ignoring it.", arg) 

1455 del kargs[arg] 

1456 

1457 def _init_socket(iface, # type: _GlobInterfaceType 

1458 count, # type: int 

1459 L2socket=L2socket # type: Optional[Type[SuperSocket]] 

1460 ): 

1461 # type: (...) -> Tuple[SuperSocket, _GlobInterfaceType] 

1462 if isinstance(iface, SuperSocket): 

1463 return iface, "iface%d" % count 

1464 else: 

1465 if not L2socket: 

1466 iface = resolve_iface(iface or conf.iface) 

1467 L2socket = iface.l2socket() 

1468 return L2socket(iface=iface), iface 

1469 sckt1, if1 = _init_socket(if1, 1) 

1470 sckt2, if2 = _init_socket(if2, 2) 

1471 peers = {if1: sckt2, if2: sckt1} 

1472 xfrms = {} 

1473 if xfrm12 is not None: 

1474 xfrms[if1] = xfrm12 

1475 if xfrm21 is not None: 

1476 xfrms[if2] = xfrm21 

1477 

1478 def prn_send(pkt): 

1479 # type: (Packet) -> None 

1480 try: 

1481 sendsock = peers[pkt.sniffed_on or ""] 

1482 except KeyError: 

1483 return 

1484 if pkt.sniffed_on in xfrms: 

1485 try: 

1486 _newpkt = xfrms[pkt.sniffed_on](pkt) 

1487 except Exception: 

1488 log_runtime.warning( 

1489 'Exception in transformation function for packet [%s] ' 

1490 'received on %s -- dropping', 

1491 pkt.summary(), pkt.sniffed_on, exc_info=True 

1492 ) 

1493 return 

1494 else: 

1495 if isinstance(_newpkt, bool): 

1496 if not _newpkt: 

1497 return 

1498 newpkt = pkt 

1499 else: 

1500 newpkt = _newpkt 

1501 else: 

1502 newpkt = pkt 

1503 try: 

1504 sendsock.send(newpkt) 

1505 except Exception: 

1506 log_runtime.warning('Cannot forward packet [%s] received on %s', 

1507 pkt.summary(), pkt.sniffed_on, exc_info=True) 

1508 if prn is None: 

1509 prn = prn_send 

1510 else: 

1511 prn_orig = prn 

1512 

1513 def prn(pkt): 

1514 # type: (Packet) -> Any 

1515 prn_send(pkt) 

1516 return prn_orig(pkt) 

1517 

1518 return sniff(opened_socket={sckt1: if1, sckt2: if2}, prn=prn, 

1519 *args, **kargs) 

1520 

1521 

1522@conf.commands.register 

1523def tshark(*args, **kargs): 

1524 # type: (Any, Any) -> None 

1525 """Sniff packets and print them calling pkt.summary(). 

1526 This tries to replicate what text-wireshark (tshark) would look like""" 

1527 

1528 if 'iface' in kargs: 

1529 iface = kargs.get('iface') 

1530 elif 'opened_socket' in kargs: 

1531 iface = cast(SuperSocket, kargs.get('opened_socket')).iface 

1532 else: 

1533 iface = conf.iface 

1534 print("Capturing on '%s'" % iface) 

1535 

1536 # This should be a nonlocal variable, using a mutable object 

1537 # for Python 2 compatibility 

1538 i = [0] 

1539 

1540 def _cb(pkt): 

1541 # type: (Packet) -> None 

1542 print("%5d\t%s" % (i[0], pkt.summary())) 

1543 i[0] += 1 

1544 

1545 sniff(prn=_cb, store=False, *args, **kargs) 

1546 print("\n%d packet%s captured" % (i[0], 's' if i[0] > 1 else ''))