I read this way of routing the traffic of a specific interface with Cgroups (Cgroups1): https://superuser.com/a/1048913/1662108
Is there a way of doing the same thing with Cgroups2?
Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.
Sign up to join this communityI read this way of routing the traffic of a specific interface with Cgroups (Cgroups1): https://superuser.com/a/1048913/1662108
Is there a way of doing the same thing with Cgroups2?
After reading a lot I discovered how:
First the cgroup2 filesystem should be mounted at /sys/fs/cgroup
mount -t cgroup2
A cgroup must be created:
sudo mkdir -p /sys/fs/cgroup/direct
The shell must me added to the task list of cgroup, so all the child processes will run inside this cgroup:
echo $$ | sudo tee /sys/fs/cgroup/direct/cgroup.procs > /dev/null
The cgroup folder must have writing permissions to current user:
sudo chown -R "$(id -g -n)":"$(id -g -n)" /sys/fs/cgroup/direct
Iptables rules should be added:
sudo iptables -t mangle -A OUTPUT -m cgroup --path direct -j MARK --set-mark 2147483647
sudo iptables -t nat -A POSTROUTING -m cgroup --path direct -o eth0 -j MASQUERADE
A routing table must be added to iproute2:
echo 252 direct | sudo tee -a /etc/iproute2/rt_tables > /dev/null
A firewall mark and a additional route must be added:
sudo ip rule add fwmark 2147483647 table direct
sudo ip route add default via 192.168.1.1 table direct dev eth0
RP Filter should be disabled:
sudo sysctl -q -w net.ipv4.conf.eth0.rp_filter=0
sudo sysctl -q -w net.ipv4.conf.all.rp_filter=0
Any program running in this shell will use the additional route and will have its traffic forwarded to eth0:
sudo openvpn --config /path/to/some/config_file.ovpn
Cleaning all the mess:
iptables -t mangle -D OUTPUT -m cgroup --path direct -j MARK --set-mark 2147483647
iptables -t nat -D POSTROUTING -m cgroup --path direct -o eth0 -j MASQUERADE
ip rule del fwmark 2147483647 table direct
ip route del default via 192.168.1.1 table direct dev eth0
sed -i "/^252\s/d" /etc/iproute2/rt_tables
sysctl -q -w net.ipv4.conf.eth0.rp_filter=1
sysctl -q -w net.ipv4.conf.all.rp_filter=1
cat /sys/fs/cgroup/direct/cgroup.procs | while read task_pid; do echo ${task_pid} | tee /sys/fs/cgroup/cgroup.procs > /dev/null; done
rmdir /sys/fs/cgroup/direct