# ############################################################################ # """ Save configuration """ # ############################################################################ conf.contribs['ISOTP'] = \ {'use-can-isotp-kernel-module': ISOTP_KERNEL_MODULE_AVAILABLE} # ############################################################################ # """ reload ISOTP kernel module in case configuration changed """ # ############################################################################ if six.PY3: import importlib if "scapy.contrib.isotp" in sys.modules: importlib.reload(scapy.contrib.isotp) load_contrib("isotp", globals_dict=globals()) if six.PY3 and ISOTP_KERNEL_MODULE_AVAILABLE: if not ISOTPSocket == ISOTPNativeSocket: raise Scapy_Exception("Error in ISOTPSocket import!") else: if not ISOTPSocket == ISOTPSoftSocket: raise Scapy_Exception("Error in ISOTPSocket import!") # ############################################################################ # """ Prepare send_delay on Ecu Answering Machine to stabilize unit tests """ # ############################################################################ from scapy.contrib.automotive.ecu import * log_runtime.debug("Set send delay to lower utilization on CI machines") conf.contribs['EcuAnsweringMachine']['send_delay'] = 0.004
#!/usr/bin/env python import sys import struct import os import argparse from scapy.all import sniff, sendp, hexdump, get_if_list, get_if_hwaddr, bind_layers from scapy.all import Packet, IPOption from scapy.all import PacketListField, ShortField, IntField, LongField, BitField, FieldListField, FieldLenField from scapy.all import IP, UDP, TCP, Ether from scapy.layers.inet import _IPOption_HDR from scapy.fields import * from scapy.all import load_contrib load_contrib('nsh') def get_if(): ifs = get_if_list() iface = None for i in get_if_list(): if "eth0" in i: iface = i break if not iface: print "Cannot find eth0 interface" exit(1) return iface def handle_pkt(pkt, iface): print "got a packet"
def analyze_udp_in_mpls_packets(packets, ip_address, ttl, packet_count, destination_port): """ Analyze passed packets Args: packets('str'): Packets to analyze ip_address ('str'): Destination IP address ttl (`int`): Time to live packet_count (`int`): Packet count to check during packet analysis destination_port (`int`): Destination port start "traceroute" Returns: pkt count Raises: None """ try: from scapy.all import load_contrib, UDP except ImportError: raise ImportError( 'scapy is not installed, please install it by running: ' 'pip install scapy') from None count = 0 for pkt in packets: # Analyze MPLS packets if pkt.type == 34887: load_contrib("mpls") mpls_pkt = MPLS(pkt["Raw"]) if (mpls_pkt.haslayer("IP") and mpls_pkt["IP"].dst == ip_address and mpls_pkt["IP"].ttl == ttl and mpls_pkt.haslayer("UDP")): # Catch the start of source and destination ports if count == 0: sport_count = mpls_pkt["UDP"].sport dport_count = destination_port log.info( "Found a packet that meets the requirement:\nDestination:\t{" "ip_pkt_dst}\nDestination Port:\t{dst_port}\nSource:\t\t{" "ip_pkt_src}\nSource Port:\t{src_port}\nUDP Packet:\t{" "mpls_pkt}\n".format( ip_pkt_dst=mpls_pkt["IP"].dst, dst_port=dport_count, ip_pkt_src=mpls_pkt["IP"].src, src_port=sport_count, mpls_pkt="True" if mpls_pkt["UDP"] else "False", )) count += 1 continue # Verify source and destination ports are incrementing if mpls_pkt["UDP"].sport != sport_count + 1: log.info( "Source port didn't increment to " "{source_port} as expected; instead it is {sp}".format( source_port=sport_count + 1, destination_port=dport_count + 1, sp=mpls_pkt["UDP"].sport, )) return None, 0 elif mpls_pkt["UDP"].dport != dport_count + 1: log.info("destination port didn't increment to " "{destination_port} as expected; instead " "it is {dp}".format( source_port=sport_count + 1, destination_port=dport_count + 1, dp=mpls_pkt["UDP"].dport, )) return None, 0 else: count += 1 sport_count += 1 dport_count += 1 log.info( 'Found a packet that "meets" the requirement:\nDestination:\t{' "ip_pkt_dst}\nDestination Port:\t{dst_port}\nSource:\t\t{" "ip_pkt_src}\nSource Port:\t{src_port}\nUDP Packet:\t{" "mpls_pkt}\n".format( ip_pkt_dst=mpls_pkt["IP"].dst, dst_port=dport_count, ip_pkt_src=mpls_pkt["IP"].src, src_port=sport_count, mpls_pkt="True" if mpls_pkt["UDP"] else "False", )) if count == packet_count: return pkt, count return None, count
STDOUT = sys.stdout logging.getLogger("scapy.loading").setLevel(logging.ERROR) def _get_contrib(): import scapy mods = [] name = "*.py" name = os.path.join(os.path.dirname(scapy.__file__), "contrib", name) for f in glob.glob(name): mod = os.path.basename(f) if mod.startswith("__"): continue if mod.endswith(".py"): mod = mod[:-3] mods.append(mod) return mods try: from scapy import all as scapylib mods = _get_contrib() for mod in mods: scapylib.load_contrib(mod) except ImportError as err: print( '*WARN* import scapy failed, please check whether scapy is installed') raise err finally: sys.stdout = STDOUT
#!/usr/bin/env python from scapy.all import send, IP, load_contrib load_contrib('mpls') p = Ether(type=34887) / IP(dst='10.0.0.2') / MPLS() p = MPLS(p) # print(p.show()) send(p, count=4)
#! /usr/bin/env python # -*- coding: utf-8 -*- import yaml import copy import traceback from scapy.all import (TCP, UDP, IP, IPv6, Ether, Dot1Q, sendp, ARP, ICMP, load_contrib) load_contrib("ospf") def is_proto(proto, s): if isinstance(proto, str): return proto == s if isinstance(proto, list) and len(proto) > 0: return proto[0] == s return False def get_ipver(s): if s is not None and ":" in s: return 5 return 4 class TxPayload(object): def __init__(self, cfg): self.cfg = cfg def pkt(self): args = copy.copy(self.cfg) proto = args.pop("proto")
str("[!] Unknown message Exception: " + packet.__repr__()), "red")) pkt.extended_address = extID1 CanSocket_communication.sniff(prn=get_ISOTP_FC, timeout=0.2, started_callback=lambda: CanSocket_communication. send(pkt)) time.sleep(0.5) for id in range(min_ID, max_ID + 1): pkt.identifier = id fast_search(load) load_contrib("isotp") load_contrib("cansocket") load_layer("can") extended = False scan_done = False awake_interface = False extended_only = False # Dictionary with Send-to-ID as key and a tuple (received packet, Recv_ID) found_packets = {} # List with paket-IDs of background noise packets noise_IDs = [] # Seconds to listen to noise noise_listen_time = 6 # Number of pakets send in a single blow extended_load = 100
import os import glob STDOUT = sys.stdout logging.getLogger("scapy.loading").setLevel(logging.ERROR) def _get_contrib(): import scapy mods = [] name="*.py" name = os.path.join(os.path.dirname(scapy.__file__), "contrib", name) for f in glob.glob(name): mod = os.path.basename(f) if mod.startswith("__"): continue if mod.endswith(".py"): mod = mod[:-3] mods.append(mod) return mods try: from scapy import all as scapylib mods = _get_contrib() for mod in mods: scapylib.load_contrib(mod) except ImportError, err: print '*WARN* import scapy failed, please check whether scapy is installed' raise err finally: sys.stdout = STDOUT