List rules
iptables -L -v -n --line-numers
We can use the line numbers later to delete rules.
Delete rules
iptables -D INPUT 1
INPUT is the chain from which we delete the rule with line number 1
Allow incoming connection to a port
Allow incoming connections to port 1510 on external port eth0:
iptables -A INPUT -p tcp -i eth0 --dport 1510 -j ACCEPT
iptables -A OUTPUT -p tcp -o eth0 --sport 1510 -m conntrack --ctstate ESTABLISHED -j ACCEPT
Allow outbound connection to a port
Allow outbound traffic to port 8000 on external port eth0 to the external destination: 192.168.22.70:8000
iptables -A OUTPUT -p tcp -o eth0 -d 192.168.22.70 --dport 8000 -j ACCEPT
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -p tcp -i eth0 -s 192.168.22.70 --sport 8000 -j ACCEPT
Allow all local connections
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
Drop all other connections by changing policies
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP
How to configure a router?
echo 1 > /proc/sys/net/ipv4/ip_forward
The same to remain after reboot:
vim /etc/sysctl.conf
Find and change:
net.ipv4.ip_forward = 1
Add iptables
rules:
ext="eth0"
int="eth1"
iptables -t nat -A POSTROUTING -o ${ext} -j MASQUERADE
iptables -A FORWARD -i ${ext} -o ${int} -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i ${int} -o ${ext} -j ACCEPT
How to forward a port to a service in the local network?
We will forward port 1550 from client facing ip to the internal service ip with port 1500:
external_client_ip="192.168.22.70"
client_facing_ip="192.168.22.67"
client_facing_port=1550
internal_service_ip="192.168.22.157"
internal_service_port=1500
iptables -t nat -A PREROUTING -s ${external_client_ip} -d ${client_facing_ip} -p tcp -m tcp --dport ${client_facing_port} -j DNAT --to-destination ${internal_service_ip}:${internal_service_port}
iptables -t nat -A POSTROUTING -s ${external_client_ip} -d ${internal_service_ip} -j MASQUERADE