Course contentsShow
← Linux
Lesson 1125 of 1,81910. Network Administration and Kernel StacksFree lesson

Policy Routing with Firewall Marks

Use netfilter marks to influence routing decisions for specific packet flows.

In this lesson, you will learn how to use netfilter marks to force specific traffic flows through a dedicated routing table, bypassing the standard destination-based routing logic.

The Concept: Marking Traffic

Standard Linux routing relies solely on the destination IP address. However, as a network administrator, you often need to route traffic based on the application or the protocol generating the packet. We achieve this by "marking" packets at the netfilter level (the same layer used by iptables or nftables) and then telling the kernel to consult a specific routing table for any packet carrying that mark.

Think of it as adding a "VIP sticker" to specific envelopes. The post office (the kernel's routing engine) sees the sticker and sends those envelopes to a private courier, while all other mail follows the standard public route.

Implementation Flow

  1. Mark the Packet: Use iptables in the mangle table to apply a numerical mark (the "fwmark") to packets matching your criteria (e.g., port 80 traffic).
  2. Assign the Mark to a Table: Use ip rule to link that mark to a custom routing table.
  3. Define the Routes: Add routes specifically to that table.

Here is how you would configure this for traffic coming from a specific service:

# 1. Mark outgoing packets with ID 100
iptables -t mangle -A OUTPUT -p tcp --dport 80 -j MARK --set-mark 100

# 2. Tell the kernel that packets marked '100' should use routing table '100'
ip rule add fwmark 100 table 100

# 3. Add a default gateway for that specific routing table
ip route add default via 192.168.2.1 dev eth1 table 100

Why This Matters

By using fwmark, you decouple the routing decision from the interface or destination IP. This is incredibly powerful for complex scenarios like split-tunnel VPNs, where you want to send all encrypted traffic through a specific gateway, or for policy-based load balancing where you want to steer specific application traffic (like high-latency video streams) through a secondary high-bandwidth link regardless of the destination IP.

Key Takeaway: By assigning a firewall mark to a flow, you grant the kernel permission to ignore default routing rules and force packets through a custom, purpose-built routing table.