forked from cloudflare/bpftools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iptables_bpf_chain
executable file
·188 lines (156 loc) · 4.69 KB
/
iptables_bpf_chain
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#!/usr/bin/env python
template = r'''
#!/bin/bash
#
# This script is ***AUTOGENERATED***
#
# To apply the iptables BPF rule run this script:
#
# ./%(fname)s
#
# This script creates an ipset "%(ipsetname)s". You can manage it
# manually:
#
# ipset add %(ipsetname)s %(sampleips)s
#
# To clean the iptables rule and ipset run:
#
# ./%(fname)s --delete
#
#
set -o noclobber
set -o errexit
set -o nounset
set -o pipefail
: ${IPTABLES:="%(iptables)s"}
: ${IPSET:="ipset"}
: ${INPUTPLACE:="1"}
: ${DEFAULTINT:=`awk 'BEGIN {n=0} $2 == "00000000" {n=1; print $1; exit} END {if (n=0) {print "eth0"}}' /proc/net/route`}
main_match () {
${IPTABLES} \
--wait \
${*} \
-i ${DEFAULTINT} \
-p udp --dport 53 \
-m set --match-set %(ipsetname)s dst \
-j %(chain)s
}
chain_create() {
${IPTABLES} --wait -N %(chain)s
%(accept_cmds)s
%(drop_cmds)s
${IPTABLES} --wait -A %(chain)s -j RETURN
}
chain_delete() {
${IPTABLES} --wait -F %(chain)s
${IPTABLES} --wait -X %(chain)s
}
if [ "$*" == "--delete" ]; then
A=`(main_match -C INPUT || echo "error") 2>/dev/null`
if [ "${A}" != "error" ]; then
main_match -D INPUT
chain_delete
fi
${IPSET} -exist destroy %(ipsetname)s 2>/dev/null
else
${IPSET} -exist create %(ipsetname)s hash:net family %(ipsetfamily)s
for IP in %(ips)s $@; do
${IPSET} -exist add %(ipsetname)s "$IP"
done
A=`(main_match -C INPUT || echo "error") 2>/dev/null`
if [ "${A}" == "error" ]; then
chain_create
main_match -I INPUT ${INPUTPLACE}
fi
fi
'''.lstrip()
import argparse
import os
import stat
import string
import sys
import bpftools
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=r'''
This program generates a bash script. The script when run will insert
(or remove) an iptable chain and ipset. The iptable chain drops
traffic that matches requests with domains given with "--accept"
options and drops domains listed with "--drop" option. Example:
%(prog)s -a www.example.com -a ns1.example.com -d *.example.com -w example_com
'''.strip())
parser.add_argument('-6', '--inet6', action='store_true',
help='generate script for IPv6')
parser.add_argument('-i', '--ip', metavar='ip', action='append',
help='preset IP in the set')
parser.add_argument('-w', '--write', metavar='name',
help='name the generated script')
parser.add_argument('-a', '--accept', metavar='accept', action='append',
help='accept domains')
parser.add_argument('-d', '--drop', metavar='drop', action='append',
help='drop domains')
args = parser.parse_args()
if not args.write:
print "set name with -w"
sys.exit(-1)
inet = 4 if not args.inet6 else 6
fname = args.write +'_ip'+str(inet)+'.sh'
meta = []
for action, list_of_patterns in [('ACCEPT', args.accept), ('DROP', args.drop)]:
cmds = []
for domain in list_of_patterns:
if domain != 'any':
_, bytecode = bpftools.gen('dns',
['-i', domain],
assembly=False,
l3_off=0,
ipversion=inet,
)
if int(bytecode.split(',')[0]) > 63:
raise Exception("bytecode too long!")
cmd = r'''
${IPTABLES} \
--wait \
-A %s \
-m bpf --bytecode "%s" \
-m comment --comment "%s" \
-j %s
''' % (args.write.upper(), bytecode, "dns -- -i " + domain, action)
cmds.append(cmd.strip('\n'))
else:
cmd = r'''
${IPTABLES} \
--wait \
-A %s \
-m comment --comment "%s" \
-j %s
''' % (args.write.upper(), "dns -- -i " + domain, action)
cmds.append(cmd.strip('\n'))
meta.append(cmds)
accept_cmds = meta[0]
drop_cmds = meta[1]
ctx = {
'accept_cmds': '\n'.join(accept_cmds),
'drop_cmds': '\n'.join(drop_cmds),
'fname': fname,
'ipsetname': args.write + '_ip' + str(inet),
'chain': args.write.upper(),
'ips': ' '.join(repr(s) for s in (args.ip or [])),
}
if inet == 4:
ctx.update({
'iptables': 'iptables',
'ipsetfamily': 'inet',
'sampleips': '1.1.1.1/32',
})
else:
ctx.update({
'iptables': 'ip6tables',
'ipsetfamily': 'inet6',
'sampleips': '2a00:1450:4009:803::1008/128',
})
f = open(fname, 'wb')
f.write(template % ctx)
f.flush()
print "Generated file %r" % (fname,)
os.chmod(fname, 0750)