[SOLVED] UFW script for VPN drop protection (kill switch)

Forum rules
Before you post please read how to get help
Post Reply
redlined
Level 3
Level 3
Posts: 127
Joined: Wed Jun 06, 2018 8:12 pm
Location: Mile High, Green State (Denver, CO:)

[SOLVED] UFW script for VPN drop protection (kill switch)

Post by redlined » Sat Oct 27, 2018 3:05 pm

hiya folks,

I found this simple advice VPN drop protection on making a couple scripts to force internet block if VPN fails or closes. So far so good, and it works! (something nice about simple:D)

Two things about it-

1. is this really so simple to do? (iow, is script safe and fail-proof as written and can it be improved?)

2. one issue I found was when dropping VPN I was unable to reconnect the VPN with the 'kill switch' rule set loaded. I had to load regular rule set (using the undo script) in order to reconnect VPN and not liking that too much as it defeats the purpose. Is this supposed to happen? if VPN should be able to reconnect with kill switch rules in place then how can I fix this?

Thanks for any ideas related
Last edited by redlined on Thu Nov 01, 2018 3:48 pm, edited 1 time in total.
Moem kōan 42: Should tool manufacturers be required to fix their products so that you cannot use their saws to cut the tree branch that you're sitting on?

(The answer to the ultimate question of life, the universe and everything is... 42!!;)

User avatar
phd21
Level 17
Level 17
Posts: 7272
Joined: Thu Jan 09, 2014 9:42 pm
Location: Florida

Re: UFW script for VPN drop protection (kill switch)

Post by phd21 » Sat Oct 27, 2018 5:14 pm

HI redlined,

That is a good set of bash scripts in the web link you referenced to enable a VPN "kill switch" or to disable it for any vpn provider, this has been discussed in previous forum posts on this topic. These could be integrated as an option into the Linux Mint system and or Network Manager whenever connecting to a VPN server or disconnecting from a vpn server.

The Best VPN Kill Switch For Linux Using Easy Firewall Rules
https://thetinhat.com/tutorials/misc/li ... ewall.html

But, not all vpn connections make a "tun0" network interface when connected to their vpn, so you might have to adjust the script to whatever network tunnel the VPN creates and that may change depending upon the VPN provider or server you connect with. Of course, you could create multiple vpn start killswitch script files for various tunnels you may encounter, for example: "killswitch-on1.sh" (tun0), killswitch-on2.sh" (tun1), "firewall_killswitch1.sh" (tun0), "firewall_killswitch2.sh" (tun1), etc... or shorter versions "fw_ks1.sh", "fw_ks2.sh", etc... I do not know if there is a generic vpn tunnel name that can be used to represent any vpn tunnel with ufw commands instead of a specific vpn tunnel reference like tun0, tun1, tun2, etc... like "tun?" or "tun*"

You only need the one script to disable the vpn killswitch and go back to normal firewall settings like "killswitch-off.sh".
phd21 wrote: * VIP Note: I am not sure if these scripts referred to in the web link will remove any custom firewall rules users and or applications may have added because those scripts use the ufw firewall "reset" function, perhaps they could be modified to preserve the existing firewall rules configuration and to restore them without using the firewall "reset" command, see below.

Maybe "iptables-save" and "iptables-restore" would work?

in the start vpn killswitch scripts save the current firewall rules before changing them

Code: Select all

sudo iptables-save > firewall-rules.txt
in the stop disable killswitch script and restore normal firewall networking without the vpn connection, restore the saved firewall rules.

Code: Select all

sudo iptables-restore < firewall-rules.txt
So the start vpn killswitch script would look like this
sample start 'killswitch-on.sh' script wrote:

Code: Select all

#!/bin/bash
# delete any older existing firewall-rules text file
rm firewall-rules.txt
# now save the current firewall rules into a text file
sudo iptables-save > firewall-rules.txt
sudo ufw default deny incoming
sudo ufw default deny outgoing
sudo ufw allow out on tun0 from any to any
sudo ufw enable
.
And the stop disable vpn killswitch script would look like this
sample stop disable the vpn 'killswitch-off.sh' script wrote:

Code: Select all

#!/bin/bash
# restore the firewall rules from before starting the vpn killswitch script
sudo iptables-restore < firewall-rules.txt
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw enable
.
These could be combined into one bash script file just called 'killswitch.sh" where it asks the user to turn on (enable the vpn killswitch or to turn off (disable) the vpn killswitch.
Nowadays, a fair amount of the VPN providers have a "killswitch" option available in their Linux client application like PIA, ProtonVPN, vpn.ac, etc... But, if the existing vpn kill switch does not work or the way you want it to work, you could use these simple bash scripts with any vpn provider.

FYI: Some applications like Torrent clients have network settings option that can be set to use only the VPN network interface tun0, or tun1, etc.. must be set while connected to a VPN or the Tunnel interfaces will not be there.

There is a really nice indicator that can be installed on any Linux system called "indictor-ip" which when clicked will show you the network interfaces information including VPN tunnels. On some systems like my KDE systems, this shows no icon in the system tray but takes up the space of an icon which still works. Linux Cinnamon has a really nice "vpn Look Out" applet.

indicator-ip: Ubuntu indicator that displays local and external IP addresses.
https://github.com/bovender/indicator-ip

Applets : VPN Look-Out Applet : Cinnamon Spices
https://cinnamon-spices.linuxmint.com/applets/view/305

Tip Note: In Cinnamon's settings there is an option to display indicators, turn that on and restart or at least logout and back in. Why is this off as a default?


======================================================================================================
Some other VPN killswitch options and articles:

killswitch-for-openvpn: A killswitch script with autoconnecting function for OpenVPN
https://github.com/renapoliveira/killswitch-for-openvpn


Here is another interesting and simple approach to a vpn killswitch for "openvpn" vpn connections the most common and secure vpn connections used by most vpn providers using group permissions but requires editing the openvpn configuration files (somewhere.ovpn) for each server being used.
vpn - OpenVPN kill switch on Linux - Information Security Stack Exchange
https://security.stackexchange.com/ques ... h-on-linux

Private Internet Access - ArchWiki
- see Killswitch
https://wiki.archlinux.org/index.php/Pr ... _switch.22


Hope this helps ...
.
indicator-ip.jpg
Linux KDE - "indicator-ip" when connected to a VPN server.
.
.
FYI: This is the excellent "vpn.ac" vpn provider's killswitch script which preserves the current firewall settings and restores them when finished, but I do not know if this works without using their Linux client although I am sure it could be modified to do so.

Code: Select all

#!/bin/bash
GREP='/usr/bin/grep'
MAINARG=$1
SECONDARG=$2
THIRDARG=$3
ORIGINALIPTABLES=/etc/iptables.orig

## Flush old rules.

function _test {
    echo 'TEST COMMAND EXECUTED'
}

function _enable {
    {

	if iptables -L -n |grep -q "vpnacallowedip"; then
	echo "iptables rules overwritten"
	else
	#save user iptables rules if any
        iptables-save > $ORIGINALIPTABLES
	fi
	iptables -L -n |
        iptables -F
        iptables -X
        iptables -t nat -F
        iptables -t nat -X
        iptables -t mangle -F
        iptables -t mangle -X
        iptables -N vpnacallowedip
        iptables -N lan

        ## Traffic on the loopback interface is accepted.
        iptables -A INPUT -i lo -j ACCEPT
        ## Established incoming connections are accepted.
        iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
        ## Allow all incoming/outgoing connections on the virtual VPN network interface.
        iptables -A INPUT -i tun+ -j ACCEPT
        iptables -A OUTPUT -o tun+ -j ACCEPT
        ## Existing connections are accepted.
        iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
	## Allow traffic to VPN server inbound IP
        iptables -A vpnacallowedip -d $SECONDARG -j ACCEPT
        ## Reject all other outgoing traffic.
        iptables -A OUTPUT -j vpnacallowedip
        iptables -A OUTPUT -j lan
	iptables -A OUTPUT -j DROP
	## Allow DHCP in LAN.
        iptables -A OUTPUT -s 192.168.0.0/16,10.0.0.0/8,172.16.0.0/12 -p udp --sport 67:68 --dport 67:68 -j lan
    } &>/dev/null
    echo 'ENABLED'
}

function _restore {
    {
        if [ -f $ORIGINALIPTABLES ]; then
	iptables-restore < $ORIGINALIPTABLES
	else
	iptables -F
	iptables -X
	fi

    } &>/dev/null
    echo 'RESTORED'
}

function _disable {
    {
	#if original iptables rules exist reapply them
	if [ -f $ORIGINALIPTABLES ]; then
	iptables-restore < $ORIGINALIPTABLES
	else
	iptables -F
	iptables -X
	fi

    } &>/dev/null
    echo 'DISABLED'
}

function _replace {
    {
        iptables -F vpnacallowedip
        iptables -A vpnacallowedip -d $SECONDARG -j ACCEPT
        iptables -A vpnacallowedip -s $SECONDARG -j ACCEPT
    } &> /dev/null
    echo 'OK'
}

function _localnetwork_allow {
    #echo 'Allow LAN traffic'
    {
        iptables -A lan ! -o tun+ -s 192.168.0.0/16,10.0.0.0/8,172.16.0.0/12 -d 192.168.0.0/16,10.0.0.0/8,172.16.0.0/12 -j ACCEPT
    } &> /dev/null
    echo 'OK (LAN allowed)'
}

function _localnetwork_deny {
    #echo 'Deny LAN traffic'
    {
        iptables -F lan
    } &> /dev/null
    echo 'OK (LAN blocked)'
}

function _status {
    {
       # RESULT=$(iptables --list | $GREP 'RELATED')
         RESULT=$(iptables --list)
    } &> /dev/null
    #echo `$Result`
    if [[ $RESULT =~ "ESTABLISHED" ]]; then
        echo 'ENABLED status'
    else
        echo 'DISABLED status'
    fi
}

case $MAINARG in
    enable)
        _enable
        ;;
    restore)
        _restore
        ;;
    disable)
        _disable
        ;;
    status)
        _status
        ;;
    replace)
        _replace
        ;;
    test)
        _test
        ;;

    # Change localnetwork state
    localnetwork)
        case $SECONDARG in
            allow)
                _localnetwork_allow
                ;;
            deny)
                _localnetwork_deny
                ;;
            *)
        esac
        ;;
    *)
   echo 'Usage: vpn.ac-killswitch.sh {enable|restore|disable|replace [ server IP]|localnetwork allow|localnetwork deny}'
   exit 1
   ;;
esac
Phd21: Mint KDE 17.3 & 18.3, 64-bit Awesome OS, Ancient Dell OptiPlex 780 Core2Duo E8400 3GHz,4gb Ram,256gb SDD, Video: Intel 4 Graphics, DVD Lightscribe. Why I use KDE?:https://opensource.com/life/15/4/9-reasons-to-use-kde

redlined
Level 3
Level 3
Posts: 127
Joined: Wed Jun 06, 2018 8:12 pm
Location: Mile High, Green State (Denver, CO:)

Re: UFW script for VPN drop protection (kill switch)

Post by redlined » Sat Oct 27, 2018 8:57 pm

Thank you for the response phd21, good info!

I wasn't aware of other tunnel network interfaces being added/used like that but have confirmed mine is tun0, this is something I will keep an eye on and modify scripts as necessary. The network connections option to automatically connect to VPN when using enp2s0 was a really nice feature to find, and adding VPN by simply importing .ovpn file was a treat.

Saying that, I opened my VPN settings in network connections and see "Advanced" in the VPN tab, which appears to give the option to name the tunnel in the general tab "set "set virtual device type: (TUN) and name: tun <---if I change that to tun0 will this ensure tun0 will always be used for this VPN connection?

Also, I also see the value of your sample killswitch-on script, in preserving iptables rules set (as it was I had no special rules set beforehand, just the default UFW on/enabled setting). I will modify mine locally to include yours so as to preserve any I may make in the future though.

about VPN providers having a killswitch, I first tried using eddie client (from airVPN) and for some reason it will not connect to my VPN provider (Cotse, eddie is supposed to work by manually adding to their list of availables).. couldn't figure what eddie issue was, no logs, so kept searching and found the killswitch article as a workaround to the problem I have with VPN drops being so silent and hard to see... (tiny lock on network tray icon, bah! how about automatic reconnects until user chooses otherwise! :D

re: VPN-Outlook applet, sigh.. one tool I found indespensible when on cinnamon, and I see the developer has been busy on his spices page- good updates to it!
~ hence my resent question about applets on Mate (which I started using Mate DE since LM19 cinnamon was a tad too heavy on this old laptop- going to get a new ssd this blackFri/cyberMonday and some ram for my modern laptop though, yeah!)

re: Indicator-IP, looking now, thanks for that tip! (looking now:)
Moem kōan 42: Should tool manufacturers be required to fix their products so that you cannot use their saws to cut the tree branch that you're sitting on?

(The answer to the ultimate question of life, the universe and everything is... 42!!;)

User avatar
phd21
Level 17
Level 17
Posts: 7272
Joined: Thu Jan 09, 2014 9:42 pm
Location: Florida

Re: UFW script for VPN drop protection (kill switch)

Post by phd21 » Sat Oct 27, 2018 10:56 pm

Hi redlined,

You are welcome...
redlined wrote:I wasn't aware of other tunnel network interfaces being added/used like that but have confirmed mine is tun0, this is something I will keep an eye on and modify scripts as necessary. The network connections option to automatically connect to VPN when using enp2s0 was a really nice feature to find, and adding VPN by simply importing .ovpn file was a treat.
"The normal typical VPN connection usually creates the "tun0", but when testing other systems, I have seen that be tun1 or tun2.

Using the Network Manager (NM) for Importing VPN provider's servers is the normal Desktop GUI way to add vpn servers unless the VPN provider has their own Linux client application. Even if a VPN provider has their own Linux client, you can still add their servers through the NM as well if they provide their server configuration file(s). One issue with using the console terminal for connecting to your VPN servers is that you do not get any desktop notifications that you are connected to an active vpn server (like the NM icon with a lock). Some of the vpn providers Linux applications have their own icon with vpn connection status and various features.

"The network connections option to automatically connect to VPN when using enp2s0 was a really nice feature to find". Where is that mentioned?

I know anyone can select a particular NM installed vpn server to use in the NM by going to network connections, edit your local isp connection General Tab and selecting a vpn server location.
redlined wrote:Saying that, I opened my VPN settings in network connections and see "Advanced" in the VPN tab, which appears to give the option to name the tunnel in the general tab "set "set virtual device type: (TUN) and name: tun <---if I change that to tun0 will this ensure tun0 will always be used for this VPN connection?
I do not know that answer to this question, but it looks like you can force the use of "tun" and select a custom name. But, since most systems will create the tun0 anyway...
redlined wrote:Also, I also see the value of your sample killswitch-on script, in preserving iptables rules set (as it was I had no special rules set beforehand, just the default UFW on/enabled setting). I will modify mine locally to include yours so as to preserve any I may make in the future though.
I use custom firewall rules for my UMS (Ultimate Media Server), certain File sharing apps, sip phone (Linphone), etc... I do not know for certain that the original killswitch script's command "ufw reset" would erase any existing firewall rules, although I suspect that it does, but I know the "iptables-save" works.
redlined wrote:about VPN providers having a killswitch, I first tried using eddie client (from airVPN) and for some reason it will not connect to my VPN provider (Cotse, eddie is supposed to work by manually adding to their list of availables).. couldn't figure what eddie issue was, no logs, so kept searching and found the killswitch article as a workaround to the problem I have with VPN drops being so silent and hard to see... (tiny lock on network tray icon, bah! how about automatic reconnects until user chooses otherwise! :D
I do not yet know how to add "auto-reconnect" option(s).

Out of curiosity, why are you using the "Cotse" vpn provider versus "PIA", 'ProtonVPN", or "vpn.ac", etc... which have similar or better pricing? I never heard of them until your post.
redlined wrote:re: VPN-Outlook applet, sigh.. one tool I found indespensible when on cinnamon, and I see the developer has been busy on his spices page- good updates to it!
~ hence my resent question about applets on Mate (which I started using Mate DE since LM19 cinnamon was a tad too heavy on this old laptop- going to get a new ssd this blackFri/cyberMonday and some ram for my modern laptop though, yeah!)
Although I really like all the wonderful editions of Linux Mint, KDE is still my favorite with Cinnamon second, and "Mate" and "Xfce" do not have all the applets, desklets, widgets, etc... that Cinnamon or KDE has that I really like and use.

It would be great if the developer of the "vpn-outlook" applet could make it so that it would work on any Linux system other than as an applet just for Cinnamon (Gnome/GTK), including Mate, Xfce, and KDE. Perhaps a stand-alone indicator / application. Even KDE does not have any vpn widgets like this and I want one. Everyone should write to him and request this and support this developer (if they can).
redlined wrote:re: Indicator-IP, looking now, thanks for that tip! (looking now:)
I have been using the indicator-ip for a long time now and I always install it. It works on all Linux Mint editions.

...
Phd21: Mint KDE 17.3 & 18.3, 64-bit Awesome OS, Ancient Dell OptiPlex 780 Core2Duo E8400 3GHz,4gb Ram,256gb SDD, Video: Intel 4 Graphics, DVD Lightscribe. Why I use KDE?:https://opensource.com/life/15/4/9-reasons-to-use-kde

User avatar
phd21
Level 17
Level 17
Posts: 7272
Joined: Thu Jan 09, 2014 9:42 pm
Location: Florida

Re: UFW script for VPN drop protection (kill switch)

Post by phd21 » Sun Oct 28, 2018 12:03 am

Hi redlined,

While researching your post, I came across an article claiming that vpn connections using "openvpn" already have the option to automatically re-connect.

ubuntu gnome - Auto reconnect to VPN on disconnect? - Ask Ubuntu
https://askubuntu.com/questions/679059/ ... disconnect
May 30 '16 at 8:43 OttoEisen wrote:OpenVPN has a built-in mechanism to automatically detect dead links and reconnect. In Network Manager go to "Edit Connections", select your VPN connection and choose "Edit". In the "VPN" tab click on "Advanced..." and go to the "General" Tab. There you have two relevant options:

"Specify ping interval" tell OpenVPN how frequently to check if the link is still alive. "Specify exit or restart ping" tells it how long to wait until it takes action and which action to take.

Example: My setting are "30 / ping-restart / 300". This means OpenVPN checks every 30 seconds if the link is still active. If the link is down for 300 seconds it initiates a restart.

This way there is no need for external scripts...


Other links:

Automatically reconnect to your VPN on Linux – GabSoftware
https://www.gabsoftware.com/tips/automa ... -on-linux/

How to automatically connect to a VPN in Ubuntu 16.04? : linuxquestions
https://www.reddit.com/r/linuxquestions ... in_ubuntu/

How to Connect to a VPN Automatically on Linux - Make Tech Easier
https://www.maketecheasier.com/connect- ... lly-linux/

Auto-reconnect script file to OpenVPN via NetworkManager
https://gist.github.com/antoniy/f925ae55410a092c9e75

Hope this helps ...
.
NM_vpn_auto_reconnect1.jpg
Network Manager openVPN VPN connections
- advanced options for auto reconnect.
Phd21: Mint KDE 17.3 & 18.3, 64-bit Awesome OS, Ancient Dell OptiPlex 780 Core2Duo E8400 3GHz,4gb Ram,256gb SDD, Video: Intel 4 Graphics, DVD Lightscribe. Why I use KDE?:https://opensource.com/life/15/4/9-reasons-to-use-kde

redlined
Level 3
Level 3
Posts: 127
Joined: Wed Jun 06, 2018 8:12 pm
Location: Mile High, Green State (Denver, CO:)

Re: UFW script for VPN drop protection (kill switch)

Post by redlined » Sun Oct 28, 2018 2:31 pm

phd21 wrote:
Sun Oct 28, 2018 12:03 am
Hi redlined,
While researching your post, I came across an article claiming that vpn connections using "openvpn" already have the option to automatically re-connect. ubuntu gnome - Auto reconnect to VPN on disconnect? - Ask Ubuntu
May 30 '16 at 8:43 OttoEisen wrote:OpenVPN has a built-in mechanism to automatically detect dead links and reconnect. In Network Manager go to "Edit Connections", select your VPN connection and choose "Edit". In the "VPN" tab click on "Advanced..." and go to the "General" Tab. There you have two relevant options:
"Specify ping interval" tell OpenVPN how frequently to check if the link is still alive. "Specify exit or restart ping" tells it how long to wait until it takes action and which action to take.
Example: My setting are "30 / ping-restart / 300". This means OpenVPN checks every 30 seconds if the link is still active. If the link is down for 300 seconds it initiates a restart.
This way there is no need for external scripts...
This is awesome! lol, if it's not a new(ish) feature then I am ashamed to not have learned of it till now... :oops: :lol: most excellent info indeed!
phd21 wrote:
Sat Oct 27, 2018 10:56 pm
redlined wrote:I wasn't aware of other tunnel network interfaces being added/used like that but have confirmed mine is tun0, this is something I will keep an eye on and modify scripts as necessary. The network connections option to automatically connect to VPN when using enp2s0 was a really nice feature to find, and adding VPN by simply importing .ovpn file was a treat.
"The normal typical VPN connection usually creates the "tun0", but when testing other systems, I have seen that be tun1 or tun2.
got it, and something to keep an eye on for this and the other computers managed locally.
phd21 wrote: "The network connections option to automatically connect to VPN when using enp2s0 was a really nice feature to find". Where is that mentioned?
I know anyone can select a particular NM installed vpn server to use in the NM by going to network connections, edit your local isp connection General Tab and selecting a vpn server location.
Yes, that is what I refer to, using NM and edit settings for my isp connection on enp2s0 and telling it to automatically connect to VPN (also set in NM as tun0 connection details) when using this ehternet connection.
phd21 wrote:
redlined wrote:Also, I also see the value of your sample killswitch-on script, in preserving iptables rules set (as it was I had no special rules set beforehand, just the default UFW on/enabled setting). I will modify mine locally to include yours so as to preserve any I may make in the future though.
I use custom firewall rules for my UMS (Ultimate Media Server), certain File sharing apps, sip phone (Linphone), etc... I do not know for certain that the original killswitch script's command "ufw reset" would erase any existing firewall rules, although I suspect that it does, but I know the "iptables-save" works.
the output in terminal when run suggests it does backup custom rules, if I read this correctly:

Code: Select all

anyuser@OEMTUFFBOOK:~$ ./UFW-VPNonly.sh
[sudo] password for anyuser: 
Resetting all rules to installed defaults. Proceed with operation (y|n)? y
Backing up 'user.rules' to '/etc/ufw/user.rules.20181028_103849'
Backing up 'before.rules' to '/etc/ufw/before.rules.20181028_103849'
Backing up 'after.rules' to '/etc/ufw/after.rules.20181028_103849'
Backing up 'user6.rules' to '/etc/ufw/user6.rules.20181028_103849'
Backing up 'before6.rules' to '/etc/ufw/before6.rules.20181028_103849'
Backing up 'after6.rules' to '/etc/ufw/after6.rules.20181028_103849'
Default incoming policy changed to 'deny'
(be sure to update your rules accordingly)
Default outgoing policy changed to 'deny'
(be sure to update your rules accordingly)
Rules updated
Rules updated (v6)
Firewall is active and enabled on system startup
anyuser@OEMTUFFBOOK:~$ 
which also wipes custom rules, adding your script command will add those custom rules back in, if I understand correctly. (I do see I have some iptables work to do as I cannot list directories when connected to my FTPS server if VPNonly script is in effect).. I also want to lock ip6 down completely, including full block in UFW for the protocol as that output above says it's open.I already modified the sysctl file, now plan to edit grub and etc/hosts file to comment ip6 lines as found in recent local forum advice, great thread! Security flaw found in systemd
phd21 wrote: Out of curiosity, why are you using the "Cotse" vpn provider versus "PIA", 'ProtonVPN", or "vpn.ac", etc... which have similar or better pricing? I never heard of them until your post.
I've been with cotse since 2002 for email and proxy/tunnels, and I simply trust Steve (it's basically a one man show, besides, what's not to love about the Church Of The Swimming Elephant!:D). Their VPN service was added about ten years ago and the outside US servers (UK and Amsterdam) were added over the past few years, so not a ton of options there, but his price is comparable: $5.95/month with a free month for every 6 signed on for, so a little over $5/m, $61/yr). I am planning to buy a year of service from AirVPN during this years black Friday weekend sale (%30 off, iirc) as I like what I see in their "about us" and in their dedicated forums. just need to get their client sorted, it's built on OpenVPN so not sure what the issue was trying to connect to other provider though..
phd21 wrote:
redlined wrote:re: VPN-Outlook applet, sigh.. one tool I found indespensible when on cinnamon, and I see the developer has been busy on his spices page- good updates to it! ~ hence my resent question about applets on Mate (which I started using Mate DE since LM19 cinnamon was a tad too heavy on this old laptop- going to get a new ssd this blackFri/cyberMonday and some ram for my modern laptop though, yeah!)
Although I really like all the wonderful editions of Linux Mint, KDE is still my favorite with Cinnamon second, and "Mate" and "Xfce" do not have all the applets, desklets, widgets, etc... that Cinnamon or KDE has that I really like and use.

It would be great if the developer of the "vpn-outlook" applet could make it so that it would work on any Linux system other than as an applet just for Cinnamon (Gnome/GTK), including Mate, Xfce, and KDE. Perhaps a stand-alone indicator / application. Even KDE does not have any vpn widgets like this and I want one. Everyone should write to him and request this and support this developer (if they can).
I agree on the desire to see vpn-outlook applet written for all distro/environments, it is just a sweet little tool that woldbe appreciated by many as a stand alone app.
about KDE...Mint is dropping KDE though, right? I think I shied from it over that reason, even though I found a few tools designed for that DE that I really liked. and moving from Cinnamon to Mate after 6 months was ok, except certain eye-candy and gui managed stuff I had grown used to and relied on. Will have my bells and whistles laptop up and sprinting by December, if all goes well till then :)
phd21 wrote:
redlined wrote:re: Indicator-IP, looking now, thanks for that tip! (looking now:)
I have been using the indicator-ip for a long time now and I always install it. It works on all Linux Mint editions.
installed it via ppa instructions and have an issue :wink:
I may need a screenshot to better explain this... The indicator-ip is running and has integrated into systray, but more as a place holder needing to be clicked on to see the IP info- there is nothing displayed otherwise besides a small empty space between Firetools and MintUpdate tray icons. The info it shows on click is correct, but it is not usefull as it is not showing anything at glance so again drops would be silent.

For sure going to apply the check and autoreconnect settings for OpenVPN that you found and have at least that reassurance while I figure out the indicator-ip issue. that's what I like about linux, each version of windows was fairly simple to 'master over these past couple decades', with linux the fun never ends! :lol:

Thank you for your time phd21! searching, typing, sharing, informing- big Salute! it's truly appreciated by this old army retired guy.
Moem kōan 42: Should tool manufacturers be required to fix their products so that you cannot use their saws to cut the tree branch that you're sitting on?

(The answer to the ultimate question of life, the universe and everything is... 42!!;)

User avatar
phd21
Level 17
Level 17
Posts: 7272
Joined: Thu Jan 09, 2014 9:42 pm
Location: Florida

Re: UFW script for VPN drop protection (kill switch)

Post by phd21 » Sun Oct 28, 2018 5:36 pm

Hi redlined,

You are welcome...
redlined wrote:This is awesome! lol, if it's not a new(ish) feature then I am ashamed to not have learned of it till now... :oops: :lol: most excellent info indeed!
Me too, I did not know that the Network Manager (NM) for openVPN VPN servers had the auto-reconnect option built-in either. Maybe that should be better documented.
redlined wrote: the output in terminal when run suggests it does backup custom rules, if I read this correctly:

Code: Select all

anyuser@OEMTUFFBOOK:~$ ./UFW-VPNonly.sh
[sudo] password for anyuser: 
Resetting all rules to installed defaults. Proceed with operation (y|n)? y
Backing up 'user.rules' to '/etc/ufw/user.rules.20181028_103849'
Backing up 'before.rules' to '/etc/ufw/before.rules.20181028_103849'
Backing up 'after.rules' to '/etc/ufw/after.rules.20181028_103849'
Backing up 'user6.rules' to '/etc/ufw/user6.rules.20181028_103849'
Backing up 'before6.rules' to '/etc/ufw/before6.rules.20181028_103849'
Backing up 'after6.rules' to '/etc/ufw/after6.rules.20181028_103849'
Default incoming policy changed to 'deny'
(be sure to update your rules accordingly)
Default outgoing policy changed to 'deny'
(be sure to update your rules accordingly)
Rules updated
Rules updated (v6)
Firewall is active and enabled on system startup
anyuser@OEMTUFFBOOK:~$ 
That looks like a custom script that is different from the original scripts you referred to and my changes as well. I am not sure that you can restore those firewall rules using the "iptables-retore" option, but you can try it AFTER creating a new file using the "iptables-save > firewall-rules.txt" command which you can restore.

redlined wrote:I've been with cotse since 2002 for email and proxy/tunnels, and I simply trust Steve (it's basically a one man show, besides, what's not to love about the Church Of The Swimming Elephant!:D). Their VPN service was added about ten years ago and the outside US servers (UK and Amsterdam) were added over the past few years, so not a ton of options there, but his price is comparable: $5.95/month with a free month for every 6 signed on for, so a little over $5/m, $61/yr). I am planning to buy a year of service from AirVPN during this years black Friday weekend sale (%30 off, iirc) as I like what I see in their "about us" and in their dedicated forums. just need to get their client sorted, it's built on OpenVPN so not sure what the issue was trying to connect to other provider though..
I use Gmail and gpg/pgp encryption for secure email. If you use a VPN, why do you need proxy trunnels? For VPN providers, I still recommend PIA, ProtonVPN, vpn.ac, etc...
redlined wrote:I agree on the desire to see vpn-outlook applet written for all distro/environments, it is just a sweet little tool that woldbe appreciated by many as a stand alone app.
Please contact the developer and ask if he would please port his Cinnamon applet into a stand-alone indicator application. I will, again. It really is a great and convenient applet.

redlined wrote:I may need a screenshot to better explain this... The indicator-ip is running and has integrated into systray, but more as a place holder needing to be clicked on to see the IP info- there is nothing displayed otherwise besides a small empty space between Firetools and MintUpdate tray icons. The info it shows on click is correct, but it is not usefull as it is not showing anything at glance so again drops would be silent.
I have the same problem with no actual indicator-ip icon in the system tray, but it is still useful because it shows me active network connections. So, if a VPN is connected I will see a "Tun" entry, and if there is no VPN connection there will be no "Tun" entry, and when I am connected to a VPN the public wan IP address should be different than my regular Public (wan) IP address, and I can easily see my local area network (lan) IP address is too.
redlined wrote:about KDE...Mint is dropping KDE though, right? I think I shied from it over that reason, even though I found a few tools designed for that DE that I really liked. and moving from Cinnamon to Mate after 6 months was ok, except certain eye-candy and gui managed stuff I had grown used to and relied on. Will have my bells and whistles laptop up and sprinting by December, if all goes well till then :)
Linux Mint KDE 18.3 is still supported through 2021. Anyone can still install the KDE desktop into a Linux Mint 19.x edition and use that which does work well, if they want. I used Linux Mint 19 Xfce and added the KDE Kubuntu desktop, removed the Xfce desktop packages although I could have kept them, added the Kubuntu PPA, then added a whole bunch of typical but missing KDE and Plasma software packages using the "Synaptic Package Manager (SPM)", and I call it "Linux Mint 19 xKDE".
redlined wrote:For sure going to apply the check and autoreconnect settings for OpenVPN that you found and have at least that reassurance while I figure out the indicator-ip issue. that's what I like about linux, each version of windows was fairly simple to 'master over these past couple decades', with linux the fun never ends! :lol:
I already changed all my VPN server connections to use the auto-reconnect options. I will do this from now on whenever I add another VPN server connection too.

You can contact the developer of the "indictor-ip" application like I did and make feature requests, complain about the icon not showing up, etc...


Regards,
Phil (phd21)
Phd21: Mint KDE 17.3 & 18.3, 64-bit Awesome OS, Ancient Dell OptiPlex 780 Core2Duo E8400 3GHz,4gb Ram,256gb SDD, Video: Intel 4 Graphics, DVD Lightscribe. Why I use KDE?:https://opensource.com/life/15/4/9-reasons-to-use-kde

redlined
Level 3
Level 3
Posts: 127
Joined: Wed Jun 06, 2018 8:12 pm
Location: Mile High, Green State (Denver, CO:)

Re: UFW script for VPN drop protection (kill switch)

Post by redlined » Sun Oct 28, 2018 6:59 pm

phd21 wrote:
Sun Oct 28, 2018 5:36 pm
redlined wrote: the output in terminal when run suggests it does backup custom rules, if I read this correctly:

Code: Select all

anyuser@OEMTUFFBOOK:~$ ./UFW-VPNonly.sh
[sudo] password for anyuser: 
Resetting all rules to installed defaults. Proceed with operation (y|n)? y
Backing up 'user.rules' to '/etc/ufw/user.rules.20181028_103849'
Backing up 'before.rules' to '/etc/ufw/before.rules.20181028_103849'
Backing up 'after.rules' to '/etc/ufw/after.rules.20181028_103849'
Backing up 'user6.rules' to '/etc/ufw/user6.rules.20181028_103849'
Backing up 'before6.rules' to '/etc/ufw/before6.rules.20181028_103849'
Backing up 'after6.rules' to '/etc/ufw/after6.rules.20181028_103849'
Default incoming policy changed to 'deny'
(be sure to update your rules accordingly)
Default outgoing policy changed to 'deny'
(be sure to update your rules accordingly)
Rules updated
Rules updated (v6)
Firewall is active and enabled on system startup
anyuser@OEMTUFFBOOK:~$ 
That looks like a custom script that is different from the original scripts you referred to and my changes as well. I am not sure that you can restore those firewall rules using the "iptables-retore" option, but you can try it AFTER creating a new file using the "iptables-save > firewall-rules.txt" command which you can restore.
the above is terminal output when I run the original script posted about:

Code: Select all

#!/bin/bash
sudo ufw reset
sudo ufw default deny incoming
sudo ufw default deny outgoing
sudo ufw allow out on tun0 from any to any
sudo ufw enable
do you see something that looks wrong? I have not added your iptables-restore option yet (doing it now, before that braincell gets lost again:D)
phd21 wrote: I use Gmail and gpg/pgp encryption for secure email. If you use a VPN, why do you need proxy trunnels? For VPN providers, I still recommend PIA, ProtonVPN, vpn.ac, etc...
I was invited to gmail beta test time by an insider, waybackthen (early 2004 iirc)... pgp/gpg definitely a must (from back in the pre-6.5.8CKT and beyond days, encryption was my hobby:D).. but I'd already started down the privacy path before gmail for a couple years and cotse fit the budget and bill for concerns, as well a identity not tied to my .mil email address. Added pay for features early, as they tested them, and locked into socks+ when first offered (nice to get away from chaining local portable app proxies and still useful if/when I find a lack of ability to setup and run a VPN) and years later added VPN when it was offered. it's really a loyalty and trust deal.

I will look at the vpn providers you mention again though as I have a better appreciation after AirVPN forum lurking on what to expect and support provided.
phd21 wrote:
redlined wrote:I agree on the desire to see vpn-outlook applet written for all distro/environments, it is just a sweet little tool that woldbe appreciated by many as a stand alone app.
Please contact the developer and ask if he would please port his Cinnamon applet into a stand-alone indicator application. I will, again. It really is a great and convenient applet.
phd21 wrote:
redlined wrote:I may need a screenshot to better explain this... The indicator-ip is running and has integrated into systray, but more as a place holder needing to be clicked on to see the IP info- there is nothing displayed otherwise besides a small empty space between Firetools and MintUpdate tray icons. The info it shows on click is correct, but it is not usefull as it is not showing anything at glance so again drops would be silent.
I have the same problem with no actual indicator-ip icon in the system tray, but it is still useful because it shows me active network connections. So, if a VPN is connected I will see a "Tun" entry, and if there is no VPN connection there will be no "Tun" entry, and when I am connected to a VPN the public wan IP address should be different than my regular Public (wan) IP address, and I can easily see my local area network (lan) IP address is too.
yeah, I think I need to find screenshot app for this. by tray icon I mean there is nothing shown anywhere by indicator-ip except a new small empty space in my systray that ends up between two other icons in tray (namely firetools and update manager icons).
there is no address shown by adapter anywhere else unless I click that empty space and get a drop-down type of info box showing the addresses for enp2s0, tun0, public as well refresh, about and quit. The picture on the github page shows what appears to be a panel reserved space that constantly shows an address- not sure if which address it shows is configurable though, if it always showed public IP on some panel space would be best, imo.
phd21 wrote: You can contact the developer of the "indictor-ip" application like I did and make feature requests, complain about the icon not showing up, etc...
I have considered this (same with VPN-Lookout applet- for all!:) however, I also realize I am very wordy and the simple and direct manner which I see most in the linux community has me concerned it will get me spam filtered or somesuch, lol... I need to get bug report format down and make contact though. Thanks again Phil, and for your quick roll-your-own linux version overview- enough info to make me even more dangerous (to my OS;) but opening doors, for sure
Moem kōan 42: Should tool manufacturers be required to fix their products so that you cannot use their saws to cut the tree branch that you're sitting on?

(The answer to the ultimate question of life, the universe and everything is... 42!!;)

redlined
Level 3
Level 3
Posts: 127
Joined: Wed Jun 06, 2018 8:12 pm
Location: Mile High, Green State (Denver, CO:)

Re: UFW script for VPN drop protection (kill switch)

Post by redlined » Thu Nov 01, 2018 3:47 pm

phd21 wrote:
Sun Oct 28, 2018 5:36 pm
redlined wrote:This is awesome! lol, if it's not a new(ish) feature then I am ashamed to not have learned of it till now... :oops: :lol: most excellent info indeed!
Me too, I did not know that the Network Manager (NM) for openVPN VPN servers had the auto-reconnect option built-in either. Maybe that should be better documented.
little follow-up on this, I imagine the assumption in NM is VPN config details are learned from OVPN docs (and not redundantly detailed in NM docs? why recreate the wheel thoughts).. anyways, upon rereading OVPN docs I do recall seeing ping and ping-restart info before- just didn't understand what I was reading at the time :roll:

posting this here since we wandered into this topic as well, from OVPN 23manpage

Code: Select all

In any case, OpenVPN's internal ping packets (which are just keepalives) and TLS control packets are not considered "activity", nor are they counted as traffic, as they are used internally by OpenVPN and are not an indication of actual user activity. 
--ping n
    Ping remote over the TCP/UDP control channel if no packets have been sent for at least n seconds (specify --ping on both peers to cause ping packets to be sent in both directions since OpenVPN ping packets are not echoed like IP ping packets). When used in one of OpenVPN's secure modes (where --secret, --tls-server, or --tls-client is specified), the ping packet will be cryptographically secure.

    This option has two intended uses:

    (1) Compatibility with stateful firewalls. The periodic ping will ensure that a stateful firewall rule which allows OpenVPN UDP packets to pass will not time out.

    (2) To provide a basis for the remote to test the existence of its peer using the --ping-exit option. 
--ping-exit n
    Causes OpenVPN to exit after n seconds pass without reception of a ping or other packet from remote. This option can be combined with --inactive, --ping, and --ping-exit to create a two-tiered inactivity disconnect.

    For example,

    openvpn [options...] --inactive 3600 --ping 10 --ping-exit 60

    when used on both peers will cause OpenVPN to exit within 60 seconds if its peer disconnects, but will exit after one hour if no actual tunnel data is exchanged. 
--ping-restart n
    Similar to --ping-exit, but trigger a SIGUSR1 restart after n seconds pass without reception of a ping or other packet from remote.

    This option is useful in cases where the remote peer has a dynamic IP address and a low-TTL DNS name is used to track the IP address using a service such as http://dyndns.org/ + a dynamic DNS client such as ddclient.

    If the peer cannot be reached, a restart will be triggered, causing the hostname used with --remote to be re-resolved (if --resolv-retry is also specified).

    In server mode, --ping-restart, --inactive, or any other type of internally generated signal will always be applied to individual client instance objects, never to whole server itself. Note also in server mode that any internally generated signal which would normally cause a restart, will cause the deletion of the client instance object instead.

    In client mode, the --ping-restart parameter is set to 120 seconds by default. This default will hold until the client pulls a replacement value from the server, based on the --keepalive setting in the server configuration. To disable the 120 second default, set --ping-restart 0 on the client.

    See the signals section below for more information on SIGUSR1.

    Note that the behavior of SIGUSR1 can be modified by the --persist-tun, --persist-key, --persist-local-ip, and --persist-remote-ip options.

    Also note that --ping-exit and --ping-restart are mutually exclusive and cannot be used together. 
--keepalive interval timeout
    A helper directive designed to simplify the expression of --ping and --ping-restart.

    This option can be used on both client and server side, but it is in enough to add this on the server side as it will push appropriate --ping and --ping-restart options to the client. If used on both server and client, the values pushed from server will override the client local values.

    The timeout argument will be twice as long on the server side. This ensures that a timeout is detected on client side before the server side drops the connection.

    For example, --keepalive 10 60 expands as follows:

     if mode server:
       ping 10                    # Argument: interval
       ping-restart 120           # Argument: timeout*2
       push "ping 10"             # Argument: interval
       push "ping-restart 60"     # Argument: timeout
     else
       ping 10                    # Argument: interval
       ping-restart 60            # Argument: timeout

--ping-timer-rem
    Run the --ping-exit / --ping-restart timer only if we have a remote address. Use this option if you are starting the daemon in listen mode (i.e. without an explicit --remote peer), and you don't want to start clocking timeouts until a remote peer connects. 
--persist-tun
    Don't close and reopen TUN/TAP device or run up/down scripts across SIGUSR1 or --ping-restart restarts.

    SIGUSR1 is a restart signal similar to SIGHUP, but which offers finer-grained control over reset options. 
--persist-key
    Don't re-read key files across SIGUSR1 or --ping-restart.

    This option can be combined with --user nobody to allow restarts triggered by the SIGUSR1 signal. Normally if you drop root privileges in OpenVPN, the daemon cannot be restarted since it will now be unable to re-read protected key files.

    This option solves the problem by persisting keys across SIGUSR1 resets, so they don't need to be re-read. 
--persist-local-ip
    Preserve initially resolved local IP address and port number across SIGUSR1 or --ping-restart restarts. 
--persist-remote-ip
    Preserve most recently authenticated remote IP address and port number across SIGUSR1 or --ping-restart restarts. 
I also see a lot of good work ahead figuring out routes and such from OVPN docs which should allow VPN to reconnect when under my VPN only script. So far I've had some luck with --persist commands (-tun -key -local&remote IP) added to my OVPN config. and this inital thought seems to work nicely as my script was blocking, modifying it with your commands as well, still had to run my undo script before VPN could reconnect. otherwise ping 10 and ping-restart 60 is what I set in NM advanced options (other option is modify .ovpn file using --keepalive 10 60 for same results)

marking topic as solved since the original sledgehammer script was vouched-safe as well as improved. The other, perhaps better option is the lengthy bash script also referrenced this thread. On sorting issues with kill switch prohibiting VPN reconnect I seem to have success using --persist commands in ovpn config file without having to undo the ufw 'killswitch' ruleset. Further learning required to get iptables rules sorted (so my two scripts harden up both eth and TUN adapters) and perhaps routes set in ovpn config will also help.

spent the rest of the weekend getting dnscrypt-proxy set up and working(!) using genric linux manual method (vs debian-ubuntu ppa which I learned of after, lol) for both my LM19 Mate laptop and win7 desktop- feeling real good about using DNS over HTTPS (DoH, both cloudflare and google public DNS support it now!) to encrypt my DNS querries, and when added to VPN for everything else nobody but my system knows where I go and what I do on the internet. using dnscrypt-proxy blacklist is a mighty fine replacement for HOSTS file I've been using forever on win and trying to get sorted on linux- now just use the proxy dev's blacklist python script to build my own- real cool!
Moem kōan 42: Should tool manufacturers be required to fix their products so that you cannot use their saws to cut the tree branch that you're sitting on?

(The answer to the ultimate question of life, the universe and everything is... 42!!;)

Pippin
Level 3
Level 3
Posts: 159
Joined: Wed Dec 13, 2017 11:14 am
Location: NL/DE/TH

Re: [SOLVED] UFW script for VPN drop protection (kill switch)

Post by Pippin » Thu Nov 01, 2018 4:42 pm

Hi,

OpenVPN does not provide kill switch functionality, no matter how you configure it.

iptables can do it using the owner match (xt_owner module) and it's one of the very few ways to do it properly and compared to other ways the easiest. Take a look at the post of Max-P:
https://www.privateinternetaccess.com/a ... killswitch

Someone else has to chime in here how to do that on Mint though as I don't know how changing group/user for OpenVPN influences other parts of Mint, think NM... OpenVPN runs as root on Mint...
"I'm not in this world to live up your expectations, neither are you here to live up to mine.”
F.P. & P.T.

redlined
Level 3
Level 3
Posts: 127
Joined: Wed Jun 06, 2018 8:12 pm
Location: Mile High, Green State (Denver, CO:)

Re: [SOLVED] UFW script for VPN drop protection (kill switch)

Post by redlined » Thu Nov 01, 2018 5:34 pm

Pippin wrote:
Thu Nov 01, 2018 4:42 pm
Hi,

OpenVPN does not provide kill switch functionality, no matter how you configure it.
correct, trying to get OpenVPN to reconnect client to server though is what me and phd21 found can be done in NM advanced settings or in OVPN config using --ping interval and ping-restart timeout (or --keepalive interval timeout).
Pippin wrote: iptables can do it using the owner match (xt_owner module) and it's one of the very few ways to do it properly and compared to other ways the easiest. Take a look at the post of Max-P:
https://www.privateinternetaccess.com/a ... killswitch

Someone else has to chime in here how to do that on Mint though as I don't know how changing group/user for OpenVPN influences other parts of Mint, think NM... OpenVPN runs as root on Mint...
now this is cool...AF!
Thank you for that link Pippin! it sure appears to be a much simpler and, dare I say, elegant approach than my sledgehammer UFW script and the other bash scripts I've been reading up on.

edit to add:
It also shows me why I could not get OVPN to reconnect when my simple UFW VPN only script was in effect!
[url=https://www.privateinternetaccess.com/archive/forum/discussion/comment/55417/#Comment_55417 wrote:somethingdumb[/url]' allow 1194/udp to let VPN reconnect on failure,'

but of course! :roll: :lol:
Moem kōan 42: Should tool manufacturers be required to fix their products so that you cannot use their saws to cut the tree branch that you're sitting on?

(The answer to the ultimate question of life, the universe and everything is... 42!!;)

Post Reply

Return to “Scripts & Bash”