Keep source IP after NAT
Posted
by
John Miller
on Server Fault
See other posts from Server Fault
or by John Miller
Published on 2012-11-26T12:42:19Z
Indexed on
2012/11/26
17:07 UTC
Read the original article
Hit count: 277
Until today I used a cheapy router so I can share my internet connection and keep a webserver online too, while using NAT. Users IP ($_SERVER['REMOTE_ADDR']) was fine, I was seeing class A IPs of users.
But as traffic grown up everyday, I had to install a Linux Server (Debian) to share my Internet Connection, because my old router couldn't keep the traffic anymore. I shared the internet via IPTABLES using NAT, but now, after forwarding port 80 to my webserver, now instead of seeing real users IP, I see my Gateway IP (Linux Internal IP) as any user IP Address.
How to solve this issue?
I edited my post, so I can paste the rules I'm currently using.
#!/bin/sh
#I made a script to set the rules
#I flush everything here.
iptables --flush
iptables --table nat --flush
iptables --delete-chain
iptables --table nat --delete-chain
iptables -F
iptables -X
# I drop everything as a general rule, but this is disabled under testing
# iptables -P INPUT DROP
# iptables -P OUTPUT DROP
# these are the loopback rules
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
# here I set the SSH port rules, so I can connect to my server
iptables -A INPUT -p tcp --sport 513:65535 --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp --sport 22 --dport 513:65535 -m state --state ESTABLISHED -j ACCEPT
# These are the forwards for 80 port
iptables -t nat -A PREROUTING -p tcp -s 0/0 -d xx.xx.xx.xx --dport 80 -j DNAT --to 192.168.42.3:80
iptables -t nat -A POSTROUTING -o eth0 -d xx.xx.xx.xx -j SNAT --to-source 192.168.42.3
iptables -A FORWARD -p tcp -s 192.168.42.3 --sport 80 -j ACCEPT
# These are the forwards for bind/dns
iptables -t nat -A PREROUTING -p udp -s 0/0 -d xx.xx.xx.xx --dport 53 -j DNAT --to 192.168.42.3:53
iptables -t nat -A POSTROUTING -o eth0 -d xx.xx.xx.xx -j SNAT --to-source 192.168.42.3
iptables -A FORWARD -p udp -s 192.168.42.3 --sport 53 -j ACCEPT
# And these are the rules so I can share my internet connection
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables -A FORWARD -i eth0:1 -j ACCEPT
If I delete the MASQUERADE part, I see my real IP while echoing it with PHP, but I don't have internet. How to do, to have internet and see my real IP while ports are forwarded too?
** xx.xx.xx.xx - is my public IP. I hid it for security reasons.
© Server Fault or respective owner