Introducing netjail

Long time ago I felt the need to force a single application to use a specific network connection. Or to be more specific I needed to ensure that my torrent client cannot escape the VPN connection. Today the internet is full of scripts and tools to realize that under any kind of OS and many people just use container virtualization like docker or LXC.
Anyway I started to write a bash script which should be able to cage an application into an extra network namespace in which only a OpenVPN connection is available. At first I wrote down a special routing+iptables felony but then I realized, that I just can move an existing TUN Interface to another namespace. It’s called netjail [1]
Here is an example:

ip netns add netjail
ip link set tun0 netns netjail

The tricky thing is that it’s necessary to reconfigure the IPs and routes after that because the interface looses all its config when it changes the networknamespace. Normally OpenVPN configures the Interfaces it creates automatically but for special cases like this it can call bash scripts and pass them more or less every configuration parameter. So I just added few lines of bash inspired by [2] which can be called by OpenVPN during initialisation. They move the interface inside netjails network namespace and configure it there [3].

Last but not least, the script is able to directly start an application inside this new namespace. This application can only use the OpenVPN connection to talk to the outside. If OpenVPN dies, the application is offline.

Its also possible to use the script to prepare network namespaces for container usage or to push an OpenVPN interface to an already existing namespace.

[3] \