ID_EXPERIMENTO: 002
Raw Socket Packet Sniffer
ACTIVE
Python script utilizing raw sockets to capture and parse TCP/IP headers manually. Implements basic SYN-scan detection without relying on libpcap.
OBJETIVO
Manually parse IP/TCP headers to understand protocol structures and detect scanning patterns without relying on Wireshark.
RESTRICCIONES
Requires root/admin privileges. Linux only (AF_PACKET). For macOS use BPF socket instead.
Python Networking Raw Sockets
src/main.py
import socketimport structETH_P_IP = 0x0800def parse_ip(raw: bytes) -> tuple[int, int, str, str]:# Skip 14-byte Ethernet header on AF_PACKETiph = struct.unpack("!BBHHHBBH4s4s", raw[14:34])ihl = (iph[0] & 0xF) * 4proto = iph[6]src = socket.inet_ntoa(iph[8])dst = socket.inet_ntoa(iph[9])return ihl + 14, proto, src, dstdef parse_tcp(raw: bytes, offset: int) -> tuple[int, int, int]:tcph = struct.unpack("!HHLLBBHHH", raw[offset:offset + 20])flags = tcph[5]syn = (flags & 0x02) >> 1fin = flags & 0x01return tcph[0], tcph[1], syndef sniff() -> None:sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_IP))print("[*] Sniffing TCP — Ctrl+C to stop")while True:raw, _ = sock.recvfrom(65535)try:offset, proto, src, dst = parse_ip(raw)if proto != 6: # TCP onlycontinuesp, dp, syn = parse_tcp(raw, offset)if syn:print(f"[SYN] {src}:{sp} -> {dst}:{dp}")except struct.error:continueif __name__ == "__main__":sniff()
MODO_SOLO_LECTURAUTF-8