summaryrefslogtreecommitdiffstats
path: root/sbin/init.d/firewall
blob: 4b9b947771801063b22bc14dee20166e37124c75 (plain) (blame)
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
#!/bin/bash 

. `dirname $0`/functions

option	confdir		standard_option /etc/firewall
option	current		standard_option	current
option	backup		standard_option	backup
option	maint		standard_option	maint
option	hashsize	standard_option 65536
option	forward		boolean_option	1
option	filter		boolean_option	1
option	stateful	boolean_option	1
option	nat		boolean_option
option	conntrack	option_conntrack
option	modprobe	multiple_option

IPTABLES=/sbin/iptables
IPRESTORE=/sbin/iptables-restore

conntrack_args=( )

function do_help {
    echo "Usage: ${0##*/} <status|start|revert|maint|stop|route|block|help>"
    echo "                <new|gen|try>"
    echo "List of config.rc options (name, type, default value, current value) :"
    echo
    echo "   - confdir  : dir     ; def='/etc/firewall' ; cur=$opt_confdir"
    echo "   - current  : subdir  ; def='current'       ; cur=$opt_current"
    echo "   - backup   : subdir  ; def='backup'        ; cur=$opt_backup"
    echo "   - maint    : subdir  ; def='maint'         ; cur=$opt_maint"
    echo "   - hashsize : integer ; def=65536           ; cur=$opt_hashsize"
    echo "   - forward  : boolean ; def=1               ; cur=$opt_forward"
    echo "   - filter   : boolean ; def=1               ; cur=$opt_filter"
    echo "   - stateful : boolean ; def=1               ; cur=$opt_stateful"
    echo "   - nat      : boolean ; def=                ; cur=$opt_nat"
    echo "   - conntrack: var=val ; eg: max=1048576     ; cur='${conntrack_args[@]}'"
    echo "   - modprobe : mod arg ; eg: ip_nat_ftp      ; cur='${opt_modprobe[@]}'"
    echo
    echo "The configuration file is $opt_confdir/$opt_current/conf-$(uname -n).ipt"
    echo
    exit 1 
}

###############################################################################
# internal functions
###############################################################################

# checks wether the core firewall modules are loaded
# returns 0 if they are, 1 if not.
function check_modules {
    test -e /proc/net/ip_tables_names && test -n "$(cat /proc/net/ip_tables_names)"
}

# unloads all firewall modules unconditionally. Note: this can take some time
# if the session cache is heavily loaded.
function unload_modules {
    recursive_rmmod iptable_nat
    recursive_rmmod ip_conntrack
    recursive_rmmod iptable_filter
    recursive_rmmod iptable_mangle
    recursive_rmmod ip_tables
}

# loads the firewall modules, and sets some parameters. It is assumed
# that these modules are not loaded yet (check with check_modules) if unsure.
# If an error arises, the modules are unloaded and 1 is returned. 0 is returned
# if everything's OK.
function load_modules {
    local arg var val
    local sys1=/proc/sys/net/ipv4
    local sys2=/proc/sys/net/ipv4/netfilter

    /sbin/modprobe ip_tables 2>/dev/null
    /sbin/modprobe iptable_filter 2>/dev/null
    /sbin/modprobe iptable_mangle 2>/dev/null

    if ! grep -q "^filter$" /proc/net/ip_tables_names; then
	echo "Error: filtering module did not load correctly."
	unload_modules
	return 1
    fi

    if [ -n "$opt_stateful" ]; then
    	/sbin/modprobe ip_conntrack hashsize=$opt_hashsize
	if [ ! -e $sys1/ip_conntrack_max -a \
	     ! -e $sys2/ip_conntrack_max ]; then
	     echo "Error: conntrack module did not load correctly."
	     echo "    -> Check 'stateful' and 'hashsize' options."
	     unload_modules
	     return 1
	fi

    	[ -n "$opt_nat" ] && /sbin/modprobe iptable_nat 2>/dev/null

	for arg in "${conntrack_args[@]}"; do
	    var=${arg%%=*} ; val=${arg##*=}
	    if [ -e "$sys1/ip_conntrack_$var" ]; then
		echo "$val" > "$sys1/ip_conntrack_$var"
	    elif [ -e "$sys2/ip_conntrack_$var" ]; then
		echo "$val" > "$sys2/ip_conntrack_$var"
	    else
		echo "Warning: no equivalent sysctl for 'conntrack $var' in configuration file $CONFIG."
	    fi
	done
    fi

    # now load all user-supplied modules
    arg=0
    while [ $arg -lt ${#opt_modprobe[*]} ]; do
        if [ "${opt_modprobe[$arg]}" != "#" ]; then
            /sbin/modprobe ${opt_modprobe[$arg]} || { echo "Warning: could not load module ${opt_modprobe[$arg]}"; return 1; }
        fi
        arg=$[$arg+1]
    done

    return 0
}

# flushes all firewall rules in all tables, and sets the default policy to DROP.
# this function assumes that the firewall modules are already loaded.
function flush_rules {
    local chain chains table

    # filter chain has a default policy set to DROP
    for chain in INPUT OUTPUT FORWARD; do
	$IPTABLES -t filter -P $chain DROP
    done

    # flush all rules in all tables
    for table in mangle filter ${opt_stateful:+${opt_nat:+nat}}; do
	$IPTABLES -t $table -F
	$IPTABLES -t $table -X
    done

    # other chains have a default policy set to ACCEPT
    for table in mangle ${opt_stateful:+${opt_nat:+nat}}; do
	chains=$($IPTABLES -t $table -L | grep "^Chain " | cut -f2 -d' ')
	for chain in $chains; do
	    $IPTABLES -t $table -P $chain ACCEPT
	done
    done

    # it's OK now.
    return 0
}

# enables ip forwarding
function enable_forwarding {
    echo 1 > /proc/sys/net/ipv4/ip_forward
}

# disables ip forwarding
function disable_forwarding {
    echo 0 > /proc/sys/net/ipv4/ip_forward
}

# this function loads the specified policy file.
# it assumes that the rules have been flushed and that
# the default policies have been set.
# It returns 0 if the policy could be loaded, or 1 if not,
# in which case it may flush all rules again to protect the
# system.
function load_policy {
    [ -n "$1" ] || return 1
    if ! [ -r "$opt_confdir/$1" ] || ! $IPRESTORE < "$opt_confdir/$1"; then
	flush_rules
	return 1
    fi
    return 0
}


# used by start/revert/maint... functions. Relies on load_policy() but makes
# the output a bit more verbose. The first argument is the policy name to be
# displayed, and the second one is the policy file relative to the firewall
# directory. 0 Is returned if OK.
# IP forwarding will then be enabled if needed.
function verbose_load {
    echo -n "Firewall: loading $1 policy... "
    if load_policy $2; then
	echo "OK."
	if [ -n "$opt_forward" ]; then
            echo -n "Firewall: enabling IP forwarding... "
	    enable_forwarding
	    echo "OK."
	    return 0
	fi
	return 0
    fi
    echo "FAILED."
    return 1
}

# blocks new external traffic when an error is detected during policy loading.
function block_on_error {
    echo "Firewall: CRITICAL! cannot load any policy file !"
    # we'll block external traffic and enable internal one in this case
    echo "Firewall: Changing policy to block external traffic..."
    $IPTABLES -t filter -P INPUT DROP
    $IPTABLES -t filter -P OUTPUT DROP
    $IPTABLES -t filter -P FORWARD DROP
    $IPTABLES -t filter -F

    $IPTABLES -t filter -A INPUT -i lo -j ACCEPT
    $IPTABLES -t filter -A OUTPUT -o lo -j ACCEPT
    [ -n "$opt_stateful" ] && $IPTABLES -t filter -A INPUT -m state --state ESTABLISHED -j ACCEPT
    [ -n "$opt_stateful" ] && $IPTABLES -t filter -A OUTPUT -m state --state ESTABLISHED -j ACCEPT

    $IPTABLES -t mangle -P PREROUTING ACCEPT
    $IPTABLES -t mangle -P INPUT ACCEPT
    $IPTABLES -t mangle -P FORWARD DROP
    $IPTABLES -t mangle -P POSTROUTING ACCEPT
    $IPTABLES -t mangle -P OUTPUT ACCEPT
    $IPTABLES -t mangle -F

    $IPTABLES -t mangle -A PREROUTING -i lo -j ACCEPT
    $IPTABLES -t mangle -A INPUT -i lo -j ACCEPT
    $IPTABLES -t mangle -A POSTROUTING -o lo -j ACCEPT
    $IPTABLES -t mangle -A OUTPUT -o lo -j ACCEPT
    disable_forwarding
    echo
    echo "################################################################"
    echo "Firewall: There was a critical error. Only established sessions"
    echo "from and to the firewall will still work. Everything else has"
    echo "been blocked, and forwarding has been disabled."
    echo "################################################################"
    echo
    return 1
}

###############################################################################
# special functions to handle config parameters
###############################################################################

# usage: conntrack <entry> '=' <value>
#    eg: conntrack max=12000

function option_conntrack {
    local arg

    shift
    arg="$*"
    if [ -z "$arg" -o -n "${arg//*=*/}" ]; then
	echo "Firewall: unknown argument 'conntrack $*' in configuration file $CONFIG."
	return 1
    fi
    set -- ${arg/=/ }
    conntrack_args=( "${conntrack_args[@]}" "$1=$2" )
}


###############################################################################
# exported functions
###############################################################################


# checks wether the firewall modules are loaded
function do_status {
    if check_modules; then
	    echo "Firewall modules are loaded."
	    return 0
    fi
    echo "Firewall modules are not loaded."
    return 1
}

# Load files from the specified directories in the same order
# the syntax is : { <dir_name> <description> }*
# It returns 0 if it succeeds, 1 otherwise.
#
# eg: $0 $opt_current Current $opt_backup Backup

function load_in_order {
    local file_found dir_found
    local file dir 

    file_found=0
    dir_found=0

    if [ ! -d "$opt_confdir/." ]; then
        echo "Firewall: CRITICAL: no configuration directory found."
        echo "          Please create '$opt_confdir'."
    else
        while [ $# -gt 1 ]; do
	    dir="$1" ; shift ; desc="$1" ; shift
            if [ ! -d "$opt_confdir/$dir/." ]; then
                echo "Firewall: WARNING: subdirectory '$dir' does not exist."
                continue
            fi
            dir_found=1
            for file in "conf-$(uname -n).ipt" conf.ipt; do
                [ -e "$opt_confdir/$dir/$file" ] || continue
                file_found=1
                if [ ! -r "$opt_confdir/$dir/$file" ]; then
                    echo "Firewall: WARNING: skipping unreadable policy file '$opt_confdir/$dir/$file'."
                    continue
                fi
		verbose_load "$desc" "$dir/$file" && return 0
                echo "Firewall: WARNING: errors found in policy file '$opt_confdir/$dir/$file'. Skipping to next one."
            done
        done
    fi

    if [ $dir_found -eq 0 ]; then
        echo "Firewall: CRITICAL: no configuration subdirectory found."
        echo "          Please at least create '$opt_confdir/$opt_current'."
    fi

    if [ $file_found -eq 0 ]; then
        echo "Firewall: CRITICAL: no configuration file found."
        echo "          Please create '$opt_confdir/$opt_current/conf.ipt'."
    fi

    return 1
}


# load current configuration
function do_start {
    echo -n "Disabling IP forwarding... "
    disable_forwarding
    echo "OK."

    if ! check_modules; then
	echo -n "Firewall: loading modules... "
	if ! load_modules; then
	    echo "FAILED"
	    return 1
	else
	    echo "OK."
	fi
    fi 

    echo -n "Firewall: flushing all rules... "
    flush_rules
    echo "OK."

    if [ -z "$opt_filter" ]; then
	# filter chain has a default policy set to ACCEPT if "no filter" is used
	echo -n "Firewall: setting default policy to ACCEPT... "
	for chain in INPUT OUTPUT FORWARD; do
	    $IPTABLES -t filter -P $chain ACCEPT
	done
	echo "OK."
	if [ -n "$opt_forward" ]; then
            echo -n "Firewall: enabling IP forwarding... "
	    enable_forwarding
	    echo "OK."
	    return 0
	fi
	return 0
    fi

    load_in_order "$opt_current" Current "$opt_backup" Backup "$opt_maint" Maint && return 0
    block_on_error
    return 1
}


# load backup configuration
function do_revert {
    echo -n "Disabling IP forwarding... "
    disable_forwarding
    echo "OK."

    if ! check_modules; then
	echo -n "Firewall: loading modules... "
	if ! load_modules; then
	    echo "FAILED"
	    return 1
	else
	    echo "OK."
	fi
    fi 

    echo -n "Firewall: flushing all rules... "
    flush_rules
    echo "OK."

    load_in_order "$opt_backup" Backup "$opt_current" Current "$opt_maint" Maintenance && return 0
    block_on_error
    return 1
}


# load maintenance configuration
function do_maint {
    echo -n "Disabling IP forwarding... "
    disable_forwarding
    echo "OK."

    if ! check_modules; then
	echo -n "Firewall: loading modules... "
	if ! load_modules; then
	    echo "FAILED"
	    return 1
	else
	    echo "OK."
	fi
    fi 

    echo -n "Firewall: flushing all rules... "
    flush_rules
    echo "OK."

    load_in_order "$opt_maint" Maintenance && return 0
    block_on_error
    return 1
}

# stops the firewall and unloads the modules
function do_stop {
    # stop forwarding
    echo -n "Firewall: disabling IP forwarding... "
    disable_forwarding
    echo "OK."

    if check_modules; then
	echo -n "Firewall: flushing all rules... " ; flush_rules ; echo "OK."
	echo -n "Firewall: unloading modules... " ; unload_modules ; echo "OK."
    else
	echo "Firewall: already stopped."
    fi
    return 0
}

# block all incoming/outgoing traffic, but allows local communications
function do_block {
    local table chain chains

    echo -n "Disabling IP forwarding... "
    disable_forwarding
    echo "OK."

    if check_modules; then
	echo -n "Firewall: flushing all rules... " ; flush_rules ; echo "OK."
	echo -n "Firewall: unloading modules... " ; unload_modules ; echo "OK."
    fi

    # we force some options to ensure proper blocking
    unset opt_stateful
    unset opt_forward
    opt_filter=1

    echo -n "Firewall: loading modules... "
    if ! load_modules; then
	echo "FAILED"
	return 1
    else
	echo "OK."
    fi

    echo -n "Firewall: Changing policy to block all external traffic... "
    $IPTABLES -t filter -A INPUT -i lo -j ACCEPT
    $IPTABLES -t filter -A OUTPUT -o lo -j ACCEPT
    $IPTABLES -t mangle -P PREROUTING DROP
    $IPTABLES -t mangle -P INPUT DROP
    $IPTABLES -t mangle -P FORWARD DROP
    $IPTABLES -t mangle -P POSTROUTING DROP
    $IPTABLES -t mangle -P OUTPUT DROP
    $IPTABLES -t mangle -A PREROUTING -i lo -j ACCEPT
    $IPTABLES -t mangle -A INPUT -i lo -j ACCEPT
    $IPTABLES -t mangle -A POSTROUTING -o lo -j ACCEPT
    $IPTABLES -t mangle -A OUTPUT -o lo -j ACCEPT
    echo "OK."
    return 0
}

# unload the firewall and enable ip forwarding unconditionnaly
function do_route {
    if check_modules; then
	echo -n "Firewall: flushing all rules... " ; flush_rules ; echo "OK."
	echo -n "Firewall: unloading modules... " ; unload_modules ; echo "OK."
    fi

    # enable ip forwarding
    echo -n "Firewall: enabling IP forwarding..."
    enable_forwarding
    echo "OK."
    return 0
}

# create new test directory
function do_new {
    if [ -e $opt_confdir/new ] ; then
      echo -n "A pending firewall config already exists, remove [y/N] ? "
      read
      if [ "$REPLY" != y -a "$REPLY" != Y ] ; then
        echo "Operation cancelled." >&2
        return 1
      fi
      rm -f $opt_confdir/new
    fi 

    local NEWDATE=$(date +%Y%m%d-%H%M)

    if ! mkdir $opt_confdir/$NEWDATE 2>/dev/null ; then
      echo "A pending directory already exist for this time, " >&2
      echo "Try in 1 minute or edit $opt_confdir/new" >&2
      return 1   
    fi

    ln -s $NEWDATE $opt_confdir/new

    if [ -d $opt_confdir/current/. ] ; then
      cp -a $opt_confdir/current/. $opt_confdir/new/.
    elif [ -d $opt_confdir/backup/. ] ; then
      cp -a $opt_confdir/backup/. $opt_confdir/new/.
    elif [ -d $opt_confdir/maint/. ] ; then
      cp -a $opt_confdir/maint/. $opt_confdir/new/.
    fi

    echo "Pending config ($NEWDATE) create in $opt_confdir/new" >&2

    return 0  
}

# generate ipt config file for host with genrules with pending config
function do_gen {
    _GENRULES=$(type -p genrules 2>/dev/null)
    if [ $? != 0 ] ; then
      echo "Can not find binary 'genrules' in PATH" >&2
      return 1
    fi

    if [ ! -e $opt_confdir/new ] ; then
      echo "The pending directory doesn't exists, run 'new' before 'gen'" >&2
      return 1
    fi

    $_GENRULES $opt_confdir/new $(uname -n)
 
    return $?
}

# apply new config but do not save it
function do_try {
    if [ ! -e $opt_confdir/new/conf-$(uname -n).ipt ] ; then
      echo "No config in the pending directory, run 'gen' before 'try'" >&2
      return 1
    fi

    local TEMP=/tmp/fw.try.$RANDOM.$RANDOM

    /sbin/iptables-save > $TEMP

    if ! /sbin/iptables-restore < $opt_confdir/new/conf-$(uname -n).ipt ; then
      /sbin/iptables-restore < $TEMP
      rm -f $TEMP
      echo "Error loading pending config" >&2
      return 1
    fi

    echo "Try succedded, run 'save' to save it as current config" >&2

    rm -f $TEMP

    return 0
}

# save the new config in current profile
function do_save {
    if [ ! -e $opt_confdir/new ] ; then
      echo "No pending config to save" >&2
      return 1
    fi

    if [ ! -e $opt_confdir/backup -o -L $opt_confdir/backup ] ; then
      [ -e $opt_confdir/backup ] \
        && rm -f $opt_confdir/backup
    else
      echo "$opt_confdir/backup isn't a symbolic link, can't save" >&2
      return 1
    fi
    if [ ! -e $opt_confdir/current -o -L $opt_confdir/current ] ; then
      [ -e $opt_confdir/current ] \
        && mv $opt_confdir/current $opt_confdir/backup
    else
      echo "$opt_confdir/current isn't a symbolic link, can't save" >&2
      return 1
    fi
    mv $opt_confdir/new $opt_confdir/current
    return 0
}

load_config