Show HN: Scapy for the Agentic SRE A developer released Crafty, a packet-crafting and network-testing tool modeled on Scapy, in which traffic is sent from a real interface and the program reacts to returning packets. Crafty lets users build packets bit by bit or from its own protocol stacks, with internals exposed through a script language: stacks are written as slash-separated layers like /IP(dst=192.0.2.10)/UDP(dst=7), terminal layers such as Raw, Request, Reply, Query and Answer end a stack and send the message, and blocks support repeat loops, expect with timeouts, try/retry error handling and catchable errors including Timeout, Closed, CannotConnect, NoRoute, NoPort, Unset, Invalid, Unresolved and Assertion. In the posted example, a script sends three UDP datagrams to an echo server at 192.0.2.10 port 7 and reports "3 answers out of 3: all back" after 0.3s with status OK, run via sudo crafty --udp 40000-40010 --fw intro.cfty. Crafty sends traffic from a real interface and reacts to what comes back, Packets can be crafted to the bit or built by crafty's own stacks, which internals are accessible. Three datagrams to a UDP echo server: how many come back? "IP", "UDP" and "Raw" are layers of a protocol stack. Every stack starts at the interface, with an "Eth" layer that can be left out: /IP dst=192.0.2.10 /UDP dst=7 is /Eth/IP dst=192.0.2.10 /UDP dst=7 . Followed by a block, a stack is the current stack of that block: /IP dst=192.0.2.10 /UDP dst=7 { answers = 0 "answers" is a variable holding integers Repeats the block 3 times, "I" being the loop counter, from 0: repeat var=I count=3 every=100ms { Raw is a terminal layer: it sends the message made from /IP dst=192.0.2.10 /UDP dst=7 /Raw "ping ${I}" Unset options will be filled in automatically. Raw "ping ${I}" expect waits for a packet that matches a pattern; here, any Raw layer on top of the current stack, coming back: expect timeout=1s Raw { answers += 1 print MATCH Raw .data MATCH is the packet that matched } else {} after the timeout: a lost answer is no error } An "if", as a block, is worth the value of the branch it runs: verdict = if answers == 3 { "all back" } else { "some lost" } print "${answers} answers out of 3: ${verdict}" } % sudo crafty --udp 40000-40010 --fw intro.cfty ... ping 0 ping 1 ping 2 3 answers out of 3: all back Done after 0.3s, status: OK. A stack is layers and their options, separated by slashes, like file paths. An absolute stack starts with /IP with an Eth layer implied . A relative stack goes on top of the current one. Some layers are terminal Raw , Request , Reply , Query , Answer : they end the stack and send the message. An incomplete stack is followed instead, on the same line, by a block of further instructions. A few layers can be both HttpRequest , HttpAnswer , WebSocket , and are terminal unless followed by a block or a layer. So X/Y { Z } is not X/Y then { Z } on the next line: that sends X/Y or fails, if Y cannot end a message , then runs Z apart. The layers of a stack are streams: UDP picks its source port once from --udp , and every message sent and every pattern on top of it belong to that stream. An error leaves the enclosing blocks one after the other until an enclosing try handles it or a retry runs its block again; uncaught errors end the program. Only these errors can be caught: Timeout of expect or on , Closed a TCP connection , CannotConnect writing to a TCP connection refused or timed out , NoRoute , NoPort no source port left to pick , Unset getenv , arg , a missing map key or packet layer , Invalid converting a string or bytes , Unresolved resolve , hostname and Assertion assert . In a handler, ERROR is the message and MATCH the packet that caused the error the RST or ICMP error refusing a connection , else empty. n = 1 try { n := int arg 0 } Unset {} no argument: keep 1 | Invalid { print err ERROR } ERROR is the message retry Timeout|Closed max=2 { retries on these errors only /IP dst=192.0.2.10 /TCP dst=7 { Raw "hello" expect timeout=1s Raw { print MATCH Raw .data } } } Is anyone listening on UDP port 7? target = ip addr getenv "TARGET" Read the envvar and cast to an IP, or fail /IP dst=target /UDP dst=7 { Raw "hello" two messages on top of the same stack: Raw "world" the same stream, from the same port Waits for the first packet that matches either pattern: a datagram back, or the ICMP error a closed port answers with. "../" goes back to /IP dst=target , and ICMP goes on top of that IP stream instead of UDP: these are the ICMP errors about it, whoever sends them a router . expect timeout=1s Raw { print MATCH Raw .data } | ../ICMP/DestUnreachable code == PORT UNREACHABLE { print "closed" } } hello With dst=8 , where nothing listens, it prints closed . Each leading ../ goes one layer down the current stack: here, ../ is /IP dst=target and ../../ is /Eth . Relative stacks reuse opened streams, whereas absolute stacks create new streams: /IP/ICMP/DestUnreachable matches any Dest-Unreachable packet whereas ../ICMP matches only those about the packets of /IP dst=target . Like relative patterns, relative stacks can go back with ../ and modify upper layers' options while reusing the stream: The same stream, but for one datagram with a TTL of 1: /IP dst=192.0.2.10 /TCP dst=7 { Raw "ttl 64" print "Sent from port ${LAST TCP .src}" LAST is the last packet sent ../../ goes back to /Eth, where IP and TCP land on the IP and TCP of the current stack. They overlay them: the same streams, with their options dst, the ports, TCP internal state unless overwritten. ttl=1 is for this message only. ../../IP ttl=1 /TCP/Raw "ttl 1" print "Also sent from port ${LAST TCP .src}" repeat count=2 { Wait for Raw in the same stream unlike with /IP/TCP/Raw that would match even outside this stream expect timeout=1s Raw { print MATCH Raw .data } } } Sent from port 40000 Also sent from port 40000 ttl 64 ttl 1 The rule, for stacks and patterns alike: relative ones stay on the streams of the current stack ../ overlaying some of its layers ; absolute ones start anew from Eth . Overlaying can set a temporary value for an earlier option. So far, streams were self-driven : crafty resolves addresses, connects, retransmits, fragments and reassembles. A bang makes a layer manual , for packets as on the wire: TCP flags=SYN, ack num=0 is a SYN packet with this sequence number regardless of the state of the TCP connection. On reception, IP sees each fragment and TCP each segment, even without data. A SYN of our own, and the SYN-ACK that answers it: target = 192.0.2.10 { "on" runs its block for each matching packet, while the enclosing block goes on; here, for one SYN-ACK at most, until 1s after the block: on max=1 linger=1s /IP src == target /TCP src == 7 && flags & SYN && ack num 1000 && ack num <= 2000 { print "SYN-ACK: seq ${MATCH TCP .seq num}, ack ${MATCH TCP .ack num}" } Sends the segment, and waits until it is seen leaving: "seg" is the packet as captured. seg = /IP dst=target /TCP src=40000, dst=7, flags=SYN, seq num=1000 /Raw print "SYN of seq ${seg TCP .seq num} sent" } % sudo crafty --tcp 40000 --fw syn.cfty SYN of seq 1000 sent SYN-ACK: seq 1969569245, ack 1001 encode STACK is the bytes of the layers of STACK , all manual, as if sent. An IP or IP6 right below them fills in the checksum of what they carry. This is how to fragment by hand, since no fragment has what the checksum covers: A datagram in two fragments, the last first: /IP dst=target, id=1234, proto=17 { d = encode UDP src=4000, dst=7 /Raw randbytes 100 ../IP frag offset=8 /Raw d 64: ../IP more frags=true /Raw d :64 } crafty options file arg... or crafty options -e program arg... , where file - is stdin. What follow the file are the program's own arguments that are returned by arg n . With -e , every argument that's not an option is a program's argument, and -- ends the options. Options: - -e PROG : the program itself, rather than a file. - -i IFACE : the interface to send from and capture on, rather than that of the default route. Crafty needs root, or setcap cap net raw,cap net admin=ep . - --routing kernel|manual : kernel default uses kernel routes. manual takes gateway from the interface and then does ARP etc. - --tcp LO-HI , --udp LO-HI repeatable : the ranges to pick source ports from see also Budget, ports and permissions budget-ports-and-permissions . - --fw : crafty shares the interface's address with the host, whose kernel would answer what crafty receives with TCP resets and ICMP port unreachables. --fw keeps the kernel off the ports of --tcp and --udp . - --ip ADDR : an address of crafty's own instead, on the interface's network, for which crafty answers ARP. Then --fw is not needed. - -p /PATTERN or --print-packets : prints the packets à la tcpdump. - --format csv|json : change the output format to csv or json json makes -p print all available details of every packet . - --stats : prints the stats of each stream see stats as it ends. - --check : check the program and quit. - --max-duration default: 10m , --max-packets , --max-bytes , --max-packets-per-secs , --max-bytes-per-secs , --max-syns , --max-syns-per-secs , --max-ram : self-imposed budget. - --local-ip accept|deny:CIDR , --remote-ip accept|deny:CIDR repeatable , --mac-spoofing BOOL , --exfiltration BOOL , --promiscuous BOOL : permissions see Budget, ports and permissions budget-ports-and-permissions . - --reference : prints the reference manual. - --examples : prints many examples of use. - --cliref : exhaustive list of options including seldom used ones. Exit status: 0 when the program completes, 1 when an error ends it, 2 when it does not compile, 3 when a budget stops it, 4 when it sends what its permissions deny, 130 when interrupted. - Use resolve "hostname" to resolve a hostname - Errors and warnings go to stderr, all else to stdout: filter stdout as you like, but not stderr crafty x.cfty | grep ... , not 2 &1 | grep - Quote programs as -e '...' or - <<'EOF' , lest the shell expand ${} - Parameterize your programs with arguments crafty x.cfty 10.0.0.1 5 , read with arg 0 , arg 1 or environment variables TARGET=10.0.0.1 crafty x.cfty , read with getenv "TARGET" then cast. - When unsure, use --max-duration - Crafty is not Python, despite for x in a and comprehensions: only the functions of the reference exist. - A statement ends at the end of its line or at a ; . Within parentheses, brackets and braces, after a binary operator, or before an else , elsif or | , a new line is plain white space. - Comments run from a to the end of the line. A followed by a hexadecimal digit is a byte literal instead. - Names of layers, fields, functions and keywords are case insensitive. Constants, MATCH , LAST , OWN IP and OWN IPS are upper case. Variables and constructors are case sensitive. - bool : true , false . - int : 42 , -1 , 0x1f , 0o17 , 0b101 . - float : 1.5 , 2e-3 . - byte : 1f . - bytes: deadbeef an even number of digits . An array of bytes. - string : "text ${expr}" . - interval : 5s , 10ms , 1m30s , 1.5ms , -2s . Units: d , h , m , s , ms , us or µs , ns , ps . Printed in one unit up to s : 157.949ms , 8.85159µs , 3725.5s . - time : 2026-10-20T22:02:45.25Z , 2026-10-20T22:02+02:00 , 2026-10-20T22:02 local time . Printed in UTC. int t and float t give its unix timestamp, time secs the reverse. - ip : 192.0.2.1 , 2001:db8::1 . - mac : aa:bb:cc:dd:ee:ff . - cidr : 10.0.0.0/8 , 2001:db8::/32 , no bit set beyond the mask. ip in net tells whether an address is in it. - arrays: 1, 2, 3 . Items of one type, typed lazily when that fails: 0s 0 . - maps: 192.0.2.1: "gw", ::1: "lo" , a string ip , in no particular order. map key=k, default=v is an empty map with keys of the type of k , where missing keys have the value v . - comprehensions: e for x in a if c , k: v for x in a if c , x being an item of the array or map a as {key: k, value: v} . - records: {name: "gw", ip: 192.0.2.1} . {} is an empty block, not a record. - variants: Ok 42 , Failed "timeout" , Pending . A constructor starts with a capital letter; a bare name that is a variable is the variable. The layers of a packet are variants too, of constructors IP , UDP ... Literals are whole words: 1.2.3.4 is an IP address, 5s an interval. Strings interpolate any expression: "ttl ${MATCH IP .ttl - 1}" . Escapes: \n , \r , \t , \0 , \\ , \" , \$ , \xHH . Interpolated bytes are written in hexadecimal 68656c6c6f ; bytes passed where a string is expected, as to print , are text, as string b makes them. Conversions happen where that make sense: an int to a float, a byte to an int, an IP address or a MAC address to bytes and back, an int to a bool... Bytes compare with the others as bytes. Others use the functions int , float , bool , byte , interval , time , ip addr , mac addr and cidr , which also read a string as a literal: ip addr getenv "SERVER" . An IPv4 address converts to an int: ip addr int a + 1 . + can concatenate strings and bytes. Variants need no declaration. Where variants meet items of an array, branches of an if , values assigned to a variable... , they make one variant with the constructors of all, which case tells apart: result = Pending of type Failed string | Got int | Pending expect Raw "pong" { result := Got length MATCH } | ../ICMP { result := Failed "unreachable" } print case result Got { "${I} layers" } else { "${result}" } - x = expr declares x in the current block, with the type of expr . An inner block may shadow it. - x := expr assigns it, and x += expr also -= , = , etc. updates it. - Predefined: MATCH in the block of an expect or on , or a handler of try , ERROR in a handler of try , LAST the last packet sent, once a block has sent one , I , the counter of a repeat , BUDGET , PORTS , PERMISSIONS , OWN IPS , the addresses of the interface or --ip 's , IPv4 ones first, and OWN IP , the first of them. - LAST is the packet as given, not as it left: reading a field that only the wire knows LAST Eth .ts , or IP.id , UDP.checksum ... under a self-driven IP is an error. In contrast, p = MESSAGE captures the packet as it leaves see Self-driven vs manual stacks self-driven-vs-manual-stacks . A program may declare them, once each, at its top level, with literals only: BUDGET = {max duration: 30s, max syns: 30} PORTS = {tcp: 40000, 40100 , udp: 5000, 5000 } PERMISSIONS = {local ips: Accept 10.20.4.1 , spoofs 10.20.4.1 remote ips: Deny 192.0.2.66 , Accept 192.0.2.0/24 } - BUDGET 's fields are the budget options of crafty, named alike. - max ram , in bytes. - PORTS has ranges first, last by protocol; default to no port. - crafty runs with what both the program and the command line allow. - PERMISSIONS : - local ips , remote ips : rules Accept x or Deny x , x being a CIDR or OWN IP S ; the first that matches an address decides, and none matching denies. local ips always ends with Accept OWN IPS ; unset, remote ips accepts any. Sending from an address takes local ips accepting it. - mac spoofing : allows sending from another MAC than the interface's. - exfiltration : allows sending a payload made of the payload of a received packet or of getenv . - promiscuous : receives the frames for other addresses too, unless local ips denies them. - A sent packet denied by the above rules stops the program. A received one that is denied is dropped. Received ICMP errors are judged by the packet they quote, not by the router that sent it. Operators, from the tightest binding to the loosest: 1. x , -x . 2. , / , % : on numbers. An array, a byte or a string times an int repeats it. 3. + , - : on numbers; a time minus a time is an interval, a time plus an interval or a number of seconds is a time. + also concatenates arrays 1 + 2, 3 and appends or prepends an item 1, 2 + 3 , 0 + 1, 2 . To + , a byte is one-element bytes: 41 + 42 is 4142 . A string plus a string or bytes is a string; use string b for bytes as text. 4. << , : shift an int or a byte by an int; keeps the sign of an int, and a byte stays 8 bits. 5. & , then ^ , then | : bitwise, on ints or bytes. 6. == , = , < , <= , , = , and in an IP address in a CIDR . 7. && , then || . 8. c ? a : b : a if c , else b , computing only that one. Also: r.field , a i a -1 is the last item , m k , f arg, name=arg , and the layer selectors of Patterns patterns . Arrays, bytes and strings slice as in Python. a i := v and m k += 1 change an item, adding the key to a map if need be. Blocks, if , case , expect and try are expressions : y = if cond 1 else 2 ttl = case var=h MATCH 1 IP { h.ttl } else { 0 } resp = expect timeout=1s Raw { Got MATCH Raw .data } else { Lost } rtt = { t0 = now ; Request "ping" ; expect Reply {} ; now - t0 } code = try { MATCH DestUnreachable .code } Unset { -1 } Sent messages can be assigned to a variable: p = /IP dst=target /TCP src=1, dst=2, flags=SYN /Raw This sends a packet and waits until it is recaptured on its way out. Its timestamp p Eth .ts is therefore accurate. Through self-driven layers, p is the first frame that carries some of the message. Self-driven and manual layers can be mixed with some restrictions: a manual layer cannot carry a self-driven one: IP/TCP is fine, IP /TCP is not. - /IP/UDP dst == 7 /Raw : absolute , matched from the interface up. - Raw "pong" : relative , on top of the current stack. - ../ICMP/DestUnreachable : relative to a layer below the top of the current stack. - Raw "pong" | ../ICMP : alternatives. - UDP src == port : conditions in parentheses are boolean expressions. - IP.src is the field of the innermost IP layer, this one included. A path names the layers below the one meant, being any one: /IP.src is the first IP's src , ICMP/ /IP.src the one on top of any ICMP error. - A condition that is not a bool compares the default field: Raw "pong" is Raw data == "pong" . - The fields that can be read depend on the mode see Layers layers : a self-driven TCP shows its ports, a manual TCP each segment's header. MATCH is the packet that matched, as an array of layers: MATCH IP .src , MATCH Raw .data , with paths as in conditions MATCH /IP , MATCH ICMP/ /IP . MATCH 1 and MATCH ICMP/ are layers of any allowed kinds, which case tells apart: for l in MATCH { print case l IP { "IP from ${I.src}" } | UDP { "UDP to ${I.dst}" } else { "other" } } LAST , likewise, is the last packet sent. Self-driven layers show their options, what crafty picked source ports and their defaults ttl , but not what their engine computes checksums . - repeat var=v count=n every=d for=d { ... } : runs the block count times, or while for has not elapsed. An iteration starts every after the previous one started. v default I counts from 0. - for v in a every=d for=d { ... } : a repeat over the items v of the array or map a as {key: k, value: v} . - retry E|E max=n { ... } : runs the block again, up to n times default 3 , while it fails with one of these errors. The last error escapes. - try { ... } E|E { ... } | E { ... } else { ... } : runs the block of the first handler naming the error, or else that of else any error that can be caught . Other errors escape. - if COND STMT elsif COND STMT else STMT : conditionals. - case var=v X C { ... } | C { ... } else { ... } : runs the block of the constructor of X , where v default I is what that constructor holds. - break n : leaves the n default 1 innermost repeat , for , on or spawn . - continue n : likewise, but goes on with the next iteration of the n th or, for an on , waits for its next match . - exit : ends the program successfully, from anywhere. - wait d or sleep d : pauses. - expect timeout=d PATTERN { ... } | PATTERN { ... } else { ... } : waits for the first packet that matches any pattern, then runs its block; after the timeout none by default , runs else , or without one fails with Timeout . Its value is that of the block it ran. - on for=d linger=d timeout=d max=n PATTERN { ... } | PATTERN { ... } : the enclosing block goes on; each matching packet runs the block of its pattern, repeatedly max times or unlimited until its lifetime or that of the enclosing blocks are over. linger default 0 instructs that enclosing block to wait further. - spawn for=d { ... } : runs the block alongside the enclosing one, which goes on. With for , the enclosing block waits for at the end, cancelling it after d ; without, it ends with the statements of the enclosing block. - { ... } : a block. Ends once its statements are done, its linger s waited and its on s and spawn s with a for ended. Leaving a block, normally or on an error, cancels what it still had going. - print x , print err x : to stdout, to stderr, as "${x}" bytes as text . - string x : x as "${x}" bytes as text . - format x : any value as a string, in the format of --format . CSV takes a scalar, or a record, array or map of scalars. - summary x : return {count, min, mean, stddev, p50, p95, p99, max} from all values in x key by key if x is a map or a record . - report x, name=s : prints the summary of x according to --format . - assert cond, msg=s : fails if cond is false. - now : the current time. - stats : the stats so far of the streams of the current stack. Every stream counts packets out , packets in , bytes out , bytes in the payloads at that layer . A self-driven TCP connection counts its segments, retransmissions included, and adds, as Linux's tcp info : bytes acked , bytes received in order , retrans , dupacks , timeouts , holes in gaps opened in what was received , ooo in segments filling a gap within min rtt of the one beyond it , dup in segments with only data already receiveds , srtt , rttvar , min rtt , rtt samples , rto , snd mss , rcv mss , cwnd , ssthresh 2^31-1 before any loss , snd wnd the peer's window , rcv wnd , snd wscale and rcv wscale the window shifts the peer and we offered, -1 if none and established . An IP or IP6 stream adds fragmented , frags out , frags in , reassembled and reasm timeouts incomplete after 30s, or 60s for IP6 . - getenv name, default=s - arg n, default=s : the n-th argument after the program, from 0. nargs : how many there are. - resolve name : the addresses of a name, IPv4 first, as an array, from the system's resolver. Blocking. - hostname ip, default=s : the name of an address. Blocking. - is ip4 ip , is ip6 ip - rand max : an int or a float in 0, max or a bool if max is true - randbytes len : random bytes. - int x , float x , bool x , byte x the low 8 bits : of intervals, times, or numbers - interval secs . - exp x , ln x , log x base 10 . log2 n . - split s, by : the parts of s between the occurrences of by . - array init=v, len=n , length a or count a , of an array, a map or a string , concat a, b , append a, x , prepend x, a . - range n , range a, b : the ints from 0 or a up to, excluding, n or b . - sorted a : a sorted copy. - sort a : in place. - has m, k , remove m, k a copy , keys m , values m on map m . - any a , all a : of an array of bools or ints, or the values of a map. - sum a , min a , max a , mean a , stddev a , percentile a, p : of an array, or the values of a map. - histogram a, bucket=b : the values counted in buckets of width b from 0, as an array of {min, count, max} , min and max being observed values. - checksum b : the 2 bytes of the Internet checksum of b RFC 1071 - be16 x , le16 x , all the way to 64: the bytes of an int, big and little endian. Each field has the modes in which it can be set as an option and read in a condition or in MATCH : M manual, S self-driven. A layer with a single mode is manual. key fields tell streams apart. Every layer but the terminal ones has also length : int; read M; the bytes it carries TCP length 0 : segments with data . Raw has it too: the bytes of its data. Exception: UDP.length is the length field of the header. - src : mac; set M; read M, S. Default: the interface's. - dst : mac; set M; read M, S. Default: what the interface knows of the next hop of the route neighbors, gateway , without asking. - proto : int; set M; read M, S. Default: the layer on top. - ts : time; read M, S. When the frame was captured; for what is reassembled, the frame that completed it. Unset in LAST . Self-driven, it carries IP and IP6 , and finds next hops with ARP and neighbor discovery or ask the kernel . Eth frames go out as they are. - src key : ip; set M, S; read M, S. Default: the interface's address that reaches dst . - dst key : ip; set M, S; read M, S. Required. - proto : int; set M, S; read M, S. Default: the layer on top. - tos : int; set M, S; read M, S. - ttl : int; set M, S; read M, S. Default 64. - dont frag : bool; set M, S; read M, S. Default false. - id : int; set M; read M, S. Default: the stream's counter, from a random value. - more frags : bool; set M; read M. - frag offset : int; set M; read M. In blocks of 8 bytes. - tot len : int; set M; read M. Default: computed. - options : bytes; set M, S; read M, S. - rr slots : int; set M, S; read M, S. The slots of the record route option, up to 9, or -1 without one. - record route : ip ; set M, S; read M, S. The addresses recorded in it. Given, they fill its first slots; rr slots is then their number unless given. - is fragment : bool; read M. Self-driven IP fragments to the MTU and reassembles. tos , ttl , dont frag and options apply to what it sends, but for the segments of a self-driven TCP connection. IP sends the header as given, but for the checksum. - src key : ip; set M, S; read M, S. Default: the interface's address that reaches dst . - dst key : ip; set M, S; read M, S. Required. - proto : int; set M, S; read M, S. Default: the layer on top. Received, that past the extension headers. - traffic class : int; set M, S; read M, S. Default 0. - hop limit : int; set M, S; read M, S. Default 64. - flow label : int; set M; read M, S. Default 0. - frag id : int; set M; read M. Default 0. - frag offset : int; set M; read M. In blocks of 8 bytes. Default 0. - more frags : bool; set M; read M. Default false. - is fragment : bool; read M. The frag fields and more frags are those of the fragment header: 0 and false without one. Self-driven IP6 fragments to the MTU and reassembles, as IP . - src key : int; set M, S; read M, S. Default: a port of --tcp . - dst key : int; set M, S; read M, S. Required. - seq num : int; set M; read M. - ack num : int; set M; read M. - flags : int; set M; read M. Constants FIN , SYN , RST , PSH , ACK , URG , ECE , CWR . - win size : int; set M; read M. - urg ptr : int; set M; read M. - checksum : int; set M; read M. Default: computed, as when 0, but in a fragment see encode . - options : bytes; set M; read M. Default: none. - mss , wscale : int; set M, S; read M. The first option of each kind, or -1. - ts val , ts ecr : int; set M; read M. Those of the timestamps option, or -1. - sack ok : bool; set M; read M. Whether SACK is permitted. The fields of the options cannot be given with options . A missing ts val or ts ecr is 0. Given -1 they leave it out. Self-driven, mss and wscale are what the connection offers -1 offers no window scaling, which caps its window at 64KiB . Self-driven, the first message sent connects, and what follows waits for the connection. A TCP stream created by a pattern accepts the connection instead. TCP segments take the sequence and ack numbers, the window and the ACK|PSH flags of the stream's connection when not given, and update them. - src key : int; set M; read M. Default: a port of --udp . - dst key : int; set M; read M. Required, unless told by the layer on top. - length : int; set M; read M. Default: computed. - checksum : int; set M; read M. Default: computed, as when 0, but in a fragment see encode . - type , code : int; set M; read M. Set by the message on top, but for Raw : ICMP type=13 /Raw ... needs a type code defaults to 0 . - type , code : int; set M; read M. As those of ICMP . On top: Echo 128, 129 , DestUnreachable 1 , PacketTooBig 2 , TimeExceeded 3 , RouterSolicit 133 , RouterAdvert 134 , Redirect 137 , else Raw . IP6 computes the checksum. - id key : int; set M; read M. Default: a free random id. The stream of an echo id, for Request and Reply messages, which count their sequence numbers per stream. - seq : int; set M; read M. Default: the stream's counter, from 1. - payload : bytes; set M; read M. Default field. - code : int; set M; read M. Default 0. Constants: NET UNREACHABLE , TTL EXCEEDED , PORT UNREACHABLE6 etc. - mtu : int; set M; read M. Not in TimeExceeded ; default 0. Always 0 in a DestUnreachable of ICMP6 . On top is the quoted IP IP6 under ICMP6 the error is about, or Raw . RouterSolicit : - src lla : mac; set M; read M. Default: the interface's. RouterAdvert : - hop limit : int; set M; read M. Default 64. - managed , other config : bool; set M; read M. Default false. - flags : int; set M; read M. The 6 other bits. Default 0. - lifetime : int; set M; read M. Seconds. Default 1800. - reachable , retrans : int; set M; read M. Milliseconds. Default 0. - src lla : mac; set M; read M. Default: the interface's. - mtu : int; set M; read M. Default -1. - prefixes : records; set M; read M. Default none. Each is {prefix: cidr, on link: bool, autonomous: bool, valid: int, preferred: int} . Redirect : - target , dst : ip; set M; read M. Required. - target lla : mac; set M; read M. Default 00:00:00:00:00:00. All have options : bytes; set M; read M. On top of Redirect is the start of the packet redirected, a quoted IP6 or Raw , cut to a multiple of 8 bytes. p = {prefix: 2001:db8:1::/64, on link: true, autonomous: true, valid: 86400, preferred: 14400} /IP6 dst=ff02::1 /ICMP6/RouterAdvert mtu=1400, prefixes= p They have the fields of IP , IP6 , UDP and TCP but is fragment , all readable and settable. They are no streams: a quoted TCP segment is no part of a connection. Errors print them as IP? , IP6? , UDP? , TCP? . on for=5s /IP/ICMP/TimeExceeded/IP dst == target /UDP dst == 33434 { print "from ${MATCH /IP .src}, ttl ${MATCH TimeExceeded/IP .ttl}" } MATCH TimeExceeded/IP is the quoted packet, MATCH /IP the error's. A quote is often cut 8 bytes after the IP header: absent fields will read 0. A quoted first fragment has its UDP or TCP on top; a later one, Raw . Sent, a quoted IP or IP6 needs a src and a dst ; lengths and checksums are managed. /IP6 dst=2001:db8::2 /UDP src=4000, dst=9 /Raw "anyone?" expect timeout=1s /IP6/ICMP6/DestUnreachable code == PORT UNREACHABLE6 /IP6/UDP src == 4000 { print "closed, says ${MATCH /IP6 .src}" } - id key : int; set M; read M. Default: a free random id. The stream of a DNS id, for Query and Answer messages. - name : string; set M; read M. Default field; required. Without the trailing dot "example.com" , but for the root "." . - type : int; set M; read M. Default TYPE A . Constants TYPE A , TYPE NS , etc. - class : int; set M; read M. Default CLASS IN . - opcode : int; set M; read M. Default 0. - authoritative , truncated , rec avail , authentic data , checking disabled : bool; set M; read M. Default false. - rec desired : bool; set M; read M. Default true. - status : int; set M; read M. Default NOERROR . Constants NOERROR , FORMERR , SERVFAIL , etc. - answers , authority , additional : records; set M; read M. Default none. Each is {name: string, type: int, class: int, ttl: int, data: bytes} ; the data of an A record converts to an IP address. A message has one question name , type , class : the first, of a received message with several. The stream of the HTTP/1.x messages of a TCP connection, then, after a 101 answer received or sent, of its WebSocket frames. On TCP , each is seen once complete; on TCP , those that fill a segment. An answer without a length ends with the connection or the segment's FIN . Not seen: the answer to a HEAD it waits for a body . - method : string; set M; read M. Of HttpRequest . Default "GET" . - url : string; set M; read M. Of HttpRequest . Default field; default "/" . - code : int; set M; read M. Of HttpAnswer . Default field; required. - version : string; set M; read M. Default "HTTP/1.1" . - headers : records; set M; read M. Default none. Each is {name: string, value: string} , sent in order, as given: give a Host . Alone, a message has no body; Raw on top is its body, sent as given. Content-Length is added unless a length or Transfer-Encoding header is given. Received, MATCH Raw .data is the body, dechunked. A 101 answer to a request with a Sec-WebSocket-Key gets its Sec-WebSocket-Accept , unless given. /IP dst=192.0.2.10 /TCP dst=80 /HTTP { HttpRequest "/upload", method="POST", headers= {name: "Host", value: "example.com"} /Raw "data" expect timeout=1s HttpAnswer code = 400 { print "refused: ${MATCH HttpAnswer .code}" } } - url : string; set M. Default field; required. Gives the request line and the Host ; the stack gives the destination. No wss or https : no TLS. - version : string; set M. Default "HTTP/1.1" . - headers : records; set M. Default none. Added last, replacing those of the same name. Must give a Host if url has no host. The GET asking for a WebSocket. Only sent: it is received, matched and read back p HttpRequest as an HttpRequest . - opcode : int; set M, S; read M, S. Default field; default WS BINARY . Constants WS CONTINUATION , WS TEXT , WS BINARY , WS CLOSE , etc. - final : bool; set M; read M. Default true. - masked : bool; set M; read M. Default: whether this side sent the request. - mask : int; set M; read M. As on the wire 0 if not masked . Default: random. Raw on top is the payload, unmasked. WebSocket is each frame, sent as given. WebSocket is each message, its fragments joined, and each close; once a self-driven stack or pattern uses the stream, it answers pings which it does not show and a close it did not send. /IP dst=192.0.2.10 /TCP dst=80 /HTTP { HttpUpgrade "ws://example.com/chat" expect timeout=1s HttpAnswer 101 {} WebSocket WS TEXT /Raw "hello" expect timeout=1s WebSocket WS TEXT { print MATCH Raw .data } WebSocket WS CLOSE } Raw on Eth , IP , TCP , UDP , ICMP , the ICMP errors, the quoted layers, HttpRequest , HttpAnswer and WebSocket , terminal - data : bytes; set M; read M. Default field. What a layer carries when not decoded further. Sent as given. /IP dst=192.0.2.53 /UDP/DNS { Query "www.example.com" expect timeout=2s Answer status == NOERROR { a = MATCH Answer .answers assert length a 0 && a 0 .type == TYPE A, msg="no address" /IP dst=a 0 .data /ICMP/Echo { received = 0 repeat count=5 every=200ms { Request "hi" expect timeout=1s Reply { received += 1 print "reply from ${MATCH IP .src}: seq=${MATCH Reply .seq} ttl=${MATCH IP .ttl}" } else {} } print "${received} replies out of 5" } } | Answer { assert false, msg="DNS error ${MATCH Answer .status}" } } % sudo crafty --ip 192.0.2.5 ping.cfty reply from 192.0.2.10: seq=1 ttl=64 ... 5 replies out of 5 The replies come back to the Echo stream of the requests, whatever its id. Every 10s, the round trip times of the last 10s /IP dst=192.0.2.10 /UDP dst=7 { rtts = spawn { repeat every=10s { report rtts, name="rtt" ; rtts := } } repeat count=6000 every=10ms { p = Raw "probe ${I}" expect timeout=500ms Raw "probe ${I}" { rtts += MATCH Eth .ts - p Eth .ts } else {} } } With --format json , each report is a line such as {"type":"report","ts":10.0,"name":"rtt","value":{"count":998,"max":0.0021,"mean":0.0012,...}} intervals in seconds . The first one, at 0s, has only a count of 0. 100 probes to a UDP echo server: how many come back, and how fast? /IP dst=192.0.2.10 /UDP dst=7 { rtts = repeat count=100 every=10ms { p = Raw "probe ${I}" expect timeout=500ms Raw "probe ${I}" { rtts += MATCH Eth .ts - p Eth .ts } else {} } print "${length rtts }/100 echoed, rtt min ${min rtts } median ${percentile rtts, 50 } p99 ${percentile rtts, 99 } max ${max rtts }" for b in histogram rtts, bucket=1ms { print "${b.min} to ${b.max}: ${b.count}" } } % sudo crafty --ip 192.0.2.5 --udp 40000-40010 rtt.cfty 100/100 echoed, rtt min 4.34351ms median 7.94053ms p99 10.2825ms max 10.6628ms 4.34351ms to 4.77314ms: 8 ... The times are those of the captures, of the probe going out and of its echo coming in. Each probe expects its own echo, so that a late one is not taken for the next. BUDGET = {max duration: 61m} on for=1h /IP/TCP dst == 80 /HTTP/HttpRequest { /IP dst=MATCH IP .src /TCP src=80, dst=MATCH TCP .src /HTTP { if MATCH HttpRequest .url == "/" { HttpAnswer 200 /Raw "hello\n" } else { HttpAnswer 404 } } } % sudo crafty --tcp 80 --fw server.cfty PERMISSIONS = {exfiltration: true} it sends what's sniffed BUDGET = {max duration: 61m} on for=1h /IP/UDP dst == 7 /Raw { /IP dst=MATCH IP .src /UDP src=7, dst=MATCH UDP .src /Raw MATCH Raw .data } % sudo crafty --udp 7 --fw server.cfty 4 flows of 25 datagrams to the UDP echo server: how many get no echo? target = ip addr arg 0 lost = array init=25, len=4 { on linger=1s /IP src == target /UDP src == 7, dst = 40000, dst < 40004 { lost MATCH UDP .dst - 40000 -= 1 } repeat count=100 every=10ms { /IP dst=target /UDP src=40000 + I % 4, dst=7 /Raw "ping" } } repeat var=f count=4 { print "flow ${f}: ${lost f } lost" } % sudo crafty --udp 40000-40003 --fw losses.cfty flow 0: 0 lost ... The on starts listening before the datagrams go out, and goes on 1s after the last one. /IP dst=192.0.2.10 /TCP src=40001, dst=22 { Raw "hello" expect timeout=1s ../TCP flags & RST { print "reset by ${MATCH IP .src}" } } A reset carries no data, so a pattern on top of TCP never sees it; ../TCP sees each segment of the connection. /IP dst=192.0.2.10 /UDP dst=7 { p = Raw "ping" expect timeout=1s Raw { print "rtt: ${MATCH Eth .ts - p Eth .ts}" } } /IP dst=192.0.2.10 /TCP dst=7 { Raw "hello" expect timeout=1s Raw { s = stats print "srtt ${s.srtt}, mss ${s.snd mss}, peer window ${s.snd wnd}" } } 10s of data, as fast as the connection takes it: /IP dst=192.0.2.10 /TCP dst=7 { repeat for=10s { Raw randbytes 1000 } wait 1s for what is still buffered or in flight s = stats print "${s.bytes acked} bytes acked, ${s.retrans} retransmitted, srtt ${s.srtt}, cwnd ${s.cwnd}" } A write waits while TCP's send buffer is full, so the connection sets the rate; every=10ms would set it to 100 writes per second instead. /Eth dst=ff:ff:ff:ff:ff:ff, proto=0x88b5 /Raw "hello" /IP dst=192.0.2.10, ttl=1, id=1234, dont frag=true /UDP src=40000, dst=9 /Raw deadbeef Whole programs Every probe goes from the same UDP port to the same port, so that routers that balance per flow send them all the same way: where a hop still shows several routers, they balance per packet. usage: lbtrace.cfty TARGET PROBES MAX HOPS PORT target = resolve arg 0 0 probes = int arg 1, default="5" per hop max hops = int arg 2, default="30" port = int arg 3, default="33434" /IP dst=target /UDP dst=port { probe = 0 the IP id, that tells the probes apart repeat var=hop count=max hops { rtts = map key=0.0.0.0, default= reached = false repeat count=probes { probe += 1 p = ../../IP ttl=hop + 1, id=probe /UDP/Raw "probe" if probe == 1 { print "to ${target} from UDP port ${p UDP .src} to ${port}" } expect timeout=1s /IP/ICMP/TimeExceeded/IP id == probe, dst == target /UDP { rtts MATCH /IP .src += MATCH Eth .ts - p Eth .ts } | /IP/ICMP/DestUnreachable/IP id == probe, dst == target /UDP { rtts MATCH /IP .src += MATCH Eth .ts - p Eth .ts reached := true } else {} } head = "${hop + 1}" answered = 0 for r in rtts { answered += length r.value ms = float int float min r.value 100000.0 / 100.0 print "${head}\t${r.key}\t${length r.value }/${probes}\tmin ${ms}ms" head := "" } if answered < probes { print "${head}\t \t${probes - answered}/${probes}" } if reached { break } } } % sudo crafty --udp 40000 --fw lbtrace.cfty 10.2.1.3 8 to 10.2.1.3 from UDP port 40000 to 33434 1 10.1.1.1 8/8 min 0.04ms 2 10.1.0.5 4/8 min 37.67ms 10.1.0.6 4/8 min 34.92ms 3 10.2.0.1 2/8 min 89.71ms 10.2.0.2 6/8 min 90.97ms 4 10.2.0.6 8/8 min 117.6ms 5 10.2.1.3 8/8 min 110.92ms Hops 2 and 3 balance per packet. Behind routers that balance per flow, each hop shows one router, and another port may show another path. A line counts the probes without an answer. Echo requests that must not be fragmented, to find the path MTU in each direction: - echoed whole: the size fits both ways; - echoed in fragments: it fits the way out, and the largest fragment bounds the MTU of the way back fragments carry multiples of 8 bytes, so within 7 bytes ; - Frag-Needed: a router on the way out tells its next hop MTU; - nothing: dropped silently, on the way out or, if the reply had DF, on the way back. usage: pmtu.cfty TARGET MTU target = resolve arg 0 0 lo = 68 fits any IPv4 path hi = int arg 1, default="1500" frag max = 0 largest fragment of the last reply ret mtu = 0 the way back fragmented at this size { Raw fragments from the target, alongside the self-driven stream that reassembles them on /IP src == target && is fragment { if MATCH IP .tot len frag max { frag max := MATCH IP .tot len } } /IP dst=target, dont frag=true /ICMP/Echo { size = hi repeat count=32 { told = 0 answered = false frag max := 0 Request seq=size, payload= 00 size - 28 expect timeout=1s Reply seq == size { answered := true lo := size if frag max 0 { print "${size}: echoed in fragments of up to ${frag max} bytes" ret mtu := frag max } else { print "${size}: echoed whole" } } | /IP src = target /ICMP/DestUnreachable code == FRAG NEEDED /IP dst == target, tot len == size { told := MATCH DestUnreachable .mtu answered := true print "${size}: too big for ${MATCH /IP .src}, next hop MTU ${told}" } else {} if answered { print "${size}: no answer dropped one way or the other " } if told lo && told < size { hi := told size := told } else { if answered || told 0 { hi := size - 1 } if lo = hi { break } size := lo + hi + 1 / 2 } } } } print "way out: ${lo} bytes get through" if ret mtu 0 { print "way back: fragmented, MTU about ${ret mtu} bytes" } % sudo crafty pmtu.cfty 10.2.1.3 1500: too big for 10.1.0.5, next hop MTU 1400 1400: no answer dropped one way or the other 734: echoed whole 1067: echoed whole 1233: echoed whole 1316: no answer dropped one way or the other 1274: echoed whole 1295: no answer dropped one way or the other 1284: no answer dropped one way or the other 1279: echoed whole 1281: no answer dropped one way or the other 1280: echoed whole way out: 1280 bytes get through 10.1.0.5 reports its MTU of 1400, but a router further on drops what exceeds 1280 without a word. Probes every hop once per round, on one flow as the traceroute does, and reports each hop's losses and round trips every REPORT rounds. usage: mtr.cfty TARGET ROUNDS REPORT INTERVAL MAX HOPS PORT target = resolve arg 0 0 rounds = int arg 1, default="60" per report = int arg 2, default="10" rounds per report pace = interval arg 3, default="1s" max hops = int arg 4, default="30" less than 64 port = int arg 5, default="33434" last = max hops - 1 the target's hop, from 0, once known sent = array init=0, len=max hops rtts = array init= , len=max hops hosts = array init=map key=0.0.0.0, default=0 , len=max hops sent at = map key=0, default=now by IP id: round 64 + hop /IP dst=target /UDP dst=port { on /IP/ICMP/TimeExceeded/IP dst == target /UDP dst == port | /IP/ICMP/DestUnreachable code == PORT UNREACHABLE /IP dst == target /UDP dst == port { id = MATCH ICMP/ /IP .id if has sent at, id { hop = id % 64 rtts hop += MATCH Eth .ts - sent at id hosts hop MATCH /IP .src += 1 if MATCH /IP .src == target && hop < last { last := hop } sent at := remove sent at, id } } repeat var=r count=rounds + 1 every=pace { if r 0 && r % per report == 0 { print "after ${r} rounds:" repeat var=hop count=last + 1 { s = sent hop n = length rtts hop line = "${hop + 1}\t${keys hosts hop }\tloss ${ s - n 100 / s}%" if n 0 { avg = float int float mean rtts hop 100000.0 / 100.0 best = float int float min rtts hop 100000.0 / 100.0 worst = float int float max rtts hop 100000.0 / 100.0 line := "${line}\tavg ${avg}ms\tbest ${best}ms\tworst ${worst}ms" } print line sent hop := 0 rtts hop := hosts hop := map key=0.0.0.0, default=0 } sent at := map key=0, default=now too late for the next report } if r < rounds { repeat var=hop count=last + 1 { id = r 64 + hop % 65536 p = ../../IP ttl=hop + 1, id=id /UDP/Raw "probe" sent at id := p Eth .ts sent hop += 1 } } } } % sudo crafty --udp 40000 --fw mtr.cfty 10.2.1.3 40 20 200ms after 20 rounds: 1 10.1.1.1 loss 0% avg 0.33ms best 0.11ms worst 0.48ms 2 10.1.0.5 loss 50% avg 37.81ms best 37.6ms worst 38.1ms 3 10.2.0.2 loss 0% avg 90.91ms best 90.69ms worst 91.07ms 4 10.2.0.6 loss 10% avg 114.42ms best 114.18ms worst 115.02ms 5 10.2.1.3 loss 5% avg 114.23ms best 114.09ms worst 114.73ms after 40 rounds: 1 10.1.1.1 loss 0% avg 0.33ms best 0.09ms worst 0.6ms 2 10.1.0.5 loss 45% avg 37.81ms best 37.6ms worst 37.97ms 3 10.2.0.2 loss 0% avg 90.87ms best 90.68ms worst 91.3ms 4 10.2.0.6 loss 20% avg 114.47ms best 114.1ms worst 116.44ms 5 10.2.1.3 loss 15% avg 114.37ms best 114.02ms worst 116.14ms Hop 2 only answers half of its probes: hop 3 losing none, what is lost is the answers, not the traffic. The losses start between hops 3 and 4, and go on to the target.