What is iptables?

iptables is a user-space application that configures Linux kernel's packet filtering and NAT(Network address translation) rules
Its used to control incoming, outgoing network traffic based on predefined rules

Tables in iptables

Name Description
NAT(Network Address Translation) This table is consulted when new connection is seen.Used for translating IP Addresses & ports.
Consists of 4 builtins:
1. PREROUTING: Alter packet as soon as they came in
2. INPUT: Alter packet destinated to local socket
3. OUTPUT: Alter locally generated packet
4. POSTROUTING: alter packet as they are about to go out
Filter Default table. (if no -t option is given)
mangle For specialized packet alteration.
raw For configuring exemption for connection tracking.
security For MAC(Mandatory Network Access) rules

Examples

Add / Delete a Rule


-t: table
-A: append rule at end of chain
-j(jump): What to do if packet matches
-D: delete a rule

// Redirect incoming traffic on port=8080 to port=30080
$ sudo iptables -t nat -A PREROUTING -p tcp --dport 8080 -j REDIRECT --to-port 30080

// Redirect locally generated traffic on port=8080 to port=30080
$ sudo iptables -t nat -A OUTPUT -p tcp --dport 8080 -j REDIRECT --to-port 30080
      

List rules


-L: list all rules in chain
-n: numeric output
-v: verbose output
$ sudo iptables -t nat -L -n | grep -E '(8080|30080)'

// PREROUTING
$ sudo iptables -t nat -L PREROUTNIG -n | grep -E '(8080|30080)'

// OUTPUT
$ sudo iptables -t nat -L OUTPUT -n | grep -E '(8080|30080)'