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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
#!/bin/bash

# BASICS -----------------------------------------------------------------------
# shell options: extended globbing
shopt -qs extglob

# basic script values. SCRIPTDIR construction is deferred until initialization
declare SCRIPT="${0##*/}" SCRIPTVER='3.4' SCRIPTDIR

# associative array for paths to external commands
declare -Ax PROGRAMS

# used by the command parsing loop to detect functions exposed as user commands
declare command_prefix='cmd:' valid_commands=''

# USER CONFIG -----------------------------------------------------------------
# verbose mode, use it for extra info
# any non-null value with enable it
verbose_mode=''

# default policy
default_policy='ACCEPT'

# make sure this contains the path for "which" (in doubt type "which which")
# otherwise the script will abort at initialization
PROGRAMS['which']='/usr/bin/which'

# EXPOSED FUNCS ----------------------------------------------------------------
cmd:help() {
    VERBOSE='yes'
    _msg<<HELP<<HELP
$SCRIPT version $SCRIPTVER

Iptables helper

Usage: $SCRIPT $($(_run sed) 's/ /|/g' <<< $valid_commands)

    help
    Shows a help screen.

	start [profiles]
	Initializes the firewall according to configuration, optionally loading profiles.

	stop
	Removes any iptables state and configuration, and disables forwarding.

	switch <profile>
	Switches iptables configuration to the specified profile.

	load <profiles>
	Load the specified profile(s) into the iptables configuration preserving existing rules.

	save [-f] <profile>
	Stores current iptables configuration and state into a profile. The -f switch causes to
    overwrite an existing profile, otherwise an overwrite attempt triggers an error.

	flush [tables] [chains]
    Flushes (removes all rules) in the specified tables and/or chains.

    zero [tables] [chains]
	Zeroes packet counters in the specified tables and/or chains.

	user [tables]
    Flushes (removes) all user-defined chains in the specified tables.

    clear [tables]
	Equivalent to calling flush+zero+user in sequence.

	policy [tables] [chains] [policy]
	Sets default policy for the specified tables and/or chains.

    Notes on [tables], [chains] and [policy] arguments:
    *) All these arguments are optional, case-insensitive and can appear in any order.
    *) Policy can be one of DROP or ACCEPT, defaulting to user configuration.
    *) Whenever a [tables] or [chains] argument is completely missing, the default is to INCLUDE all tables or chains.
    *) Tables and chains are comma-delimited lists, without spaces.
    *) All the commands that operate with these arguments currently IGNORE bogus strings.

    Notes on profiles:
    *) When multiple profiles are expected they can be separated by comma or space.
    *) By default, profiles are loaded or stored from/to the same directory of this script.
    To specify another location, prepend a relative or absolute path to the profile name.
HELPHELP
}

cmd:start() {
    _msg 'Starting...'

    # clear iptables configuration and state, and set everything to default policy
    _call clear
    _call policy

    # forward any arguments passed to "load"
    (( $# )) && _call load $@

    # ADD YOUR COMMANDS HERE ---------------------------------------------------

    # enable kernel forwarding
    $(_run sysctl) -w net.ipv4.ip_forward=1

    # simple qdisc to optimize ethernet
    $(_run tc) qdisc add dev eth0 root tbf rate 256kbit latency 50ms burst 1540

    # here I force the output filter to accept
    _call policy output filter accept

    # ADD YOUR COMMANDS HERE ---------------------------------------------------

    _msg 'finished starting process.'
}

cmd:stop() {
    (( $# )) && _err "extra arguments for \"stop\""

    _msg 'Stopping...'

    # clear iptables configuration and state, and set everything to default policy
    _call clear
    _call policy

    # ADD YOUR COMMANDS HERE ---------------------------------------------------

    # turn off kernel forwarding
    $(_run sysctl) -w net.ipv4.ip_forward=0

    # remove ethernet qdisc
    $(_run tc) qdisc del dev eth0 root
    
    # ADD YOUR COMMANDS HERE ---------------------------------------------------

    _msg 'finished stopping process.'
}

cmd:switch() { 
    (( ! $# )) && _err "<profile> expected for \"switch\""
    (( $# > 2 )) && _err "extra arguments for \"switch\""

    local file=$(_getprofile "$1")
    [[ ! -f "$file" ]] && _err "file not found: $file"

    _msg <<< "Switching to profile $file ..."
    $(_run iptables-restore) < "$file"
    _msg <<< 'done.'
}

cmd:load() {
    (( ! $# )) && _err "at least one <profile> expected for \"load\""

    local file
    for file in ${@//,/ }; do
        file=$(_getprofile "$file")
        [[ ! -f "$file" ]] && _err "file not found: $file"

        _msg <<< "Loading profile $file ..."
        $(_run iptables-restore) -n < "$file"
        _msg <<< 'done.'
    done
}

cmd:save() {
    (( ! $# )) && _err "<profile> expected for \"save\""
    (( $# > 2 )) && _err "extra arguments for \"save\""

    local file overwrite arg
    for arg in $@; do
        [[ "$arg" == '-f' ]] && overwrite='yes' || file=$(_getprofile "$arg")
    done

    [[ ! $overwrite && -f "$file" ]] && _err "file \"$file\" already exists.\nIf you want to overwrite it try again with -f" 

    _msg <<< "Saving current state to $file ..."
    $(_run iptables-save) > "$file"
    _msg <<< 'done.'
}

cmd:flush() {
    _msg <<< 'Flushing builtin chains...'
    _tbchain flush $@
    _msg <<< 'done.'
}

cmd:zero() {
    _msg <<< 'Zeroing counters...'
    _tbchain zero $@
    _msg <<< 'done.'
}

cmd:user() {
    _msg <<< 'Flushing user chains...'
    _tbchain user $@
    _msg <<< 'done.'
}

cmd:clear() {
    _call flush $@
    _call zero $@
    _call user $@
}

cmd:policy() {
    _msg <<< 'Setting policies...'

    # default policy: user-defined
    local policy="$default_policy"

    # get argument policy
    for argument in $@; do
        [[ "${argument^^}" =~ (ACCEPT|DROP) ]] && policy="${argument^^}" && continue
    done
 
    # set policies
    _tbchain policy $@
    
    _msg <<< 'done.'
}

# INTERNAL FUNCS ---------------------------------------------------------------

# returns a full path to a profile, starting from an ambiguous path/profile
# argument
_getprofile() {
    [[ "$1" =~ ^(/|./|../).* ]] && echo "$1" || echo "$SCRIPTDIR/$1"
}

# process a command in some table(s) and chain(s)
_tbchain() {
    local -A tables
    local action="$1" table chain chainarg
    shift

    # get arguments
    for argument in $@; do
        [[ "${argument^^}" =~ (FILTER|NAT|MANGLE|RAW) ]] && {
            while IFS='' read -rd',' table; do
                tables[$table]=''
            done <<< "${argument,,},"
            continue
        }
        [[ "${argument^^}" =~ (INPUT|OUTPUT|FORWARD|PREROUTING|POSTROUTING) ]] && chainarg="${argument^^}" && continue
    done
 
    # default tables: all tables
    (( ! "${#tables[@]}" )) && tables=([filter]='' [nat]='' [mangle]='' [raw]='')
    
    # default chains: all chains
    [[ ! "$chainarg" ]] && chainarg="INPUT OUTPUT FORWARD PREROUTING POSTROUTING"

    # ensure that chains are defined only at tables where they exist
    for table in ${!tables[@]}; do
        while read chain; do
            [[ "$chainarg" =~ ($chain) ]] && tables[$table]="$chain ${tables[$table]}"
        done< <($(_run iptables) -L -t $table | $(_run sed) -n 's/^Chain \(.*\) (.*$/\1/p')
    done
    
    # apply actions on selected tables and chains
    for table in ${!tables[@]}; do
        for chain in ${tables[$table]}; do
            case $action in
                policy)
                    _msg <<< "$table $chain $policy"
                    $(_run iptables) -t $table -P $chain $policy &> /dev/null
                    ;;
                flush)
                    _msg <<< "$table $chain"
                    $(_run iptables) -t $table -F $chain
                    ;;
                zero)
                    _msg <<< "$table $chain"
                    $(_run iptables) -t $table -Z $chain
                    ;;
                user)
                    _msg <<< "$table"
                    $(_run iptables) -t $table -X
                    continue 2
                    ;;
            esac
        done
    done
}

_msg() {
    #dirigir todo a un stream y restaurar al salir
    #exec 1>&2

    # use params for messages with header
    (( $# )) && {
        echo -e "$SCRIPT ($$): $@"
        return
    }

    # use stdin for messages without header
    [[ "$VERBOSE" ]] && {
        local stuff
        while read stuff; do
            echo -e "$stuff"
        done
    }
}

# simple error message and termination
_err() {
    _msg "error\n$1"
    exit 1
}

# gets the path for external programs. exits with error if one isn't found
_getpath() {
    local program path
    for program in $@; do
        path="$( $(_run which) $program )"
        [[ ! -x "$path" ]] && _err "(FATAL) \"$program\" could not be found or is not executable. Aborting."
        PROGRAMS["$program"]="$path"
    done
}

# this is just a proxy to call user exposed functions internally,
# without caring for what $command_prefix is
# also switchs verbose mode to user-defined upon call
_call() { VERBOSE="$verbose_mode" $command_prefix$@; }

# retrieves from PROGRAMS the path to an external command
_run() { echo ${PROGRAMS["$1"]}; }

# START ------------------------------------------------------------------------
# get paths to programs we will use, in case we don't have a proper $PATH
# we validate WHICH too for the case the user left it misconfigured
# if you need more external programs just add them to this list
_getpath which iptables{,-save,-restore} tc sysctl readlink sed tr

# populate SCRIPTDIR correctly
SCRIPTDIR="$($(_run readlink) -f "${0%/*}")"

# filter functions exposed as user commands
valid_commands="$(declare -f | $(_run sed) -ne '/^'$command_prefix'.* ()/s/'$command_prefix'\(.*\) ().*/\1/p' | $(_run tr) '\n' ' ')"

# output messages from the command loop
VERBOSE='yes'

# command loop
while read command; do
    case "$command" in
        "") _msg <<< 'try with ?' ;;
        \?) _msg <<< "valid commands: $valid_commands" ;;
        @(${valid_commands// /|})?(+([[:space:]])*)) _call $command ;;
        *) _err "invalid command: $command\nto see available commands: $SCRIPT ?" ;;
    esac
done <<< "$@"