Allowing Established Sessions
We can allow established sessions to receive traffic:
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
If the line above doesn't work, you may be on a castrated VPS whose provider has not made available the extension, in which case an inferior version can be used as last resort:
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
Allowing Incoming Traffic on Specific Ports
sudo iptables -A INPUT -p tcp --dport ssh -j ACCEPT
Blocking Traffic
sudo iptables -A INPUT -j DROP
Enabling loopback by editing iptables :
sudo iptables -I INPUT 1 -i lo -j ACCEPT
Logging of unwanted traffic:
sudo iptables -I INPUT 4 -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7
To confirm that changes have been successfully made:
iptables -L
Chain INPUT (policy ACCEPT)
target prot opt source destination
ACCEPT all -- anywhere anywhere
ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED
ACCEPT tcp -- anywhere anywhere tcp dpt:ssh
LOG all -- anywhere anywhere limit: avg 5/min burst 5 LOG level debug prefix "iptables denied: "
DROP all -- anywhere anywhere
Use iptables -L -v
to get more details :
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
0 0 ACCEPT all -- lo any anywhere anywhere
0 0 ACCEPT all -- any any anywhere anywhere state RELATED,ESTABLISHED
0 0 ACCEPT tcp -- any any anywhere anywhere tcp dpt:ssh
0 0 LOG all -- any any anywhere anywhere limit: avg 5/min burst 5 LOG level debug prefix "iptables denied: "
0 0 DROP all -- any any anywhere anywhere
Empty iptables:
iptables -F
iptables -t nat -F
iptables -t mangle -F
iptables -X
Saving iptables
If you were to reboot your machine right now, your iptables configuration would disappear. Rather than type this each time you reboot, however, you can save the configuration, and have it start up automatically.
Save your firewall rules to a file
sudo sh -c "iptables-save > /etc/iptables.rules"
The script /etc/network/if-pre-up.d/iptablesload will contain:
#!/bin/sh
iptables-restore < /etc/iptables.rules
exit 0
and /etc/network/if-post-down.d/iptablessave will contain:
#!/bin/sh
iptables-save -c > /etc/iptables.rules
if [ -f /etc/iptables.downrules ]; then
iptables-restore < /etc/iptables.downrules
fi
exit 0
Then be sure to give both scripts execute permissions:
sudo chmod +x /etc/network/if-post-down.d/iptablessave
sudo chmod +x /etc/network/if-pre-up.d/iptablesload
Source