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.

Wednesday, March 30, 2022

Passsword Management

When talking to friends and family about cybersecurity, the first suggestion I make is to adopt some sort of password manager. The original idea of each user maintaining a single pass "word" has been obsolete for decades. Breaches are a fact of life, so re-using passwords across services is not secure. Combine this with the fact that modern digital life requires many hundreds of unique services, and you have a situation that is impossible for the human brain. The solution is to use password manager.

Benefits

Password managers have three main benefits:

  1. Generating and remembering complex unique passwords for each site.
  2. Synchronizing these entries across multiple devices automatically
  3. Auto-typing the password only on whitelisted domains.

The benefits of points one and two are obvious. The benefit of point three is an extra security buffer to interrupt domain spoofing attacks. If you somehow end up on annazon.com (instead of amazon.com) or capitaIOne.com (instead of capitalone.com) your password manager will not recognize the domain and will not pass your credentials unless you manually add that domain, or manually copy paste from your password manager into the squatting website. Usually this simple hiccup in the normal flow will be enough to slow users down and trigger deeper inspection that will prevent the attack from being successful.

I bin password managers into three levels of increasing utility (and paranoia).

Level 1 - Built into the web browser

All modern web browsers have a basic password manager built in. Just using the features that already exist in your web browser will achieve all of the benefits listed above.

Pros:

  • Generates, stores, synchronizes passwords
  • Adoption is extremely easy, built into the browser
  • Monitors breaches and notifies you when one of your passwords appears in a breach

Cons: 

  • Passwords stored in plaintext on the local machine
  • Only protected by whatever account is logged into your web browser (Mozilla or Google account)
  • Limited number of fields for storing extra information like PIN, security question answers, etc.

Just using this level (actually using it to generate random passwords) is 99% of what you need. It is such a low barrier to entry and provides such a huge advantage vice using slight variations of your one or two passwords across many sites.

Level 2 - Centralized Service like 1Password

There are many paid or freemium password managers that make slight improvements on Level 1

Pros:

  • All of Level 1
  • Additional fields to store notes about each service
  • Encrypted and locally and in the cloud

Cons:

  • Centralized storage is a larger target for attackers.
  • Higher barrier for adoption  and use
  • Cost money for all features

In general I do not recommend this level. If you want to go above Level 1, just jump to Level 3.

Level 3 - Offline Service like LastPass or KeePass*

This is the level I use, and requires some more devotion, but ends up at a paranoid level of security

Pros: 

  • All of Level 2
  • Passwords are not stored in the cloud

Cons: 

  • Passwords are not stored in the cloud (increased time demand for synchronization)
  •  Cost money for all features

Level 3 requires some manual effort on your part in order to transfer your password database between devices, but the benefit is that you now have an automatic system for backups and there is no risk of attackers reaching a centralized repository, taking your password database offline, and cracking it there.

Conclusion

One of the easiest thing you can do to increase your cybersecurity posture today is to adopt a password manager. Simply allowing the built in manager in your web browser to generate unique random passwords, remember them, and fill them for you will be a major step in improving your security. If you want to adopt an even more secure posture you can move to dedicated software like 1Password or KeePassXC. I will do a post in the future to outline the process that I use for managing and backing up my password database.

Tuesday, March 29, 2022

Book Review - Life After Google

 Title: Life After Google

Subtitle: The Fall of Big Data and the Rise of the Blockchain Economy

Author(s): George Gilder

Release Date: 2018

Link: here

Major Idea(s): The tech giants that grew to power by providing free services and aggregating massive amounts of data are going to be upset by new decentralized technologies like the blockchain.

Review: The book is equal parts captivating history of silicon valley tech giants, philosophical musing, and half-baked predictions about the future of the internet. Gilder's explanations of technologies are surface-level and do not garner faith in the rest of his writing. Most of the future predictions read like a high school student who just spent an hour on a bitcoin forming and then proceeds to rant to his friends about how the blockchain is going to change the world for the remainder of the week. The story that Gilder weaves about the rise of silicon valley and Google are interesting and provide a unique perspective, and are the only redeeming parts of the book. Overall there are some interesting ideas, but I think Gilder is far off the mark in his predictions for the future of the internet.

Rating: 2/5 

Sunday, February 27, 2022

Introduction

Motivation:

    I am starting this blog in order to establish a digital footprint and start sharing some of my projects and efforts with others. For the past 5 years I have been building, modifying, and upgrading my 'homelab' in order to suit my needs and learn about various technologies. Throughout this time, I have learned a lot, but most of it has been haphazardly documented in scrawled notes, if at all. This blog is an attempt to solve that. I do not expect the readership to be large (if there is any at all), my main purpose is to document this for myself. If a struggling enthusiast finds one of my write ups and is able to follow it to achieve her ends, then that will be a bonus. A recent Unifi update completely broke my network, so I am using the factory reset as a chance to start again and rebuild a lot of things, and document the build process this time.
    I do not promise to constrain my posts to just homelab builds. Various other facets of my life could also do with a more formal and documented history. For example, I listen to 1-2 audiobooks a week, and I think it would be beneficial to transition from keeping my thoughts in a short form journal to an electronic and indexed media. I also have an Obsidian notebook with a growing number of HackTheBox and ProvingGrounds write ups that could benefit from the light of day.

On The Name:

I did not have a name in mind for this project until blogger prompted me for one. I think of my homelab as my own small portion of the vast digital universe, my digital home, my cyber castle. The homelab is the foundational hardware that would allow the internet to become what it was first dreamed to be - a vast network of connected machines, where each person could carve out their own space, and serve up whatever they wanted. That dream has given way to a much more centralized reality, where the web is created, hosted, and monetized by a select few giants. My homelab is my attempt to take back my own portion of the web. NextCloud instead of DropBox, MailCow instead of GMail, my own webpage instead of tumblr. I realize the irony of writing this on...Blogger, but my long term vision is to transition from this to a self-hosted solution. The main impediment at this point is my fear of the increased footprint and risk that any sort of self-hosted content management system will create.

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...