summarylogtreecommitdiffstats
path: root/nftables.initd
blob: 651c4fe09968bb4a8614c32c3cd5fef4ec837694 (plain)
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
#!/sbin/openrc-run
# Copyright 2018 William Vigolo da Silva
# Copyright 2014-2017 Nicholas Vinson
# Copyright 1999-2017 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

extra_commands="flush list panic save"
extra_started_commands="reload"
depend() {
    need localmount
    before net
}

start_pre() {
    checkkernel && checkconfig && return 0
    return 1
}

flush() {
    nft flush ruleset || return 1
}

list() {
    nft list ruleset || return 1
}

_panic() {
    yesno "${PANIC_ON_FAIL:-yes}" && checkkernel && checkconfig && panic
    return $?
}

panic() {
    if service_started "${RC_SVCNAME}"; then
	rc-service "${RC_SVCNAME}" stop
    fi

    ebegin "Dropping all packets"

    flush
    for protocol in ip ip6; do
	nft create table $protocol filter 2>/dev/null || continue

	nft -f /dev/stdin <<-EOF
	table $protocol filter {
	    chain input { type filter hook input priority 0; drop; }
	    chain forward { type filter hook forward priority 0; drop; }
	    chain output { type filter hook output priority 0; drop; }
	}
	EOF
    done
}

reload() {
    start_pre || return 1
    ebegin "Flushing firewall"
    flush
    start
}

save() {
    ebegin "Saving nftables ruleset"
    checkpath -q -d "$(dirname "${NFTABLES_CONFIG}")"
    checkpath -q -m 0700 -f "${NFTABLES_CONFIG}"
    echo "#!/bin/nft -f" >"${NFTABLES_CONFIG}"
    nft ${SAVE_OPTIONS} list ruleset >>"${NFTABLES_CONFIG}"
    return $?
}

start() {
    ebegin "Loading ruleset and starting firewall"
    flush
    nft -f "${NFTABLES_CONFIG}" || _panic
    eend $?
}

stop() {
    yesno "${SAVE_ON_STOP:-no}" && (save || return 1)

    ebegin "Stopping firewall"
    flush
    eend $?
}

checkconfig() {
    [ -r "${NFTABLES_CONFIG}" ] && return 0
    eerror "Could not read configuration file '${NFTABLES_CONFIG}'"
    eerror "Populate it or use a different file by setting \$NFTABLES_CONFIG in"
    eerror "the service configuration file"
    eerror "Alternatively, create some rules and then run:"
    eerror "rc-service ${RC_SVCNAME} save"
    return 1
}

checkkernel() {
    (nft list tables >/dev/null 2>&1) && return 0
    eerror "Your kernel lacks nftables support, please load"
    eerror "appropriate modules and try again."
    return 1
}