Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/scapy/layers/inet.py: 33%

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

1440 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""" 

7IPv4 (Internet Protocol v4). 

8""" 

9 

10import time 

11import struct 

12import re 

13import random 

14import select 

15import socket 

16from collections import defaultdict 

17 

18from scapy.utils import checksum, do_graph, graphviz_escape, incremental_label, \ 

19 linehexdump, strxor, whois, colgen 

20from scapy.ansmachine import AnsweringMachine 

21from scapy.base_classes import Gen, Net, _ScopedIP 

22from scapy.consts import OPENBSD 

23from scapy.data import ( 

24 ETH_P_IP, 

25 ETH_P_ALL, 

26 DLT_RAW, 

27 DLT_RAW_ALT, 

28 DLT_IPV4, 

29 IP_PROTOS, 

30 TCP_SERVICES, 

31 UDP_SERVICES, 

32) 

33from scapy.layers.l2 import ( 

34 CookedLinux, 

35 Dot3, 

36 Ether, 

37 GRE, 

38 Loopback, 

39 SNAP, 

40 arpcachepoison, 

41 getmacbyip, 

42) 

43from scapy.compat import raw, chb, bytes_encode, Optional 

44from scapy.config import conf 

45from scapy.fields import ( 

46 BitEnumField, 

47 BitField, 

48 ByteEnumField, 

49 ByteField, 

50 ConditionalField, 

51 DestField, 

52 Emph, 

53 FieldLenField, 

54 FieldListField, 

55 FlagsField, 

56 IPField, 

57 IP6Field, 

58 IntField, 

59 MayEnd, 

60 MultiEnumField, 

61 MultipleTypeField, 

62 PacketField, 

63 PacketListField, 

64 ShortEnumField, 

65 ShortField, 

66 SourceIPField, 

67 StrField, 

68 StrFixedLenField, 

69 StrLenField, 

70 TrailerField, 

71 XByteField, 

72 XShortField, 

73) 

74from scapy.packet import Packet, bind_layers, bind_bottom_up, NoPayload 

75from scapy.volatile import RandShort, RandInt, RandBin, RandNum, VolatileValue 

76from scapy.sendrecv import sr, sr1 

77from scapy.plist import _PacketList, PacketList, SndRcvList 

78from scapy.automaton import Automaton, ATMT 

79from scapy.error import log_runtime, warning 

80from scapy.pton_ntop import inet_pton 

81 

82import scapy.as_resolvers 

83 

84#################### 

85# IP Tools class # 

86#################### 

87 

88 

89class IPTools(object): 

90 """Add more powers to a class with an "src" attribute.""" 

91 __slots__ = [] 

92 

93 def whois(self): 

94 """whois the source and print the output""" 

95 print(whois(self.src).decode("utf8", "ignore")) 

96 

97 def _ttl(self): 

98 """Returns ttl or hlim, depending on the IP version""" 

99 return self.hlim if isinstance(self, scapy.layers.inet6.IPv6) else self.ttl # noqa: E501 

100 

101 def ottl(self): 

102 t = sorted([32, 64, 128, 255] + [self._ttl()]) 

103 return t[t.index(self._ttl()) + 1] 

104 

105 def hops(self): 

106 return self.ottl() - self._ttl() 

107 

108 

109_ip_options_names = {0: "end_of_list", 

110 1: "nop", 

111 2: "security", 

112 3: "loose_source_route", 

113 4: "timestamp", 

114 5: "extended_security", 

115 6: "commercial_security", 

116 7: "record_route", 

117 8: "stream_id", 

118 9: "strict_source_route", 

119 10: "experimental_measurement", 

120 11: "mtu_probe", 

121 12: "mtu_reply", 

122 13: "flow_control", 

123 14: "access_control", 

124 15: "encode", 

125 16: "imi_traffic_descriptor", 

126 17: "extended_IP", 

127 18: "traceroute", 

128 19: "address_extension", 

129 20: "router_alert", 

130 21: "selective_directed_broadcast_mode", 

131 23: "dynamic_packet_state", 

132 24: "upstream_multicast_packet", 

133 25: "quick_start", 

134 30: "rfc4727_experiment", 

135 } 

136 

137 

138class _IPOption_HDR(Packet): 

139 fields_desc = [BitField("copy_flag", 0, 1), 

140 BitEnumField("optclass", 0, 2, {0: "control", 2: "debug"}), 

141 BitEnumField("option", 0, 5, _ip_options_names)] 

142 

143 

144class IPOption(Packet): 

145 name = "IP Option" 

146 fields_desc = [_IPOption_HDR, 

147 FieldLenField("length", None, fmt="B", # Only option 0 and 1 have no length and value # noqa: E501 

148 length_of="value", adjust=lambda pkt, l:l + 2), # noqa: E501 

149 StrLenField("value", "", length_from=lambda pkt:pkt.length - 2)] # noqa: E501 

150 

151 def extract_padding(self, p): 

152 return b"", p 

153 

154 registered_ip_options = {} 

155 

156 @classmethod 

157 def register_variant(cls): 

158 cls.registered_ip_options[cls.option.default] = cls 

159 

160 @classmethod 

161 def dispatch_hook(cls, pkt=None, *args, **kargs): 

162 if pkt: 

163 opt = pkt[0] & 0x1f 

164 if opt in cls.registered_ip_options: 

165 return cls.registered_ip_options[opt] 

166 return cls 

167 

168 

169class IPOption_EOL(IPOption): 

170 name = "IP Option End of Options List" 

171 option = 0 

172 fields_desc = [_IPOption_HDR] 

173 

174 

175class IPOption_NOP(IPOption): 

176 name = "IP Option No Operation" 

177 option = 1 

178 fields_desc = [_IPOption_HDR] 

179 

180 

181class IPOption_Security(IPOption): 

182 name = "IP Option Security" 

183 copy_flag = 1 

184 option = 2 

185 fields_desc = [_IPOption_HDR, 

186 ByteField("length", 11), 

187 ShortField("security", 0), 

188 ShortField("compartment", 0), 

189 ShortField("handling_restrictions", 0), 

190 StrFixedLenField("transmission_control_code", "xxx", 3), 

191 ] 

192 

193 

194class IPOption_RR(IPOption): 

195 name = "IP Option Record Route" 

196 option = 7 

197 fields_desc = [_IPOption_HDR, 

198 FieldLenField("length", None, fmt="B", 

199 length_of="routers", adjust=lambda pkt, l:l + 3), # noqa: E501 

200 ByteField("pointer", 4), # 4 is first IP 

201 FieldListField("routers", [], IPField("", "0.0.0.0"), 

202 length_from=lambda pkt:pkt.length - 3) 

203 ] 

204 

205 def get_current_router(self): 

206 return self.routers[self.pointer // 4 - 1] 

207 

208 

209class IPOption_LSRR(IPOption_RR): 

210 name = "IP Option Loose Source and Record Route" 

211 copy_flag = 1 

212 option = 3 

213 

214 

215class IPOption_SSRR(IPOption_RR): 

216 name = "IP Option Strict Source and Record Route" 

217 copy_flag = 1 

218 option = 9 

219 

220 

221class IPOption_Stream_Id(IPOption): 

222 name = "IP Option Stream ID" 

223 copy_flag = 1 

224 option = 8 

225 fields_desc = [_IPOption_HDR, 

226 ByteField("length", 4), 

227 ShortField("security", 0), ] 

228 

229 

230class IPOption_MTU_Probe(IPOption): 

231 name = "IP Option MTU Probe" 

232 option = 11 

233 fields_desc = [_IPOption_HDR, 

234 ByteField("length", 4), 

235 ShortField("mtu", 0), ] 

236 

237 

238class IPOption_MTU_Reply(IPOption_MTU_Probe): 

239 name = "IP Option MTU Reply" 

240 option = 12 

241 

242 

243class IPOption_Traceroute(IPOption): 

244 name = "IP Option Traceroute" 

245 option = 18 

246 fields_desc = [_IPOption_HDR, 

247 ByteField("length", 12), 

248 ShortField("id", 0), 

249 ShortField("outbound_hops", 0), 

250 ShortField("return_hops", 0), 

251 IPField("originator_ip", "0.0.0.0")] 

252 

253 

254class IPOption_Timestamp(IPOption): 

255 name = "IP Option Timestamp" 

256 optclass = 2 

257 option = 4 

258 fields_desc = [_IPOption_HDR, 

259 ByteField("length", None), 

260 ByteField("pointer", 9), 

261 BitField("oflw", 0, 4), 

262 BitEnumField("flg", 1, 4, 

263 {0: "timestamp_only", 

264 1: "timestamp_and_ip_addr", 

265 3: "prespecified_ip_addr"}), 

266 ConditionalField(IPField("internet_address", "0.0.0.0"), 

267 lambda pkt: pkt.flg != 0), 

268 IntField('timestamp', 0)] 

269 

270 def post_build(self, p, pay): 

271 if self.length is None: 

272 p = p[:1] + struct.pack("!B", len(p)) + p[2:] 

273 return p + pay 

274 

275 

276class IPOption_Address_Extension(IPOption): 

277 name = "IP Option Address Extension" 

278 copy_flag = 1 

279 option = 19 

280 fields_desc = [_IPOption_HDR, 

281 ByteField("length", 10), 

282 IPField("src_ext", "0.0.0.0"), 

283 IPField("dst_ext", "0.0.0.0")] 

284 

285 

286class IPOption_Router_Alert(IPOption): 

287 name = "IP Option Router Alert" 

288 copy_flag = 1 

289 option = 20 

290 fields_desc = [_IPOption_HDR, 

291 ByteField("length", 4), 

292 ShortEnumField("alert", 0, {0: "router_shall_examine_packet"}), ] # noqa: E501 

293 

294 

295class IPOption_SDBM(IPOption): 

296 name = "IP Option Selective Directed Broadcast Mode" 

297 copy_flag = 1 

298 option = 21 

299 fields_desc = [_IPOption_HDR, 

300 FieldLenField("length", None, fmt="B", 

301 length_of="addresses", adjust=lambda pkt, l:l + 2), # noqa: E501 

302 FieldListField("addresses", [], IPField("", "0.0.0.0"), 

303 length_from=lambda pkt:pkt.length - 2) 

304 ] 

305 

306 

307TCPOptions = ( 

308 {0: ("EOL", None), 

309 1: ("NOP", None), 

310 2: ("MSS", "!H"), 

311 3: ("WScale", "!B"), 

312 4: ("SAckOK", None), 

313 5: ("SAck", "!"), 

314 8: ("Timestamp", "!II"), 

315 14: ("AltChkSum", "!BH"), 

316 15: ("AltChkSumOpt", None), 

317 19: ("MD5", "16s"), 

318 25: ("Mood", "!p"), 

319 28: ("UTO", "!H"), 

320 29: ("AO", None), 

321 34: ("TFO", "!II"), 

322 # RFC 3692 

323 # 253: ("Experiment", "!HHHH"), 

324 # 254: ("Experiment", "!HHHH"), 

325 }, 

326 {"EOL": 0, 

327 "NOP": 1, 

328 "MSS": 2, 

329 "WScale": 3, 

330 "SAckOK": 4, 

331 "SAck": 5, 

332 "Timestamp": 8, 

333 "AltChkSum": 14, 

334 "AltChkSumOpt": 15, 

335 "MD5": 19, 

336 "Mood": 25, 

337 "UTO": 28, 

338 "AO": 29, 

339 "TFO": 34, 

340 }) 

341 

342 

343class TCPAOValue(Packet): 

344 """Value of TCP-AO option""" 

345 fields_desc = [ 

346 ByteField("keyid", None), 

347 ByteField("rnextkeyid", None), 

348 StrLenField("mac", "", length_from=lambda p:len(p.original) - 2), 

349 ] 

350 

351 

352def get_tcpao(tcphdr): 

353 # type: (TCP) -> Optional[TCPAOValue] 

354 """Get the TCP-AO option from the header""" 

355 for optid, optval in tcphdr.options: 

356 if optid == 'AO': 

357 return optval 

358 return None 

359 

360 

361class RandTCPOptions(VolatileValue): 

362 def __init__(self, size=None): 

363 if size is None: 

364 size = RandNum(1, 5) 

365 self.size = size 

366 

367 def _fix(self): 

368 # Pseudo-Random amount of options 

369 # Random ("NAME", fmt) 

370 rand_patterns = [ 

371 random.choice(list( 

372 (opt, fmt) for opt, fmt in TCPOptions[0].values() 

373 if opt != 'EOL' 

374 )) 

375 for _ in range(self.size) 

376 ] 

377 rand_vals = [] 

378 for oname, fmt in rand_patterns: 

379 if fmt is None: 

380 rand_vals.append((oname, b'')) 

381 else: 

382 # Process the fmt arguments 1 by 1 

383 structs = re.findall(r"!?([bBhHiIlLqQfdpP]|\d+[spx])", fmt) 

384 rval = [] 

385 for stru in structs: 

386 stru = "!" + stru 

387 if "s" in stru or "p" in stru: # str / chr 

388 v = bytes(RandBin(struct.calcsize(stru))) 

389 else: # int 

390 _size = struct.calcsize(stru) 

391 v = random.randint(0, 2 ** (8 * _size) - 1) 

392 rval.append(v) 

393 rand_vals.append((oname, tuple(rval))) 

394 return rand_vals 

395 

396 def __bytes__(self): 

397 return TCPOptionsField.i2m(None, None, self._fix()) 

398 

399 

400class TCPOptionsField(StrField): 

401 islist = 1 

402 

403 def getfield(self, pkt, s): 

404 opsz = (pkt.dataofs - 5) * 4 

405 if opsz < 0: 

406 log_runtime.info( 

407 "bad dataofs (%i). Assuming dataofs=5", pkt.dataofs 

408 ) 

409 opsz = 0 

410 return s[opsz:], self.m2i(pkt, s[:opsz]) 

411 

412 def m2i(self, pkt, x): 

413 opt = [] 

414 while x: 

415 onum = x[0] 

416 if onum == 0: 

417 opt.append(("EOL", None)) 

418 break 

419 if onum == 1: 

420 opt.append(("NOP", None)) 

421 x = x[1:] 

422 continue 

423 try: 

424 olen = x[1] 

425 except IndexError: 

426 olen = 0 

427 if olen < 2: 

428 log_runtime.info( 

429 "Malformed TCP option (announced length is %i)", olen 

430 ) 

431 olen = 2 

432 oval = x[2:olen] 

433 if onum in TCPOptions[0]: 

434 oname, ofmt = TCPOptions[0][onum] 

435 if onum == 5: # SAck 

436 ofmt += "%iI" % (len(oval) // 4) 

437 if onum == 29: # AO 

438 oval = TCPAOValue(oval) 

439 if ofmt and struct.calcsize(ofmt) == len(oval): 

440 oval = struct.unpack(ofmt, oval) 

441 if len(oval) == 1: 

442 oval = oval[0] 

443 opt.append((oname, oval)) 

444 else: 

445 opt.append((onum, oval)) 

446 x = x[olen:] 

447 return opt 

448 

449 def i2h(self, pkt, x): 

450 if not x: 

451 return [] 

452 return x 

453 

454 def i2m(self, pkt, x): 

455 opt = b"" 

456 for oname, oval in x: 

457 # We check for a (0, b'') or (1, b'') option first 

458 oname = {0: "EOL", 1: "NOP"}.get(oname, oname) 

459 if isinstance(oname, str): 

460 if oname == "NOP": 

461 opt += b"\x01" 

462 continue 

463 elif oname == "EOL": 

464 opt += b"\x00" 

465 continue 

466 elif oname in TCPOptions[1]: 

467 onum = TCPOptions[1][oname] 

468 ofmt = TCPOptions[0][onum][1] 

469 if onum == 5: # SAck 

470 ofmt += "%iI" % len(oval) 

471 _test_isinstance = not isinstance(oval, (bytes, str)) 

472 if ofmt is not None and (_test_isinstance or "s" in ofmt): 

473 if not isinstance(oval, tuple): 

474 oval = (oval,) 

475 oval = struct.pack(ofmt, *oval) 

476 if onum == 29: # AO 

477 oval = bytes(oval) 

478 else: 

479 warning("Option [%s] unknown. Skipped.", oname) 

480 continue 

481 else: 

482 onum = oname 

483 if not isinstance(onum, int): 

484 warning("Invalid option number [%i]" % onum) 

485 continue 

486 if not isinstance(oval, (bytes, str)): 

487 warning("Option [%i] is not bytes." % onum) 

488 continue 

489 if isinstance(oval, str): 

490 oval = bytes_encode(oval) 

491 opt += chb(onum) + chb(2 + len(oval)) + oval 

492 return opt + b"\x00" * (3 - ((len(opt) + 3) % 4)) # Padding 

493 

494 def randval(self): 

495 return RandTCPOptions() 

496 

497 

498class ICMPTimeStampField(IntField): 

499 re_hmsm = re.compile("([0-2]?[0-9])[Hh:](([0-5]?[0-9])([Mm:]([0-5]?[0-9])([sS:.]([0-9]{0,3}))?)?)?$") # noqa: E501 

500 

501 def i2repr(self, pkt, val): 

502 if val is None: 

503 return "--" 

504 else: 

505 sec, milli = divmod(val, 1000) 

506 min, sec = divmod(sec, 60) 

507 hour, min = divmod(min, 60) 

508 return "%d:%d:%d.%d" % (hour, min, sec, int(milli)) 

509 

510 def any2i(self, pkt, val): 

511 if isinstance(val, str): 

512 hmsms = self.re_hmsm.match(val) 

513 if hmsms: 

514 h, _, m, _, s, _, ms = hmsms.groups() 

515 ms = int(((ms or "") + "000")[:3]) 

516 val = ((int(h) * 60 + int(m or 0)) * 60 + int(s or 0)) * 1000 + ms # noqa: E501 

517 else: 

518 val = 0 

519 return val 

520 

521 def i2m(self, pkt, x): 

522 if x is None: 

523 x = int((time.time() % (24 * 60 * 60)) * 1000) 

524 return super(ICMPTimeStampField, self).i2m(pkt, x) 

525 

526 

527class DestIPField(IPField, DestField): 

528 bindings = {} 

529 

530 def __init__(self, name, default): 

531 IPField.__init__(self, name, None) 

532 DestField.__init__(self, name, default) 

533 

534 def i2m(self, pkt, x): 

535 if x is None: 

536 x = self.dst_from_pkt(pkt) 

537 return IPField.i2m(self, pkt, x) 

538 

539 def i2h(self, pkt, x): 

540 if x is None: 

541 x = self.dst_from_pkt(pkt) 

542 return IPField.i2h(self, pkt, x) 

543 

544 

545class IP(Packet, IPTools): 

546 name = "IP" 

547 fields_desc = [BitField("version", 4, 4), 

548 BitField("ihl", None, 4), 

549 XByteField("tos", 0), 

550 ShortField("len", None), 

551 ShortField("id", 1), 

552 FlagsField("flags", 0, 3, ["MF", "DF", "evil"]), 

553 BitField("frag", 0, 13), 

554 ByteField("ttl", 64), 

555 ByteEnumField("proto", 0, IP_PROTOS), 

556 XShortField("chksum", None), 

557 # IPField("src", "127.0.0.1"), 

558 Emph(SourceIPField("src")), 

559 Emph(DestIPField("dst", "127.0.0.1")), 

560 PacketListField("options", [], IPOption, length_from=lambda p:p.ihl * 4 - 20)] # noqa: E501 

561 

562 def post_build(self, p, pay): 

563 ihl = self.ihl 

564 p += b"\0" * ((-len(p)) % 4) # pad IP options if needed 

565 if ihl is None: 

566 ihl = len(p) // 4 

567 p = chb(((self.version & 0xf) << 4) | ihl & 0x0f) + p[1:] 

568 if self.len is None: 

569 tmp_len = len(p) + len(pay) 

570 p = p[:2] + struct.pack("!H", tmp_len) + p[4:] 

571 if self.chksum is None: 

572 ck = checksum(p) 

573 p = p[:10] + chb(ck >> 8) + chb(ck & 0xff) + p[12:] 

574 return p + pay 

575 

576 def extract_padding(self, s): 

577 tmp_len = self.len - (self.ihl << 2) 

578 if tmp_len < 0: 

579 return s, b"" 

580 return s[:tmp_len], s[tmp_len:] 

581 

582 def route(self): 

583 dst = self.dst 

584 scope = None 

585 if isinstance(dst, (Net, _ScopedIP)): 

586 scope = dst.scope 

587 if isinstance(dst, (Gen, list)): 

588 dst = next(iter(dst)) 

589 if conf.route is None: 

590 # unused import, only to initialize conf.route 

591 import scapy.route # noqa: F401 

592 if not isinstance(dst, (str, bytes, int)): 

593 dst = str(dst) 

594 return conf.route.route(dst, dev=scope) 

595 

596 def hashret(self): 

597 if ((self.proto == socket.IPPROTO_ICMP) and 

598 (isinstance(self.payload, ICMP)) and 

599 (self.payload.type in [3, 4, 5, 11, 12])): 

600 return self.payload.payload.hashret() 

601 if not conf.checkIPinIP and self.proto in [4, 41]: # IP, IPv6 

602 return self.payload.hashret() 

603 if self.dst == "224.0.0.251": # mDNS 

604 return struct.pack("B", self.proto) + self.payload.hashret() 

605 if conf.checkIPsrc and conf.checkIPaddr: 

606 return (strxor(inet_pton(socket.AF_INET, self.src), 

607 inet_pton(socket.AF_INET, self.dst)) + 

608 struct.pack("B", self.proto) + self.payload.hashret()) 

609 return struct.pack("B", self.proto) + self.payload.hashret() 

610 

611 def answers(self, other): 

612 if not conf.checkIPinIP: # skip IP in IP and IPv6 in IP 

613 if self.proto in [4, 41]: 

614 return self.payload.answers(other) 

615 if isinstance(other, IP) and other.proto in [4, 41]: 

616 return self.answers(other.payload) 

617 if conf.ipv6_enabled \ 

618 and isinstance(other, scapy.layers.inet6.IPv6) \ 

619 and other.nh in [4, 41]: 

620 return self.answers(other.payload) 

621 if not isinstance(other, IP): 

622 return 0 

623 if conf.checkIPaddr: 

624 if other.dst == "224.0.0.251" and self.dst == "224.0.0.251": # mDNS # noqa: E501 

625 return self.payload.answers(other.payload) 

626 elif (self.dst != other.src): 

627 return 0 

628 if ((self.proto == socket.IPPROTO_ICMP) and 

629 (isinstance(self.payload, ICMP)) and 

630 (self.payload.type in [3, 4, 5, 11, 12])): 

631 # ICMP error message 

632 return self.payload.payload.answers(other) 

633 

634 else: 

635 if ((conf.checkIPaddr and (self.src != other.dst)) or 

636 (self.proto != other.proto)): 

637 return 0 

638 return self.payload.answers(other.payload) 

639 

640 def mysummary(self): 

641 s = self.sprintf("%IP.src% > %IP.dst% %IP.proto%") 

642 if self.frag: 

643 s += " frag:%i" % self.frag 

644 return s 

645 

646 def fragment(self, fragsize=1480): 

647 """Fragment IP datagrams""" 

648 return fragment(self, fragsize=fragsize) 

649 

650 

651def in4_pseudoheader(proto, u, plen): 

652 # type: (int, IP, int) -> bytes 

653 """IPv4 Pseudo Header as defined in RFC793 as bytes 

654 

655 :param proto: value of upper layer protocol 

656 :param u: IP layer instance 

657 :param plen: the length of the upper layer and payload 

658 """ 

659 u = u.copy() 

660 if u.len is not None: 

661 if u.ihl is None: 

662 olen = sum(len(x) for x in u.options) 

663 ihl = 5 + olen // 4 + (1 if olen % 4 else 0) 

664 else: 

665 ihl = u.ihl 

666 ln = max(u.len - 4 * ihl, 0) 

667 else: 

668 ln = plen 

669 

670 # Filter out IPOption_LSRR and IPOption_SSRR 

671 sr_options = [opt for opt in u.options if isinstance(opt, IPOption_LSRR) or 

672 isinstance(opt, IPOption_SSRR)] 

673 len_sr_options = len(sr_options) 

674 if len_sr_options == 1 and len(sr_options[0].routers): 

675 # The checksum must be computed using the final 

676 # destination address 

677 u.dst = sr_options[0].routers[-1] 

678 elif len_sr_options > 1: 

679 message = "Found %d Source Routing Options! " 

680 message += "Falling back to IP.dst for checksum computation." 

681 warning(message, len_sr_options) 

682 

683 return struct.pack("!4s4sHH", 

684 inet_pton(socket.AF_INET, u.src), 

685 inet_pton(socket.AF_INET, u.dst), 

686 proto, 

687 ln) 

688 

689 

690def in4_chksum(proto, u, p): 

691 # type: (int, IP, bytes) -> int 

692 """IPv4 Pseudo Header checksum as defined in RFC793 

693 

694 :param proto: value of upper layer protocol 

695 :param u: upper layer instance 

696 :param p: the payload of the upper layer provided as a string 

697 """ 

698 if not isinstance(u, IP): 

699 warning("No IP underlayer to compute checksum. Leaving null.") 

700 return 0 

701 psdhdr = in4_pseudoheader(proto, u, len(p)) 

702 return checksum(psdhdr + p) 

703 

704 

705def _is_ipv6_layer(p): 

706 # type: (Packet) -> bytes 

707 return (isinstance(p, scapy.layers.inet6.IPv6) or 

708 isinstance(p, scapy.layers.inet6._IPv6ExtHdr)) 

709 

710 

711def tcp_pseudoheader(tcp): 

712 # type: (TCP) -> bytes 

713 """Pseudoheader of a TCP packet as bytes 

714 

715 Requires underlayer to be either IP or IPv6 

716 """ 

717 if isinstance(tcp.underlayer, IP): 

718 plen = len(bytes(tcp)) 

719 return in4_pseudoheader(socket.IPPROTO_TCP, tcp.underlayer, plen) 

720 elif conf.ipv6_enabled and _is_ipv6_layer(tcp.underlayer): 

721 plen = len(bytes(tcp)) 

722 return raw(scapy.layers.inet6.in6_pseudoheader( 

723 socket.IPPROTO_TCP, tcp.underlayer, plen)) 

724 else: 

725 raise ValueError("TCP packet does not have IP or IPv6 underlayer") 

726 

727 

728def calc_tcp_md5_hash(tcp, key): 

729 # type: (TCP, bytes) -> bytes 

730 """Calculate TCP-MD5 hash from packet and return a 16-byte string""" 

731 import hashlib 

732 

733 if not isinstance(tcp, TCP): 

734 raise TypeError("calc_tcp_md5_hash requires a TCP layer") 

735 

736 tcp_bytes = bytes(tcp) 

737 if len(tcp_bytes) < 20: 

738 raise ValueError("Truncated TCP header") 

739 doff = tcp_bytes[12] >> 4 

740 h = hashlib.md5() # nosec 

741 h.update(tcp_pseudoheader(tcp)) 

742 h.update(tcp_bytes[:16]) 

743 h.update(b"\x00\x00") 

744 h.update(tcp_bytes[18:20]) 

745 h.update(tcp_bytes[doff << 2:]) 

746 h.update(key) 

747 

748 return h.digest() 

749 

750 

751def sign_tcp_md5(tcp, key): 

752 # type: (TCP, bytes) -> None 

753 """Append TCP-MD5 signature to tcp packet""" 

754 tcp.options = tcp.options + [('MD5', b'')] 

755 sig = calc_tcp_md5_hash(tcp, key) 

756 tcp.options[-1] = ('MD5', sig) 

757 

758 

759class TCP(Packet): 

760 name = "TCP" 

761 fields_desc = [ShortEnumField("sport", 20, TCP_SERVICES), 

762 ShortEnumField("dport", 80, TCP_SERVICES), 

763 IntField("seq", 0), 

764 IntField("ack", 0), 

765 BitField("dataofs", None, 4), 

766 BitField("reserved", 0, 3), 

767 FlagsField("flags", 0x2, 9, "FSRPAUECN"), 

768 ShortField("window", 8192), 

769 XShortField("chksum", None), 

770 ShortField("urgptr", 0), 

771 TCPOptionsField("options", "")] 

772 

773 def post_build(self, p, pay): 

774 p += pay 

775 dataofs = self.dataofs 

776 if dataofs is None: 

777 opt_len = len(self.get_field("options").i2m(self, self.options)) 

778 dataofs = 5 + ((opt_len + 3) // 4) 

779 dataofs = (dataofs << 4) | p[12] & 0x0f 

780 p = p[:12] + chb(dataofs & 0xff) + p[13:] 

781 if self.chksum is None: 

782 if isinstance(self.underlayer, IP): 

783 ck = in4_chksum(socket.IPPROTO_TCP, self.underlayer, p) 

784 p = p[:16] + struct.pack("!H", ck) + p[18:] 

785 elif conf.ipv6_enabled and isinstance(self.underlayer, scapy.layers.inet6.IPv6) or isinstance(self.underlayer, scapy.layers.inet6._IPv6ExtHdr): # noqa: E501 

786 ck = scapy.layers.inet6.in6_chksum(socket.IPPROTO_TCP, self.underlayer, p) # noqa: E501 

787 p = p[:16] + struct.pack("!H", ck) + p[18:] 

788 else: 

789 log_runtime.info( 

790 "No IP underlayer to compute checksum. Leaving null." 

791 ) 

792 return p 

793 

794 def hashret(self): 

795 if conf.checkIPsrc: 

796 return struct.pack("H", self.sport ^ self.dport) + self.payload.hashret() # noqa: E501 

797 else: 

798 return self.payload.hashret() 

799 

800 def answers(self, other): 

801 if not isinstance(other, TCP): 

802 return 0 

803 # RST packets don't get answers 

804 if other.flags.R: 

805 return 0 

806 # We do not support the four-way handshakes with the SYN+ACK 

807 # answer split in two packets (one ACK and one SYN): in that 

808 # case the ACK will be seen as an answer, but not the SYN. 

809 if self.flags.S: 

810 # SYN packets without ACK are not answers 

811 if not self.flags.A: 

812 return 0 

813 # SYN+ACK packets answer SYN packets 

814 if not other.flags.S: 

815 return 0 

816 if conf.checkIPsrc: 

817 if not ((self.sport == other.dport) and 

818 (self.dport == other.sport)): 

819 return 0 

820 # Do not check ack value for SYN packets without ACK 

821 if not (other.flags.S and not other.flags.A) \ 

822 and abs(other.ack - self.seq) > 2: 

823 return 0 

824 # Do not check ack value for RST packets without ACK 

825 if self.flags.R and not self.flags.A: 

826 return 1 

827 if abs(other.seq - self.ack) > 2 + len(other.payload): 

828 return 0 

829 return 1 

830 

831 def mysummary(self): 

832 if isinstance(self.underlayer, IP): 

833 return self.underlayer.sprintf("TCP %IP.src%:%TCP.sport% > %IP.dst%:%TCP.dport% %TCP.flags%") # noqa: E501 

834 elif conf.ipv6_enabled and isinstance(self.underlayer, scapy.layers.inet6.IPv6): # noqa: E501 

835 return self.underlayer.sprintf("TCP %IPv6.src%:%TCP.sport% > %IPv6.dst%:%TCP.dport% %TCP.flags%") # noqa: E501 

836 else: 

837 return self.sprintf("TCP %TCP.sport% > %TCP.dport% %TCP.flags%") 

838 

839 

840class UDP(Packet): 

841 name = "UDP" 

842 fields_desc = [ShortEnumField("sport", 53, UDP_SERVICES), 

843 ShortEnumField("dport", 53, UDP_SERVICES), 

844 ShortField("len", None), 

845 XShortField("chksum", None), ] 

846 

847 def post_build(self, p, pay): 

848 p += pay 

849 tmp_len = self.len 

850 if tmp_len is None: 

851 tmp_len = len(p) 

852 p = p[:4] + struct.pack("!H", tmp_len) + p[6:] 

853 if self.chksum is None: 

854 if isinstance(self.underlayer, IP): 

855 ck = in4_chksum(socket.IPPROTO_UDP, self.underlayer, p) 

856 # According to RFC768 if the result checksum is 0, it should be set to 0xFFFF # noqa: E501 

857 if ck == 0: 

858 ck = 0xFFFF 

859 p = p[:6] + struct.pack("!H", ck) + p[8:] 

860 elif isinstance(self.underlayer, scapy.layers.inet6.IPv6) or isinstance(self.underlayer, scapy.layers.inet6._IPv6ExtHdr): # noqa: E501 

861 ck = scapy.layers.inet6.in6_chksum(socket.IPPROTO_UDP, self.underlayer, p) # noqa: E501 

862 # According to RFC2460 if the result checksum is 0, it should be set to 0xFFFF # noqa: E501 

863 if ck == 0: 

864 ck = 0xFFFF 

865 p = p[:6] + struct.pack("!H", ck) + p[8:] 

866 else: 

867 log_runtime.info( 

868 "No IP underlayer to compute checksum. Leaving null." 

869 ) 

870 return p 

871 

872 def extract_padding(self, s): 

873 tmp_len = self.len - 8 

874 return s[:tmp_len], s[tmp_len:] 

875 

876 def hashret(self): 

877 return self.payload.hashret() 

878 

879 def answers(self, other): 

880 if not isinstance(other, UDP): 

881 return 0 

882 if conf.checkIPsrc: 

883 if self.dport != other.sport: 

884 return 0 

885 return self.payload.answers(other.payload) 

886 

887 def mysummary(self): 

888 if isinstance(self.underlayer, IP): 

889 return self.underlayer.sprintf("UDP %IP.src%:%UDP.sport% > %IP.dst%:%UDP.dport%") # noqa: E501 

890 elif isinstance(self.underlayer, scapy.layers.inet6.IPv6): 

891 return self.underlayer.sprintf("UDP %IPv6.src%:%UDP.sport% > %IPv6.dst%:%UDP.dport%") # noqa: E501 

892 else: 

893 return self.sprintf("UDP %UDP.sport% > %UDP.dport%") 

894 

895 

896# RFC 4884 ICMP extensions 

897_ICMP_classnums = { 

898 # https://www.iana.org/assignments/icmp-parameters/icmp-parameters.xhtml#icmp-parameters-ext-classes 

899 1: "MPLS", 

900 2: "Interface Information", 

901 3: "Interface Identification", 

902 4: "Extended Information", 

903} 

904 

905 

906class ICMPExtension_Object(Packet): 

907 name = "ICMP Extension Object" 

908 show_indent = 0 

909 fields_desc = [ 

910 ShortField("len", None), 

911 ByteEnumField("classnum", 0, _ICMP_classnums), 

912 ByteField("classtype", 0), 

913 ] 

914 

915 def post_build(self, p, pay): 

916 if self.len is None: 

917 tmp_len = len(p) + len(pay) 

918 p = struct.pack("!H", tmp_len) + p[2:] 

919 return p + pay 

920 

921 registered_icmp_exts = {} 

922 

923 @classmethod 

924 def register_variant(cls): 

925 cls.registered_icmp_exts[cls.classnum.default] = cls 

926 

927 @classmethod 

928 def dispatch_hook(cls, _pkt=None, *args, **kargs): 

929 if _pkt and len(_pkt) >= 4: 

930 classnum = _pkt[2] 

931 if classnum in cls.registered_icmp_exts: 

932 return cls.registered_icmp_exts[classnum] 

933 return cls 

934 

935 

936class ICMPExtension_InterfaceInformation(ICMPExtension_Object): 

937 name = "ICMP Extension Object - Interface Information Object (RFC5837)" 

938 

939 fields_desc = [ 

940 ShortField("len", None), 

941 ByteEnumField("classnum", 2, _ICMP_classnums), 

942 BitField("classtype", 0, 2), 

943 BitField("reserved", 0, 2), 

944 BitField("has_ifindex", 0, 1), 

945 BitField("has_ipaddr", 0, 1), 

946 BitField("has_ifname", 0, 1), 

947 BitField("has_mtu", 0, 1), 

948 ConditionalField(IntField("ifindex", None), lambda pkt: pkt.has_ifindex == 1), 

949 ConditionalField(ShortField("afi", None), lambda pkt: pkt.has_ipaddr == 1), 

950 ConditionalField(ShortField("reserved2", 0), lambda pkt: pkt.has_ipaddr == 1), 

951 ConditionalField(IPField("ip4", None), lambda pkt: pkt.afi == 1), 

952 ConditionalField(IP6Field("ip6", None), lambda pkt: pkt.afi == 2), 

953 ConditionalField( 

954 FieldLenField("ifname_len", None, fmt="B", length_of="ifname"), 

955 lambda pkt: pkt.has_ifname == 1, 

956 ), 

957 ConditionalField( 

958 StrLenField("ifname", None, length_from=lambda pkt: pkt.ifname_len), 

959 lambda pkt: pkt.has_ifname == 1, 

960 ), 

961 ConditionalField(IntField("mtu", None), lambda pkt: pkt.has_mtu == 1), 

962 ] 

963 

964 def self_build(self, **kwargs): 

965 if self.afi is None: 

966 if self.ip4 is not None: 

967 self.afi = 1 

968 elif self.ip6 is not None: 

969 self.afi = 2 

970 return ICMPExtension_Object.self_build(self, **kwargs) 

971 

972 

973class ICMPExtension_Header(Packet): 

974 r""" 

975 ICMP Extension per RFC4884. 

976 

977 Example:: 

978 

979 pkt = IP(dst="127.0.0.1", src="127.0.0.1") / ICMP( 

980 type="time-exceeded", 

981 code="ttl-zero-during-transit", 

982 ext=ICMPExtension_Header() / ICMPExtension_InterfaceInformation( 

983 has_ifindex=1, 

984 has_ipaddr=1, 

985 has_ifname=1, 

986 ip4="10.10.10.10", 

987 ifname="hey", 

988 ) 

989 ) / IPerror(src="12.4.4.4", dst="12.1.1.1") / \ 

990 UDPerror(sport=42315, dport=33440) / \ 

991 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 

992 """ 

993 

994 name = "ICMP Extension Header (RFC4884)" 

995 show_indent = 0 

996 fields_desc = [ 

997 BitField("version", 2, 4), 

998 BitField("reserved", 0, 12), 

999 XShortField("chksum", None), 

1000 ] 

1001 

1002 _min_ieo_len = len(ICMPExtension_Object()) 

1003 

1004 def post_build(self, p, pay): 

1005 p += pay 

1006 if self.chksum is None: 

1007 ck = checksum(p) 

1008 p = p[:2] + chb(ck >> 8) + chb(ck & 0xFF) + p[4:] 

1009 return p 

1010 

1011 def guess_payload_class(self, payload): 

1012 if len(payload) < self._min_ieo_len: 

1013 return Packet.guess_payload_class(self, payload) 

1014 return ICMPExtension_Object 

1015 

1016 

1017class _ICMPExtensionField(TrailerField): 

1018 # We use a TrailerField for building only. Dissection is normal. 

1019 

1020 def __init__(self): 

1021 super(_ICMPExtensionField, self).__init__( 

1022 PacketField( 

1023 "ext", 

1024 None, 

1025 ICMPExtension_Header, 

1026 ), 

1027 ) 

1028 

1029 def getfield(self, pkt, s): 

1030 # RFC4884 section 5.2 says if the ICMP packet length 

1031 # is >144 then ICMP extensions start at byte 137. 

1032 if len(pkt.original) < 144: 

1033 return s, None 

1034 offset = 136 + len(s) - len(pkt.original) 

1035 data = s[offset:] 

1036 # Validate checksum 

1037 if checksum(data) == data[3:5]: 

1038 return s, None # failed 

1039 # Dissect 

1040 return s[:offset], ICMPExtension_Header(data) 

1041 

1042 def addfield(self, pkt, s, val): 

1043 if val is None: 

1044 return s 

1045 data = bytes(val) 

1046 # Calc how much padding we need, not how much we deserve 

1047 pad = 136 - len(pkt.payload) - len(s) 

1048 if pad < 0: 

1049 warning("ICMPExtension_Header is after the 136th octet of ICMP.") 

1050 return data 

1051 return super(_ICMPExtensionField, self).addfield(pkt, s, b"\x00" * pad + data) 

1052 

1053 

1054class _ICMPExtensionPadField(TrailerField): 

1055 def __init__(self): 

1056 super(_ICMPExtensionPadField, self).__init__( 

1057 StrFixedLenField("extpad", "", length=0) 

1058 ) 

1059 

1060 def i2repr(self, pkt, s): 

1061 if s and s == b"\x00" * len(s): 

1062 return "b'' (%s octets)" % len(s) 

1063 return self.fld.i2repr(pkt, s) 

1064 

1065 

1066def _ICMP_extpad_post_dissection(self, pkt): 

1067 # If we have padding, put it in 'extpad' for re-build 

1068 if pkt.ext: 

1069 pad = pkt.lastlayer() 

1070 if isinstance(pad, conf.padding_layer): 

1071 pad.underlayer.remove_payload() 

1072 pkt.extpad = pad.load 

1073 

1074 

1075icmptypes = {0: "echo-reply", 

1076 3: "dest-unreach", 

1077 4: "source-quench", 

1078 5: "redirect", 

1079 8: "echo-request", 

1080 9: "router-advertisement", 

1081 10: "router-solicitation", 

1082 11: "time-exceeded", 

1083 12: "parameter-problem", 

1084 13: "timestamp-request", 

1085 14: "timestamp-reply", 

1086 15: "information-request", 

1087 16: "information-response", 

1088 17: "address-mask-request", 

1089 18: "address-mask-reply", 

1090 30: "traceroute", 

1091 31: "datagram-conversion-error", 

1092 32: "mobile-host-redirect", 

1093 33: "ipv6-where-are-you", 

1094 34: "ipv6-i-am-here", 

1095 35: "mobile-registration-request", 

1096 36: "mobile-registration-reply", 

1097 37: "domain-name-request", 

1098 38: "domain-name-reply", 

1099 39: "skip", 

1100 40: "photuris"} 

1101 

1102 

1103icmpcodes = {3: {0: "network-unreachable", 

1104 1: "host-unreachable", 

1105 2: "protocol-unreachable", 

1106 3: "port-unreachable", 

1107 4: "fragmentation-needed", 

1108 5: "source-route-failed", 

1109 6: "network-unknown", 

1110 7: "host-unknown", 

1111 9: "network-prohibited", 

1112 10: "host-prohibited", 

1113 11: "TOS-network-unreachable", 

1114 12: "TOS-host-unreachable", 

1115 13: "communication-prohibited", 

1116 14: "host-precedence-violation", 

1117 15: "precedence-cutoff", }, 

1118 5: {0: "network-redirect", 

1119 1: "host-redirect", 

1120 2: "TOS-network-redirect", 

1121 3: "TOS-host-redirect", }, 

1122 11: {0: "ttl-zero-during-transit", 

1123 1: "ttl-zero-during-reassembly", }, 

1124 12: {0: "ip-header-bad", 

1125 1: "required-option-missing", }, 

1126 40: {0: "bad-spi", 

1127 1: "authentication-failed", 

1128 2: "decompression-failed", 

1129 3: "decryption-failed", 

1130 4: "need-authentification", 

1131 5: "need-authorization", }, } 

1132 

1133 

1134_icmp_answers = [ 

1135 (8, 0), 

1136 (13, 14), 

1137 (15, 16), 

1138 (17, 18), 

1139 (33, 34), 

1140 (35, 36), 

1141 (37, 38), 

1142] 

1143 

1144icmp_id_seq_types = [0, 8, 13, 14, 15, 16, 17, 18, 37, 38] 

1145 

1146 

1147class ICMP(Packet): 

1148 name = "ICMP" 

1149 fields_desc = [ 

1150 ByteEnumField("type", 8, icmptypes), 

1151 MultiEnumField("code", 0, icmpcodes, 

1152 depends_on=lambda pkt:pkt.type, fmt="B"), 

1153 XShortField("chksum", None), 

1154 ConditionalField( 

1155 XShortField("id", 0), 

1156 lambda pkt: pkt.type in icmp_id_seq_types 

1157 ), 

1158 ConditionalField( 

1159 XShortField("seq", 0), 

1160 lambda pkt: pkt.type in icmp_id_seq_types 

1161 ), 

1162 ConditionalField( 

1163 # Timestamp only (RFC792) 

1164 ICMPTimeStampField("ts_ori", None), 

1165 lambda pkt: pkt.type in [13, 14] 

1166 ), 

1167 ConditionalField( 

1168 # Timestamp only (RFC792) 

1169 ICMPTimeStampField("ts_rx", None), 

1170 lambda pkt: pkt.type in [13, 14] 

1171 ), 

1172 ConditionalField( 

1173 # Timestamp only (RFC792) 

1174 ICMPTimeStampField("ts_tx", None), 

1175 lambda pkt: pkt.type in [13, 14] 

1176 ), 

1177 ConditionalField( 

1178 # Redirect only (RFC792) 

1179 IPField("gw", "0.0.0.0"), 

1180 lambda pkt: pkt.type == 5 

1181 ), 

1182 ConditionalField( 

1183 # Parameter problem only (RFC792) 

1184 ByteField("ptr", 0), 

1185 lambda pkt: pkt.type == 12 

1186 ), 

1187 ConditionalField( 

1188 ByteField("reserved", 0), 

1189 lambda pkt: pkt.type in [3, 11] 

1190 ), 

1191 ConditionalField( 

1192 ByteField("length", 0), 

1193 lambda pkt: pkt.type in [3, 11, 12] 

1194 ), 

1195 ConditionalField( 

1196 IPField("addr_mask", "0.0.0.0"), 

1197 lambda pkt: pkt.type in [17, 18] 

1198 ), 

1199 ConditionalField( 

1200 ShortField("nexthopmtu", 0), 

1201 lambda pkt: pkt.type == 3 

1202 ), 

1203 MultipleTypeField( 

1204 [ 

1205 (ShortField("unused", 0), 

1206 lambda pkt:pkt.type in [11, 12]), 

1207 (IntField("unused", 0), 

1208 lambda pkt:pkt.type not in [0, 3, 5, 8, 11, 12, 

1209 13, 14, 15, 16, 17, 

1210 18]) 

1211 ], 

1212 StrFixedLenField("unused", "", length=0), 

1213 ), 

1214 # RFC4884 ICMP extension 

1215 ConditionalField( 

1216 _ICMPExtensionPadField(), 

1217 lambda pkt: pkt.type in [3, 11, 12], 

1218 ), 

1219 ConditionalField( 

1220 _ICMPExtensionField(), 

1221 lambda pkt: pkt.type in [3, 11, 12], 

1222 ), 

1223 ] 

1224 

1225 # To handle extpad 

1226 post_dissection = _ICMP_extpad_post_dissection 

1227 

1228 def post_build(self, p, pay): 

1229 p += pay 

1230 if self.chksum is None: 

1231 ck = checksum(p) 

1232 p = p[:2] + chb(ck >> 8) + chb(ck & 0xff) + p[4:] 

1233 return p 

1234 

1235 def hashret(self): 

1236 if self.type in icmp_id_seq_types: 

1237 return struct.pack("HH", self.id, self.seq) + self.payload.hashret() # noqa: E501 

1238 return self.payload.hashret() 

1239 

1240 def answers(self, other): 

1241 if not isinstance(other, ICMP): 

1242 return 0 

1243 if ((other.type, self.type) in _icmp_answers and 

1244 self.id == other.id and 

1245 self.seq == other.seq): 

1246 return 1 

1247 return 0 

1248 

1249 def guess_payload_class(self, payload): 

1250 if self.type in [3, 4, 5, 11, 12]: 

1251 return IPerror 

1252 else: 

1253 return None 

1254 

1255 def mysummary(self): 

1256 extra = "" 

1257 if self.ext: 

1258 extra = self.ext.payload.sprintf(" ext:%classnum%") 

1259 if isinstance(self.underlayer, IP): 

1260 return self.underlayer.sprintf( 

1261 "ICMP %IP.src% > %IP.dst% %ICMP.type% %ICMP.code%" 

1262 ) + extra 

1263 else: 

1264 return self.sprintf("ICMP %ICMP.type% %ICMP.code%") + extra 

1265 

1266 

1267# IP / TCP / UDP error packets 

1268 

1269class IPerror(IP): 

1270 name = "IP in ICMP" 

1271 

1272 def answers(self, other): 

1273 if not isinstance(other, IP): 

1274 return 0 

1275 

1276 # Check if IP addresses match 

1277 test_IPsrc = not conf.checkIPsrc or self.src == other.src 

1278 test_IPdst = self.dst == other.dst 

1279 

1280 # Check if IP ids match 

1281 test_IPid = not conf.checkIPID or self.id == other.id 

1282 test_IPid |= conf.checkIPID and self.id == socket.htons(other.id) 

1283 

1284 # Check if IP protocols match 

1285 test_IPproto = self.proto == other.proto 

1286 

1287 if not (test_IPsrc and test_IPdst and test_IPid and test_IPproto): 

1288 return 0 

1289 

1290 return self.payload.answers(other.payload) 

1291 

1292 def mysummary(self): 

1293 return Packet.mysummary(self) 

1294 

1295 

1296class TCPerror(TCP): 

1297 name = "TCP in ICMP" 

1298 fields_desc = ( 

1299 TCP.fields_desc[:2] + 

1300 # MayEnd after the 8 first octets. 

1301 [MayEnd(TCP.fields_desc[2])] + 

1302 TCP.fields_desc[3:] 

1303 ) 

1304 

1305 def answers(self, other): 

1306 if not isinstance(other, TCP): 

1307 return 0 

1308 if conf.checkIPsrc: 

1309 if not ((self.sport == other.sport) and 

1310 (self.dport == other.dport)): 

1311 return 0 

1312 if conf.check_TCPerror_seqack: 

1313 if self.seq is not None: 

1314 if self.seq != other.seq: 

1315 return 0 

1316 if self.ack is not None: 

1317 if self.ack != other.ack: 

1318 return 0 

1319 return 1 

1320 

1321 def mysummary(self): 

1322 return Packet.mysummary(self) 

1323 

1324 

1325class UDPerror(UDP): 

1326 name = "UDP in ICMP" 

1327 

1328 def answers(self, other): 

1329 if not isinstance(other, UDP): 

1330 return 0 

1331 if conf.checkIPsrc: 

1332 if not ((self.sport == other.sport) and 

1333 (self.dport == other.dport)): 

1334 return 0 

1335 return 1 

1336 

1337 def mysummary(self): 

1338 return Packet.mysummary(self) 

1339 

1340 

1341class ICMPerror(ICMP): 

1342 name = "ICMP in ICMP" 

1343 

1344 def answers(self, other): 

1345 if not isinstance(other, ICMP): 

1346 return 0 

1347 if not ((self.type == other.type) and 

1348 (self.code == other.code)): 

1349 return 0 

1350 if self.code in [0, 8, 13, 14, 17, 18]: 

1351 if (self.id == other.id and 

1352 self.seq == other.seq): 

1353 return 1 

1354 else: 

1355 return 0 

1356 else: 

1357 return 1 

1358 

1359 def mysummary(self): 

1360 return Packet.mysummary(self) 

1361 

1362 

1363bind_layers(Ether, IP, type=2048) 

1364bind_layers(CookedLinux, IP, proto=2048) 

1365bind_layers(GRE, IP, proto=2048) 

1366bind_layers(SNAP, IP, code=2048) 

1367bind_bottom_up(Loopback, IP, type=0) 

1368bind_layers(Loopback, IP, type=socket.AF_INET) 

1369bind_layers(IPerror, IPerror, frag=0, proto=4) 

1370bind_layers(IPerror, ICMPerror, frag=0, proto=1) 

1371bind_layers(IPerror, TCPerror, frag=0, proto=6) 

1372bind_layers(IPerror, UDPerror, frag=0, proto=17) 

1373bind_layers(IP, IP, frag=0, proto=4) 

1374bind_layers(IP, ICMP, frag=0, proto=1) 

1375bind_layers(IP, TCP, frag=0, proto=6) 

1376bind_layers(IP, UDP, frag=0, proto=17) 

1377bind_layers(IP, GRE, frag=0, proto=47) 

1378bind_layers(UDP, GRE, dport=4754) 

1379 

1380conf.l2types.register(DLT_RAW, IP) 

1381conf.l2types.register_num2layer(DLT_RAW_ALT, IP) 

1382conf.l2types.register(DLT_IPV4, IP) 

1383if OPENBSD: 

1384 conf.l2types.register_num2layer(228, IP) 

1385 

1386conf.l3types.register(ETH_P_IP, IP) 

1387conf.l3types.register_num2layer(ETH_P_ALL, IP) 

1388 

1389 

1390def inet_register_l3(l2, l3): 

1391 """ 

1392 Resolves the default L2 destination address when IP is used. 

1393 """ 

1394 return getmacbyip(l3.dst) 

1395 

1396 

1397conf.neighbor.register_l3(Ether, IP, inet_register_l3) 

1398conf.neighbor.register_l3(Dot3, IP, inet_register_l3) 

1399 

1400 

1401################### 

1402# Fragmentation # 

1403################### 

1404 

1405@conf.commands.register 

1406def fragment(pkt, fragsize=1480): 

1407 """Fragment a big IP datagram""" 

1408 if fragsize < 8: 

1409 warning("fragsize cannot be lower than 8") 

1410 fragsize = max(fragsize, 8) 

1411 lastfragsz = fragsize 

1412 fragsize -= fragsize % 8 

1413 lst = [] 

1414 for p in pkt: 

1415 s = raw(p[IP].payload) 

1416 nb = (len(s) - lastfragsz + fragsize - 1) // fragsize + 1 

1417 for i in range(nb): 

1418 q = p.copy() 

1419 del q[IP].payload 

1420 del q[IP].chksum 

1421 del q[IP].len 

1422 if i != nb - 1: 

1423 q[IP].flags |= 1 

1424 fragend = (i + 1) * fragsize 

1425 else: 

1426 fragend = i * fragsize + lastfragsz 

1427 q[IP].frag += i * fragsize // 8 

1428 r = conf.raw_layer(load=s[i * fragsize:fragend]) 

1429 r.overload_fields = p[IP].payload.overload_fields.copy() 

1430 q.add_payload(r) 

1431 lst.append(q) 

1432 return lst 

1433 

1434 

1435@conf.commands.register 

1436def overlap_frag(p, overlap, fragsize=8, overlap_fragsize=None): 

1437 """Build overlapping fragments to bypass NIPS 

1438 

1439p: the original packet 

1440overlap: the overlapping data 

1441fragsize: the fragment size of the packet 

1442overlap_fragsize: the fragment size of the overlapping packet""" 

1443 

1444 if overlap_fragsize is None: 

1445 overlap_fragsize = fragsize 

1446 q = p.copy() 

1447 del q[IP].payload 

1448 q[IP].add_payload(overlap) 

1449 

1450 qfrag = fragment(q, overlap_fragsize) 

1451 qfrag[-1][IP].flags |= 1 

1452 return qfrag + fragment(p, fragsize) 

1453 

1454 

1455class MissingFragments(Exception): 

1456 pass 

1457 

1458 

1459class BadFragments(ValueError): 

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

1461 self.frags = kwargs.pop("frags", None) 

1462 super(BadFragments, self).__init__(*args, **kwargs) 

1463 

1464 

1465def _defrag_iter_and_check_offsets(frags): 

1466 """ 

1467 Internal generator used in _defrag_ip_pkt 

1468 """ 

1469 offset = 0 

1470 for pkt, o, length, mf in frags: 

1471 if offset < o: 

1472 raise MissingFragments 

1473 elif offset > o: 

1474 warning("Fragment overlap (%i > %i) on %r" % (offset, o, pkt)) 

1475 raise BadFragments 

1476 offset += length 

1477 yield bytes(pkt[IP].payload) 

1478 

1479 

1480def _defrag_ip_pkt(pkt, frags): 

1481 """ 

1482 Defragment a single IP packet. 

1483 

1484 :param pkt: the new pkt 

1485 :param frags: a defaultdict(list) used for storage 

1486 :return: a tuple (fragmented, defragmented_value) 

1487 """ 

1488 ip = pkt[IP] 

1489 if pkt.frag != 0 or ip.flags.MF: 

1490 # fragmented ! 

1491 uid = (ip.id, ip.src, ip.dst, ip.proto) 

1492 if ip.len is None or ip.ihl is None: 

1493 fraglen = len(ip.payload) 

1494 else: 

1495 fraglen = ip.len - (ip.ihl << 2) 

1496 # (pkt, frag offset, frag len, LF) 

1497 curfrags = frags[uid] 

1498 lf = (curfrags and curfrags[-1][3]) or not ip.flags.MF 

1499 curfrags.append((pkt, ip.frag << 3, fraglen, not ip.flags.MF)) 

1500 if lf: # last fragment 

1501 curfrags.sort(key=lambda x: x[1]) # sort by offset 

1502 try: 

1503 data = b"".join(_defrag_iter_and_check_offsets(curfrags)) 

1504 except MissingFragments: 

1505 return True, None 

1506 except ValueError: 

1507 # bad fragment 

1508 del frags[uid] 

1509 raise BadFragments(frags=curfrags) 

1510 # re-build initial packet without fragmentation 

1511 p = curfrags[0][0].copy() 

1512 pay_class = p[IP].payload.__class__ 

1513 p[IP].flags.MF = False 

1514 p[IP].remove_payload() 

1515 p[IP].len = None 

1516 p[IP].chksum = None 

1517 # append defragmented payload 

1518 p /= pay_class(data) 

1519 # cleanup 

1520 del frags[uid] 

1521 return True, p 

1522 return True, None 

1523 return False, pkt 

1524 

1525 

1526def _defrag_logic(plist, complete=False): 

1527 """ 

1528 Internal function used to defragment a list of packets. 

1529 It contains the logic behind the defrag() and defragment() functions 

1530 """ 

1531 frags = defaultdict(list) 

1532 final = [] 

1533 notfrag = [] 

1534 badfrag = [] 

1535 # Defrag 

1536 for i, pkt in enumerate(plist): 

1537 if IP not in pkt: 

1538 # no IP layer 

1539 if complete: 

1540 final.append(pkt) 

1541 continue 

1542 try: 

1543 fragmented, defragmented_value = _defrag_ip_pkt( 

1544 pkt, 

1545 frags, 

1546 ) 

1547 except BadFragments as ex: 

1548 if complete: 

1549 final.extend(t[0] for t in ex.frags) 

1550 else: 

1551 badfrag.extend(t[0] for t in ex.frags) 

1552 continue 

1553 if complete and defragmented_value: 

1554 final.append(defragmented_value) 

1555 elif defragmented_value: 

1556 if fragmented: 

1557 final.append(defragmented_value) 

1558 else: 

1559 notfrag.append(defragmented_value) 

1560 # Missing fragments 

1561 for lst in frags.values(): 

1562 if complete: 

1563 final.extend(t[0] for t in lst) 

1564 else: 

1565 badfrag.extend(t[0] for t in lst) 

1566 # Return 

1567 if complete: 

1568 if hasattr(plist, "listname"): 

1569 name = "Defragmented %s" % plist.listname 

1570 else: 

1571 name = "Defragmented" 

1572 return PacketList(final, name=name) 

1573 else: 

1574 return PacketList(notfrag), PacketList(final), PacketList(badfrag) 

1575 

1576 

1577@conf.commands.register 

1578def defrag(plist): 

1579 """defrag(plist) -> ([not fragmented], [defragmented], 

1580 [ [bad fragments], [bad fragments], ... ])""" 

1581 return _defrag_logic(plist, complete=False) 

1582 

1583 

1584@conf.commands.register 

1585def defragment(plist): 

1586 """defragment(plist) -> plist defragmented as much as possible """ 

1587 return _defrag_logic(plist, complete=True) 

1588 

1589 

1590# Add timeskew_graph() method to PacketList 

1591def _packetlist_timeskew_graph(self, ip, **kargs): 

1592 """Tries to graph the timeskew between the timestamps and real time for a given ip""" # noqa: E501 

1593 # Defer imports of matplotlib until its needed 

1594 # because it has a heavy dep chain 

1595 from scapy.libs.matplot import ( 

1596 plt, 

1597 MATPLOTLIB_INLINED, 

1598 MATPLOTLIB_DEFAULT_PLOT_KARGS 

1599 ) 

1600 

1601 # Filter TCP segments which source address is 'ip' 

1602 tmp = (self._elt2pkt(x) for x in self.res) 

1603 b = (x for x in tmp if IP in x and x[IP].src == ip and TCP in x) 

1604 

1605 # Build a list of tuples (creation_time, replied_timestamp) 

1606 c = [] 

1607 tsf = ICMPTimeStampField("", None) 

1608 for p in b: 

1609 opts = p.getlayer(TCP).options 

1610 for o in opts: 

1611 if o[0] == "Timestamp": 

1612 c.append((p.time, tsf.any2i("", o[1][0]))) 

1613 

1614 # Stop if the list is empty 

1615 if not c: 

1616 warning("No timestamps found in packet list") 

1617 return [] 

1618 

1619 # Prepare the data that will be plotted 

1620 first_creation_time = c[0][0] 

1621 first_replied_timestamp = c[0][1] 

1622 

1623 def _wrap_data(ts_tuple, wrap_seconds=2000): 

1624 """Wrap the list of tuples.""" 

1625 

1626 ct, rt = ts_tuple # (creation_time, replied_timestamp) 

1627 X = ct % wrap_seconds 

1628 Y = ((ct - first_creation_time) - ((rt - first_replied_timestamp) / 1000.0)) # noqa: E501 

1629 

1630 return X, Y 

1631 

1632 data = [_wrap_data(e) for e in c] 

1633 

1634 # Mimic the default gnuplot output 

1635 if kargs == {}: 

1636 kargs = MATPLOTLIB_DEFAULT_PLOT_KARGS 

1637 lines = plt.plot(data, **kargs) 

1638 

1639 # Call show() if matplotlib is not inlined 

1640 if not MATPLOTLIB_INLINED: 

1641 plt.show() 

1642 

1643 return lines 

1644 

1645 

1646_PacketList.timeskew_graph = _packetlist_timeskew_graph 

1647 

1648 

1649# Create a new packet list 

1650class TracerouteResult(SndRcvList): 

1651 __slots__ = ["graphdef", "graphpadding", "graphASres", "padding", "hloc", 

1652 "nloc"] 

1653 

1654 def __init__(self, res=None, name="Traceroute", stats=None): 

1655 SndRcvList.__init__(self, res, name, stats) 

1656 self.graphdef = None 

1657 self.graphASres = None 

1658 self.padding = 0 

1659 self.hloc = None 

1660 self.nloc = None 

1661 

1662 def show(self): 

1663 return self.make_table(lambda s, r: (s.sprintf("%IP.dst%:{TCP:tcp%ir,TCP.dport%}{UDP:udp%ir,UDP.dport%}{ICMP:ICMP}"), # noqa: E501 

1664 s.ttl, 

1665 r.sprintf("%-15s,IP.src% {TCP:%TCP.flags%}{ICMP:%ir,ICMP.type%}"))) # noqa: E501 

1666 

1667 def get_trace(self): 

1668 trace = {} 

1669 for s, r in self.res: 

1670 if IP not in s: 

1671 continue 

1672 d = s[IP].dst 

1673 if d not in trace: 

1674 trace[d] = {} 

1675 trace[d][s[IP].ttl] = r[IP].src, ICMP not in r 

1676 for k in trace.values(): 

1677 try: 

1678 m = min(x for x, y in k.items() if y[1]) 

1679 except ValueError: 

1680 continue 

1681 for li in list(k): # use list(): k is modified in the loop 

1682 if li > m: 

1683 del k[li] 

1684 return trace 

1685 

1686 def trace3D(self, join=True): 

1687 """Give a 3D representation of the traceroute. 

1688 right button: rotate the scene 

1689 middle button: zoom 

1690 shift-left button: move the scene 

1691 left button on a ball: toggle IP displaying 

1692 double-click button on a ball: scan ports 21,22,23,25,80 and 443 and display the result""" # noqa: E501 

1693 # When not ran from a notebook, vpython pooly closes itself 

1694 # using os._exit once finished. We pack it into a Process 

1695 import multiprocessing 

1696 p = multiprocessing.Process(target=self.trace3D_notebook) 

1697 p.start() 

1698 if join: 

1699 p.join() 

1700 

1701 def trace3D_notebook(self): 

1702 """Same than trace3D, used when ran from Jupyter notebooks""" 

1703 trace = self.get_trace() 

1704 import vpython 

1705 

1706 class IPsphere(vpython.sphere): 

1707 def __init__(self, ip, **kargs): 

1708 vpython.sphere.__init__(self, **kargs) 

1709 self.ip = ip 

1710 self.label = None 

1711 self.setlabel(self.ip) 

1712 self.last_clicked = None 

1713 self.full = False 

1714 self.savcolor = vpython.vec(*self.color.value) 

1715 

1716 def fullinfos(self): 

1717 self.full = True 

1718 self.color = vpython.vec(1, 0, 0) 

1719 a, b = sr(IP(dst=self.ip) / TCP(dport=[21, 22, 23, 25, 80, 443], flags="S"), timeout=2, verbose=0) # noqa: E501 

1720 if len(a) == 0: 

1721 txt = "%s:\nno results" % self.ip 

1722 else: 

1723 txt = "%s:\n" % self.ip 

1724 for s, r in a: 

1725 txt += r.sprintf("{TCP:%IP.src%:%TCP.sport% %TCP.flags%}{TCPerror:%IPerror.dst%:%TCPerror.dport% %IP.src% %ir,ICMP.type%}\n") # noqa: E501 

1726 self.setlabel(txt, visible=1) 

1727 

1728 def unfull(self): 

1729 self.color = self.savcolor 

1730 self.full = False 

1731 self.setlabel(self.ip) 

1732 

1733 def setlabel(self, txt, visible=None): 

1734 if self.label is not None: 

1735 if visible is None: 

1736 visible = self.label.visible 

1737 self.label.visible = 0 

1738 elif visible is None: 

1739 visible = 0 

1740 self.label = vpython.label(text=txt, pos=self.pos, space=self.radius, xoffset=10, yoffset=20, visible=visible) # noqa: E501 

1741 

1742 def check_double_click(self): 

1743 try: 

1744 if self.full or not self.label.visible: 

1745 return False 

1746 if self.last_clicked is not None: 

1747 return (time.time() - self.last_clicked) < 0.5 

1748 return False 

1749 finally: 

1750 self.last_clicked = time.time() 

1751 

1752 def action(self): 

1753 self.label.visible ^= 1 

1754 if self.full: 

1755 self.unfull() 

1756 

1757 vpython.scene = vpython.canvas() 

1758 vpython.scene.title = "<center><u><b>%s</b></u></center>" % self.listname # noqa: E501 

1759 vpython.scene.append_to_caption( 

1760 re.sub( 

1761 r'\%(.*)\%', 

1762 r'<span style="color: red">\1</span>', 

1763 re.sub( 

1764 r'\`(.*)\`', 

1765 r'<span style="color: #3399ff">\1</span>', 

1766 """<u><b>Commands:</b></u> 

1767%Click% to toggle information about a node. 

1768%Double click% to perform a quick web scan on this node. 

1769<u><b>Camera usage:</b></u> 

1770`Right button drag or Ctrl-drag` to rotate "camera" to view scene. 

1771`Shift-drag` to move the object around. 

1772`Middle button or Alt-drag` to drag up or down to zoom in or out. 

1773 On a two-button mouse, `middle is wheel or left + right`. 

1774Touch screen: pinch/extend to zoom, swipe or two-finger rotate.""" 

1775 ) 

1776 ) 

1777 ) 

1778 vpython.scene.exit = True 

1779 rings = {} 

1780 tr3d = {} 

1781 for i in trace: 

1782 tr = trace[i] 

1783 tr3d[i] = [] 

1784 for t in range(1, max(tr) + 1): 

1785 if t not in rings: 

1786 rings[t] = [] 

1787 if t in tr: 

1788 if tr[t] not in rings[t]: 

1789 rings[t].append(tr[t]) 

1790 tr3d[i].append(rings[t].index(tr[t])) 

1791 else: 

1792 rings[t].append(("unk", -1)) 

1793 tr3d[i].append(len(rings[t]) - 1) 

1794 

1795 for t in rings: 

1796 r = rings[t] 

1797 tmp_len = len(r) 

1798 for i in range(tmp_len): 

1799 if r[i][1] == -1: 

1800 col = vpython.vec(0.75, 0.75, 0.75) 

1801 elif r[i][1]: 

1802 col = vpython.color.green 

1803 else: 

1804 col = vpython.color.blue 

1805 

1806 s = IPsphere(pos=vpython.vec((tmp_len - 1) * vpython.cos(2 * i * vpython.pi / tmp_len), (tmp_len - 1) * vpython.sin(2 * i * vpython.pi / tmp_len), 2 * t), # noqa: E501 

1807 ip=r[i][0], 

1808 color=col) 

1809 for trlst in tr3d.values(): 

1810 if t <= len(trlst): 

1811 if trlst[t - 1] == i: 

1812 trlst[t - 1] = s 

1813 forecol = colgen(0.625, 0.4375, 0.25, 0.125) 

1814 for trlst in tr3d.values(): 

1815 col = vpython.vec(*next(forecol)) 

1816 start = vpython.vec(0, 0, 0) 

1817 for ip in trlst: 

1818 vpython.cylinder(pos=start, axis=ip.pos - start, color=col, radius=0.2) # noqa: E501 

1819 start = ip.pos 

1820 

1821 vpython.rate(50) 

1822 

1823 # Keys handling 

1824 # TODO: there is currently no way of closing vpython correctly 

1825 # https://github.com/BruceSherwood/vpython-jupyter/issues/36 

1826 # def keyboard_press(ev): 

1827 # k = ev.key 

1828 # if k == "esc" or k == "q": 

1829 # pass # TODO: close 

1830 # 

1831 # vpython.scene.bind('keydown', keyboard_press) 

1832 

1833 # Mouse handling 

1834 def mouse_click(ev): 

1835 if ev.press == "left": 

1836 o = vpython.scene.mouse.pick 

1837 if o and isinstance(o, IPsphere): 

1838 if o.check_double_click(): 

1839 if o.ip == "unk": 

1840 return 

1841 o.fullinfos() 

1842 else: 

1843 o.action() 

1844 

1845 vpython.scene.bind('mousedown', mouse_click) 

1846 

1847 def world_trace(self): 

1848 """Display traceroute results on a world map.""" 

1849 

1850 # Check that the geoip2 module can be imported 

1851 # Doc: http://geoip2.readthedocs.io/en/latest/ 

1852 from scapy.libs.matplot import plt, MATPLOTLIB, MATPLOTLIB_INLINED 

1853 

1854 try: 

1855 # GeoIP2 modules need to be imported as below 

1856 import geoip2.database 

1857 import geoip2.errors 

1858 except ImportError: 

1859 log_runtime.error( 

1860 "Cannot import geoip2. Won't be able to plot the world." 

1861 ) 

1862 return [] 

1863 # Check availability of database 

1864 if not conf.geoip_city: 

1865 log_runtime.error( 

1866 "Cannot import the geolite2 CITY database.\n" 

1867 "Download it from http://dev.maxmind.com/geoip/geoip2/geolite2/" # noqa: E501 

1868 " then set its path to conf.geoip_city" 

1869 ) 

1870 return [] 

1871 # Check availability of plotting devices 

1872 try: 

1873 import cartopy.crs as ccrs 

1874 except ImportError: 

1875 log_runtime.error( 

1876 "Cannot import cartopy.\n" 

1877 "More infos on http://scitools.org.uk/cartopy/docs/latest/installing.html" # noqa: E501 

1878 ) 

1879 return [] 

1880 if not MATPLOTLIB: 

1881 log_runtime.error( 

1882 "Matplotlib is not installed. Won't be able to plot the world." 

1883 ) 

1884 return [] 

1885 

1886 # Open & read the GeoListIP2 database 

1887 try: 

1888 db = geoip2.database.Reader(conf.geoip_city) 

1889 except Exception: 

1890 log_runtime.error( 

1891 "Cannot open geoip2 database at %s", 

1892 conf.geoip_city 

1893 ) 

1894 return [] 

1895 

1896 # Regroup results per trace 

1897 ips = {} 

1898 rt = {} 

1899 ports_done = {} 

1900 for s, r in self.res: 

1901 ips[r.src] = None 

1902 if s.haslayer(TCP) or s.haslayer(UDP): 

1903 trace_id = (s.src, s.dst, s.proto, s.dport) 

1904 elif s.haslayer(ICMP): 

1905 trace_id = (s.src, s.dst, s.proto, s.type) 

1906 else: 

1907 trace_id = (s.src, s.dst, s.proto, 0) 

1908 trace = rt.get(trace_id, {}) 

1909 if not r.haslayer(ICMP) or r.type != 11: 

1910 if trace_id in ports_done: 

1911 continue 

1912 ports_done[trace_id] = None 

1913 trace[s.ttl] = r.src 

1914 rt[trace_id] = trace 

1915 

1916 # Get the addresses locations 

1917 trt = {} 

1918 for trace_id in rt: 

1919 trace = rt[trace_id] 

1920 loctrace = [] 

1921 for i in range(max(trace)): 

1922 ip = trace.get(i, None) 

1923 if ip is None: 

1924 continue 

1925 # Fetch database 

1926 try: 

1927 sresult = db.city(ip) 

1928 except geoip2.errors.AddressNotFoundError: 

1929 continue 

1930 loctrace.append((sresult.location.longitude, sresult.location.latitude)) # noqa: E501 

1931 if loctrace: 

1932 trt[trace_id] = loctrace 

1933 

1934 # Load the map renderer 

1935 plt.figure(num='Scapy') 

1936 ax = plt.axes(projection=ccrs.PlateCarree()) 

1937 # Draw countries 

1938 ax.coastlines() 

1939 ax.stock_img() 

1940 # Set normal size 

1941 ax.set_global() 

1942 # Add title 

1943 plt.title("Scapy traceroute results") 

1944 

1945 from matplotlib.collections import LineCollection 

1946 from matplotlib import colors as mcolors 

1947 colors_cycle = iter(mcolors.BASE_COLORS) 

1948 lines = [] 

1949 

1950 # Split traceroute measurement 

1951 for key, trc in trt.items(): 

1952 # Get next color 

1953 color = next(colors_cycle) 

1954 # Gather mesurments data 

1955 data_lines = [(trc[i], trc[i + 1]) for i in range(len(trc) - 1)] 

1956 # Create line collection 

1957 line_col = LineCollection(data_lines, linewidths=2, 

1958 label=key[1], 

1959 color=color) 

1960 lines.append(line_col) 

1961 ax.add_collection(line_col) 

1962 # Create map points 

1963 lines.extend([ax.plot(*x, marker='.', color=color) for x in trc]) 

1964 

1965 # Generate legend 

1966 ax.legend() 

1967 

1968 # Call show() if matplotlib is not inlined 

1969 if not MATPLOTLIB_INLINED: 

1970 plt.show() 

1971 

1972 # Clean 

1973 ax.remove() 

1974 

1975 # Return the drawn lines 

1976 return lines 

1977 

1978 def make_graph(self, ASres=None, padding=0): 

1979 self.graphASres = ASres 

1980 self.graphpadding = padding 

1981 ips = {} 

1982 rt = {} 

1983 ports = {} 

1984 ports_done = {} 

1985 for s, r in self.res: 

1986 r = r.getlayer(IP) or (conf.ipv6_enabled and r[scapy.layers.inet6.IPv6]) or r # noqa: E501 

1987 s = s.getlayer(IP) or (conf.ipv6_enabled and s[scapy.layers.inet6.IPv6]) or s # noqa: E501 

1988 ips[r.src] = None 

1989 if TCP in s: 

1990 trace_id = (s.src, s.dst, 6, s.dport) 

1991 elif UDP in s: 

1992 trace_id = (s.src, s.dst, 17, s.dport) 

1993 elif ICMP in s: 

1994 trace_id = (s.src, s.dst, 1, s.type) 

1995 else: 

1996 trace_id = (s.src, s.dst, s.proto, 0) 

1997 trace = rt.get(trace_id, {}) 

1998 ttl = conf.ipv6_enabled and scapy.layers.inet6.IPv6 in s and s.hlim or s.ttl # noqa: E501 

1999 if not (ICMP in r and r[ICMP].type == 11) and not (conf.ipv6_enabled and scapy.layers.inet6.IPv6 in r and scapy.layers.inet6.ICMPv6TimeExceeded in r): # noqa: E501 

2000 if trace_id in ports_done: 

2001 continue 

2002 ports_done[trace_id] = None 

2003 p = ports.get(r.src, []) 

2004 if TCP in r: 

2005 p.append(r.sprintf("<T%ir,TCP.sport%> %TCP.sport% %TCP.flags%")) # noqa: E501 

2006 trace[ttl] = r.sprintf('"%r,src%":T%ir,TCP.sport%') 

2007 elif UDP in r: 

2008 p.append(r.sprintf("<U%ir,UDP.sport%> %UDP.sport%")) 

2009 trace[ttl] = r.sprintf('"%r,src%":U%ir,UDP.sport%') 

2010 elif ICMP in r: 

2011 p.append(r.sprintf("<I%ir,ICMP.type%> ICMP %ICMP.type%")) 

2012 trace[ttl] = r.sprintf('"%r,src%":I%ir,ICMP.type%') 

2013 else: 

2014 p.append(r.sprintf("{IP:<P%ir,proto%> IP %proto%}{IPv6:<P%ir,nh%> IPv6 %nh%}")) # noqa: E501 

2015 trace[ttl] = r.sprintf('"%r,src%":{IP:P%ir,proto%}{IPv6:P%ir,nh%}') # noqa: E501 

2016 ports[r.src] = p 

2017 else: 

2018 trace[ttl] = r.sprintf('"%r,src%"') 

2019 rt[trace_id] = trace 

2020 

2021 # Fill holes with unk%i nodes 

2022 unknown_label = incremental_label("unk%i") 

2023 blackholes = [] 

2024 bhip = {} 

2025 for rtk in rt: 

2026 trace = rt[rtk] 

2027 max_trace = max(trace) 

2028 for n in range(min(trace), max_trace): 

2029 if n not in trace: 

2030 trace[n] = next(unknown_label) 

2031 if rtk not in ports_done: 

2032 if rtk[2] == 1: # ICMP 

2033 bh = "%s %i/icmp" % (rtk[1], rtk[3]) 

2034 elif rtk[2] == 6: # TCP 

2035 bh = "%s %i/tcp" % (rtk[1], rtk[3]) 

2036 elif rtk[2] == 17: # UDP 

2037 bh = '%s %i/udp' % (rtk[1], rtk[3]) 

2038 else: 

2039 bh = '%s %i/proto' % (rtk[1], rtk[2]) 

2040 ips[bh] = None 

2041 bhip[rtk[1]] = bh 

2042 bh = '"%s"' % bh 

2043 trace[max_trace + 1] = bh 

2044 blackholes.append(bh) 

2045 

2046 # Find AS numbers 

2047 ASN_query_list = set(x.rsplit(" ", 1)[0] for x in ips) 

2048 if ASres is None: 

2049 ASNlist = [] 

2050 else: 

2051 ASNlist = ASres.resolve(*ASN_query_list) 

2052 

2053 ASNs = {} 

2054 ASDs = {} 

2055 for ip, asn, desc, in ASNlist: 

2056 if asn is None: 

2057 continue 

2058 iplist = ASNs.get(asn, []) 

2059 if ip in bhip: 

2060 if ip in ports: 

2061 iplist.append(ip) 

2062 iplist.append(bhip[ip]) 

2063 else: 

2064 iplist.append(ip) 

2065 ASNs[asn] = iplist 

2066 ASDs[asn] = desc 

2067 

2068 backcolorlist = colgen("60", "86", "ba", "ff") 

2069 forecolorlist = colgen("a0", "70", "40", "20") 

2070 

2071 s = "digraph trace {\n" 

2072 

2073 s += "\n\tnode [shape=ellipse,color=black,style=solid];\n\n" 

2074 

2075 s += "\n#ASN clustering\n" 

2076 for asn in ASNs: 

2077 s += '\tsubgraph cluster_%s {\n' % asn 

2078 col = next(backcolorlist) 

2079 s += '\t\tcolor="#%s%s%s";' % col 

2080 s += '\t\tnode [fillcolor="#%s%s%s",style=filled];' % col 

2081 s += '\t\tfontsize = 10;' 

2082 s += '\t\tlabel = "%s\\n[%s]"\n' % ( 

2083 graphviz_escape(asn), 

2084 graphviz_escape(ASDs[asn]), 

2085 ) 

2086 for ip in ASNs[asn]: 

2087 

2088 s += '\t\t"%s";\n' % ip 

2089 s += "\t}\n" 

2090 

2091 s += "#endpoints\n" 

2092 for p in ports: 

2093 s += '\t"%s" [shape=record,color=black,fillcolor=green,style=filled,label="%s|%s"];\n' % (p, p, "|".join(ports[p])) # noqa: E501 

2094 

2095 s += "\n#Blackholes\n" 

2096 for bh in blackholes: 

2097 s += '\t%s [shape=octagon,color=black,fillcolor=red,style=filled];\n' % bh # noqa: E501 

2098 

2099 if padding: 

2100 s += "\n#Padding\n" 

2101 pad = {} 

2102 for snd, rcv in self.res: 

2103 if rcv.src not in ports and rcv.haslayer(conf.padding_layer): 

2104 p = rcv.getlayer(conf.padding_layer).load 

2105 if p != b"\x00" * len(p): 

2106 pad[rcv.src] = None 

2107 for rcv in pad: 

2108 s += '\t"%s" [shape=triangle,color=black,fillcolor=red,style=filled];\n' % rcv # noqa: E501 

2109 

2110 s += "\n\tnode [shape=ellipse,color=black,style=solid];\n\n" 

2111 

2112 for rtk in rt: 

2113 s += "#---[%s\n" % repr(rtk) 

2114 s += '\t\tedge [color="#%s%s%s"];\n' % next(forecolorlist) 

2115 trace = rt[rtk] 

2116 maxtrace = max(trace) 

2117 for n in range(min(trace), maxtrace): 

2118 s += '\t%s ->\n' % trace[n] 

2119 s += '\t%s;\n' % trace[maxtrace] 

2120 

2121 s += "}\n" 

2122 self.graphdef = s 

2123 

2124 def graph(self, ASres=conf.AS_resolver, padding=0, **kargs): 

2125 """x.graph(ASres=conf.AS_resolver, other args): 

2126 ASres=None : no AS resolver => no clustering 

2127 ASres=AS_resolver() : default whois AS resolver (riswhois.ripe.net) 

2128 ASres=AS_resolver_cymru(): use whois.cymru.com whois database 

2129 ASres=AS_resolver(server="whois.ra.net") 

2130 type: output type (svg, ps, gif, jpg, etc.), passed to dot's "-T" option # noqa: E501 

2131 target: filename or redirect. Defaults pipe to Imagemagick's display program # noqa: E501 

2132 prog: which graphviz program to use""" 

2133 if (self.graphdef is None or 

2134 self.graphASres != ASres or 

2135 self.graphpadding != padding): 

2136 self.make_graph(ASres, padding) 

2137 

2138 return do_graph(self.graphdef, **kargs) 

2139 

2140 

2141@conf.commands.register 

2142def traceroute(target, dport=80, minttl=1, maxttl=30, sport=RandShort(), l4=None, filter=None, timeout=2, verbose=None, **kargs): # noqa: E501 

2143 """Instant TCP traceroute 

2144 

2145 :param target: hostnames or IP addresses 

2146 :param dport: TCP destination port (default is 80) 

2147 :param minttl: minimum TTL (default is 1) 

2148 :param maxttl: maximum TTL (default is 30) 

2149 :param sport: TCP source port (default is random) 

2150 :param l4: use a Scapy packet instead of TCP 

2151 :param filter: BPF filter applied to received packets 

2152 :param timeout: time to wait for answers (default is 2s) 

2153 :param verbose: detailed output 

2154 :return: an TracerouteResult, and a list of unanswered packets""" 

2155 if verbose is None: 

2156 verbose = conf.verb 

2157 if filter is None: 

2158 # we only consider ICMP error packets and TCP packets with at 

2159 # least the ACK flag set *and* either the SYN or the RST flag 

2160 # set 

2161 filter = "(icmp and (icmp[0]=3 or icmp[0]=4 or icmp[0]=5 or icmp[0]=11 or icmp[0]=12)) or (tcp and (tcp[13] & 0x16 > 0x10))" # noqa: E501 

2162 if l4 is None: 

2163 a, b = sr(IP(dst=target, id=RandShort(), ttl=(minttl, maxttl)) / TCP(seq=RandInt(), sport=sport, dport=dport), # noqa: E501 

2164 timeout=timeout, filter=filter, verbose=verbose, **kargs) 

2165 else: 

2166 # this should always work 

2167 filter = "ip" 

2168 a, b = sr(IP(dst=target, id=RandShort(), ttl=(minttl, maxttl)) / l4, 

2169 timeout=timeout, filter=filter, verbose=verbose, **kargs) 

2170 

2171 a = TracerouteResult(a.res) 

2172 if verbose: 

2173 a.show() 

2174 return a, b 

2175 

2176 

2177@conf.commands.register 

2178def traceroute_map(ips, **kargs): 

2179 """Util function to call traceroute on multiple targets, then 

2180 show the different paths on a map. 

2181 

2182 :param ips: a list of IPs on which traceroute will be called 

2183 :param kargs: (optional) kwargs, passed to traceroute 

2184 """ 

2185 kargs.setdefault("verbose", 0) 

2186 return traceroute(ips)[0].world_trace() 

2187 

2188############################# 

2189# Simple TCP client stack # 

2190############################# 

2191 

2192 

2193class TCP_client(Automaton): 

2194 """ 

2195 Creates a TCP Client Automaton. 

2196 This automaton will handle TCP 3-way handshake. 

2197 

2198 Usage: the easiest usage is to use it as a SuperSocket. 

2199 >>> a = TCP_client.tcplink(HTTP, "www.google.com", 80) 

2200 >>> a.send(HTTPRequest()) 

2201 >>> a.recv() 

2202 

2203 :param ip: the ip to connect to 

2204 :param port: 

2205 :param src: (optional) use another source IP 

2206 :param sport: (optional) the TCP source port (default: random) 

2207 :param seq: (optional) initial TCP sequence number (default: random) 

2208 """ 

2209 

2210 def parse_args(self, ip, port, srcip=None, sport=None, seq=None, ack=0, **kargs): 

2211 from scapy.sessions import TCPSession 

2212 self.dst = str(Net(ip)) 

2213 self.dport = port 

2214 self.sport = sport if sport is not None else random.randrange(0, 2**16) 

2215 self.l4 = IP(dst=ip, src=srcip) / TCP( 

2216 sport=self.sport, dport=self.dport, 

2217 flags=0, 

2218 seq=seq if seq is not None else random.randrange(0, 2**32), 

2219 ack=ack, 

2220 ) 

2221 self.src = self.l4.src 

2222 self.sack = self.l4[TCP].ack 

2223 self.rel_seq = None 

2224 self.rcvbuf = TCPSession() 

2225 bpf = "host %s and host %s and port %i and port %i" % (self.src, 

2226 self.dst, 

2227 self.sport, 

2228 self.dport) 

2229 Automaton.parse_args(self, filter=bpf, **kargs) 

2230 

2231 def _transmit_packet(self, pkt): 

2232 """Transmits a packet from TCPSession to the SuperSocket""" 

2233 self.oi.tcp.send(raw(pkt[TCP].payload)) 

2234 

2235 def master_filter(self, pkt): 

2236 return (IP in pkt and 

2237 pkt[IP].src == self.dst and 

2238 pkt[IP].dst == self.src and 

2239 TCP in pkt and 

2240 pkt[TCP].sport == self.dport and 

2241 pkt[TCP].dport == self.sport and 

2242 self.l4[TCP].seq >= pkt[TCP].ack and # XXX: seq/ack 2^32 wrap up # noqa: E501 

2243 ((self.l4[TCP].ack == 0) or (self.sack <= pkt[TCP].seq <= self.l4[TCP].ack + pkt[TCP].window))) # noqa: E501 

2244 

2245 @ATMT.state(initial=1) 

2246 def START(self): 

2247 pass 

2248 

2249 @ATMT.state() 

2250 def SYN_SENT(self): 

2251 pass 

2252 

2253 @ATMT.state() 

2254 def ESTABLISHED(self): 

2255 pass 

2256 

2257 @ATMT.state() 

2258 def LAST_ACK(self): 

2259 pass 

2260 

2261 @ATMT.state(final=1) 

2262 def CLOSED(self): 

2263 pass 

2264 

2265 @ATMT.state(stop=1) 

2266 def STOP(self): 

2267 pass 

2268 

2269 @ATMT.state() 

2270 def STOP_SENT_FIN_ACK(self): 

2271 pass 

2272 

2273 @ATMT.condition(START) 

2274 def connect(self): 

2275 raise self.SYN_SENT() 

2276 

2277 @ATMT.action(connect) 

2278 def send_syn(self): 

2279 self.l4[TCP].flags = "S" 

2280 self.send(self.l4) 

2281 self.l4[TCP].seq += 1 

2282 

2283 @ATMT.receive_condition(SYN_SENT) 

2284 def synack_received(self, pkt): 

2285 if pkt[TCP].flags.SA: 

2286 raise self.ESTABLISHED().action_parameters(pkt) 

2287 

2288 @ATMT.action(synack_received) 

2289 def send_ack_of_synack(self, pkt): 

2290 self.l4[TCP].ack = pkt[TCP].seq + 1 

2291 self.l4[TCP].flags = "A" 

2292 self.send(self.l4) 

2293 

2294 @ATMT.receive_condition(ESTABLISHED) 

2295 def incoming_data_received(self, pkt): 

2296 if not isinstance(pkt[TCP].payload, (NoPayload, conf.padding_layer)): 

2297 raise self.ESTABLISHED().action_parameters(pkt) 

2298 

2299 @ATMT.action(incoming_data_received) 

2300 def receive_data(self, pkt): 

2301 data = raw(pkt[TCP].payload) 

2302 if data and self.l4[TCP].ack == pkt[TCP].seq: 

2303 self.sack = self.l4[TCP].ack 

2304 self.l4[TCP].ack += len(data) 

2305 self.l4[TCP].flags = "A" 

2306 # Answer with an Ack 

2307 self.send(self.l4) 

2308 # Process data - will be sent to the SuperSocket through this 

2309 pkt = self.rcvbuf.process(pkt) 

2310 if pkt: 

2311 self._transmit_packet(pkt) 

2312 

2313 @ATMT.ioevent(ESTABLISHED, name="tcp", as_supersocket="tcplink") 

2314 def outgoing_data_received(self, fd): 

2315 raise self.ESTABLISHED().action_parameters(fd.recv()) 

2316 

2317 @ATMT.action(outgoing_data_received) 

2318 def send_data(self, d): 

2319 self.l4[TCP].flags = "PA" 

2320 self.send(self.l4 / d) 

2321 self.l4[TCP].seq += len(d) 

2322 

2323 @ATMT.receive_condition(ESTABLISHED) 

2324 def reset_received(self, pkt): 

2325 if pkt[TCP].flags.R: 

2326 raise self.CLOSED() 

2327 

2328 @ATMT.receive_condition(ESTABLISHED) 

2329 def fin_received(self, pkt): 

2330 if pkt[TCP].flags.F: 

2331 raise self.LAST_ACK().action_parameters(pkt) 

2332 

2333 @ATMT.action(fin_received) 

2334 def send_finack(self, pkt): 

2335 self.l4[TCP].flags = "FA" 

2336 self.l4[TCP].ack = pkt[TCP].seq + 1 

2337 self.send(self.l4) 

2338 self.l4[TCP].seq += 1 

2339 

2340 @ATMT.receive_condition(LAST_ACK) 

2341 def ack_of_fin_received(self, pkt): 

2342 if pkt[TCP].flags.A: 

2343 raise self.CLOSED() 

2344 

2345 @ATMT.condition(STOP) 

2346 def stop_requested(self): 

2347 raise self.STOP_SENT_FIN_ACK() 

2348 

2349 @ATMT.action(stop_requested) 

2350 def stop_send_finack(self): 

2351 self.l4[TCP].flags = "FA" 

2352 self.send(self.l4) 

2353 self.l4[TCP].seq += 1 

2354 

2355 @ATMT.receive_condition(STOP_SENT_FIN_ACK) 

2356 def stop_fin_received(self, pkt): 

2357 if pkt[TCP].flags.F: 

2358 raise self.CLOSED().action_parameters(pkt) 

2359 

2360 @ATMT.action(stop_fin_received) 

2361 def stop_send_ack(self, pkt): 

2362 self.l4[TCP].flags = "A" 

2363 self.l4[TCP].ack = pkt[TCP].seq + 1 

2364 self.send(self.l4) 

2365 

2366 @ATMT.timeout(SYN_SENT, 1) 

2367 def syn_ack_timeout(self): 

2368 raise self.CLOSED() 

2369 

2370 @ATMT.timeout(STOP_SENT_FIN_ACK, 1) 

2371 def stop_ack_timeout(self): 

2372 raise self.CLOSED() 

2373 

2374 

2375##################### 

2376# Reporting stuff # 

2377##################### 

2378 

2379 

2380@conf.commands.register 

2381def report_ports(target, ports): 

2382 """portscan a target and output a LaTeX table 

2383report_ports(target, ports) -> string""" 

2384 ans, unans = sr(IP(dst=target) / TCP(dport=ports), timeout=5) 

2385 rep = "\\begin{tabular}{|r|l|l|}\n\\hline\n" 

2386 for s, r in ans: 

2387 if not r.haslayer(ICMP): 

2388 if r.payload.flags == 0x12: 

2389 rep += r.sprintf("%TCP.sport% & open & SA \\\\\n") 

2390 rep += "\\hline\n" 

2391 for s, r in ans: 

2392 if r.haslayer(ICMP): 

2393 rep += r.sprintf("%TCPerror.dport% & closed & ICMP type %ICMP.type%/%ICMP.code% from %IP.src% \\\\\n") # noqa: E501 

2394 elif r.payload.flags != 0x12: 

2395 rep += r.sprintf("%TCP.sport% & closed & TCP %TCP.flags% \\\\\n") 

2396 rep += "\\hline\n" 

2397 for i in unans: 

2398 rep += i.sprintf("%TCP.dport% & ? & unanswered \\\\\n") 

2399 rep += "\\hline\n\\end{tabular}\n" 

2400 return rep 

2401 

2402 

2403@conf.commands.register 

2404def IPID_count(lst, funcID=lambda x: x[1].id, funcpres=lambda x: x[1].summary()): # noqa: E501 

2405 """Identify IP id values classes in a list of packets 

2406 

2407lst: a list of packets 

2408funcID: a function that returns IP id values 

2409funcpres: a function used to summarize packets""" 

2410 idlst = [funcID(e) for e in lst] 

2411 idlst.sort() 

2412 classes = [idlst[0]] 

2413 classes += [t[1] for t in zip(idlst[:-1], idlst[1:]) if abs(t[0] - t[1]) > 50] # noqa: E501 

2414 lst = [(funcID(x), funcpres(x)) for x in lst] 

2415 lst.sort() 

2416 print("Probably %i classes: %s" % (len(classes), classes)) 

2417 for id, pr in lst: 

2418 print("%5i" % id, pr) 

2419 

2420 

2421@conf.commands.register 

2422def fragleak(target, sport=123, dport=123, timeout=0.2, onlyasc=0, count=None): 

2423 load = "XXXXYYYYYYYYYY" 

2424 pkt = IP(dst=target, id=RandShort(), options=b"\x00" * 40, flags=1) 

2425 pkt /= UDP(sport=sport, dport=sport) / load 

2426 s = conf.L3socket() 

2427 intr = 0 

2428 found = {} 

2429 try: 

2430 while count is None or count: 

2431 if count is not None and isinstance(count, int): 

2432 count -= 1 

2433 try: 

2434 if not intr: 

2435 s.send(pkt) 

2436 sin = select.select([s], [], [], timeout)[0] 

2437 if not sin: 

2438 continue 

2439 ans = s.recv(1600) 

2440 if not isinstance(ans, IP): # TODO: IPv6 

2441 continue 

2442 if not isinstance(ans.payload, ICMP): 

2443 continue 

2444 if not isinstance(ans.payload.payload, IPerror): 

2445 continue 

2446 if ans.payload.payload.dst != target: 

2447 continue 

2448 if ans.src != target: 

2449 print("leak from", ans.src) 

2450 if not ans.haslayer(conf.padding_layer): 

2451 continue 

2452 leak = ans.getlayer(conf.padding_layer).load 

2453 if leak not in found: 

2454 found[leak] = None 

2455 linehexdump(leak, onlyasc=onlyasc) 

2456 except KeyboardInterrupt: 

2457 if intr: 

2458 raise 

2459 intr = 1 

2460 except KeyboardInterrupt: 

2461 pass 

2462 

2463 

2464@conf.commands.register 

2465def fragleak2(target, timeout=0.4, onlyasc=0, count=None): 

2466 found = {} 

2467 try: 

2468 while count is None or count: 

2469 if count is not None and isinstance(count, int): 

2470 count -= 1 

2471 

2472 pkt = IP(dst=target, options=b"\x00" * 40, proto=200) 

2473 pkt /= "XXXXYYYYYYYYYYYY" 

2474 p = sr1(pkt, timeout=timeout, verbose=0) 

2475 if not p: 

2476 continue 

2477 if conf.padding_layer in p: 

2478 leak = p[conf.padding_layer].load 

2479 if leak not in found: 

2480 found[leak] = None 

2481 linehexdump(leak, onlyasc=onlyasc) 

2482 except Exception: 

2483 pass 

2484 

2485 

2486@conf.commands.register 

2487class connect_from_ip: 

2488 """ 

2489 Open a TCP socket to a host:port while spoofing another IP. 

2490 

2491 :param host: the host to connect to 

2492 :param port: the port to connect to 

2493 :param srcip: the IP to spoof. the cache of the gateway will 

2494 be poisonned with this IP. 

2495 :param poison: (optional, default True) ARP poison the gateway (or next hop), 

2496 so that it answers us (only one packet). 

2497 :param timeout: (optional) the socket timeout. 

2498 

2499 Example - Connect to 192.168.0.1:80 spoofing 192.168.0.2:: 

2500 

2501 from scapy.layers.http import HTTP, HTTPRequest 

2502 client = connect_from_ip("192.168.0.1", 80, "192.168.0.2") 

2503 sock = SSLStreamSocket(client.sock, HTTP) 

2504 resp = sock.sr1(HTTP() / HTTPRequest(Path="/")) 

2505 

2506 Example - Connect to 192.168.0.1:443 with TLS wrapping spoofing 192.168.0.2:: 

2507 

2508 import ssl 

2509 from scapy.layers.http import HTTP, HTTPRequest 

2510 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) 

2511 context.check_hostname = False 

2512 context.verify_mode = ssl.CERT_NONE 

2513 client = connect_from_ip("192.168.0.1", 443, "192.168.0.2") 

2514 sock = context.wrap_socket(client.sock) 

2515 sock = SSLStreamSocket(client.sock, HTTP) 

2516 resp = sock.sr1(HTTP() / HTTPRequest(Path="/")) 

2517 """ 

2518 

2519 def __init__(self, host, port, srcip, poison=True, timeout=1, debug=0): 

2520 host = str(Net(host)) 

2521 if poison: 

2522 # poison the next hop 

2523 gateway = conf.route.route(host)[2] 

2524 if gateway == "0.0.0.0": 

2525 # on lan 

2526 gateway = host 

2527 getmacbyip(gateway) # cache real gateway before poisoning 

2528 arpcachepoison(gateway, srcip, count=1, interval=0, verbose=0) 

2529 # create a socket pair 

2530 self._sock, self.sock = socket.socketpair() 

2531 self.sock.settimeout(timeout) 

2532 self.client = TCP_client( 

2533 host, port, 

2534 srcip=srcip, 

2535 external_fd={"tcp": self._sock}, 

2536 debug=debug, 

2537 ) 

2538 # start the TCP_client 

2539 self.client.runbg() 

2540 

2541 def close(self): 

2542 self.client.stop() 

2543 self.client.destroy() 

2544 self.sock.close() 

2545 self._sock.close() 

2546 

2547 

2548class ICMPEcho_am(AnsweringMachine): 

2549 """Responds to ICMP Echo-Requests (ping)""" 

2550 function_name = "icmpechod" 

2551 

2552 def is_request(self, req): 

2553 if req.haslayer(ICMP): 

2554 icmp_req = req.getlayer(ICMP) 

2555 if icmp_req.type == 8: # echo-request 

2556 return True 

2557 

2558 return False 

2559 

2560 def print_reply(self, req, reply): 

2561 print("Replying %s to %s" % (reply[IP].dst, req[IP].dst)) 

2562 

2563 def make_reply(self, req): 

2564 reply = req.copy() 

2565 reply[ICMP].type = 0 # echo-reply 

2566 # Force re-generation of the checksum 

2567 reply[ICMP].chksum = None 

2568 if req.haslayer(IP): 

2569 reply[IP].src, reply[IP].dst = req[IP].dst, req[IP].src 

2570 reply[IP].chksum = None 

2571 if req.haslayer(Ether): 

2572 reply[Ether].src, reply[Ether].dst = ( 

2573 None if req[Ether].dst == "ff:ff:ff:ff:ff:ff" else req[Ether].dst, 

2574 req[Ether].src, 

2575 ) 

2576 return reply 

2577 

2578 

2579conf.stats_classic_protocols += [TCP, UDP, ICMP] 

2580conf.stats_dot11_protocols += [TCP, UDP, ICMP] 

2581 

2582if conf.ipv6_enabled: 

2583 import scapy.layers.inet6