Working with iptables

1. Flushing current iptables
iptables -F or iptables –flush

2. Stating default action for a chain
iptables -P “chain name” “action”
or
iptables –policy “chain name” “action”

For a complete filtering, specify INPUT, OUTPUT, FORWARD for a chaing name.
FOWARD filters NIC to another NIC packets.
e.g.
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP

3. Allow all packets based on interface.
e.g. Allow all packets from loopback interface.
# for incming
iptables -A INPUT -i lo -j ACCEPT
# for outgoing
iptables -A OUTPUT -o lo -j ACCEPT

4. IP address based filtering, you can also combine with interface filtering above.
e.g.
# For incoming
iptables -A INPUT -s “10.0.0.1/24” -j DROP
# For outgoing
iptables -A OUTPUT -d “10.0.0.1/24” -j DROP

5. Port based filtering(-p udp to filter udp). You can also combine with ip address and interface based filtering.
# For incoming
iptables -A OUTPUT -p tcp –dport 22 -j ACCEPT
# For outgoing.
iptables -A INPUT -p tcp –sport 22 -j ACCEPT

6. NAT
Make sure to allow incoming packets to the forwarded port or ip address.
# Destination NAT (Port only, ip address is unaltered )
iptables -t nat -A PREROUTING -p tcp –dport 9999 -j DNAT –to 22
# Source NAT (Port only, ip address is unchanged )
iptables -t nat -A POSTROUTING -p tcp –sport 9991 -j SNAT –to 122

# Destination NAT (IP address only, port unaltered )
iptables -t nat -A PREROUTING -d “10.0.0.1/24” -j DNAT –to “192.168.0.1”
# Source NAT (Port only, ip address is unchanged )
iptables -t nat -A POSTROUTING -d “10.0.0.1/24” -j SNAT –to “192.168.0.1”

# Destination NAT (IP address and Port)
iptables -t nat -A PREROUTING -d “10.0.0.1/24” -p tcp –dport 22-j DNAT –to “192.168.0.1:12222”
# Source NAT (Port only, ip address is unchanged )
iptables -t nat -A POSTROUTING -d “10.0.0.1/24” -p tcp –sport 80 -j SNAT –to “192.168.0.1:18888”

7. Modifying tables
# Specifying position to insert to
iptables -I INPUT “rule number” “some policy”
# Replace some rule
iptables -R OUTPUT “rule number” “some polixy”
# Delete some rule
iptables -D INPUT “rule number”

8. Permitting established connections
iptables -A INPUT -m conntrack –ctstate ESTABLISHED -j ACCEPT

If you want to permit related connections as well,
iptables -A INPUT -m conntrack –ctstate ESTABLISHED,RELATED -j ACCEPT

8. Saving the rule
For CentOS 7.2
/usr/libexec/iptables/iptables.init save

Advertisements
Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: