def BEGIN(self): self.blocksize = 512 self.my_tid = self.sport or RandShort()._fix() bind_bottom_up(UDP, TFTP, dport=self.my_tid) self.server_tid = None self.res = "" self.l3 = IP(dst=self.server) / UDP(sport=self.my_tid, dport=self.port) / TFTP() # noqa: E501 self.last_packet = self.l3 / TFTP_RRQ(filename=self.filename, mode="octet") # noqa: E501 self.send(self.last_packet) self.awaiting = 1 raise self.WAITING()
def BEGIN(self): self.blocksize = 512 self.my_tid = self.sport or RandShort()._fix() bind_bottom_up(UDP, TFTP, dport=self.my_tid) self.server_tid = None self.res = b"" self.l3 = IP(dst=self.server) / UDP(sport=self.my_tid, dport=self.port) / TFTP() # noqa: E501 self.last_packet = self.l3 / TFTP_RRQ(filename=self.filename, mode="octet") # noqa: E501 self.send(self.last_packet) self.awaiting = 1 raise self.WAITING()
def BEGIN(self): self.data = [self.origdata[i * self.blocksize:(i + 1) * self.blocksize] for i in range(len(self.origdata) / self.blocksize + 1)] self.my_tid = self.sport or RandShort()._fix() bind_bottom_up(UDP, TFTP, dport=self.my_tid) self.server_tid = None self.l3 = IP(dst=self.server) / UDP(sport=self.my_tid, dport=self.port) / TFTP() # noqa: E501 self.last_packet = self.l3 / TFTP_WRQ(filename=self.filename, mode="octet") # noqa: E501 self.send(self.last_packet) self.res = "" self.awaiting = 0 raise self.WAITING_ACK()
def BEGIN(self): self.data = [self.origdata[i * self.blocksize:(i + 1) * self.blocksize] for i in range(len(self.origdata) // self.blocksize + 1)] self.my_tid = self.sport or RandShort()._fix() bind_bottom_up(UDP, TFTP, dport=self.my_tid) self.server_tid = None self.l3 = IP(dst=self.server) / UDP(sport=self.my_tid, dport=self.port) / TFTP() # noqa: E501 self.last_packet = self.l3 / TFTP_WRQ(filename=self.filename, mode="octet") # noqa: E501 self.send(self.last_packet) self.res = "" self.awaiting = 0 raise self.WAITING_ACK()
def parse_args(self, store=None, joker=None, dir=None, ip=None, sport=None, serve_one=False, **kargs): # noqa: E501 Automaton.parse_args(self, **kargs) if store is None: store = {} if dir is not None: self.dir = os.path.join(os.path.abspath(dir), "") else: self.dir = None self.store = store self.joker = joker self.ip = ip self.sport = sport self.serve_one = serve_one self.my_tid = self.sport or random.randint(10000, 65500) bind_bottom_up(UDP, TFTP, dport=self.my_tid)
def parse_args(self, store=None, joker=None, dir=None, ip=None, sport=None, serve_one=False, **kargs): # noqa: E501 Automaton.parse_args(self, **kargs) if store is None: store = {} if dir is not None: self.dir = os.path.join(os.path.abspath(dir), "") else: self.dir = None self.store = store self.joker = joker self.ip = ip self.sport = sport self.serve_one = serve_one self.my_tid = self.sport or random.randint(10000, 65500) bind_bottom_up(UDP, TFTP, dport=self.my_tid)
def _bind_someip_layers(): bind_top_down(UDP, SOMEIP, sport=30490, dport=30490) for i in range(15): bind_bottom_up(UDP, SOMEIP, sport=30490 + i) bind_bottom_up(TCP, SOMEIP, sport=30490 + i) bind_bottom_up(UDP, SOMEIP, dport=30490 + i) bind_bottom_up(TCP, SOMEIP, dport=30490 + i)
def run(self): try: kwargs = { 'filter': 'port %d' % self._port, 'store': False, 'prn': self._handle_packet, 'iface': self._iface, 'stop_filter': lambda p: self._wants_stop, 'session': TCPSession, } from scapy.config import conf level = self._options.get('log_level') conf.logLevel = level message = self._options.get('message') if message == 'thrift': from .thrift_parser import Thrift from .thrift_idl import parse_idl_file if self._options.get('transport'): conf.contribs["thrift"]["transport"] = self._options[ 'transport'] if self._options.get('protocol'): conf.contribs["thrift"]["protocol"] = self._options[ 'protocol'] if self._options.get('finagle'): conf.contribs["thrift"]["finagle"] = self._options[ 'finagle'] if self._options.get('idl_file'): conf.contribs["thrift"]["idl_file"] = parse_idl_file( self._options['idl_file']) bind_bottom_up(TCP, Thrift, sport=self._port) bind_bottom_up(TCP, Thrift, dport=self._port) elif message == 'http': from scapy.layers.http import HTTP bind_bottom_up(TCP, HTTP, sport=self._port) bind_bottom_up(TCP, HTTP, dport=self._port) else: raise ValueError("Invalid message type '%s'" % message) self._wants_stop = False sniff(**kwargs) except Exception as ex: logging.error("Sniffer start on '%s' error: %s\n%s" % (self._iface, ex, traceback.format_exc()))
# ofpt_cls allows generic method OpenFlow() to choose the right class for dissection # noqa: E501 ofpt_cls = { 0: OFPTHello, # 1: OFPTError, 2: OFPTEchoRequest, 3: OFPTEchoReply, 4: OFPTVendor, 5: OFPTFeaturesRequest, 6: OFPTFeaturesReply, 7: OFPTGetConfigRequest, 8: OFPTGetConfigReply, 9: OFPTSetConfig, 10: OFPTPacketIn, 11: OFPTFlowRemoved, 12: OFPTPortStatus, 13: OFPTPacketOut, 14: OFPTFlowMod, 15: OFPTPortMod, # 16: OFPTStatsRequest, # 17: OFPTStatsReply, 18: OFPTBarrierRequest, 19: OFPTBarrierReply, 20: OFPTQueueGetConfigRequest, 21: OFPTQueueGetConfigReply } bind_bottom_up(TCP, OpenFlow, dport=6653) bind_bottom_up(TCP, OpenFlow, sport=6653) bind_bottom_up(TCP, OpenFlow, dport=6633) bind_bottom_up(TCP, OpenFlow, sport=6633)
else: return Dot15d4FCS class ZEP1(ZEP2): name = "Zigbee Encapsulation Protocol (V1)" fields_desc = [ StrFixedLenField("preamble", "EX", length=2), ByteField("ver", 0), ByteField("channel", 0), ShortField("device", 0), ByteField("lqi_mode", 0), ByteField("lqi_val", 0), BitField("res", 0, 56), # 7 bytes reserved field ByteField("len", 0), ] # Bindings # # TODO: find a way to chose between ZigbeeNWK and SixLoWPAN (cf. sixlowpan.py) # Currently: use conf.dot15d4_protocol value # bind_layers( Dot15d4Data, ZigbeeNWK) bind_layers(ZigbeeAppDataPayload, ZigbeeAppCommandPayload, frametype=1) bind_layers(Dot15d4Beacon, ZigBeeBeacon) bind_bottom_up(UDP, ZEP2, sport=17754) bind_bottom_up(UDP, ZEP2, sport=17754) bind_layers(UDP, ZEP2, sport=17754, dport=17754)
from scapy.packet import Packet, bind_layers, bind_bottom_up from scapy.fields import BitField, FlagsField, XByteField from scapy.layers.inet import UDP class BFD(Packet): name = "BFD" fields_desc = [ BitField("version", 1, 3), BitField("diag", 0, 5), BitField("sta", 3, 2), FlagsField("flags", 0x00, 6, ['P', 'F', 'C', 'A', 'D', 'M']), XByteField("detect_mult", 0x03), XByteField("len", 24), BitField("my_discriminator", 0x11111111, 32), BitField("your_discriminator", 0x22222222, 32), BitField("min_tx_interval", 1000000000, 32), BitField("min_rx_interval", 1000000000, 32), BitField("echo_rx_interval", 1000000000, 32) ] def mysummary(self): return self.sprintf("BFD (my_disc=%BFD.my_discriminator%," "your_disc=%BFD.my_discriminator%)") bind_bottom_up(UDP, BFD, dport=3784) bind_bottom_up(UDP, BFD, sport=3784) bind_layers(UDP, BFD, sport=3784, dport=3784)
return self.payload.answers(other.payload) return 0 def extract_padding(self, s): return s[:self.length - 2], s[self.length - 2:] def post_build(self, pkt, pay): """ This will set the LenField 'length' to the correct value. """ if self.length is None: pkt = struct.pack("!I", len(pay) + 2) + pkt[4:] return pkt + pay bind_bottom_up(TCP, HSFZ, sport=6801) bind_bottom_up(TCP, HSFZ, dport=6801) bind_layers(TCP, HSFZ, sport=6801, dport=6801) bind_layers(HSFZ, UDS) # ########################HSFZSocket################################### class HSFZSocket(StreamSocket): def __init__(self, ip='127.0.0.1', port=6801): self.ip = ip self.port = port s = socket.socket() s.connect((self.ip, self.port)) StreamSocket.__init__(self, s, HSFZ)
return Packet.guess_payload_class(self, payload) class HSRPmd5(Packet): name = "HSRP MD5 Authentication" fields_desc = [ ByteEnumField("type", 4, {4: "MD5 authentication"}), ByteField("len", None), ByteEnumField("algo", 0, {1: "MD5"}), ByteField("padding", 0x00), XShortField("flags", 0x00), SourceIPField("sourceip", None), XIntField("keyid", 0x00), StrFixedLenField("authdigest", b"\00" * 16, 16)] def post_build(self, p, pay): if self.len is None and pay: tmp_len = len(pay) p = p[:1] + hex(tmp_len)[30:] + p[30:] return p bind_bottom_up(UDP, HSRP, dport=1985) bind_bottom_up(UDP, HSRP, sport=1985) bind_bottom_up(UDP, HSRP, dport=2029) bind_bottom_up(UDP, HSRP, sport=2029) bind_layers(UDP, HSRP, dport=1985, sport=1985) bind_layers(UDP, HSRP, dport=2029, sport=2029) DestIPField.bind_addr(UDP, "224.0.0.2", dport=1985) DestIP6Field.bind_addr(UDP, "ff02::66", dport=2029)
s += chb(o) + b"\0" elif isinstance(o, (str, bytes)): s += raw(o) else: warning("Malformed option %s", o) return s class DHCP(Packet): name = "DHCP options" fields_desc = [DHCPOptionsField("options", b"")] bind_layers(UDP, BOOTP, dport=67, sport=68) bind_layers(UDP, BOOTP, dport=68, sport=67) bind_bottom_up(UDP, BOOTP, dport=67, sport=67) bind_layers(BOOTP, DHCP, options=b'c\x82Sc') @conf.commands.register def dhcp_request(iface=None, **kargs): """Send a DHCP discover request and return the answer""" if conf.checkIPaddr != 0: warning("conf.checkIPaddr is not 0, I may not be able to match the answer") # noqa: E501 if iface is None: iface = conf.iface fam, hw = get_if_raw_hwaddr(iface) return srp1(Ether(dst="ff:ff:ff:ff:ff:ff") / IP(src="0.0.0.0", dst="255.255.255.255") / UDP(sport=68, dport=67) / # noqa: E501 BOOTP(chaddr=hw) / DHCP(options=[("message-type", "discover"), "end"]), iface=iface, **kargs) # noqa: E501
return SOCKS4Reply warning("No TCP underlayer, or dport/sport not in " "conf.contribs['socks']['serverports']. " "Assuming a SOCKS v5 request layer") return SOCKS5Request def add_payload(self, payload): if self.underlayer and isinstance(self.underlayer, TCP): if isinstance(payload, (SOCKS5Request, SOCKS4Request)): self.underlayer.dport = 1080 elif isinstance(payload, (SOCKS5Reply, SOCKS4Reply)): self.underlayer.sport = 1080 Packet.add_payload(self, payload) bind_bottom_up(TCP, SOCKS, sport=1080) bind_bottom_up(TCP, SOCKS, dport=1080) # SOCKS v4 _socks4_cd_request = { 1: "Connect", 2: "Bind" } class SOCKS4Request(Packet): name = "SOCKS 4 - Request" overload_fields = {SOCKS: {"vn": 0x4}} fields_desc = [ ByteEnumField("cd", 1, _socks4_cd_request),
else: self.option_array = [option_list] bind_top_down(SOMEIP, SD, srv_id=SD.SOMEIP_MSGID_SRVID, sub_id=SD.SOMEIP_MSGID_SUBID, client_id=SD.SOMEIP_CLIENT_ID, session_id=SD.SOMEIP_MINIMUM_SESSION_ID, event_id=SD.SOMEIP_MSGID_EVENTID, proto_ver=SD.SOMEIP_PROTO_VER, iface_ver=SD.SOMEIP_IFACE_VER, msg_type=SD.SOMEIP_MSG_TYPE, retcode=SD.SOMEIP_RETCODE) bind_bottom_up(SOMEIP, SD, srv_id=SD.SOMEIP_MSGID_SRVID, sub_id=SD.SOMEIP_MSGID_SUBID, client_id=SD.SOMEIP_CLIENT_ID, event_id=SD.SOMEIP_MSGID_EVENTID, proto_ver=SD.SOMEIP_PROTO_VER, iface_ver=SD.SOMEIP_IFACE_VER, msg_type=SD.SOMEIP_MSG_TYPE, retcode=SD.SOMEIP_RETCODE) # FIXME: Service Discovery messages shall be transported over UDP # (TR_SOMEIP_00248) # FIXME: The port 30490 (UDP and TCP as well) shall be only used for SOME/IP-SD # and not used for applications communicating over SOME/IP # (TR_SOMEIP_00020)
bind_layers(UDP, NBNSQueryRequest, dport=137) bind_layers(UDP, NBNSRequest, dport=137) bind_layers(UDP, NBNSQueryResponse, sport=137) bind_layers(UDP, NBNSQueryResponseNegative, sport=137) bind_layers(UDP, NBNSNodeStatusResponse, sport=137) bind_layers( NBNSNodeStatusResponse, NBNSNodeStatusResponseService, ) bind_layers( NBNSNodeStatusResponse, NBNSNodeStatusResponseService, ) bind_layers( NBNSNodeStatusResponseService, NBNSNodeStatusResponseService, ) bind_layers( NBNSNodeStatusResponseService, NBNSNodeStatusResponseEnd, ) bind_layers(UDP, NBNSWackResponse, sport=137) bind_layers(UDP, NBTDatagram, dport=138) bind_bottom_up(TCP, NBTSession, dport=445) bind_bottom_up(TCP, NBTSession, sport=445) bind_bottom_up(TCP, NBTSession, dport=139) bind_bottom_up(TCP, NBTSession, sport=139) bind_layers(TCP, NBTSession, dport=139, sport=139)
def BEGIN(self): self.blksize = 512 self.blk = 1 self.filedata = "" self.my_tid = self.sport or random.randint(10000, 65500) bind_bottom_up(UDP, TFTP, dport=self.my_tid)
else: return Dot15d4FCS class ZEP1(ZEP2): name = "Zigbee Encapsulation Protocol (V1)" fields_desc = [ StrFixedLenField("preamble", "EX", length=2), ByteField("ver", 0), ByteField("channel", 0), ShortField("device", 0), ByteField("lqi_mode", 0), ByteField("lqi_val", 0), BitField("res", 0, 56), # 7 bytes reserved field ByteField("len", 0), ] # Bindings # # TODO: find a way to chose between ZigbeeNWK and SixLoWPAN (cf. sixlowpan.py) # Currently: use conf.dot15d4_protocol value # bind_layers( Dot15d4Data, ZigbeeNWK) bind_layers(ZigbeeAppDataPayload, ZigbeeAppCommandPayload, frametype=1) bind_layers(Dot15d4Beacon, ZigBeeBeacon) bind_bottom_up(UDP, ZEP2, sport=17754) bind_bottom_up(UDP, ZEP2, sport=17754) bind_layers(UDP, ZEP2, sport=17754, dport=17754)
fields_desc = [XByteField("flags", 0), ShortField("lifetime", 180), IPField("homeaddr", "0.0.0.0"), IPField("haaddr", "0.0.0.0"), IPField("coaddr", "0.0.0.0"), LongField("id", 0), ] class MobileIPRRP(Packet): name = "Mobile IP Registration Reply (RFC3344)" fields_desc = [ByteField("code", 0), ShortField("lifetime", 180), IPField("homeaddr", "0.0.0.0"), IPField("haaddr", "0.0.0.0"), LongField("id", 0), ] class MobileIPTunnelData(Packet): name = "Mobile IP Tunnel Data Message (RFC3519)" fields_desc = [ByteField("nexthdr", 4), ShortField("res", 0)] bind_bottom_up(UDP, MobileIP, dport=434) bind_bottom_up(UDP, MobileIP, sport=434) bind_layers(UDP, MobileIP, sport=434, dport=434) bind_layers(MobileIP, MobileIPRRQ, type=1) bind_layers(MobileIP, MobileIPRRP, type=3) bind_layers(MobileIP, MobileIPTunnelData, type=4) bind_layers(MobileIPTunnelData, IP, nexthdr=4)
ASN1F_enum_INTEGER("version", 1, {0: "v1", 1: "v2c", 2: "v2", 3: "v3"}), # noqa: E501 ASN1F_STRING("community", "public"), ASN1F_CHOICE("PDU", SNMPget(), SNMPget, SNMPnext, SNMPresponse, SNMPset, SNMPtrapv1, SNMPbulk, SNMPinform, SNMPtrapv2) ) def answers(self, other): return (isinstance(self.PDU, SNMPresponse) and (isinstance(other.PDU, SNMPget) or isinstance(other.PDU, SNMPnext) or isinstance(other.PDU, SNMPset)) and self.PDU.id == other.PDU.id) bind_bottom_up(UDP, SNMP, sport=161) bind_bottom_up(UDP, SNMP, dport=161) bind_bottom_up(UDP, SNMP, sport=162) bind_bottom_up(UDP, SNMP, dport=162) bind_layers(UDP, SNMP, sport=161, dport=161) def snmpwalk(dst, oid="1", community="public"): try: while True: r = sr1(IP(dst=dst) / UDP(sport=RandShort()) / SNMP(community=community, PDU=SNMPnext(varbindlist=[SNMPvarbind(oid=oid)])), timeout=2, chainCC=1, verbose=0, retry=2) # noqa: E501 if r is None: print("No answers") break if ICMP in r: print(repr(r))
def BEGIN(self): self.blksize = 512 self.blk = 1 self.filedata = "" self.my_tid = self.sport or random.randint(10000, 65500) bind_bottom_up(UDP, TFTP, dport=self.my_tid)
name = "BFD" fields_desc = [ BitField("version", 1, 3), BitEnumField("diag", 0, 5, _diagnostics), BitEnumField("sta", 3, 2, _sta_names), FlagsField("flags", 0x00, 6, "MDACFP"), ByteField("detect_mult", 3), ByteField("len", 24), BitField("my_discriminator", 0x11111111, 32), BitField("your_discriminator", 0x22222222, 32), BitField("min_tx_interval", 1000000000, 32), BitField("min_rx_interval", 1000000000, 32), BitField("echo_rx_interval", 1000000000, 32) ] def mysummary(self): return self.sprintf("BFD (my_disc=%BFD.my_discriminator%," "your_disc=%BFD.your_discriminator%," "state=%BFD.sta%)") for _bfd_port in [ 3784, # single-hop BFD 4784, # multi-hop BFD 6784, # BFD for LAG a.k.a micro-BFD 7784 ]: # seamless BFD bind_bottom_up(UDP, BFD, dport=_bfd_port) bind_bottom_up(UDP, BFD, sport=_bfd_port) bind_layers(UDP, BFD, dport=_bfd_port, sport=_bfd_port)
# ofpt_cls allows generic method OpenFlow() to choose the right class for dissection # noqa: E501 ofpt_cls = {0: OFPTHello, # 1: OFPTError, 2: OFPTEchoRequest, 3: OFPTEchoReply, 4: OFPTVendor, 5: OFPTFeaturesRequest, 6: OFPTFeaturesReply, 7: OFPTGetConfigRequest, 8: OFPTGetConfigReply, 9: OFPTSetConfig, 10: OFPTPacketIn, 11: OFPTFlowRemoved, 12: OFPTPortStatus, 13: OFPTPacketOut, 14: OFPTFlowMod, 15: OFPTPortMod, # 16: OFPTStatsRequest, # 17: OFPTStatsReply, 18: OFPTBarrierRequest, 19: OFPTBarrierReply, 20: OFPTQueueGetConfigRequest, 21: OFPTQueueGetConfigReply} bind_bottom_up(TCP, OpenFlow, dport=6653) bind_bottom_up(TCP, OpenFlow, sport=6653) bind_bottom_up(TCP, OpenFlow, dport=6633) bind_bottom_up(TCP, OpenFlow, sport=6633)
return struct.pack("!H", self.id) class LLMNRResponse(LLMNRQuery): name = "Link Local Multicast Node Resolution - Response" qr = 1 def answers(self, other): return (isinstance(other, LLMNRQuery) and self.id == other.id and self.qr == 1 and other.qr == 0) class _LLMNR(Packet): @classmethod def dispatch_hook(cls, _pkt=None, *args, **kargs): if len(_pkt) >= 2: if (orb(_pkt[2]) & 0x80): # Response return LLMNRResponse else: # Query return LLMNRQuery return cls bind_bottom_up(UDP, _LLMNR, dport=5355) bind_bottom_up(UDP, _LLMNR, sport=5355) bind_layers(UDP, _LLMNR, sport=5355, dport=5355) # LLMNRQuery(id=RandShort(), qd=DNSQR(qname="vista.")))
implicit_tag=0x65), ASN1F_PACKET("abandonRequest", LDAP_AbandonRequest(), LDAP_AbandonRequest, implicit_tag=0x70)), # LDAP v3 only ASN1F_optional( ASN1F_SEQUENCE_OF("Controls", [], LDAP_Control, implicit_tag=0x0))) def mysummary(self): return (self.protocolOp.__class__.__name__.replace("_", " "), [LDAP]) bind_layers(LDAP, LDAP) bind_bottom_up(TCP, LDAP, dport=389) bind_bottom_up(TCP, LDAP, sport=389) bind_bottom_up(TCP, LDAP, dport=3268) bind_bottom_up(TCP, LDAP, sport=3268) bind_layers(TCP, LDAP, sport=389, dport=389) # CLDAP - rfc1798 class CLDAP(ASN1_Packet): ASN1_codec = ASN1_Codecs.BER ASN1_root = ASN1F_SEQUENCE( LDAP.ASN1_root.seq[0], # messageID ASN1F_optional(LDAPDN("user", ""), ), LDAP.ASN1_root.seq[1] # protocolOp )
name = "MGCP" longname = "Media Gateway Control Protocol" fields_desc = [StrStopField("verb", "AUEP", b" ", -1), StrFixedLenField("sep1", " ", 1), StrStopField("transaction_id", "1234567", b" ", -1), StrFixedLenField("sep2", " ", 1), StrStopField("endpoint", "*****@*****.**", b" ", -1), StrFixedLenField("sep3", " ", 1), StrStopField("version", "MGCP 1.0 NCS 1.0", b"\x0a", -1), StrFixedLenField("sep4", b"\x0a", 1), ] # class MGCP(Packet): # name = "MGCP" # longname = "Media Gateway Control Protocol" # fields_desc = [ ByteEnumField("type",0, ["request","response","others"]), # ByteField("code0",0), # ByteField("code1",0), # ByteField("code2",0), # ByteField("code3",0), # ByteField("code4",0), # IntField("trasid",0), # IntField("req_time",0), # ByteField("is_duplicate",0), # ByteField("req_available",0) ] # bind_bottom_up(UDP, MGCP, dport=2727) bind_bottom_up(UDP, MGCP, sport=2727) bind_layers(UDP, MGCP, sport=2727, dport=2727)
fields_desc = [ FlagsField("hdr", 0, 12, ['res00', 'res01', 'res02', 'res03', 'priority', 'offset', # noqa: E501 'res06', 'sequence', 'res08', 'res09', 'length', 'control']), # noqa: E501 BitEnumField("version", 2, 4, {2: 'L2TPv2'}), ConditionalField(ShortField("len", 0), lambda pkt: pkt.hdr & 'control+length'), ShortField("tunnel_id", 0), ShortField("session_id", 0), ConditionalField(ShortField("ns", 0), lambda pkt: pkt.hdr & 'sequence+control'), ConditionalField(ShortField("nr", 0), lambda pkt: pkt.hdr & 'sequence+control'), ConditionalField( PadField(ShortField("offset", 0), 4, b"\x00"), lambda pkt: not (pkt.hdr & 'control') and pkt.hdr & 'offset' ) ] def post_build(self, pkt, pay): if self.len is None and self.hdr & 'control+length': tmp_len = len(pkt) + len(pay) pkt = pkt[:2] + struct.pack("!H", tmp_len) + pkt[4:] return pkt + pay bind_bottom_up(UDP, L2TP, dport=1701) bind_bottom_up(UDP, L2TP, sport=1701) bind_layers(UDP, L2TP, dport=1701, sport=1701) bind_layers(L2TP, PPP,)
return SOCKS4Reply warning("No TCP underlayer, or dport/sport not in " "conf.contribs['socks']['serverports']. " "Assuming a SOCKS v5 request layer") return SOCKS5Request def add_payload(self, payload): if self.underlayer and isinstance(self.underlayer, TCP): if isinstance(payload, (SOCKS5Request, SOCKS4Request)): self.underlayer.dport = 1080 elif isinstance(payload, (SOCKS5Reply, SOCKS4Reply)): self.underlayer.sport = 1080 Packet.add_payload(self, payload) bind_bottom_up(TCP, SOCKS, sport=1080) bind_bottom_up(TCP, SOCKS, dport=1080) # SOCKS v4 _socks4_cd_request = {1: "Connect", 2: "Bind"} class SOCKS4Request(Packet): name = "SOCKS 4 - Request" overload_fields = {SOCKS: {"vn": 0x4}} fields_desc = [ ByteEnumField("cd", 1, _socks4_cd_request), ShortField("dstport", 80), IPField("dst", "0.0.0.0"), StrField("userid", ""),
def hashret(self): return struct.pack("!H", self.id) class LLMNRResponse(LLMNRQuery): name = "Link Local Multicast Node Resolution - Response" qr = 1 def answers(self, other): return (isinstance(other, LLMNRQuery) and self.id == other.id and self.qr == 1 and other.qr == 0) class _LLMNR(Packet): @classmethod def dispatch_hook(cls, _pkt=None, *args, **kargs): if len(_pkt) >= 2: if (orb(_pkt[2]) & 0x80): # Response return LLMNRResponse else: # Query return LLMNRQuery return cls bind_bottom_up(UDP, _LLMNR, dport=5355) bind_bottom_up(UDP, _LLMNR, sport=5355) bind_layers(UDP, _LLMNR, sport=5355, dport=5355) # LLMNRQuery(id=RandShort(), qd=DNSQR(qname="vista.")))
ByteEnumField("nlpid", 0x00, network_layer_protocol_ids), PacketField("rawdata", None, conf.raw_layer) ] def _create_cln_pdu(s, **kwargs): pdu_cls = conf.raw_layer if len(s) >= 1: nlpid = struct.unpack("!B", s[0])[0] pdu_cls = _cln_protocols.get(nlpid, _GenericClnsPdu) return pdu_cls(s, **kwargs) @conf.commands.register def register_cln_protocol(nlpid, cln_protocol_class): if nlpid is None or cln_protocol_class is None: return chk = _cln_protocols.get(nlpid, None) if chk is not None and chk != cln_protocol_class: raise ValueError("different protocol already registered!") _cln_protocols[nlpid] = cln_protocol_class bind_top_down(LLC, cln_protocol_class, dsap=0xfe, ssap=0xfe, ctrl=3) bind_top_down(LLC, _GenericClnsPdu, dsap=0xfe, ssap=0xfe, ctrl=3) bind_bottom_up(LLC, _create_cln_pdu, dsap=0xfe, ssap=0xfe, ctrl=3)
if other.__class__ == self.__class__: return self.payload.answers(other.payload) return 0 def extract_padding(self, s): return s[:self.length - 2], s[self.length - 2:] def post_build(self, pkt, pay): """ This will set the LenField 'length' to the correct value. """ if self.length is None: pkt = struct.pack("!I", len(pay) + 2) + pkt[4:] return pkt + pay bind_bottom_up(TCP, ENET, sport=6801) bind_bottom_up(TCP, ENET, dport=6801) bind_layers(TCP, ENET, sport=6801, dport=6801) bind_layers(ENET, UDS) # ########################ENETSocket################################### class ENETSocket(StreamSocket): def __init__(self, ip='127.0.0.1', port=6801): s = socket.socket() s.connect((ip, port)) StreamSocket.__init__(self, s, ENET)
class ISAKMP_payload_Hash(ISAKMP_class): name = "ISAKMP Hash" overload_fields = {ISAKMP: {"next_payload": 8}} fields_desc = [ ByteEnumField("next_payload", None, ISAKMP_payload_type), ByteField("res", 0), FieldLenField("length", None, "load", "H", adjust=lambda pkt, x:x + 4), StrLenField("load", "", length_from=lambda x:x.length - 4), ] ISAKMP_payload_type_overload = {} for i, payloadname in enumerate(ISAKMP_payload_type): name = "ISAKMP_payload_%s" % payloadname if name in globals(): ISAKMP_payload_type_overload[globals()[name]] = {"next_payload": i} del i, payloadname, name ISAKMP_class._overload_fields = ISAKMP_payload_type_overload.copy() bind_bottom_up(UDP, ISAKMP, dport=500) bind_bottom_up(UDP, ISAKMP, sport=500) bind_layers(UDP, ISAKMP, dport=500, sport=500) def ikescan(ip): return sr(IP(dst=ip) / UDP() / ISAKMP(init_cookie=RandString(8), exch_type=2) / ISAKMP_payload_SA(prop=ISAKMP_payload_Proposal())) # noqa: E501
XByteField('dst', 0), ] def hashret(self): hdr_hash = struct.pack("B", self.src ^ self.dst) pay_hash = self.payload.hashret() return hdr_hash + pay_hash def answers(self, other): if other.__class__ == self.__class__: return self.payload.answers(other.payload) return 0 def extract_padding(self, s): return s[:8], s[8:] bind_bottom_up(TCP, DoIP, sport=6801) bind_bottom_up(TCP, DoIP, dport=6801) bind_layers(TCP, DoIP, sport=6801, dport=6801) bind_layers(DoIP, UDS) # ########################DoIPSocket################################### class DoIPSocket(StreamSocket): def __init__(self, ip='127.0.0.1', port=6801): s = socket.socket() s.connect((ip, port)) StreamSocket.__init__(self, s, DoIP)
fields_desc = [ FlagsField("hdr", 0, 12, ['res00', 'res01', 'res02', 'res03', 'priority', 'offset', # noqa: E501 'res06', 'sequence', 'res08', 'res09', 'length', 'control']), # noqa: E501 BitEnumField("version", 2, 4, {2: 'L2TPv2'}), ConditionalField(ShortField("len", 0), lambda pkt: pkt.hdr & 'control+length'), ShortField("tunnel_id", 0), ShortField("session_id", 0), ConditionalField(ShortField("ns", 0), lambda pkt: pkt.hdr & 'sequence+control'), ConditionalField(ShortField("nr", 0), lambda pkt: pkt.hdr & 'sequence+control'), ConditionalField( PadField(ShortField("offset", 0), 4, b"\x00"), lambda pkt: not (pkt.hdr & 'control') and pkt.hdr & 'offset' ) ] def post_build(self, pkt, pay): if self.len is None: tmp_len = len(pkt) + len(pay) pkt = pkt[:2] + struct.pack("!H", tmp_len) + pkt[4:] return pkt + pay bind_bottom_up(UDP, L2TP, dport=1701) bind_bottom_up(UDP, L2TP, sport=1701) bind_layers(UDP, L2TP, dport=1701, sport=1701) bind_layers(L2TP, PPP,)
ByteEnumField("nlpid", 0x00, network_layer_protocol_ids), PacketField("rawdata", None, conf.raw_layer) ] def _create_cln_pdu(s, **kwargs): pdu_cls = conf.raw_layer if len(s) >= 1: nlpid = orb(s[0]) pdu_cls = _cln_protocols.get(nlpid, _GenericClnsPdu) return pdu_cls(s, **kwargs) @conf.commands.register def register_cln_protocol(nlpid, cln_protocol_class): if nlpid is None or cln_protocol_class is None: return chk = _cln_protocols.get(nlpid, None) if chk is not None and chk != cln_protocol_class: raise ValueError("different protocol already registered!") _cln_protocols[nlpid] = cln_protocol_class bind_top_down(LLC, cln_protocol_class, dsap=0xfe, ssap=0xfe, ctrl=3) bind_top_down(LLC, _GenericClnsPdu, dsap=0xfe, ssap=0xfe, ctrl=3) bind_bottom_up(LLC, _create_cln_pdu, dsap=0xfe, ssap=0xfe, ctrl=3)
def answers(self, other): """In CCP, the payload of a DTO packet is dependent on the cmd field of a corresponding CRO packet. Two packets correspond, if there ctr field is equal. If answers detect the corresponding CRO, it will interpret the payload of a DTO with the correct class. In CCP, there is no other way, to determine the class of a DTO payload. Since answers is called on sr and sr1, this modification of the original answers implementation will give a better user experience. """ if not hasattr(other, "ctr"): return 0 if self.ctr != other.ctr: return 0 if not hasattr(other, "cmd"): return 0 new_pl_cls = self.get_dto_cls(other.cmd) if self.payload_cls != new_pl_cls and \ self.payload_cls == DEFAULT_DTO: data = bytes(self.load) self.remove_payload() self.add_payload(new_pl_cls(data)) self.payload_cls = new_pl_cls return 1 def hashret(self): return struct.pack('B', self.ctr) bind_bottom_up(CCP, DTO)
def answers(self, other): if other.__class__ == self.__class__: return self.payload.answers(other.payload) return 0 def extract_padding(self, s): return s[:self.length - 2], s[self.length - 2:] def post_build(self, pkt, pay): """ This will set the LenField 'length' to the correct value. """ if self.length is None: pkt = struct.pack("!I", len(pay) + 2) + pkt[4:] return pkt + pay bind_bottom_up(TCP, ENET, sport=6801) bind_bottom_up(TCP, ENET, dport=6801) bind_layers(TCP, ENET, sport=6801, dport=6801) bind_layers(ENET, UDS) # ########################ENETSocket################################### class ENETSocket(StreamSocket): def __init__(self, ip='127.0.0.1', port=6801): s = socket.socket() s.connect((ip, port)) StreamSocket.__init__(self, s, ENET)
Dot1Q.mysummary = dot1q_summary def dot1q_post_build(self, packet, payload): """ Implement post build to calculate length for 802.3 frame. """ if self.type == None or self.type <= 1500 : l = len(payload) packet = packet[:2] + chr((l >> 8) & 0xff) + chr(l & 0xff) self.type = l return packet + payload Dot1Q.post_build = dot1q_post_build bind_layers(Dot3, Dot1Q, len = 0x8100) bind_layers(Dot1Q, LLC, type = None) bind_bottom_up(Ether, Dot1Q, type = 0x9100) bind_bottom_up(Ether, Dot1Q, type = 0x9200) bind_bottom_up(Ether, Dot1Q, type = 0x88a8) ## L2T packet extension ########################################################################### class L2T( Packet ): """ Define simple L2 header containing only a uint32 sequence number as data. Binds with ethernet layer using 0x5010 ethertype. """ name = 'L2T' fields_desc = [ IntField('l2t_seq', 0) ] def mysummary(self): """ Summary of L2T packet. """
pkt = DoIP(payload_type=0x8001, source_address=self.source_address, target_address=self.target_address) / x else: pkt = x try: x.sent_time = time.time() # type: ignore except AttributeError: pass return super(UDS_DoIPSocket, self).send(pkt) def recv(self, x=MTU): # type: (int) -> Packet pkt = super(UDS_DoIPSocket, self).recv(x) if pkt.payload_type == 0x8001: return pkt.payload else: return pkt bind_bottom_up(UDP, DoIP, sport=13400) bind_bottom_up(UDP, DoIP, dport=13400) bind_layers(UDP, DoIP, sport=13400, dport=13400) bind_layers(TCP, DoIP, sport=13400) bind_layers(TCP, DoIP, dport=13400) bind_layers(DoIP, UDS, payload_type=0x8001)
FlagsField, IPField, IntField, MACField, \ PacketListField, PadField, SecondsIntField, ShortEnumField, ShortField, \ StrField, StrFixedLenField, ThreeBytesField, UTCTimeField, XByteField, \ XShortField from scapy.packet import Packet, bind_layers, bind_bottom_up from scapy.layers.inet import UDP from scapy.layers.inet6 import IP6Field class NetflowHeader(Packet): name = "Netflow Header" fields_desc = [ShortField("version", 1)] bind_bottom_up(UDP, NetflowHeader, dport=2055) bind_bottom_up(UDP, NetflowHeader, sport=2055) bind_layers(UDP, NetflowHeader, dport=2055, sport=2055) ########################################### # Netflow Version 1 ########################################### class NetflowHeaderV1(Packet): name = "Netflow Header v1" fields_desc = [ShortField("count", 0), IntField("sysUptime", 0), UTCTimeField("unixSecs", 0), UTCTimeField("unixNanoSeconds", 0, use_nano=True)]
def mysummary(self): if self.flags.G: return self.sprintf("VXLAN (vni=%VXLAN.vni% gpid=%VXLAN.gpid%)") else: return self.sprintf("VXLAN (vni=%VXLAN.vni%)") bind_layers(UDP, VXLAN, dport=4789) # RFC standard vxlan port bind_layers(UDP, VXLAN, dport=4790) # RFC standard vxlan-gpe port bind_layers(UDP, VXLAN, dport=6633) # New IANA assigned port for use with NSH bind_layers(UDP, VXLAN, dport=8472) # Linux implementation port bind_layers(UDP, VXLAN, dport=48879) # Cisco ACI bind_layers(UDP, VXLAN, sport=4789) bind_layers(UDP, VXLAN, sport=4790) bind_layers(UDP, VXLAN, sport=6633) bind_layers(UDP, VXLAN, sport=8472) # By default, set both ports to the RFC standard bind_layers(UDP, VXLAN, sport=4789, dport=4789) # Dissection bind_bottom_up(VXLAN, Ether, NextProtocol=0) bind_bottom_up(VXLAN, IP, NextProtocol=1) bind_bottom_up(VXLAN, IPv6, NextProtocol=2) bind_bottom_up(VXLAN, Ether, NextProtocol=3) bind_bottom_up(VXLAN, Ether, NextProtocol=None) # Build bind_top_down(VXLAN, Ether, flags=12, NextProtocol=0) bind_top_down(VXLAN, IP, flags=12, NextProtocol=1) bind_top_down(VXLAN, IPv6, flags=12, NextProtocol=2) bind_top_down(VXLAN, Ether, flags=12, NextProtocol=3)
XBitField("type", 0x0403, 15), ShortField("len", None), IntField("id", 0), FecTLVField("fec", None), LabelTLVField("label", 0)] # 3.1. LDP PDUs class LDP(_LDP_Packet): name = "LDP" fields_desc = [ShortField("version", 1), ShortField("len", None), IPField("id", "127.0.0.1"), ShortField("space", 0)] def post_build(self, p, pay): pay = pay or b"" if self.len is None: tmp_len = len(p) + len(pay) - 4 p = p[:2] + struct.pack("!H", tmp_len) + p[4:] return p + pay bind_bottom_up(TCP, LDP, sport=646) bind_bottom_up(TCP, LDP, dport=646) bind_bottom_up(TCP, UDP, sport=646) bind_bottom_up(TCP, UDP, dport=646) bind_layers(TCP, LDP, sport=646, dport=646) bind_layers(UDP, LDP, sport=646, dport=646)
tcp_client.close() if iptables: assert(os.system(iptables_rule % ('D', ip)) == 0) if ans: if display: if Raw not in ans: warning("No HTTP content returned. Cannot display") return ans # Write file file = get_temp_file(autoext=".html") with open(file, "wb") as fd: fd.write(ans.load) # Open browser if WINDOWS: os.startfile(file) else: with ContextManagerSubprocess(conf.prog.universal_open): subprocess.Popen([conf.prog.universal_open, file]) return ans # Bindings bind_bottom_up(TCP, HTTP, sport=80) bind_bottom_up(TCP, HTTP, dport=80) bind_layers(TCP, HTTP, sport=80, dport=80) bind_bottom_up(TCP, HTTP, sport=8080) bind_bottom_up(TCP, HTTP, dport=8080)
ShortUploadPositiveResponse, ChecksumPositiveResponse, CalPagePositiveResponse, PagProcessorInfoPositiveResponse, PageInfoPositiveResponse, SegmentModePositiveResponse, DAQListModePositiveResponse, StartStopDAQListPositiveResponse, DAQClockListPositiveResponse, ReadDAQPositiveResponse, DAQProcessorInfoPositiveResponse, DAQResolutionInfoPositiveResponse, DAQListInfoPositiveResponse, DAQEventInfoPositiveResponse, ProgramStartPositiveResponse, PgmProcessorPositiveResponse, SectorInfoPositiveResponse] for cls in positive_response_classes: bind_top_down(CTOResponse, cls, packet_code=0xFF) bind_layers(CTOResponse, NegativeResponse, packet_code=0xFE) # Asynchronous Event/request messages from the slave bind_layers(CTOResponse, EvPacket, packet_code=0xFD) bind_layers(CTOResponse, ServPacket, packet_code=0xFC) bind_bottom_up(XCPOnCAN, CTOResponse) bind_bottom_up(XCPOnUDP, CTOResponse) bind_bottom_up(XCPOnTCP, CTOResponse)
class GTPSupportedExtensionHeadersNotification(Packet): name = "GTP Supported Extension Headers Notification" fields_desc = [PacketListField("IE_list", [IE_ExtensionHeaderList(), ], IE_Dispatcher)] class GTPmorethan1500(Packet): # 3GPP TS 29.060 V9.1.0 (2009-12) name = "GTP More than 1500" fields_desc = [ByteEnumField("IE_Cause", "Cause", IEType), BitField("IE", 1, 12000), ] # Bind GTP-C bind_bottom_up(UDP, GTPHeader, dport=2123) bind_bottom_up(UDP, GTPHeader, sport=2123) bind_layers(UDP, GTPHeader, dport=2123, sport=2123) bind_layers(GTPHeader, GTPEchoRequest, gtp_type=1, S=1) bind_layers(GTPHeader, GTPEchoResponse, gtp_type=2, S=1) bind_layers(GTPHeader, GTPCreatePDPContextRequest, gtp_type=16) bind_layers(GTPHeader, GTPCreatePDPContextResponse, gtp_type=17) bind_layers(GTPHeader, GTPUpdatePDPContextRequest, gtp_type=18) bind_layers(GTPHeader, GTPUpdatePDPContextResponse, gtp_type=19) bind_layers(GTPHeader, GTPDeletePDPContextRequest, gtp_type=20) bind_layers(GTPHeader, GTPDeletePDPContextResponse, gtp_type=21) bind_layers(GTPHeader, GTPPDUNotificationRequest, gtp_type=27) bind_layers(GTPHeader, GTPSupportedExtensionHeadersNotification, gtp_type=31, S=1) # noqa: E501 bind_layers(GTPHeader, GTP_UDPPort_ExtensionHeader, next_ex=64, E=1) bind_layers(GTPHeader, GTP_PDCP_PDU_ExtensionHeader, next_ex=192, E=1)
PacketListField, PadField, SecondsIntField, ShortEnumField, ShortField, \ StrField, StrFixedLenField, ThreeBytesField, UTCTimeField, XByteField, \ XShortField from scapy.packet import Packet, bind_layers, bind_bottom_up, Raw from scapy.data import IP_PROTOS from scapy.layers.inet import UDP from scapy.layers.inet6 import IP6Field from scapy.config import conf class NetflowHeader(Packet): name = "Netflow Header" fields_desc = [ShortField("version", 1)] bind_bottom_up(UDP, NetflowHeader, dport=2055) bind_bottom_up(UDP, NetflowHeader, sport=2055) bind_layers(UDP, NetflowHeader, dport=2055, sport=2055) ########################################### # Netflow Version 1 ########################################### class NetflowHeaderV1(Packet): name = "Netflow Header v1" fields_desc = [ ShortField("count", 0), IntField("sysUptime", 0), UTCTimeField("unixSecs", 0), UTCTimeField("unixNanoSeconds", 0, use_nano=True)
s += chb(o) + b"\0" elif isinstance(o, (str, bytes)): s += raw(o) else: warning("Malformed option %s", o) return s class DHCP(Packet): name = "DHCP options" fields_desc = [DHCPOptionsField("options", b"")] bind_layers(UDP, BOOTP, dport=67, sport=68) bind_layers(UDP, BOOTP, dport=68, sport=67) bind_bottom_up(UDP, BOOTP, dport=67, sport=67) bind_layers(BOOTP, DHCP, options=b'c\x82Sc') @conf.commands.register def dhcp_request(iface=None, **kargs): """Send a DHCP discover request and return the answer""" if conf.checkIPaddr != 0: warning( "conf.checkIPaddr is not 0, I may not be able to match the answer" ) # noqa: E501 if iface is None: iface = conf.iface fam, hw = get_if_raw_hwaddr(iface) return srp1( Ether(dst="ff:ff:ff:ff:ff:ff") /
PacketListField("attributes", [], RadiusAttribute, length_from=lambda pkt: pkt.len - 20) ] def compute_authenticator(self, packed_request_auth, shared_secret): """ Computes the authenticator field (RFC 2865 - Section 3) """ data = prepare_packed_data(self, packed_request_auth) radius_mac = hashlib.md5(data + shared_secret) return radius_mac.digest() def post_build(self, p, pay): p += pay length = self.len if length is None: length = len(p) p = p[:2] + struct.pack("!H", length) + p[4:] return p bind_bottom_up(UDP, Radius, sport=1812) bind_bottom_up(UDP, Radius, dport=1812) bind_bottom_up(UDP, Radius, sport=1813) bind_bottom_up(UDP, Radius, dport=1813) bind_bottom_up(UDP, Radius, sport=3799) bind_bottom_up(UDP, Radius, dport=3799) bind_layers(UDP, Radius, sport=1812, dport=1812)