-
Notifications
You must be signed in to change notification settings - Fork 140
/
iptables_bpf
executable file
·187 lines (153 loc) · 4.72 KB
/
iptables_bpf
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
#!/usr/bin/env python
template = r'''
#!/bin/bash
#
# This script is ***AUTOGENERATED***
#
# This is a script for applying and removing xt_bpf iptable rule. This
# particular rule was created with:
#
# %(bpf_cmd)s
#
# To apply the iptables BPF rule against listed destination IP's run
# this script with the flooded IP addresses as parameters:
#
# ./%(fname)s %(sampleips)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
#
#
# For the record, here's the BPF assembly:
#
%(assembly)s
#
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`}
iptablesrule () {
${IPTABLES} \
--wait \
${*} \
-i ${DEFAULTINT} \
-p udp --dport 53 \
-m set --match-set %(ipsetname)s dst \
-m bpf --bytecode "%(bytecode)s" \
-m comment --comment "%(bpf_cmd_s)s" \
-j DROP
}
if [ "$*" == "--delete" ]; then
A=`(iptablesrule -C INPUT || echo "error") 2>/dev/null`
if [ "${A}" != "error" ]; then
iptablesrule -D INPUT
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=`(iptablesrule -C INPUT || echo "error") 2>/dev/null`
if [ "${A}" == "error" ]; then
iptablesrule -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 rule and ipset. The iptable rule drops traffic
that matches the BPF rule, which in turn is generated from given
parameters.
See "./bpfgen --help" for more information on BPF generators.
Usage example:
%(prog)s dns -- *.example.com
%(prog)s dns -- --ignorecase *.example.com
%(prog)s -6 dns -- *.example.com
%(prog)s dns_validate -- --strict
'''.strip())
parser.add_argument('-6', '--inet6', action='store_true',
help='generate script for IPv6')
parser.add_argument('-c', '--comment',
help='Add a comment to better identify this rule in iptables -nvL'),
parser.add_argument('-i', '--ip', metavar='ip', action='append',
help='preset IP in the set')
parser.add_argument('-n', '--negate', action='store_true',
help='negate the logic')
parser.add_argument('-w', '--write', metavar='file',
help='name the generated script')
parser.add_argument('type', nargs=1, choices=bpftools.generator_names,
help='BPF generator')
parser.add_argument('parameters', nargs='*',
help='parameters passed to the BPF generator')
args = parser.parse_args()
if len(args.type) != 1:
parser.print_help()
sys.exit(-1)
inet = 4 if not args.inet6 else 6
a = []
for assembly in [False, True]:
name, ret = bpftools.gen(args.type[0],
args.parameters,
assembly=assembly,
l3_off=0,
ipversion=inet,
negate=args.negate,
)
a.append(ret)
bytecode, assembly = a
if int(bytecode.split(',')[0]) > 63:
raise Exception("bytecode too long!")
name = 'bpf_%s_ip%s%s%s' % (args.type[0], inet, '_' if name else '', name)
fname = args.write or name + '.sh'
if fname == '-':
f = sys.stdout
else:
f = open(fname, 'wb')
cmd = sys.argv[1:]
bpf_cmd_s = args.comment if args.comment else ' '.join(cmd).replace('"', "").replace("$", "")
ctx = {
'bpf_cmd': cmd,
'bpf_cmd_s': bpf_cmd_s,
'bytecode': bytecode,
'assembly': '# ' + '\n# '.join(assembly.split('\n')),
'fname': fname if fname != '-' else name + '.sh',
'ipsetname': name[:31],
'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.write(template % ctx)
f.flush()
if f != sys.stdout:
print "Generated file %r" % (fname,)
os.chmod(fname, 0750)