Skip to content

Instantly share code, notes, and snippets.

@dogbunny
Last active October 7, 2023 10:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dogbunny/fda68f21784025876c57a4dfc3fb6bcc to your computer and use it in GitHub Desktop.
Save dogbunny/fda68f21784025876c57a4dfc3fb6bcc to your computer and use it in GitHub Desktop.
Linux using TC for ingress (port) filtering
# This a solution for inducing latency on ingress traffic to a specific port
# note: ianae, but many hours of sleuthing and experimenting got me to this answer
# Adapted from https://wiki.gentoo.org/wiki/Traffic_shaping
# Note technically TC can only induce latency on egress traffic so we add an intermediate device which allows
# us to first identify the traffic we want to affect and then send it to a queue to do <stuff>
# eth0 is the external interface receiving the traffic we want to filter, 4222 is the port we want to add latency to.
# Those are the only values that you should need to change, if necessary.
# Add a TC ingress queue to your external interface, by default you shouldn't have one
sudo tc qdisc add dev eth0 handle ffff: ingress
# make sure ifb module is loaded and bring up the interface (IFB = Intermediate Functional Block device)
sudo modprobe ifb
sudo ifconfig ifb0 up
# redirect all traffic to the ifb so that we can later filter on the traffic that leaves that interface
sudo tc filter add dev eth0 parent ffff: protocol all u32 match u32 0 0 action mirred egress redirect dev ifb0
# build up our egress queues and filters
# we need a root, this one uses priority queues which defaults to not modifying any traffic
sudo tc qdisc add dev ifb0 root handle 1: prio
# add a special queue that induces latency
sudo tc qdisc add dev ifb0 parent 1:1 handle 2: netem delay 100ms 50ms distribution normal
# if we find a packet that matches our destination port, send it to the above queue
sudo tc filter add dev ifb0 protocol ip parent 1:0 prio 1 u32 match ip dport 4222 0xffff flowid 2:1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment