Skip to content

Instantly share code, notes, and snippets.

@vincentbernat
Created April 28, 2014 10:19
Show Gist options
  • Save vincentbernat/11367741 to your computer and use it in GitHub Desktop.
Save vincentbernat/11367741 to your computer and use it in GitHub Desktop.
Use of Linux network namespace to test and commit a firewall
#!/bin/zsh
# Use a dedicated network namespace to build and test firewall rules
# before applying them.
set -e
zparseopts -D n=dryrun -dry-run=dryrun t=trace -trace=trace f=iptables
[[ -n $trace ]] && setopt xtrace
[[ -z $iptables ]] && {
# Execute iptables stuff into a dedicated network namespace
if (( $+dryrun[1] )); then
unshare -n -- $0 -f ${trace:+-t} 4> >(sed 's/^/IPv4: /') 6> >(sed 's/^/IPv6: /')
else
unshare -n -- $0 -f ${trace:+-t} 4> >(iptables-restore) 6> >(ip6tables-restore) && {
# Enable forwarding
sysctl -w net.ipv4.ip_forward=1
sysctl -w net.ipv6.conf.all.forwarding=1
}
fi
exit 0
}
ip46tables() {
iptables "$@"
ip6tables "$@"
}
### ------------------ Default policy
ip46tables -P INPUT DROP
ip46tables -P FORWARD DROP
ip46tables -P OUTPUT ACCEPT
# Allow loopback traffic
ip46tables -A INPUT -i lo -j ACCEPT
# Allow some ICMP traffic
iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 50/s -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-request -j DROP
ip6tables -A INPUT -p icmpv6 --icmpv6-type echo-request -m limit --limit 50/s -j ACCEPT
ip6tables -A INPUT -p icmpv6 --icmpv6-type echo-request -j DROP
# Enable conntrack
ip46tables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
ip46tables -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
# IPv6
ip6tables -A INPUT -m rt --rt-type 0 -j DROP
ip6tables -A INPUT -p icmpv6 --icmpv6-type neighbor-solicitation -m hl --hl-eq 255 -j ACCEPT
ip6tables -A INPUT -p icmpv6 --icmpv6-type neighbor-advertisement -m hl --hl-eq 255 -j ACCEPT
### ------------------ Logs
ip46tables -A INPUT -m limit --limit 1/s -j LOG --log-level notice --log-prefix "DROP INPUT: "
ip46tables -A FORWARD -m limit --limit 1/s -j LOG --log-level notice --log-prefix "DROP FORWARD: "
iptables-save >&4
ip6tables-save >&6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment