In this lesson, you will learn how to bypass the standard destination-only routing table to steer traffic based on its source, specific markings, or protocol type.
Beyond Destination Routing
Standard Linux routing relies solely on the destination IP address. However, in advanced network administration, you often need to decide where a packet goes based on who sent it or what it is. This is known as Policy-Based Routing (PBR).
In Linux, PBR is implemented using the IP Route Policy Database (RPDB). Instead of one single routing table, the kernel maintains a list of rules that prioritize different tables.
Implementing PBR
Think of the RPDB as a "chooser" that looks at a packet and decides which routing table to consult. If you have two different ISPs (e.g., isp1 and isp2), you can ensure traffic originating from your internal server 192.168.1.50 always exits via isp1, regardless of the destination.
First, you define a custom routing table in /etc/iproute2/rt_tables:
echo 200 isp1_table >> /etc/iproute2/rt_tables
Next, you add a rule to the RPDB:
# Direct traffic from source 192.168.1.50 to our custom table
ip rule add from 192.168.1.50 table isp1_table
# Add a default route specifically for that table
ip route add default via 10.0.0.1 dev eth1 table isp1_table
Using Firewall Marks
You can also route traffic based on its "identity" by using iptables or nftables to mark packets. If you want to force all HTTP (port 80) traffic through a specific VPN tunnel, you can tag those packets with a "mark" and tell the RPDB to look for that mark:
# Mark outgoing web traffic with a hex value
iptables -t mangle -A OUTPUT -p tcp --dport 80 -j MARK --set-mark 1
# Tell the kernel to route marked packets through a specific table
ip rule add fwmark 1 table vpn_table
By separating the "lookup rule" (the ip rule) from the "routing decision" (the ip route), you gain granular control over your network traffic that a standard table cannot provide.
Key Takeaway: Policy-Based Routing allows you to override standard destination-based routing by using the RPDB to map packet attributes—like source address or firewall marks—to custom routing tables.