1#!/bin/bash
2# SPDX-License-Identifier: GPL-2.0
3
4# return code to signal skipped test
5ksft_skip=4
6rc=0
7
8if ! iptables --version >/dev/null 2>&1; then
9	echo "SKIP: Test needs iptables"
10	exit $ksft_skip
11fi
12if ! ip -V >/dev/null 2>&1; then
13	echo "SKIP: Test needs iproute2"
14	exit $ksft_skip
15fi
16if ! nc -h >/dev/null 2>&1; then
17	echo "SKIP: Test needs netcat"
18	exit $ksft_skip
19fi
20
21pattern="foo bar baz"
22patlen=11
23hdrlen=$((20 + 8)) # IPv4 + UDP
24ns="ns-$(mktemp -u XXXXXXXX)"
25trap 'ip netns del $ns' EXIT
26ip netns add "$ns"
27ip -net "$ns" link add d0 type dummy
28ip -net "$ns" link set d0 up
29ip -net "$ns" addr add 10.1.2.1/24 dev d0
30
31#ip netns exec "$ns" tcpdump -npXi d0 &
32#tcpdump_pid=$!
33#trap 'kill $tcpdump_pid; ip netns del $ns' EXIT
34
35add_rule() { # (alg, from, to)
36	ip netns exec "$ns" \
37		iptables -A OUTPUT -o d0 -m string \
38			--string "$pattern" --algo $1 --from $2 --to $3
39}
40showrules() { # ()
41	ip netns exec "$ns" iptables -v -S OUTPUT | grep '^-A'
42}
43zerorules() {
44	ip netns exec "$ns" iptables -Z OUTPUT
45}
46countrule() { # (pattern)
47	showrules | grep -c -- "$*"
48}
49send() { # (offset)
50	( for ((i = 0; i < $1 - $hdrlen; i++)); do
51		printf " "
52	  done
53	  printf "$pattern"
54	) | ip netns exec "$ns" nc -w 1 -u 10.1.2.2 27374
55}
56
57add_rule bm 1000 1500
58add_rule bm 1400 1600
59add_rule kmp 1000 1500
60add_rule kmp 1400 1600
61
62zerorules
63send 0
64send $((1000 - $patlen))
65if [ $(countrule -c 0 0) -ne 4 ]; then
66	echo "FAIL: rules match data before --from"
67	showrules
68	((rc--))
69fi
70
71zerorules
72send 1000
73send $((1400 - $patlen))
74if [ $(countrule -c 2) -ne 2 ]; then
75	echo "FAIL: only two rules should match at low offset"
76	showrules
77	((rc--))
78fi
79
80zerorules
81send $((1500 - $patlen))
82if [ $(countrule -c 1) -ne 4 ]; then
83	echo "FAIL: all rules should match at end of packet"
84	showrules
85	((rc--))
86fi
87
88zerorules
89send 1495
90if [ $(countrule -c 1) -ne 1 ]; then
91	echo "FAIL: only kmp with proper --to should match pattern spanning fragments"
92	showrules
93	((rc--))
94fi
95
96zerorules
97send 1500
98if [ $(countrule -c 1) -ne 2 ]; then
99	echo "FAIL: two rules should match pattern at start of second fragment"
100	showrules
101	((rc--))
102fi
103
104zerorules
105send $((1600 - $patlen))
106if [ $(countrule -c 1) -ne 2 ]; then
107	echo "FAIL: two rules should match pattern at end of largest --to"
108	showrules
109	((rc--))
110fi
111
112zerorules
113send $((1600 - $patlen + 1))
114if [ $(countrule -c 1) -ne 0 ]; then
115	echo "FAIL: no rules should match pattern extending largest --to"
116	showrules
117	((rc--))
118fi
119
120zerorules
121send 1600
122if [ $(countrule -c 1) -ne 0 ]; then
123	echo "FAIL: no rule should match pattern past largest --to"
124	showrules
125	((rc--))
126fi
127
128exit $rc
129