Marking packets with iptables with a NAT

I have to write bash scripts for a router to control bandwidth limitation for a given user on a given domain name.

For this, I'm using iptables to mark the packets incoming from a restricted domain to a user ip address in the private network. With each couple user_ip/domain_ip I have a single key with which I can mark the packet.

I add those rules in the mangle table like this :

$iptables -t mangle -A PREROUTING -p tcp -d $userIp -s $restrictedDom -j MARK --set-mark $id 
$iptables -t mangle -A PREROUTING -p tcp -d $userIp -s $restrictedDom -j RETURN

My NAT setting in the nat table (eth0 is my internet interface, and I used tap0 for Lan interface) is

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

The packet for my Lan user should match a rule in the mangle table but is not catch.

Example : (table mangle in the PREROUTING CHAIN) This is for example for marking packets coming from slashdot.org for the user 192.168.0.2 in the Lan network.

Chain PREROUTING (policy ACCEPT 14858 packets, 7215129 bytes)
pkts      bytes target     prot opt in     out     source               destination      
 0        0 MARK       tcp  --  *      *       216.34.181.45        192.168.0.2         MARK xset 0x9/0xffffffff 
 0        0 RETURN     tcp  --  *      *       216.34.181.45        192.168.0.2         

However, If I try to mark packets coming from slashdot.org on the internet interface of the router, the packets are catched, and if a computer in the Lan also consult slashdot.org, the same rule will mark them too.

So I guess there is a problem because of the NAT translation and I don't know exactly when to and in which order apply the rules.

In a first time, are my NAT settings good or incomplete in iptables ? Did I miss an important thing about the rules or iptables concept ?

Thanks in advance.


I think that you should use the POSTROUTING mangle table since you are marking the packets in the PREROUTING before the NAT engine.

Have a look at the IPTABLE Chain :

IPTABLES CHAIN DRAWING