Retrieved article excerpt
Open article · Retrieved 2026-11-24T11:22:16.548363+00:00
# The crafty language
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.
## 1. Introduction
### A first program
```
# 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.
### Errors
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) }
}
}
```
### Going down the stack
```
# 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)`.
### Overlaying
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.
### Manual layers
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])
}
```
### Running crafty
`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](https://github.com/rixed/robinet/blob/master/docs/crafty.md#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](https://github.com/rixed/robinet/blob/master/docs/crafty.md#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.
### Tips
- 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.
## 2. Reference
### Lexical conventions
- 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.
### Types and literals
- `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