Putting the firewall into place involves three files, four, five files if you include logging. This firewall is the most basic, using Packet-Filtering rules to accept IP addresses, ports, and protocols.
/etc/nftables/firewall.nft
/etc/nftables/scripts/apply-firewall.sh
/etc/rsyslog.d/30-nftables.conf
/var/log/nftables.log
apply-firewall.sh #Automated load script
/etc/rsyslog.d/30-nftables.conf also if you will add to this file to direct logging to a file.
nft flush ruleset
nft add table inet myfirewall
# myfirewall is the name of the table. (like a variable name, the variable type is table)
nft add chain inet myfirewall input { type filter hook input priority 0; policy drop; }
#Allow established connections, localhost (loopback) and ping
nft add rule inet myfirewall input ct state established, related accept
nft add rule inet myfirewall input iif lo accept
nft add rule inet myfirewall input icmp type echo-request accept
#basic filewall to allow incoming traffic for SSH, HTTP, HTTPS, and drops everything else
nft add rule inet myfirewall input tcp dport 22 accept
nft add rule inet myfirewall input tcp dport { 80,443 } accept
# To allow incoming traffic for node.js MySQL and Maria DB
nft add rule inet myfirewall input tcp dport 3000 accept
nft add rule inet myfirewall input tcp dport 3306 accept
# Log the dropped traffic
nft add rule inet myfirewall input log prefix “DROP_LOG: “ flags all
#----
# Save myfirewall configuration
sudo nft list ruleset > /etc/nftables.conf
# Enable nftables
sudo systemctl start nftables
# Load on Startup
sudo systemctl enable nftables
file: “apply-firewall.sh”
#!/bin/bash
# file: /etc/nftables/scripts/apply-firewall.sh
echo “Loading nftables rules...”
nft flush ruleset
nft -f /etc/nftables/firewall.nft
if [ $? -eq 0 ]; then
echo “checked Rules loaded successfully.”
else
echo “ Error applying rules.”
exit 1
fi
Make the file executable:
chmod +x /etc/nftables/scripts/apply-firewall.sh
Lexical Conventions
A hash sign (#) begins a comment. All following characters on the same line are ignored.
file for firewall: firewall.nft
#!/usr/sbin/nft -f
# /etc/nftables/firewall.nft
table inet myfirewall {
chain input {
type filter hook input priority 0; policy drop;
ct state established,related accept
iifname "lo" accept
icmp type echo-request accept
tcp dport 22 accept #SSH
tcp dport { 80, 443 } accept # HTTP and HTTPS
tcp dport { 3000, 3306 } accept # MySQL and MariaDB
log prefix “Server Block: “ flags all
}
}