[SOLVED] Only making deluge use vpn and vpn only

General support for problems installing or using Deluge
mooninite
New User
New User
Posts: 8
Joined: Sat Aug 22, 2015 4:05 am

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

Post by mooninite »

This thread has a ton of possible options. However, the original solution is not completely correct. The other options found via a Google search are either not complete, not correct, or obsolete.

If anyone is interested in isolating a 'deluge' user to only routing through a PIA tun0 OpenVPN device and keep web UI access using modern tools follow along. This will create a completely automated solution for isolating deluge and optionally controlling port forwarding. This solution is only if you are running your OpenVPN tunnel AND deluge on the same machine.

1. Create a routing table for the deluge user
a. Append a table alias to the iproute file (optional, but helps you remember what this is later)

Code: Select all

echo 200 deluge >> /etc/iproute2/rt_tables
b. Add routing rule to send all traffic with a '0x1' mark to the deluge table. Adding this to your /etc/rc.d/rc.local file will get it to run at startup.

Code: Select all

ip rule add fwmark 0x1 lookup deluge
c. Default the routing table with a blackhole. This will keep the deluge user from being able to communicate when the tunnel is down / offline / disconnected. Adding this to your /etc/rc.d/rc.local file will get it to run at startup.

Code: Select all

ip route add blackhole default metric 2 table deluge
2. Update your iptables rules.
a. Mark all traffic except the web app port. Add the following 'mangle' table rules to your iptables rules. Replace 'deluge' with the name of your deluge daemon user.

Code: Select all

-A OUTPUT -m owner --uid-owner deluge -p tcp --sport 8112 -j ACCEPT
-A OUTPUT -m owner --uid-owner deluge -j MARK --set-mark 0x1/0xffffffff
b. Update the 'nat' table rules for OpenVPN traffic.

Code: Select all

-A POSTROUTING -o tun0 -j MASQUERADE
c. Create a deluge chain for port forwarding rules. Add a rule to your 'filter' table. A systemd service will dynamically update this. This is optional. Skip if you don't want port forwarding.

Code: Select all

:deluge-INPUT - [0:0]
-A INPUT -j deluge-INPUT
3. Update your kernel routing policy. 2 is better than 0. Set these in your distribution's sysctl conf file to retain at boot.

Code: Select all

sysctl -w net.ipv4.conf.default.rp_filter=2
sysctl -w net.ipv4.conf.all.rp_filter=2
4. Create a 'up' script that will be called by the OpenVPN connection when it starts.
a. Add the script to your PIA openvpn config file

Code: Select all

script-security 2
up /etc/openvpn/pia-up.sh
b. Inside the script file, add the default route to your deluge routing table.

Code: Select all

/sbin/ip route add default via $5 metric 1 table deluge
5. Optional: Port forwarding systemd service and companion script. REQUIRES: deluge-console to be installed
a. systemd service - replace 'CA-Toronto.service' with the name of your openvpn service. You must use a PIA host that supports port forwarding. Only a few do. Toronto is one.

Code: Select all

[Unit]
Description=Private Internet Access Port Forwarding Setup
BindsTo=openvpn-client@CA-Toronto.service
After=openvpn-client@CA-Toronto.service

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/bin/pia-port-forward.sh start
ExecStop=/usr/local/bin/pia-port-forward.sh stop

[Install]
WantedBy=multi-user.target
b. /usr/local/bin/pia-port-forward.sh script - replace the deluge /var/ directory with the location you have installed deluge and its config directory.

Code: Select all

#!/bin/bash

start() {
CLIENT_ID=$(/bin/head -n 100 /dev/urandom | /bin/sha256sum | /bin/tr -d " -")

API_JSON=$(/bin/curl --interface tun0 "http://resolver1.privateinternetaccess.com:2000/?client_id=$CLIENT_ID" 2> /dev/null)

PORT=$(echo $API_JSON | /bin/cut -d ':' -f 2 | /bin/sed 's/}//')
echo Port: $PORT
if [ -z $PORT ]
then
   echo "API closed on us, reconnect"
else
   /sbin/iptables -F deluge-INPUT
   /sbin/iptables -A deluge-INPUT -i tun0 -p tcp -m tcp --dport $PORT -m state --state NEW -j ACCEPT
   /sbin/iptables -A deluge-INPUT -i tun0 -p udp -m udp --dport $PORT -m state --state NEW -j ACCEPT
   /bin/deluge-console -c /var/lib/deluge/.config/deluge/ "config --set listen_ports ($PORT, $PORT)"
fi
}

stop() {
   /sbin/iptables -F deluge-INPUT
}

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  *)
    exit 0
esac

exit 0
cbrace
Member
Member
Posts: 35
Joined: Thu Jan 31, 2019 4:09 pm
Location: Amsterdam

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

Post by cbrace »

bmn wrote: This works quite well.
But I can't access the daemon remotely via lan and not via the public ip of my server (using dyndns).
How did you manage to connect to the daemon remotely?
Correct, this is because all traffic is now redirected through the VPN, including that to and from your client.

Best way to solve this is to set up an ssh tunnel as explained here: https://dev.deluge-torrent.org/wiki/Use ... eSSHTunnel. This "bypasses" the VPN.
rexeus
New User
New User
Posts: 1
Joined: Fri Oct 11, 2019 7:33 pm

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

Post by rexeus »

mooninite wrote:This thread has a ton of possible options. However, the original solution is not completely correct. The other options found via a Google search are either not complete, not correct, or obsolete.

If anyone is interested in isolating a 'deluge' user to only routing through a PIA tun0 OpenVPN device and keep web UI access using modern tools follow along. This will create a completely automated solution for isolating deluge and optionally controlling port forwarding. This solution is only if you are running your OpenVPN tunnel AND deluge on the same machine.

1. Create a routing table for the deluge user
a. Append a table alias to the iproute file (optional, but helps you remember what this is later)

Code: Select all

echo 200 deluge >> /etc/iproute2/rt_tables
b. Add routing rule to send all traffic with a '0x1' mark to the deluge table. Adding this to your /etc/rc.d/rc.local file will get it to run at startup.

Code: Select all

ip rule add fwmark 0x1 lookup deluge
c. Default the routing table with a blackhole. This will keep the deluge user from being able to communicate when the tunnel is down / offline / disconnected. Adding this to your /etc/rc.d/rc.local file will get it to run at startup.

Code: Select all

ip route add blackhole default metric 2 table deluge
2. Update your iptables rules.
a. Mark all traffic except the web app port. Add the following 'mangle' table rules to your iptables rules. Replace 'deluge' with the name of your deluge daemon user.

Code: Select all

-A OUTPUT -m owner --uid-owner deluge -p tcp --sport 8112 -j ACCEPT
-A OUTPUT -m owner --uid-owner deluge -j MARK --set-mark 0x1/0xffffffff
b. Update the 'nat' table rules for OpenVPN traffic.

Code: Select all

-A POSTROUTING -o tun0 -j MASQUERADE
c. Create a deluge chain for port forwarding rules. Add a rule to your 'filter' table. A systemd service will dynamically update this. This is optional. Skip if you don't want port forwarding.

Code: Select all

:deluge-INPUT - [0:0]
-A INPUT -j deluge-INPUT
3. Update your kernel routing policy. 2 is better than 0. Set these in your distribution's sysctl conf file to retain at boot.

Code: Select all

sysctl -w net.ipv4.conf.default.rp_filter=2
sysctl -w net.ipv4.conf.all.rp_filter=2
4. Create a 'up' script that will be called by the OpenVPN connection when it starts.
a. Add the script to your PIA openvpn config file

Code: Select all

script-security 2
up /etc/openvpn/pia-up.sh
b. Inside the script file, add the default route to your deluge routing table.

Code: Select all

/sbin/ip route add default via $5 metric 1 table deluge
5. Optional: Port forwarding systemd service and companion script. REQUIRES: deluge-console to be installed
a. systemd service - replace 'CA-Toronto.service' with the name of your openvpn service. You must use a PIA host that supports port forwarding. Only a few do. Toronto is one.

Code: Select all

[Unit]
Description=Private Internet Access Port Forwarding Setup
BindsTo=openvpn-client@CA-Toronto.service
After=openvpn-client@CA-Toronto.service

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/bin/pia-port-forward.sh start
ExecStop=/usr/local/bin/pia-port-forward.sh stop

[Install]
WantedBy=multi-user.target
b. /usr/local/bin/pia-port-forward.sh script - replace the deluge /var/ directory with the location you have installed deluge and its config directory.

Code: Select all

#!/bin/bash

start() {
CLIENT_ID=$(/bin/head -n 100 /dev/urandom | /bin/sha256sum | /bin/tr -d " -")

API_JSON=$(/bin/curl --interface tun0 "http://resolver1.privateinternetaccess.com:2000/?client_id=$CLIENT_ID" 2> /dev/null)

PORT=$(echo $API_JSON | /bin/cut -d ':' -f 2 | /bin/sed 's/}//')
echo Port: $PORT
if [ -z $PORT ]
then
   echo "API closed on us, reconnect"
else
   /sbin/iptables -F deluge-INPUT
   /sbin/iptables -A deluge-INPUT -i tun0 -p tcp -m tcp --dport $PORT -m state --state NEW -j ACCEPT
   /sbin/iptables -A deluge-INPUT -i tun0 -p udp -m udp --dport $PORT -m state --state NEW -j ACCEPT
   /bin/deluge-console -c /var/lib/deluge/.config/deluge/ "config --set listen_ports ($PORT, $PORT)"
fi
}

stop() {
   /sbin/iptables -F deluge-INPUT
}

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  *)
    exit 0
esac

exit 0

Thanks for this solution, wanted to confirm that this only forces Deluge application ports to connect via VPN and rest of the ports are not using VPN tun0 ? thanks again and sorry if the answer is obvious.. i am new to Linux
mhertz
Moderator
Moderator
Posts: 2215
Joined: Wed Jan 22, 2014 5:05 am
Location: Denmark

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

Post by mhertz »

I previously posted a drop-in systemd-file to use deluged in locked down namespace using namespaced-openvpn, and there I used a static 5 sec wait to fix a DHT-bootstrap issue, but I remade it to now only wait as long as needed instead of a static value. Note, pretty crude(regarding the "stop" command, which could be more "elegant"), but works fine :) Remember fix paths and user-name for deluged command, as I personally override that.

Again, this method utilices the "new'er" namespace-method for simultanious split-routing and kill-switch, including protects against general vpn issues like DNS leaks, port-fail and route-injection, without the older methods needs of extra firewall rules and manual routing table changes, etc. This method uses a small, single-file python script without extra deps needed, acting as openvpn-wrapper and which don't hang around in memory afterwards.
  • * Download, chmod +x' and place under PATH:
    https://github.com/slingamn/namespaced- ... ed-openvpn.

    * Make dir: '/etc/systemd/system/deluged.service.d', and place following file in it named 'VPN.conf'(name needs to start with higher char than 'u' in alphabet, to ovrride 'user.conf') and afterwards run 'sudo systemctl daemon-reload'.

    Code: Select all

    [Service]
    User=
    ExecStart=
    ExecStart=/usr/bin/ip netns exec protected sudo -u martin /usr/bin/deluged -d
    ExecStartPre=/home/martin/.local/bin/namespaced-openvpn --config /etc/openvpn/client/windscribe.conf --cd /etc/openvpn/client --daemon
    ExecStartPre=/usr/bin/bash -c 'while ! [[ $(ip netns exec protected ip addr | grep tun0) ]]; do /usr/bin/sleep 1; done'
    ExecStopPost=/usr/bin/pkill openvpn
    
I then make an alias in my .zshrc to run all apps I need run under the VPN and with included kill-switch(only deluge-console for me personally), so I just precede the command with 'vrun <command>': 'vrun='sudo ip netns exec protected sudo -u "$USER"''.

I also have two other aliases added, 'von' and 'voff', to start and stop VPN at will(without deluged), and with 'vrun' to run anything under it, mentioned above(aliase-names is abriations for vpnon, vpnoff and vpnrun).

If wanting standard behaviour of running under deluge-user, then remove the 'User=' line, and precede all commands needing root-privileges with '/usr/bin/sudo' infront, or whatever your path for 'sudo' is(systemd-spec states to use full path under these directives in unit-files, as I guess they aren't run under regular shell with PATH-expansion).

Lastly, there's also another systemd unit posted for namespaced-openvpn alone, on the github project page under I can't remember pull-requests or issues, for if wanting to seperate the openvpn-wrapper and deluged.
EDIT: here: https://github.com/slingamn/namespaced- ... /issues/15
mhertz
Moderator
Moderator
Posts: 2215
Joined: Wed Jan 22, 2014 5:05 am
Location: Denmark

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

Post by mhertz »

Yesterday I setup a VPN for torrenting for a family-member, and that was qbittorrent on windows as they preferred that.

I myself always use split tunneling on Linux, as only want VPN for torrenting and regular net access for everything else, e.g when browsing or otherwise. Setting that up on windows isn't as easy as Linux, unless using old PPTP protocol or something, and is cumbersome, and the one old guide I once tried using many years ago, I also had issues with, but I now noticed a new project released on github by tool-maker, which consists of two batch files, to run as admin, one to run before starting VPN and another after stopping VPN. You don't need the stopping VPN script actually, unless needing to not use split tunneling again next time, and the starting script only needs run once on every boot up, but I tested adding both scripts as up and down directives to the openvpn config and it worked.

I prefer the open-source and lightweight openvpn-gui client included with the windows openvpn installer(under community downloads of openvpn site), which both has GUI and command-line versions included, instead of the official client of VPN provider, in the cases I tried, as much lighter both in footprint and resources used, and in startup time and in flexibility of being able to edit openvpn configs yourself if needed, and very streamlined interface.

Note, if using that client, you need running the GUI client as admin for the scripts to work(using up/down directives in config, or renaming the scripts to configname_up.bat and configname_down.bat, which is a feature of openvpn-gui to load scripts before/after without needing changing the config, there's also configname_pre.bat). The reason being that even though the GUI client uses a background-service to auto-elevate, which works for everything else, then doesn't for these scripts, so either setup openvpn-gui to run at bootup as admin from task schedular(so avoiding UAC prompt), or just set the main script to run as admin at bootup from task schedular, and you will have it working fine then, as no need really for the down script(set to run at bootup with highest rights, which avoid UAC prompt, and as SYSTEM user, which will make the batchfile run hidden).

Also, if using openvpn-gui, you have to implement yourself a kill switch and disable ipv6 etc, but often that is the better way anyhow, because as some VPN vendors also admits, then depending on implementation it is possible for the kill-switch to fail if client should crash + atleast in older times I read there where issues often with the killswitches and/or ipv6 and dns protections which wasn't always that stable, though probably is better today and of course depends on vendor used, but regardless. If using split tunneling and binding torrent client to interface or ip of VPN, while additionally adding a couple of windows firewall rules restricting traffic from torrent client only through the VPN, then that is imho, atleast as safe as using kill-switch etc in VPN providers own client, probably more secure imho. I also disable ipv6 just in case, which is just rightclicking adapters and un-ticking ipv6.

In qbittorrent it was easier because can define to bind to Tap VPN adapter under advanced settings, and then to further harden kill-switch I made some in and out rules in windows firewall to allow only incoming on public networks and for blocking all outgoing on non-public networks, since by default your main connection is private and others added as public like your VPN, but could also have used, and I think actually now is better, to instead filter by ip subnets instead, so the rules separate between e.g 192.168.0.0/16 and 10.0.4.0/16 etc.

I tested it worked fine in qbittorrent(ipmagnet, stopping VPN during download, firewall rules and qbittorrent binding), and also tested it in deluge2 before posting here, by adding local ip of VPN to in and out binding network options. If you use same vpn country each time, then sometimes you have same local ip everytime for a long time at least, and I don't know also if you can make a static local ip of a VPN, but otherwise to avoid checking new ip and entering it, then some scripting can be added to use the new ip with e.g I believe $4 which I think holds new ip in openvpn, and using deluge-console to apply it(or editing core.conf directly), from an up script, which you can look up ideas for online by searching e.g 'openvpn up script deluge-console ip' or alike.

All credits goes to tool-maker for this great idea and nice scripts: (I myself deleted last line of both scripts so they don't stay on screen after finished, stating press any key to continue - remember needs admin rights)

https://github.com/tool-maker/VPN_just_ ... lt-Gateway

Edit: Instead of above scripts, then nicer method imho, is simply adding these four lines to your openvpn config:

Code: Select all

route 0.0.0.0 192.0.0.0 net_gateway
route 64.0.0.0 192.0.0.0 net_gateway
route 128.0.0.0 192.0.0.0 net_gateway
route 192.0.0.0 192.0.0.0 net_gateway
Last edited by mhertz on Sat Jul 11, 2020 6:57 pm, edited 2 times in total.
Eagle
New User
New User
Posts: 1
Joined: Fri Feb 28, 2020 7:08 am

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

Post by Eagle »

cbrace wrote:
bmn wrote: This works quite well.
But I can't access the daemon remotely via lan and not via the public ip of my server (using dyndns).
How did you manage to connect to the daemon remotely?
Correct, this is because all traffic is now redirected through the VPN, including that to and from your client.

Best way to solve this is to set up an ssh tunnel as explained here: https://dev.deluge-torrent.org/wiki/Use ... eSSHTunnel. This "bypasses" the VPN.
So I just setup this namespace-OpenVPN, which is totally awesome! But I had a really hard time connecting to the WebUI in this setup. Ultimately what worked was a socat TCP port forward running in both the root and protected namespace, which I found here: https://unix.stackexchange.com/question ... e-with-vpn. However, I also tried to get this SSH tunnel setup, but I couldn't get it working. In the guide it says to use 127.0.0.2 as the hostname, which I did, and according the putty logs everything worked as it should, but I still couldn't access the deluge daemon from either a thinclient or the webUI. I tried adding the source port normally and as "localhost:port" and my destination was 127.0.0.2:port.

Has anyone got this to work, or have any other clever way to access webUI or thinclient remotely? If so, can you share some advice? Thanks!
mhertz
Moderator
Moderator
Posts: 2215
Joined: Wed Jan 22, 2014 5:05 am
Location: Denmark

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

Post by mhertz »

I just wanted to add a workaround for using interface names on windows to bind to, for split tunneling and/or kill-switch.

You can either use deluge-console, or edit core.conf directly, but just remember that if opening GTK-UI's preferences dialog and pressing OK in it, no matter if having changed anything or not(cancel or X in upper-corner is fine though), then it will need get reapplied(unrelated, but likewise with 'stop_seed_ratio' of '0.0' also getting reverted to GTK-UI default of '0.5' in that case), as gets trimmed to 15 chars(outgoing_interface of deluge2, not listen_interface of deluge1/deluge2).

Anyway, dispite the GTK-UI option names and help-text there, the underlying libtorrent options that gets defined from these, does indeed support interfaces for both options(only one option available in deluge1 sadly, as outgoing_interface is a new option from deluge2 ), and that the rule merely is that it needs specifically be GUIDs on windows, and you can obtain the correct GUID for your VPN interface by running from an elevated cmd prompt(tested on win10 vm):

Code: Select all

net start dot3svc & netsh lan show interfaces & net stop dot3svc
Then define the GUID as listen_interface and outgoing_interface(if using deluge2), either directly from core.conf of deluge profile folder, or from deluge-console(with deluged running) like this as example(GUID just made up for this example):

Code: Select all

deluge-console config -s listen_interface {123-456789-101112-13141-51617}
deluge-console config -s outgoing_interface {123-456789-101112-13141-51617}
I have reported a bugticket about this a few days ago(GTK-UI only supporting 15 chars max, and deluged's -i and -o options for in/out binds, has same restrictions when applied internally), and just wanted to post this workaround in meantime. The deluge plugin ifacewatch doesn't work on deluge2 for windows, and even if did, I believe only sets listen_interface and not outgoing_interface, which too is needed.

https://dev.deluge-torrent.org/ticket/3415

Sorry for rebumping this old thread, but it's just a nice thread sumerizing alot of the available possibilities regarding the methods of kill-switches and/or split routing, plus on different platforms etc, so just thought would fit nicely and be a nice addendum to include too.

Binding to interfaces is an often used functionality on e.g. qbittorrent, but just feel is a seldom used feature on deluge, much also because of the "uncertainess" of it all, e.g. interface names on windows etc.

Note, you don't need GUIDs on linux, and is only a windows thing. Also, on windows, the GUIDs needs be uppercased and enclosed in curly-brazes always.

Edit: Crap, i'm sorry, scratch the above as won't work without deluge python code-change I see now unfortunetly, so I aologize for that. I just tested before with a made up GUID, on linux, but forgot GUIDs also has letters in them, and so listen_interface is fine with that(in this workaround), but outgoing_interface clears out any such defined GUID, as internally runs some checks on them for allowed chars etc, so sorry again, and as said will need actual code change to work, and i'm not gonna post some crude hack here which also would get overridden and need reapplied upon every deluge update, and so you will need to wait for said bugticket to be resolved, and in mean time use local IP of VPN, e.g. you can automate it with an UP script from your openvpn configuration and have it auomatically apply through something along the lines of: 'deluge-console config -s listen_interface $4' and same for outgoing_interface option of deluge2, or start deluged from said UP script using the -i and -o in/out bind options with same $4 openvpn variable for resolved local VPN IP to bind to, or use a script to start deluge which parses local VPN IP from ipconfig and binds deluge to it on startup. Sorry again for not testing better before posting failed workaround attempt, doh!

Edit2: Just came to think about why not simply use ltconfig plugin to set the two libtorrent options directly as workaround untill my bug-ticket gets resolved.

Just remember that for the listen_interfaces libtorrent option, then you specifically need set a listen port, so add a colon after the upper-cased and curly-braced GUID with your defined incoming port number you use in deluge, so '{GUID}:port'. Deluge does this internally btw, and is needed on both IP or interface, but only on listen_interfaces and the other option should not include any port(outgoing_interfaces). They are named in plural form in libtorrent, because supports several IPs and interfaces each, in coma separated lists, if wanted, whereas deluge never came that far yet.
tugurlann
Member
Member
Posts: 27
Joined: Sun Dec 14, 2014 1:01 am

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

Post by tugurlann »

Hello,

I have struggled with the same problem, but I've found a different solution with

Code: Select all

ifmetric
.

While it is not as precise as redirecting only deluge traffic through a specific nic, it does allow for some redundancy in case the mostly dedicated nic fails.

On ubuntu 18.04, I'm setting one of the nics to be more expensive and as such the traffic goes on the cheaper one.

I have encountered one issue: if i try to set the metric either via config or cron with @reboot, something messes the config and I can no longer establish lan conections to my system (my server is behind two lans via each nic).

As a result, I'm running the commands hourly via cron to make sure I account for any disconnects from ISP or any other changes.

Not pretty, but gets the job done.
Post Reply