Linux socket setting mark necessity

  

Linux Netfilter hook point location will cause some strange problems, such as the packet sent by the machine can not use mark-based policy routing, because mark is generally carried out in Netfilter Linux routing is before the OUTPUT hook point, so this is a sequential inversion problem, how to solve it? Only mark before the route, and we know that for externally entered packets, mark is in PREROUTING Therefore, for externally entered packets, policy routing is good. For packets sent by this machine, the route can only be the socket layer before. Why can't it be done in the transport layer? Because the transport layer is more complicated, the second one is Many protocols go directly to the IP layer, such as OSPF. Third, many transport layer protocols also need route lookup. For example, when TCP connects, it needs to find the route to determine the source IP address (if there is no bind).

Fortunately, Linux sockets support an option such as SO_MARK, which can be easily used:

mark = 100;

setsockopt(client_socket, SOL_SOCKET, SO_MARK, & ;mark, sizeof(mark));

1. Impact on TRACK

Although the raw table is the first table passed by the packet, using SO_MARK can still work in the entire raw table. Do some mark before, so that the package issued by a specific socket is all NOTRACK:

iptables -t raw -A OUTPUT -m mark --mark 100 -j NOTRACK

If this is not the case, you will need:

iptables -t raw -A OUTPUT [-s xxxx] [-d yyyy] [-p tcp| Udp [--sport X] [--dport Y] ... -j MARK --set-mark 100

...[a lot of similar rules above]

iptables -t raw -A OUTPUT -m mark --mark 100 -j NOTRACK

As the raw table on PREROUTING needs to do. We are proud that OUTPUT is a socket, the world of applications, and PREROUTING is the kernel and the world of drivers. The latter is too messy and inconvenient to do more, while the former is the scope we can control.

2. Impact on Policy Routing

The biggest beneficiary of SO_MARK is policy routing, if we are the following route:

ip rule add fwmark 100 table abc

ip route add 1.2.3.4/32 via 192.168.0.254 table abc

ip route del 1.2.3.4/32 table Main

Without setting SO_MARK, all traffic accessing 1.2.3.4 will be discarded because there is no route, because the route must be searched before entering PREROUTING, but not marked at this time. And thus will not match the route in the abc policy table, and the corresponding route in the main table has been deleted...but if we add in the application:

mark = 100;

setsockopt(client_socket, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));

Access is fine, because the mark is already there when looking for routes.

Copyright © Windows knowledge All Rights Reserved