Files
LEAF/tests/drill_synsensor.py

190 lines
7.4 KiB
Python
Raw Normal View History

2026-11-15 17:42:41 +01:00
#!/usr/bin/env python3
"""Sensor-side synthetic injector for the live socket drills.
Uses AF_PACKET raw sockets and requires root. Frames are addressed to
the selected gateway MAC. Traffic is visible to the sensor only when its
path crosses the configured mirror; select the interface and route accordingly.
Bounded by design: source and destination must be TEST-NET
(192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24) unless --allow-real-src
is passed (then src stays the sensor's real address). count is capped.
--pcap writes a fixture without sending traffic.
Modes:
icmp echo-request -> sid 1000001 (leaf_action block, any src)
syn TCP SYN ->port -> sid 1000030 when src is 203.0.113.0/24
--no-arp: do not ping the gateway first; use the existing ARP entry only.
--src SRC: forge src (TEST-NET enforced); ARP is still only ever
for the gateway MAC, the forged src never touches ARP.
"""
import argparse
import ipaddress
import re
import socket
import struct
import subprocess
import time
from pathlib import Path
TESTNET = ('192.0.2.0/24', '198.51.100.0/24', '203.0.113.0/24')
_NETS = tuple(ipaddress.ip_network(n) for n in TESTNET)
def in_testnet(addr):
ip = ipaddress.ip_address(addr)
return any(ip in net for net in _NETS)
def checksum(data):
if len(data) % 2:
data += b'\x00'
total = sum(struct.unpack('!%dH' % (len(data) // 2), data))
while total >> 16:
total = (total & 0xffff) + (total >> 16)
return (~total) & 0xffff
def syn_packet(src, dst, dport, index, smac, dmac, flags=2):
a, b = socket.inet_aton(src), socket.inet_aton(dst)
tcp = struct.pack('!HHIIBBHHH', 40000 + index % 20000, dport,
7000 + index, 0, 0x50, flags, 1024, 0, 0)
pseudo = a + b + struct.pack('!BBH', 0, 6, len(tcp))
tcp = tcp[:16] + struct.pack('!H', checksum(pseudo + tcp)) + tcp[18:]
ip = struct.pack('!BBHHHBBH4s4s', 0x45, 0, 40, index % 65536, 0, 64, 6,
0, a, b)
ip = ip[:10] + struct.pack('!H', checksum(ip)) + ip[12:]
return dmac + smac + b'\x08\x00' + ip + tcp
def icmp_packet(src, dst, index, smac, dmac):
payload = b'LEAFDRILL' + bytes((index % 100,) * 8)
icmp = struct.pack('!BBHHH', 8, 0, 0, 0x4C42, index % 65536) + payload
ck = checksum(icmp)
icmp = icmp[:2] + struct.pack('!H', ck) + icmp[4:]
total = 20 + len(icmp)
a, b = socket.inet_aton(src), socket.inet_aton(dst)
ip = struct.pack('!BBHHHBBH4s4s', 0x45, 0, total, index % 65536, 0, 64,
1, 0, a, b)
ip = ip[:10] + struct.pack('!H', checksum(ip)) + ip[12:]
return dmac + smac + b'\x08\x00' + ip + icmp
def pcap_write(path, packets):
with path.open('wb') as f:
f.write(struct.pack('<IHHIIII', 0xa1b2c3d4, 2, 4, 0, 0, 65535, 1))
t = time.time()
for i, data in enumerate(packets):
stamp = t + i * 0.001
f.write(struct.pack('<IIII', int(stamp), int(stamp % 1 * 1e6),
len(data), len(data)) + data)
def resolve_gateway_mac(gateway, interface):
text = subprocess.run(['ip', 'neigh', 'show', gateway, 'dev', interface],
capture_output=True, text=True).stdout
match = re.search(r'lladdr ([0-9a-f:]{17})', text)
return bytes.fromhex(match.group(1).replace(':', '')) if match else None
def route_via(dst):
"""Resolve (gw, dev) for a destination via the kernel routing table."""
out = subprocess.run(['ip', 'route', 'get', dst],
capture_output=True, text=True).stdout
m = re.search(r'via (\S+) dev (\S+)', out)
return m.groups() if m else (None, None)
def mac(value):
return bytes.fromhex(value.replace(':', ''))
def main():
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument('mode', choices=['icmp', 'syn'])
ap.add_argument('--dst', required=True,
help='comma-separated TEST-NET destinations (one-shot '
'flows per dst in (a)); single dst for bursts in (b)')
ap.add_argument('--count', type=int, default=1, help='packets per dst')
ap.add_argument('--port', type=int, default=22)
ap.add_argument('--src', default='', help='spoofed TEST-NET source')
ap.add_argument('--allow-real-src', action='store_true',
help='use the interface address as src (no spoofing)')
ap.add_argument('--interface', default='eth0')
ap.add_argument('--gateway', default='', help='override next-hop (default: '
'kernel route for first --dst)')
ap.add_argument('--no-arp', action='store_true',
help='skip gateway ping probe, use cached ARP entry only')
ap.add_argument('--interval', type=float, default=0.25)
ap.add_argument('--pcap', type=Path,
help='write fixture pcap instead of sending (never on live)')
a = ap.parse_args()
nets = list(_NETS)
dsts = [d.strip() for d in a.dst.split(',') if d.strip()]
if not dsts or not all(in_testnet(d) for d in dsts):
ap.error('--dst must be TEST-NET address(es) only')
if a.src and not in_testnet(a.src):
ap.error('--src must be TEST-NET')
if a.src and a.allow_real_src:
ap.error('--src and --allow-real-src are mutually exclusive')
if not 1 <= a.count <= 500 or not 1 <= a.port <= 65535:
ap.error('count must be 1..500 and port 1..65535')
smac = dmac = b'\x00' * 6 # PCAP fixtures need no real Ethernet endpoint
def build(src, dst, i):
if a.mode == 'icmp':
return icmp_packet(src, dst, i, smac, dmac)
return syn_packet(src, dst, a.port, i, smac, dmac)
if a.pcap:
packets = []
for dst in dsts:
for i in range(a.count):
packets.append(build(a.src or '198.51.100.7', dst, i))
pcap_write(a.pcap, packets)
print('wrote %d packets to %s' % (len(packets), a.pcap))
return
gw, dev = route_via(dsts[0])
if a.gateway:
gw = a.gateway
iface = dev or a.interface
if not gw:
ap.error('no via-route for %s on this sensor' % dsts[0])
smac = mac(Path('/sys/class/net', iface, 'address').read_text().strip())
dmac = resolve_gateway_mac(gw, iface)
if dmac is None:
if a.no_arp:
ap.error('gateway MAC not cached and --no-arp set')
subprocess.run(['ping', '-c1', '-W1', gw], capture_output=True)
dmac = resolve_gateway_mac(gw, iface)
if dmac is None:
ap.error('gateway MAC unresolved for %s' % gw)
if not a.src and not a.allow_real_src:
ap.error('src defaults to real interface address: pass --src '
'or --allow-real-src')
if a.allow_real_src:
out = subprocess.run(['ip', '-4', 'addr', 'show', iface],
capture_output=True, text=True).stdout
m = re.search(r'inet (\d+\.\d+\.\d+\.\d+)/', out)
if not m:
ap.error('no inet address on interface')
real = m.group(1)
sent = 0
with socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) as s:
s.bind((iface, 0))
for dst in dsts:
src = a.src or real
for i in range(a.count):
s.send(build(src, dst, i))
sent += 1
time.sleep(a.interval)
print('sent %d %s packets -> %s' % (sent, a.mode, ','.join(dsts)))
if __name__ == '__main__':
main()