How to use NAT iptables rules for hostapd

Solution 1:

In the simplest form:

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

That will allow all WiFi users access to the Internet.

Of course assuming your other routing setup is already done, namely:

  1. Forwarding enabled in the kernel

    sysctl net.ipv4.ip_forward=1
    
  2. Forwarding enabled in iptables:

    iptables -P FORWARD ACCEPT
    iptables -F FORWARD
    

Use tcpdump -nn -i eth0 to watch the traffic on eth0 in case of problems to see if it gets NATed properly, if the response is coming back, etc.

EDIT: "I have to add manually each time i boot computer (from startup script)..." It depends on what Linux distribution you have. Sadly pretty much each distro has its own Firewall tool - in the end they're only calling iptables but for some reason the authors believe that obfuscating the way iptables work is what the users want.

To answer your question - the most likely your firewall can be configured to add this NAT rule automatically. The exact way however varies between Linux distros for no good reason. Sad but true.

Solution 2:

I wrote a firewall for all occasions. Please read the README and the SCRIPT before using it. I included the necessary rules for HOSTAP

Essential Parts:

HostAP

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE 
iptables -A FORWARD -i eth0 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT 
iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT

HostAP requires the lines below to both be ACCEPT to function

iptables -A INPUT -j ACCEPT >> /dev/null 2>&1 
iptables -A OUTPUT -j ACCEPT >> /dev/null 2>&1

https://github.com/diveyez/fw.sh