Saturday, April 16, 2022

Tunnelling All Traffic on a VLAN Through a VPN

Introduction

One of the core elements of my home network is a specific VLAN which sends all of its traffic out over a VPN. I use my UniFi USG4 and ProtonVPN in order to accomplish this. Much of the configuration is taken from the guide written by 'rggn' here and some from the video here.

This setup gives me some peace of mind, because I know that any device running on that VLAN (or its acompanying SSID) is ensured to be tunneled through a VPN. This avoids problems with a VPN client on a device going down without me knowing.

Recently, a bad UniFi update completly bricked my network, so I had to run through this process again, and found it a little bit tedious so... time to automate. There is defenetley a lesson learned there about not just backing up, but restoring from backups, but getting a chance to touch this again was beneficial.

Setup

This is pretty much just following the first guide again. I recomend building each of these on a remote machine and then scping them onto the USG.

Here are the files I will use:

charon.conf
config.gateway.json        # note that this one goes on the UniFi Cloud Controller
ipsec-updown.sh
protonvpn-check
protonvpn.ipsec.conf
protonvpn.ipsec.secrets

charon.conf

charon {
    install_routes = no
    install_virtual_ip = no
}

config.gateway.json

The config.gateway.json is the only file that gets placed on the UniFi Cloud Key. If you dont remember that you may spend several hours repeatedly putting it on your USG (like every other file) and wondering why things are not working. T his file is where you are going to create your custom routing rules. It is pretty self explanatory. If you get confused to can take the existing config off of the USG (located at /config/config.boot) and throw it into a json linter in order to see all the moving parts and assign the right things. This isn't exactly whats in the guide from rggn because they were tunneling all of their traffic, and I had to add a custom rule to only send a specific VLAN. If this is your first time doing this, before you make this file you should go into your UniFi Network GUI and make a new VLAN XX that will be your VPN VLAN, and assign it a subnet A.B.XX.0/24. Just sub this subnet and mask into the line 13 below, assign whatever description you want in line 8, and put the VLAN ID in line 34. you should be good. As long as you dont have any crazy rules existing in your iptables, the rule numbers should not overlap.

{
  "firewall": {
    "modify": {
      "SOURCE_ROUTE": {
        "rule": {
          "10": {
            "action": "modify",
            "description": "route VLANXX to protonVPN",
            "modify": {
              "table": "5"
            },
            "source": {
              "address": "10.0.XX.0/24"
            }
          }
        }
      }
    },
    "options": {
      "mss-clamp": {
        "interface-type": [
          "pppoe",
          "pptp",
          "vti"
        ],
        "mss": "1350"
      }
    }
  },
  "interfaces": {
    "ethernet": {
      "eth0": {
        "vif": {
          "XX": {
            "firewall": {
              "in": {
                "modify": "SOURCE_ROUTE",
                "name": "LAN_IN"
              }
            }
          }
        }
      }
    },
    "vti": {
      "vti0": {
        "description": "IPSec VTI interface"
      }
    }
  },
  "protocols": {
    "static": {
      "table": {
        "5": {
          "interface-route": {
            "0.0.0.0/0": {
              "next-hop-interface": {
                "vti0": "''"
              }
            }
          }
        }
      }
    }
  },
  "service": {
    "nat": {
      "rule": {
        "5004": {
          "description": "masq to vpn vti0",
          "destination": {
            "address": "0.0.0.0/0"
          },
          "outbound-interface": "vti0",
          "type": "masquerade"
        }
      }
    }
  },
  "vpn": {
    "ipsec": {
      "auto-firewall-nat-exclude": "enable",
      "include-ipsec-conf": "/config/protonvpn.ipsec.conf",
      "include-ipsec-secrets": "/config/auth/protonvpn.ipsec.secrets"
    }
  }
}

ipsec-updown.sh

#!/bin/bash
set -o nounset
set -o errexit

# $VTI_IFACE must match the interface in config.gateway.json
VTI_IFACE="vti0"

case "${PLUTO_VERB}" in
    up-client)
        echo "Creating tunnel interface ${VTI_IFACE}"
        ip tunnel add "${VTI_IFACE}" local "${PLUTO_ME}" remote "${PLUTO_PEER}" mode vti

        echo "Activating tunnel interface ${VTI_IFACE}"
        ip link set "${VTI_IFACE}" up

        echo "Adding ${PLUTO_MY_SOURCEIP} to ${VTI_IFACE}"
        ip addr add "${PLUTO_MY_SOURCEIP}" dev "${VTI_IFACE}"

        echo "Disabling IPsec policy (SPD) for ${VTI_IFACE}"
        sysctl -w "net.ipv4.conf.${VTI_IFACE}.disable_policy=1"

        DEFAULT_ROUTE="$(ip route show default | grep default | awk '{print $3}')"
        echo "Identified default route as ${DEFAULT_ROUTE}"
        echo "Adding route: ${PLUTO_PEER} via ${DEFAULT_ROUTE} dev ${PLUTO_INTERFACE}"
        ip route add "${PLUTO_PEER}" via "${DEFAULT_ROUTE}" dev "${PLUTO_INTERFACE}"
        ;;
    down-client)
        echo "Deleting interface ${VTI_IFACE}"
        ip tunnel del "${VTI_IFACE}"

        echo "Deleting route for ${PLUTO_PEER}"
        ip route del "${PLUTO_PEER}"
        ;;
esac

protonvpn-check

* * * * * root /usr/sbin/ipsec statusall | grep '0 up' && /usr/sbin/ipsec up protonvpn

protonvpn.ipsec.conf

I made some slight updates to protonvpn.ipsec.conf. I changed reauth to yes in order to prevent some annoying glitches where the tunnel would go down until manually restarted (even despite the cronjob). Set the right to whatever server you want to use. You can also list several servers seperated by commas.

conn %default
    keyexchange = ikev2
    type = tunnel

conn protonvpn
    dpddelay = 30s      # check peer liveness every 30s if there's no traffic
    dpdtimeout = 90s    # peer is considered dead after 90s, re-establish IKE_SA
    dpdaction = restart
    reauth = yes        # ProtonVPN sets IKE_SA lifetime, see notes
    auto = start        # can't use auto=route, see notes

    leftsourceip = %config4
    leftsubnet = 0.0.0.0/0
    leftupdown = /config/ipsec-updown.sh
    leftauth = eap-mschapv2
    eap_identity = abcDEFghiJKLmnoPQR

    right = us.protonvpn.com
    rightid = %any
    rightsubnet = 0.0.0.0/0
    rightauth = pubkey

protonvpn.ipsec.secrets

For protonvpn.ipsec.secrets, grab your credentials from the protonVPN website, and substitute them for the two asdfs below. Leave the spaces, colon, and EAP

unameasdf : EAP passwordasdf

Automation

Now that I have all my files on the local machine, I made a script to automatically place them at the correct places on the USG.

push_VPN_VLAN_

#!/bin/bash

# CREATED BY NISB 15 APRIL 2022
#
# This script is designed to automatically put all fo the correct files in place on
# a USG Pro 4 and UniFi Cloud Key to allow for selectively routing one already
# created VLAN 
#
# First thing you need to do is go in and make sure the EAP identitites and
# config.json are appropriatley configured so that they can be coppied over

###
# VARIABLES
###

usg_uname = "XXX"
usg_ip = "10.0.0.1"

uck_uname = "XXX"
uck_ip = "10.0.0.11"

###
# END VARIABLES
###

usg = "$usg_uname@$usg_ip"
uck = "$uck_uname@$uck_ip"


# First lets pull down the latest protonVPN.der
curl -fsSL -O https://protonvpn.com/download/ProtonVPN_ike_root.der


### USG ###
echo "use the USG password for $usg_uname for the next 5 SCPs"

# Upload all of our files to the USG
scp charon.conf "$usg:/etc/strongswan.d/"
scp ipsec-updown.sh protonvpn.ipsec.conf "$usg:/config/"
scp protonvpn-check "$usg:/etc/cron.d/"
scp protonvpn.ipsec.secrets "$usg:/config/auth/"
scp ProtonVPN_ike_root.der "$usg:/etc/ipsec.d/cacerts/"

# Go in to the usg and modify the files that need executable permisions
ssh $usg "chmod +x /config/ipsec-updown.sh; chmod +x /etc/cron.d/protonvpn-check"


### UCK ###
echo "use the UCK password for $uck_uname for the next SSH and  SCP"

# Make the directory for our config to sit in
ssh $uck "mkdir -p /srv/unifi/data/sites/default/"

# Put the file in place
scp config.gateway.json "$ucc:/srv/unifi/data/sites/default/"

So you will have to input the passwords for each of the scp and ssh calls, but I did not want to get into dependencies with installing sshpass (plus this is not great for security)

Conclusion

This method should also work for any VPN provider who allows IKEv2, can be adapted for OpenVPN configurations, and potentially could be exported out to more UniFi products (untested).

Tuesday, April 5, 2022

Password Management - Extreme

My specific implementation of password management is heavily influenced by Michael Bazzell's suggestions. I use VeraCrypt, KeePassXC, YubiKeys, and several micro SD cards hidden inside of covert nickels in order to achieve a system that is secure and redundant.

VeraCrypt Containers

The first level of my stack is a VeraCrypt container to store everything in. This aleviates any concerns about the encryption of the database or files I am storing. I just throw everything that I want to keep safe inside of a VeraCrypt container. The container apears like a file to a casual observer, but will become a mounted folder (or disk) when opened with the VeraCypt GUI or CLI tool. So for example I could place a file called 'totally_not_passwords.txt' in //path//to//really//obscure//directory//. This might provide a modicum of security, but any real attacker is just going to dump your entire user folder and quickly see the weird txt file that is 1000 times bigger than any txt file has any right to be, and also happens to be exactly 1 GB in size. That is okay though, because the point is not really to hide it, but to rely on VeraCrypt's encryption. VeraCrypt is a trusted name, even among the paranoid security crowd. There are some entertaining conspiracy that sprang up around the EOLing of TrueCrypt and the subsequent assendance of VeraCrypt, but there are no credible complaints with VeraCrypt, and you can rely on it when used properly.

When setting up VeraCrypt, you have several options beyond just a vanilla passphrase:

  • PIM: The PIM is the number of iterations that the header key derivation algorithm runs. If you want to add a second factor that an attacker will need to guess, you can set this. Default is 98, higher is more secure.
  • Key Files: A key file is yet another factor that can be required to open your container. Obviously a file stored on a computer can store a greater amount of random data than a human can remember, so I recommend using a key file. They can be used either in conjunction with a password or independently of each other. So if you use both, an attacker would need to get your container, key file, and your password. Of course, this introduces another layer of security, but it also introduces another layer of complexity when it comes to backups and synchronizing things.
  • Hidden Containers: Hidden containers give you a veil of plausible deniability to hide what is actually in your container, even when you give up the password. You make a normal container, called the outer volume, and put some bait inside it (something that is somewhat believable that you would want to hide, like your diary or secret plans to take over the world,), and then VeraCrypt will create a second container that is 'hidden' within the larger container. This hidden container has to be smaller than the outer volume and hides your actual sensitive files. If you ever have to give up your password under duress, you can give up the password to the outer volume, and the attacker will be unable to prove that there is also a hidden volume where your real sensitive data resides.

Within my container I store all of my sensitive files:

  • KeePassXC password manager database
  • SSH key files
  • Yubikey configuration files
  • rclone configuration files
  • canary tokens Most of these are beyond the scope of this post, but they usually also have a second password integrated.

Using KeePassXC

I use KeePassXC, as my password manager because it fulfills all of the requirements that I was looking for, and I have been satisfied with no reason to look for a replacement. KeePassXC is cross-platform, has a good browser extension in Mozilla, and supports YubiKeys. Setup is very straightforward for KeePassXC. You can import a CSV (which your web browser will export for you if you have been using it as a password manager), and then choose a password, key file, and challenge/response (i.e. YubiKey).

Transferring Between Devices

Once you have your password manager's vault in a VeraCrypt container, you now have to find a way to transfer these files between computers if you want to be able to create new accounts on one device and then use them on a different device. Rather than trying to use a cloud service, I rely on manual updates. I store my 'main' container on a specific device, and periodically update my secondary device. I eject the micro SD card from my secondary device, insert it into my primary device, mount both containers, merge the secondary vault into the primary vault (this will pull any accounts created on the secondary device into the main vault), and then overwrite the secondary vault with the main. The benefit of this process is that it avoids unnecessary exposure (like on a cloud service), and forces me to perform manual backups regularly.

Making Backups

The last step in my process is maintaining a system of offline backups. If anything should happen to my primary and secondary containers at the same time (a house fire), I have remote (and hidden) backups in various places. I regularly make a copy of the current version of my main container onto a spare micro SD card, hide that card inside a covert nickel, and then hide that nickel somewhere. Some of these nickels I would be able to get to in a matter of minutes to hours, some are very far away. Of course this can get confusing, so I keep a spreadsheet outlining the location of each of these and when they were last updated (this spreadsheet is stored inside the same container as the vault). Some of these backups get to be many months old before I can access them, but the system of various ages at various locations keeps me confident in both my redundancy and resiliency.

Tunnelling All Traffic on a VLAN Through a VPN

Introduction One of the core elements of my home network is a specific VLAN which sends all of its traffic out over a VPN. I use my UniFi U...