# iptables

#### list rules with line numbers
    sudo iptables --list --line-numbers

#### delete a rule with number
    sudo iptables -D INPUT <number>

#### add an input rule
    sudo iptables -A INPUT -p tcp --dport 25 -j ACCEPT

#### make iptables persistent
    sudo apt install iptables-persistent
    sudo netfilter-persistent save

#### only allow communication when connected to VPN
iptables config to prevent communication unless connected to a VPN.
``` bash
#!/bin/sh

IPT="/sbin/iptables"

# Allow loopback device
$IPT -A INPUT -i lo -j ACCEPT
$IPT -A OUTPUT -o lo -j ACCEPT

# Allow all local traffic.
$IPT -A INPUT -s 192.168.1.0/24 -j ACCEPT
$IPT -A OUTPUT -d 192.168.1.0/24 -j ACCEPT
$IPT -A INPUT -s 10.0.1.0/24 -j ACCEPT
$IPT -A OUTPUT -d 10.0.1.0/24 -j ACCEPT

# Allow VPN establishment
$IPT -A OUTPUT -p udp --dport 1194 -j ACCEPT
$IPT -A INPUT -p udp --sport 1194 -j ACCEPT

# Accept all TUN connections (tun = VPN tunnel)
$IPT -A OUTPUT -o tun+ -j ACCEPT
$IPT -A INPUT -i tun+ -j ACCEPT

# Set default policies to drop all communication unless specifically allowed
$IPT -P INPUT DROP
$IPT -P OUTPUT DROP
$IPT -P FORWARD DROP
```

#### ipv4 iptables rules for a VPS
``` iptables
*filter

# Allow all loopback (lo0) traffic and reject traffic
# to localhost that does not originate from lo0.
-A INPUT -i lo -j ACCEPT
-A INPUT ! -i lo -s 127.0.0.0/8 -j REJECT

# Allow ping.
-A INPUT -p icmp -m state --state NEW --icmp-type 8 -j ACCEPT

# Allow SSH connections.
-A INPUT -p tcp --dport 22 -m state --state NEW -j ACCEPT

# Allow HTTP and HTTPS connections from anywhere
# (the normal ports for web servers).
-A INPUT -p tcp --dport 80 -m state --state NEW -j ACCEPT
-A INPUT -p tcp --dport 443 -m state --state NEW -j ACCEPT

# Allow inbound traffic from established connections.
# This includes ICMP error returns.
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Log what was incoming but denied (optional but useful).
#-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables_INPUT_denied: " --log-level 7

# Reject all other inbound.
-A INPUT -j REJECT

# Log any traffic that was sent to you
# for forwarding (optional but useful).
-A FORWARD -m limit --limit 5/min -j LOG --log-prefix "iptables_FORWARD_denied: " --log-level 7

# Reject all traffic forwarding.
-A FORWARD -j REJECT

# Block docker access
-A DOCKER-USER -m state --state ESTABLISHED,RELATED -j ACCEPT
-A DOCKER-USER -i eth0 ! -s 127.0.0.1 -j DROP

COMMIT
```
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9