[SOLVED] Only making deluge use vpn and vpn only

General support for problems installing or using Deluge
bluenote
New User
New User
Posts: 3
Joined: Wed Aug 26, 2015 8:59 pm

Re: [SOLVED] Only making deluge use vpn and vpn only

Post by bluenote »

OP was kind enough to PM me a link to his blog which details his solution:

https://blog.tmlmt.com/hacking/deluge-vpn

I was able to co-opt this with a few changes for my needs.

Thanks OP :)
ScottyDelicious

Re: [SOLVED] Only making deluge use vpn and vpn only

Post by ScottyDelicious »

bluenote wrote:Could you post your procedure for binding deluge to the interface? I have this working (kind of) but it's very, very, manual.
I have to manually delete the default route for the openvpn tunnel as well which is a pain.

Thanks
I am using OpenVPN on a headless Ubuntu server, but the procedure will be similar for any linux distro connecting through openvpn. My VPN provider is Private Internet Access (PIA).

I set up OpenVPN to connect on boot to the PIA Netherlands gateway. In my configuration file (/etc/openvpn/Netherlands.conf), there is a directive you can use called "up". This directive calls a script once the tunnel is up. My configuration file looks like this:

Code: Select all

client
dev tun
proto udp
remote nl.privateinternetaccess.com 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
tls-client
remote-cert-tls server
auth-user-pass /etc/openvpn/login.conf
comp-lzo
verb 1
reneg-sec 0
auth-nocache
script-security 2
up /etc/openvpn/up.sh
The last line that says "up /etc/openvpn/up.sh" tells openvpn to run that script when the tunnel connection is up. I use this script to stop the deluged daemon, replace "listen_address" and "listen_interface" with the IP address assigned to me when the tunnel connected, then restart the deluged daemon.

Use vim or nano as sudo to edit /etc/openvpn/up.sh

Code: Select all

#!/bin/sh
/usr/sbin/service deluged stop
sudo -u vagrant -g vagrant sed -ie 's|\(\"listen_address\": \).*|\"listen_address\": \"'$4'\",|' /home/vagrant/.config/deluge/core.conf
sudo -u vagrant -g vagrant sed -ie 's|\(\"listen_interface\": \).*|\"listen_interface\": \"'$4'\",|' /home/vagrant/.config/deluge/core.conf
/usr/sbin/service deluged start
Make sure you sudo chmod +x /etc/openvpn/up.sh to make it executable.

I am running deluge in a VM (using vagrant) for sandboxing and to ensure that the only connection to the VM is the VPN tunnel and the ports that vagrant exposes on the host machine to talk to the VM. I have setup the Upstart scripts to start the deluged daemon and deluge-web running as the user:group "vagrant". You would replace "vagrant" in the -u and -g flags with the user you have deluged running under, and of course point it to the correct location of the deluge configuration file "core.conf". For me, the configuration file for deluge is located at "/home/vagrant/.config/deluge/core.conf"

The script uses sed (Unix Stream Editor) to find a regular expression ("listen_address": {plus whatever follows to the end of this line}) and replace it with "listen_address": "the.IP.assigned.by.PIA", which is stored in the variable "$4" (an openvpn convention). "sed -ie" tells sed to do an inline edit, meaning it will write the changes to the same file.

I also have a cron job running every 5 minutes checking to see if the VPN is up. If not, it restarts the openvpn service, which in turn stops deluge, updates the config automatically, binding deluge to the new VPN IP address, and restarts deluged.

When the VPN is down and the IP address is no longer available, deluge completely stops, so there is no deluge traffic ever going in or out on my ISP assigned IP address.

Let me know if you need more clarification.
bluenote
New User
New User
Posts: 3
Joined: Wed Aug 26, 2015 8:59 pm

Re: [SOLVED] Only making deluge use vpn and vpn only

Post by bluenote »

ScottyDelicious wrote:
bluenote wrote:Could you post your procedure for binding deluge to the interface? I have this working (kind of) but it's very, very, manual.
I have to manually delete the default route for the openvpn tunnel as well which is a pain.

Thanks
I am using OpenVPN on a headless Ubuntu server, but the procedure will be similar for any linux distro connecting through openvpn. My VPN provider is Private Internet Access (PIA).

I set up OpenVPN to connect on boot to the PIA Netherlands gateway. In my configuration file (/etc/openvpn/Netherlands.conf), there is a directive you can use called "up". This directive calls a script once the tunnel is up. My configuration file looks like this:

Code: Select all

client
dev tun
proto udp
remote nl.privateinternetaccess.com 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
tls-client
remote-cert-tls server
auth-user-pass /etc/openvpn/login.conf
comp-lzo
verb 1
reneg-sec 0
auth-nocache
script-security 2
up /etc/openvpn/up.sh
The last line that says "up /etc/openvpn/up.sh" tells openvpn to run that script when the tunnel connection is up. I use this script to stop the deluged daemon, replace "listen_address" and "listen_interface" with the IP address assigned to me when the tunnel connected, then restart the deluged daemon.

Use vim or nano as sudo to edit /etc/openvpn/up.sh

Code: Select all

#!/bin/sh
/usr/sbin/service deluged stop
sudo -u vagrant -g vagrant sed -ie 's|\(\"listen_address\": \).*|\"listen_address\": \"'$4'\",|' /home/vagrant/.config/deluge/core.conf
sudo -u vagrant -g vagrant sed -ie 's|\(\"listen_interface\": \).*|\"listen_interface\": \"'$4'\",|' /home/vagrant/.config/deluge/core.conf
/usr/sbin/service deluged start
Make sure you sudo chmod +x /etc/openvpn/up.sh to make it executable.

I am running deluge in a VM (using vagrant) for sandboxing and to ensure that the only connection to the VM is the VPN tunnel and the ports that vagrant exposes on the host machine to talk to the VM. I have setup the Upstart scripts to start the deluged daemon and deluge-web running as the user:group "vagrant". You would replace "vagrant" in the -u and -g flags with the user you have deluged running under, and of course point it to the correct location of the deluge configuration file "core.conf". For me, the configuration file for deluge is located at "/home/vagrant/.config/deluge/core.conf"

The script uses sed (Unix Stream Editor) to find a regular expression ("listen_address": {plus whatever follows to the end of this line}) and replace it with "listen_address": "the.IP.assigned.by.PIA", which is stored in the variable "$4" (an openvpn convention). "sed -ie" tells sed to do an inline edit, meaning it will write the changes to the same file.

I also have a cron job running every 5 minutes checking to see if the VPN is up. If not, it restarts the openvpn service, which in turn stops deluge, updates the config automatically, binding deluge to the new VPN IP address, and restarts deluged.

When the VPN is down and the IP address is no longer available, deluge completely stops, so there is no deluge traffic ever going in or out on my ISP assigned IP address.

Let me know if you need more clarification.

Would you mind posting your cron job script? Thanks for all the info.
Exc4pe

Re: [SOLVED] Only making deluge use vpn and vpn only

Post by Exc4pe »

Hi. Sorry for digging this one out again.
I've got deluge running on a raspberry pi. Researched, experimented and tested for about three days now and using iptables seems to be the most reliable way to make deluge use my vpn.
I've used the iptables rules from this thread and added new ones to prevent the user who runs deluge from accessing my router but I still want to be able to use a thin client to connect to the raspberry pi. Somehow I still can't connect to it and don't see anything wrong with my iptables rules. I'm also trying to use http://ipmagnet.services.cbcdn.com and it never returns anything with the iptables rules applied but it does so when they are not active.
Do you guys have any idea whats wrong?

I used these rules:
#Allow local traffic
iptables -A OUTPUT -m owner --gid-owner deluge -o lo -j ACCEPT
#Reject traffic directly to my router
iptables -A OUTPUT -m owner --gid-owner deluge -d 192.168.8.1 -j REJECT
#Allow traffic within my subnet
iptables -A OUTPUT -m owner --gid-owner deluge -o wlan0 -d 192.168.8.0/24 -j ACCEPT
#Reject everything else that doesn't use the VPN tunnel
iptables -A OUTPUT -m owner --gid-owner deluge \! -o tun0 -j REJECT


This is what I got from iptables -L -n -v:

Chain INPUT (policy ACCEPT 30M packets, 29G bytes)
pkts bytes target prot opt in out source destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination

Chain OUTPUT (policy ACCEPT 19M packets, 8430M bytes)
pkts bytes target prot opt in out source destination
10690 2803K ACCEPT all -- * lo 0.0.0.0/0 0.0.0.0/0 owner GID match 120
2932 206K REJECT all -- * * 0.0.0.0/0 192.168.8.1 owner GID match 120 reject-with icmp-port-unreachable
18807 4549K ACCEPT all -- * wlan0 0.0.0.0/0 192.168.8.0/24 owner GID match 120
215 20360 REJECT all -- * !tun0 0.0.0.0/0 0.0.0.0/0 owner GID match 120 reject-with icmp-port-unreachable
jwpierce3

Re: [SOLVED] Only making deluge use vpn and vpn only

Post by jwpierce3 »

Based on the above cron script, I created a wrapper to check for tun0 existence before starting and while running.

#! /bin/bash
function killdeluge {
while true ; do
if [ "$(ifconfig | grep tun0)" == "" ]; then
killall -9 deluge
exit
fi
sleep 1
done
}
if ! [ "$(ifconfig | grep tun0)" == "" ]; then
deluge || killdeluge
fi
shamael
Compulsive Poster
Compulsive Poster
Posts: 667
Joined: Sat Oct 08, 2016 9:28 am

Re: [SOLVED] Only making deluge use vpn and vpn only

Post by shamael »

If any interest, I started discovering the namespace solution but haven't tried yet.
https://schnouki.net/posts/2014/12/12/o ... -on-linux/

The main benefit is to never be able to reach the internet if the namespace is down (no single packet).
mhertz
Moderator
Moderator
Posts: 2195
Joined: Wed Jan 22, 2014 5:05 am
Location: Denmark

Re: [SOLVED] Only making deluge use vpn and vpn only

Post by mhertz »

Sorry for replying to old thread, but wanted to, inline with shamael above referencing the namespace solution, also post a likeminded approach here:: https://github.com/slingamn/namespaced-openvpn

Note, i've not tried it yet, but am contemplating if I should switch to it. I'm always switching back and fourth between torrent-clients, and am currently on rtorrent, and just using regular VPN split tunneling and binding the local IP of VPN to torrent client as kill-switch behaviour, and having everything else go through normal connection.

I've just implemented port-forwarding automatically, as I use PIA which has an API for this with script example to get port into variable for later processing, so not that difficult then :)

The thing i'm mostly missing, is that if the VPN goes down and restarts with a new IP, then I have no connection. There have already been provided solutions in this thread with checking this periodically and killing + restarting the torrent-client with new IP, but I recently read a clever idea.

If deluge supports using hostnames as bind-address(listen_address), like rtorrent, then you could bind a hostname instead of IP, and then in your /etc/hosts file add that hostname with correct IP and then have a cron job periodically check if the IP has changed and if it has, then (auto)change it in /etc/hosts, which means, that you'll never need to restart deluge at all upon disconnects/reconnects :) Pretty cool idea imho.
mhertz
Moderator
Moderator
Posts: 2195
Joined: Wed Jan 22, 2014 5:05 am
Location: Denmark

Re: [SOLVED] Only making deluge use vpn and vpn only

Post by mhertz »

Okay sorry for double-post, but just wanted to add that this namespace-idea of shamael is great and arguably the best method on linux for both killswitch and split-tunnel. You also solve the issue of if the VPN possibly auto-reconnects with a new IP without needing to kill/restart the torrent-client.

There where just a wiki written for rtorrent on how to use this, and it should be trivial to adapt this to deluge.

https://github.com/rakshasa/rtorrent/wi ... -Splitting

Note, defining the IP as the guide above states I feel is unneded but still doesn't hurt, and is available in deluge too, but I don't use it personally as not a requirement and doesn't help with anything.

Edit: I've finished making everything automatic/scripted for rtorrent now, and for deluge it should just be a matter of:

First get namespaced-openvpn, by running(but first change the path used to match yours!):

Code: Select all

curl -L https://github.com/slingamn/namespaced-openvpn/raw/master/namespaced-openvpn > ~/.bin/namespaced-openvpn; chmod +x ~/.bin/namespaced-openvpn
Then to start everything up run:

Code: Select all

sudo namespaced-openvpn --config /etc/openvpn/client/pia.conf --cd /etc/openvpn/client --daemon
sudo ip netns exec protected sudo -u "$USER" deluged
And run your preffered UI frontend preceded with:

Code: Select all

sudo ip netns exec protected sudo -u "$USER"
(I'm not 100% if the UI frontend needs to run in the protected namespace, or can communicate with it without, but just in case, I added that too) Also a good idea to make an alias of the above command in your .bashrc/.zshrc, so you can run it from then on with e.g. 'rprot <whatever>'.

e.g.

Code: Select all

sudo ip netns exec protected sudo -u "$USER" deluge-console
When finished, run:

Code: Select all

sudo pkill openvpn
to kill the tunnel.

Untested for now(on deluge), but this is the scenario. Note, I have all openvpn files in '/etc/openvpn/client/' as per upstream and my distro-default(arch), and so change the namespaced-openvpn command as needed. You could move them out of there fine and have them in home-folder, e.g. under '~/.config/openvpn/', but I prefer having them in that place because I can then also run openvpn normally and without namespaced-openvpn to make the entire connection tunneled, e.g. when browsing or whatever, through the standard openvpn systemd service file provided, with:

Code: Select all

Sudo systemctl start openvpn-client@pia.conf
and

Code: Select all

sudo systemctl stop openvpn-client@pia.conf
(The standard systemd service file provided with openvpn adds '/etc/openvpn/client/' as working-folder by itself, so no need for '--cd' like the namespaced-openvpn command - if you have absolute path for your certificates and everything in your openvpn config file(pia.conf above), then you don't need the '--cd' command for namespaced-openvpn either, or if you cd to the folder first, you don't either. Also, I used full path for the config in the namespaced-openvpn command, even though I had used a --cd command, but that was still needed to make it work and not an oversight :) ).

There, fool-proof killswitch behaviour and split-tunnel, with only the need of downloading and running a single small python script, without any iptables rules to add, cron-jobs, ip-binds or anything :)

Edit2: No longer untested :) The commands above works perfectly, and yes, the used UI interface needs to be also run from the protected namespace i.e. as written above, and this is because deluge frontends communicate with deluged through a TCP port, and that isn't available outside of the protected namespace(if it where using a unix socket file instead, like rtorrent can for xmlrpc calls, then it would work without running in protected namespace, but deluge doesn't use that). Sorry for long post and babblings, lol :)
mhertz
Moderator
Moderator
Posts: 2195
Joined: Wed Jan 22, 2014 5:05 am
Location: Denmark

Re: [SOLVED] Only making deluge use vpn and vpn only

Post by mhertz »

You're welcome! :) Not my method though, all credit goes too slingamn; there are several methods to utilize namespaces, this just happens to be the the most elegant/secure.

@all, Keep in mind that my instructions for starting the daemon in tunnel, used 'deluged' directly for good reason; if using instead 'systemctl start deluged', preceded with 'sudo ip netns exec protected sudo -u "$USER"' obviously, then 'deluged' will not start in the protected namespace. If wanting to use the systemd service file to initiate 'deluged', then you need changing the systemd file to run 'deluged' in protected namespace, e.g. add a drop-in file in '/etc/systemd/system/unit.d/' which changes the exec line of the official service file. I'd personally only do this if needing 'deluged' enabled at boot, as else running 'deluged' directly is fine, and changing the systemd file is unneded complexity.

Again, namespaced-openvpn by slingamn is simply a brilliant method for both split-tunnel, kill-switch and even added protection of openvpn issues and regular namespace issues:
The network namespace functionality of Linux provides, in effect, additional isolated copies of the entire kernel networking stack. The idea behind namespaced-openvpn is this: the openvpn process itself can run in the root namespace, but its tunnel interface tun0 can be transferred into a new, protected network namespace. This new namespace will have the loopback adapter lo and tun0 as its only interfaces, and all non-localhost traffic will be routed over tun0. The openvpn process is not disrupted by this because it communicates with tun0 via the file descriptor it opened to /dev/net/tun, which is unaffected by the change of namespace.

As long as sensitive applications are correctly launched within the new, isolated namespace, all of the enumerated issues are systematically resolved:

Route injection is impossible because NetworkManager, dhclient, etc. are running in the root namespace, so they can respond to any change in the external network environment without affecting the protected namespace. In essence, this is a separation of concerns: the root namespace is tasked with maintaining connectivity, including interfacing with untrusted DHCP and DNS servers, while the protected namespace is tasked with maintaining privacy.
"Port Fail" is blocked because the protected namespace has no routing exception for the remote gateway: every packet must go to tun0.
Asymmetric routing attacks, IPv6 leaks, and DNS leaks are all blocked because the protected namespace has no access to any physical interface.
The openvpn process can freely restart because it runs in the root namespace, which has unmodified routes --- so its DNS request for the remote, and then its handshake with the resulting remote IP, all use eth0.
This approach has some further strengths:

It does not require any configuration changes to the root namespace, e.g., recreating eth0 as a virtual bridge.
Non-sensitive applications are free to use the physical interfaces, which may have better bandwidth or latency characteristics.
A namespaced-openvpn instance can peacefully coexist with another OpenVPN connection in the root namespace, without any concerns about conflicting private IPv4 addresses and routes. (Use the --nobind option to prevent the second openvpn process from trying and failing to reuse port 1194 in the root namespace.)
openvpn can be stopped and started without exposing processes in the protected namespace. If tun0 goes away, those processes don't revert to using a physical interface; instead, they have no connectivity at all.
https://github.com/slingamn/namespaced-openvpn

Btw, if using PIA and wanting port-forwarding, then here's a script I made some time ago for starting 'deluged' in protected namespace with port-forwarding enabled. PIA sometimes fails sending you a forwarded port upon first request, so if that happens, the script makes subsequent requests until getting a port forwarded, though max 5 as that means the port-forwarding system must be down currently(as 6 requests continually failed), but make sure to select a server(location) supporting this in the first place. With this new API, the forwarded port last until VPN connection is stopped, so no need for polling afterwards:

Code: Select all

#!/bin/bash

sudo namespaced-openvpn --config /etc/openvpn/client/pia.conf --cd /etc/openvpn/client --daemon
sudo ip netns exec protected sudo -u "$USER" deluged
client_id=`head -n 100 /dev/urandom | sha256sum | tr -d " -"`
while ! [[ $(sudo ip netns exec protected sudo -u "$USER" ip addr | grep tun0) ]]; do sleep 1; done
json=`sudo ip netns exec protected sudo -u "$USER" curl "http://209.222.18.222:2000/?client_id=$client_id" 2>/dev/null`
if ! [ "$json" == "" ]; then
	sudo ip netns exec protected sudo -u "$USER" deluge-console "config --set listen_ports ($(echo ${json:8:5}), $(echo ${json:8:5}))"
fi
x=1 
while [[ "$json" == "" && $x -le 5 ]]; do 
	json=`sudo ip netns exec protected sudo -u "$USER" curl "http://209.222.18.222:2000/?client_id=$client_id" 2>/dev/null`
	if ! [ "$json" == "" ]; then
		sudo ip netns exec protected sudo -u "$USER" deluge-console "config --set listen_ports ($(echo ${json:8:5}), $(echo ${json:8:5}))"
	fi
	sleep 1
	x=$(($x+1))
done
Remember you need 'sudo ip netns exec protected sudo -u "$USER" deluge-(console|gtk|webui)' to query the daemon, as simply 'deluge-(console|gtk|webui)' won't cut it(so make an alias or script with said command-line).
mhertz
Moderator
Moderator
Posts: 2195
Joined: Wed Jan 22, 2014 5:05 am
Location: Denmark

Re: [SOLVED] Only making deluge use vpn and vpn only

Post by mhertz »

Just wanted to add that if wanting to use 'deluged.service' with 'namespaced-openvpn', as they don't work together by default, then this is one method to do it: (though personally I just use 'deluged' from script without the 'deluged.service'):

Code: Select all

sudo mkdir /etc/systemd/system/deluged.service.d
echo "[Service]
ExecStart=
ExecStart=sudo ip netns exec protected sudo -u deluge /usr/bin/deluged -d
ExecStartPre=sudo /home/martin/.bin/namespaced-openvpn --config /etc/openvpn/client/pia.conf --cd /etc/openvpn/client --daemon
ExecStartPre=/usr/bin/sleep 5
ExecStopPost=sudo /usr/bin/pkill openvpn" | sudo tee /etc/systemd/system/deluged.service.d/vpn.conf
sudo systemctl daemon-reload
Note: You need to first change the above to match your system i.e. change which dir you have 'namespaced-openvpn' in, and change 'pia.conf' to name of your default openvpn configuration-file and if you're not on newest openvpn version, then you probably have a '*.ovpn' ending instead '*.conf' and ditch the 'client' dir and just use preceding one('/etc/openvpn') + if you use a non-standard location then change to that obviously.

I've tested it works fine, and when running 'sudo systemctl start/stop deluged', then both 'openvpn' and 'deluged' are started/stopped accordingly and it can be used for enabling the service at boot.

I added a 5 sec delay between starting the VPN and running deluged - that isn't needed as deluged will never have access to your true IP/network in this setup, but I did it because else deluged will sometimes have trouble getting the DHT bootstrapped though downloading/uploading will still work, just DHT will fail initially, but will start again later, but that is fixed with the delay - it could also be smaller, and as said isn't mandatory.

I myself prefer running deluged as my own user and having the profile dir under there, so I would add an extra two lines + change the 4'th line's 'sudo -u deluge' to 'sudo -u martin' :

Code: Select all

User=
User=martin
Post Reply