search by tags

for the user

adventures into the land of the command line

iptables cheatsheet

there are 4 chain targets (policies): ACCEPT, DROP, QUEUE, RETURN

for the 3 types in the filter table (there are 3 other tables, won’t go into it): INPUT, FORWARD, OUTPUT

by default, each table policy is set to the policy of ACCEPT. i want to DROP all INPUT packets and then explicitly ACCEPT for specific ports. i also want to explicitly DROP for specific types of traffic

you can view the current rules

$ iptables -L

you can then begin changing stuff by flushing the current tables to start from scratch

$ iptables -F

set the chain target policy for the INPUT and OUTPUT tables

$ iptables -P OUTPUT ACCEPT
$ iptables -P INPUT DROP

allow ssh, http and https access

$ iptables -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
$ iptables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
$ iptables -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT

allow the localhost interface

$ iptables -A INPUT -i lo -j ACCEPT

allow outgoing connections

$ iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

block null packets

$ iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP

protect against a SYN-Flood attack

$ iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP

drop christmas tree packets

$ iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP

if you want to be really specific with ssh access, you can lock it down to your ip address

$ iptables -A INPUT -p tcp -s YOUR_IP_ADDRESS -m tcp --dport 22 -j ACCEPT

this also works for server to server communication, where say, you might want a database server to only accept traffic form a particular app server and nowhere else. for example, on the db server we could add something like this

$ iptables -A INPUT -p tcp -s app_server_ipaddress -m tcp --dport some_port -j ACCEPT

save your iptables

$ iptables-save | sudo tee /etc/sysconfig/iptables

restart the iptables service

$ /etc/init.d/iptables restart

if you mess something up and lock yourself out, you can console in if you have one, flush the tables and start again

$ iptables -F

alternatively you can just fill in the /etc/sysconfig/iptables file with the content you want

$ vim /etc/sysconfig/iptables

# Generated by iptables-save v1.4.7 on Tue Mar 22 23:51:33 2016
*filter
:INPUT DROP [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [13:1988]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j DROP
-A INPUT -p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -m state --state NEW -j DROP
-A INPUT -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,SYN,RST,PSH,ACK,URG -j DROP
-A INPUT -i lo -j ACCEPT
COMMIT
# Completed on Tue Mar 22 23:51:33 2016