Iptables – Configure Wireguard to Block All Non-SSH Traffic

iptableswireguard

I am trying to restrict my Wireguard VPN to only allow SSH connections between the clients and I am struggling to setup proper iptables PostUp rules for the wireguard server.

My Interface has the following PostUp rules:

PostUp   = iptables -A FORWARD -i %i -p tcp --dport 22 -j ACCEPT; iptables -A FORWARD -o %i -p tcp --dport 22 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -p tcp --dport 22 -j ACCEPT; iptables -D FORWARD -o %i -p tcp --dport 22 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE

This for some reason allows access to all ports.

I have also tried to use iptables -A FORWARD -p tcp ! -dport 22 -j DROP as an additional very first rule. But for some reason I only managed to configure to block all traffic (including ssh).

Is there any way to allow the clients to only have access to port 22?

Best Answer

I would be tempted to add a chain called perhaps called wireguard or something else with rules like these. These would be get added by something outside wireguard.

# create wireguard chain
iptables -t filter -N wireguard
# permit anything coming from or going to port 22
iptables -t filter -A wireguard -p tcp --dport 1024:65535 --sport 22 -m state --state ESTABLISHED -j ACCEPT
iptables -t filter -A wireguard -p tcp --sport 1024:65535 --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
# drop everything else
iptables -t filter -A wireguard -j DROP

Then in your wireguard PostUp, just add rules like this.

iptables -t filter -I FORWARD -i %i -j wireguard
iptables -t filter -I FORWARD -o %i -j wireguard
Related Topic