#!/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(' %s' % (sent, a.mode, ','.join(dsts))) if __name__ == '__main__': main()