Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gnanet/069fc970ff1dfb82ab84ca623e838107 to your computer and use it in GitHub Desktop.
Save gnanet/069fc970ff1dfb82ab84ca623e838107 to your computer and use it in GitHub Desktop.
NFT Ruleset plugin for Netfilter-Persistent
#!/bin/sh
# usr.share.netfilter-persistent.plugins.d.15-nft.sh
# NFT Ruleset plugin for Netfilter-Persistent
# This file is part of netfilter-persistent
# Copyright (C) 2025, Gergely Nagy <[email protected]>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
set -e
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
NFT_ETCDIR="/etc/iptables"
NFT_RULESET="${NFT_ETCDIR}/rules.nft"
NFT_CMD=$(command -v nft)
if [ ! -f ${NFT_CMD} ]; then
echo "Error: nft command missing!"
return 1
fi
if [ ! -d "${NFT_ETCDIR}/" ]; then
mkdir -p "${NFT_ETCDIR}/"
fi
init_rules()
{
if [ ! -f ${NFT_RULESET} ]; then
touch ${NFT_RULESET}
chmod 0640 ${NFT_RULESET}
fi
cat <<EOTPL > ${NFT_RULESET}
flush ruleset
add table inet filter
add chain inet filter input { type filter hook input priority 0; policy accept; }
add chain inet filter forward { type filter hook forward priority 0; policy accept; }
add chain inet filter output { type filter hook output priority 0; policy accept; }
EOTPL
}
load_rules()
{
#load nft rules
if [ ! -f ${NFT_RULESET} ]; then
echo "Warning: nft ruleset file ${NFT_RULESET} does not exist!"
if [[ "x$(${NFT_CMD} list ruleset)" == "x" ]]; then
echo "Warning: nft running ruleset empty, initialize default policy accept ruleset"
init_rules
else
echo "Info: saving current nft ruleset into ${NFT_RULESET}"
${NFT_CMD} -n list ruleset > ${NFT_RULESET}
fi
else
${NFT_CMD} -f ${NFT_RULESET}
fi
}
save_rules()
{
if [ ! -f ${NFT_RULESET} ]; then
echo "Warning: nft ruleset file ${NFT_RULESET} does not exist!"
touch ${NFT_RULESET}
chmod 0640 ${NFT_RULESET}
fi
if [[ "x$(${NFT_CMD} list ruleset)" == "x" ]]; then
echo "Warning: nft running ruleset empty, initialize default policy accept ruleset"
init_rules
else
${NFT_CMD} -n list ruleset > ${NFT_RULESET}
fi
}
flush_rules()
{
${NFT_CMD} flush ruleset
}
case "$1" in
start|restart|reload|force-reload)
load_rules
;;
save)
save_rules
;;
stop)
# Why? because if stop is used, the firewall gets flushed for a variable
# amount of time during package upgrades, leaving the machine vulnerable
# It's also not always desirable to flush during purge
echo "Automatic flushing disabled, use \"flush\" instead of \"stop\""
;;
flush)
flush_rules
;;
*)
echo "Usage: $0 {start|restart|reload|force-reload|save|flush}" >&2
exit 1
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment