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

Policy Routing based on Application Tags

Redirect traffic based on socket-level metadata and cgroup awareness.

In this lesson, you will learn how to steer network traffic based on the specific application that generated it using socket-level metadata and cgroup tagging.

Beyond Firewall Marks

Previously, we explored Policy-Based Routing (PBR) using iptables or nftables "firewall marks" (fwmark). While effective, fwmark requires identifying traffic based on IP addresses, ports, or protocols after the packet is constructed. Application-based routing goes a step further: it classifies traffic at the source (the socket level) before it even hits the network stack’s routing decision engine.

The Role of Cgroups

The Linux kernel allows you to associate a Control Group (cgroup) with a routing policy. By placing a specific application (like a web crawler or a high-priority database process) into a cgroup, you can tag its outgoing packets with a classid.

When the kernel's routing engine evaluates where to send a packet, it looks at the cgroup ID associated with the socket. We can create routing rules that instruct the kernel to use a specific routing table based on that ID:

# 1. Create a rule to look up table 100 for cgroup ID 0x00100001
ip rule add cgroup 0x00100001 table 100

# 2. Add a default route to table 100 that points to a specific ISP or VPN gateway
ip route add default via 192.168.2.1 dev eth1 table 100

Why Use This?

This approach is significantly more robust than port-based routing. If an application changes its port dynamically or uses encryption that masks its payload, traditional packet inspection might fail to categorize the traffic correctly. Because the cgroup tag is attached directly to the process's socket by the kernel, the routing decision is deterministic. It ensures that regardless of the destination or the protocol, every byte originating from that specific process follows the path you have designated.

This technique is essential for multi-homed hosts where you need to guarantee that heavy traffic (e.g., bulk backups) stays on a secondary, lower-cost interface, while latency-sensitive traffic (e.g., API calls) traverses a primary, high-performance uplink.

Key Takeaway: By assigning processes to cgroups and mapping those cgroups to specific routing tables, you can enforce path selection based on the identity of the application rather than the characteristics of the packet.