NAT no Linux
iptables NAT
Copy
Ask AI
# Habilitar forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward
# Permanent
nano /etc/sysctl.conf
net.ipv4.ip_forward = 1
sysctl -p
# SNAT (Source NAT)
iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j MASQUERADE
# DNAT (Destination NAT)
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j DNAT --to-destination 192.168.1.100:8080
nftables NAT
Copy
Ask AI
nft add table ip nat
nft add chain ip nat postrouting { type nat hook postrouting priority 100 \; }
nft add rule ip nat postrouting oifname "eth0" masquerade
nft add chain ip nat prerouting { type nat hook prerouting priority -100 \; }
nft add rule ip nat prerouting iifname "eth0" tcp dport 80 dnat to 192.168.1.100:8080
NAT com iptables completa
Copy
Ask AI
#!/bin/bash
# NAT gateway script
# Habilitar forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward
# Flush regras existentes
iptables -F
iptables -t nat -F
iptables -X
# Politicas padrao
iptables -P INPUT ACCEPT
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
# NAT
iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j MASQUERADE
# Permitir forward
iptables -A FORWARD -i eth1 -o eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT
Port Forwarding
Copy
Ask AI
# SSH
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 2222 -j DNAT --to-destination 192.168.1.100:22
# HTTP/HTTPS
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j DNAT --to-destination 192.168.1.100:80
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -j DNAT --to-destination 192.168.1.100:443
# Range
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 8000:9000 -j DNAT --to-destination 192.168.1.100:8000-9000
Hairpin NAT
Copy
Ask AI
# Permitir clientes internos acessarem via IP externo
iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -d 192.168.1.0/24 -j MASQUERADE
Verificar
Copy
Ask AI
# Ver regras NAT
iptables -t nat -L -n -v
# Ver forwarding
iptables -L FORWARD -n -v
# Testar conectividade
ping 8.8.8.8