From 24a1a00d376e6a703fd2edb82cdeb2b6b1110f36 Mon Sep 17 00:00:00 2001 From: Orazio Date: Mon, 14 Oct 2019 12:11:16 +0200 Subject: [PATCH 1/6] Refactoring + WireGuard support --- auto_install/install.sh | 2384 ++++++++++++++++++--------------------- pivpn | 106 -- scripts/backup.sh | 31 - scripts/bash-completion | 22 - scripts/clientStat.sh | 35 - scripts/listOVPN.sh | 27 - scripts/makeOVPN.sh | 415 ------- scripts/pivpnDebug.sh | 230 ---- scripts/removeOVPN.sh | 123 -- scripts/uninstall.sh | 153 --- scripts/update.sh | 99 -- 11 files changed, 1103 insertions(+), 2522 deletions(-) delete mode 100644 pivpn delete mode 100755 scripts/backup.sh delete mode 100644 scripts/bash-completion delete mode 100755 scripts/clientStat.sh delete mode 100755 scripts/listOVPN.sh delete mode 100755 scripts/makeOVPN.sh delete mode 100755 scripts/pivpnDebug.sh delete mode 100755 scripts/removeOVPN.sh delete mode 100755 scripts/uninstall.sh delete mode 100755 scripts/update.sh diff --git a/auto_install/install.sh b/auto_install/install.sh index ac2e190..653b017 100755 --- a/auto_install/install.sh +++ b/auto_install/install.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash -# PiVPN: Trivial OpenVPN setup and configuration -# Easiest setup and mangement of OpenVPN on Raspberry Pi +# PiVPN: Trivial OpenVPN or WireGUard setup and configuration +# Easiest setup and mangement of OpenVPN or WireGuard on Raspberry Pi # http://pivpn.io # Heavily adapted from the pi-hole.net project and... # https://github.com/StarshipEngineer/OpenVPN-Setup/ @@ -9,11 +9,10 @@ # # curl -L https://install.pivpn.io | bash # Make sure you have `curl` installed -set -e ######## VARIABLES ######### setupVars=/etc/pivpn/setupVars.conf -useUpdateVars=false +pivpnFilesDir="/etc/.pivpn" ### PKG Vars ### PKG_MANAGER="apt-get" @@ -21,19 +20,19 @@ PKG_CACHE="/var/lib/apt/lists/" UPDATE_PKG_CACHE="${PKG_MANAGER} update" PKG_INSTALL="${PKG_MANAGER} --yes --no-install-recommends install" PKG_COUNT="${PKG_MANAGER} -s -o Debug::NoLocking=true upgrade | grep -c ^Inst || true" -PIVPN_DEPS=(openvpn git tar wget grep iptables-persistent dnsutils expect whiptail net-tools grepcidr jq) +BASE_DEPS=(git tar wget grep iptables-persistent dnsutils whiptail net-tools dhcpcd5) -### ### - -pivpnGitUrl="https://github.com/pivpn/pivpn.git" -pivpnFilesDir="/etc/.pivpn" +pivpnGitUrl="https://github.com/orazioedoardo/pivpn.git" easyrsaVer="3.0.6" easyrsaRel="https://github.com/OpenVPN/easy-rsa/releases/download/v${easyrsaVer}/EasyRSA-unix-v${easyrsaVer}.tgz" # Raspbian's unattended-upgrades package downloads Debian's config, so this is the link for the proper config -UNATTUPG_RELEASE="1.9" +UNATTUPG_RELEASE="1.14" UNATTUPG_CONFIG="https://github.com/mvo5/unattended-upgrades/archive/${UNATTUPG_RELEASE}.tar.gz" +WG_SNAPSHOT="0.0.20190913" +WG_SOURCE="https://git.zx2c4.com/WireGuard/snapshot/WireGuard-${WG_SNAPSHOT}.tar.xz" + # Find the rows and columns. Will default to 80x24 if it can not be detected. screen_size=$(stty size 2>/dev/null || echo 24 80) rows=$(echo $screen_size | awk '{print $1}') @@ -46,13 +45,7 @@ c=$(( columns / 2 )) r=$(( r < 20 ? 20 : r )) c=$(( c < 70 ? 70 : c )) -######## Undocumented Flags. Shhh ######## -skipSpaceCheck=false -reconfigure=false -runUnattended=false - # Find IP used to route to outside world - IPv4dev=$(ip route get 8.8.8.8 | awk '{for(i=1;i<=NF;i++)if($i~/dev/)print $(i+1)}') IPv4addr=$(ip route get 8.8.8.8| awk '{print $7}') IPv4gw=$(ip route get 8.8.8.8 | awk '{print $3}') @@ -61,1076 +54,1034 @@ availableInterfaces=$(ip -o link | grep "state UP" | awk '{print $2}' | cut -d': dhcpcdFile=/etc/dhcpcd.conf # Next see if we are on a tested and supported OS -function noOS_Support() { - whiptail --msgbox --backtitle "INVALID OS DETECTED" --title "Invalid OS" "We have not been able to detect a supported OS. -Currently this installer supports Raspbian and Debian (Jessie and Stretch), Devuan (Jessie) and Ubuntu from 14.04 (trusty) to 17.04 (zesty). +noOSSupport(){ + whiptail --msgbox --backtitle "INVALID OS DETECTED" --title "Invalid OS" "We have not been able to detect a supported OS. +Currently this installer supports Raspbian (Buster). If you think you received this message in error, you can post an issue on the GitHub at https://github.com/pivpn/pivpn/issues." ${r} ${c} - exit 1 + exit 1 } -function maybeOS_Support() { - if (whiptail --backtitle "Not Supported OS" --title "Not Supported OS" --yesno "You are on an OS that we have not tested but MAY work. -Currently suppoerted: - Raspbian, Debian, Devuan (Jessie, strech, buster) - Ubuntu from 14.04 (trusty) to 18.04 (zesty). - +maybeOSSupport(){ + if (whiptail --backtitle "Not Supported OS" --title "Not Supported OS" --yesno "You are on an OS that we have not tested but MAY work. +Currently this installer supports Raspbian (Buster). Would you like to continue anyway?" ${r} ${c}) then - echo "::: Did not detect perfectly supported OS but," - echo "::: Continuing installation at user's own risk..." - else - echo "::: Exiting due to unsupported OS" - exit 1 - fi + echo "::: Did not detect perfectly supported OS but," + echo "::: Continuing installation at user's own risk..." + else + echo "::: Exiting due to unsupported OS" + exit 1 + fi } # Compatibility -distro_check() { - # if lsb_release command is on their system - if hash lsb_release 2>/dev/null; then +distroCheck(){ + # if lsb_release command is on their system + if hash lsb_release 2>/dev/null; then - PLAT=$(lsb_release -si) - OSCN=$(lsb_release -sc) # We want this to be trusty xenial, jessie, stretch, buster + PLAT=$(lsb_release -si) + OSCN=$(lsb_release -sc) # We want this to be trusty xenial or jessie - else # else get info from os-release + else # else get info from os-release - source /etc/os-release - PLAT=$(awk '{print $1}' <<< "$NAME") - VER="$VERSION_ID" - declare -A VER_MAP=(["10"]="buster" ["9"]="stretch" ["8"]="jessie" ["18.04"]="bionic" ["16.04"]="xenial" ["14.04"]="trusty") - OSCN=${VER_MAP["${VER}"]} - fi + source /etc/os-release + PLAT=$(awk '{print $1}' <<< "$NAME") + VER="$VERSION_ID" + declare -A VER_MAP=(["10"]="buster") + OSCN=${VER_MAP["${VER}"]} + fi - if [[ ${OSCN} != "bionic" ]]; then - PIVPN_DEPS+=(dhcpcd5) + case ${PLAT} in + Raspbian) + case ${OSCN} in + buster) + ;; + *) + maybeOS_Support + ;; + esac + ;; + *) + noOS_Support + ;; + esac - fi + echo "PLAT=${PLAT}" > /tmp/setupVars.conf + echo "OSCN=${OSCN}" >> /tmp/setupVars.conf +} - case ${PLAT} in - Ubuntu|Raspbian|Debian|Devuan) - case ${OSCN} in - trusty|xenial|jessie|stretch|buster|bionic) - ;; - *) - maybeOS_Support - ;; - esac - ;; - *) - noOS_Support - ;; - esac - - echo "${PLAT}" > /tmp/DET_PLATFORM +checkHostname(){ +###Checks for hostname size + host_name=$(hostname -s) + if [[ ! ${#host_name} -le 28 ]]; then + until [[ ${#host_name} -le 28 && $host_name =~ ^[a-zA-Z0-9][a-zA-Z0-9-]{1,28}$ ]]; do + host_name=$(whiptail --inputbox "Your hostname is too long.\nEnter new hostname with less then 28 characters\nNo special characters allowed." \ + --title "Hostname too long" ${r} ${c} 3>&1 1>&2 2>&3) + $SUDO hostnamectl set-hostname "${host_name}" + if [[ ${#host_name} -le 28 && $host_name =~ ^[a-zA-Z0-9][a-zA-Z0-9-]{1,28}$ ]]; then + echo "::: Hostname valid and length OK, proceeding..." + fi + done + else + echo "::: Hostname length OK" + fi } ####### FUNCTIONS ########## -spinner() -{ - local pid=$1 - local delay=0.50 - local spinstr='/-\|' - while [ "$(ps a | awk '{print $1}' | grep "${pid}")" ]; do - local temp=${spinstr#?} - printf " [%c] " "${spinstr}" - local spinstr=${temp}${spinstr%"$temp"} - sleep ${delay} - printf "\b\b\b\b\b\b" - done - printf " \b\b\b\b" +spinner(){ + local pid=$1 + local delay=0.50 + local spinstr='/-\|' + while [ "$(ps a | awk '{print $1}' | grep "${pid}")" ]; do + local temp=${spinstr#?} + printf " [%c] " "${spinstr}" + local spinstr=${temp}${spinstr%"$temp"} + sleep ${delay} + printf "\b\b\b\b\b\b" + done + printf " \b\b\b\b" } -welcomeDialogs() { - # Display the welcome dialog - whiptail --msgbox --backtitle "Welcome" --title "PiVPN Automated Installer" "This installer will transform your Raspberry Pi into an OpenVPN server!" ${r} ${c} +verifyFreeDiskSpace(){ + # If user installs unattended-upgrades we'd need about 60MB so will check for 75MB free + echo "::: Verifying free disk space..." + local required_free_kilobytes=76800 + local existing_free_kilobytes=$(df -Pk | grep -m1 '\/$' | awk '{print $4}') - # Explain the need for a static address - whiptail --msgbox --backtitle "Initiating network interface" --title "Static IP Needed" "The PiVPN is a SERVER so it needs a STATIC IP ADDRESS to function properly. + # - Unknown free disk space , not a integer + if ! [[ "${existing_free_kilobytes}" =~ ^([0-9])+$ ]]; then + echo "::: Unknown free disk space!" + echo "::: We were unable to determine available free disk space on this system." + echo "::: You may continue with the installation, however, it is not recommended." + read -r -p "::: If you are sure you want to continue, type YES and press enter :: " response + case $response in + [Y][E][S]) + ;; + *) + echo "::: Confirmation not received, exiting..." + exit 1 + ;; + esac + # - Insufficient free disk space + elif [[ ${existing_free_kilobytes} -lt ${required_free_kilobytes} ]]; then + echo "::: Insufficient Disk Space!" + echo "::: Your system appears to be low on disk space. PiVPN recommends a minimum of $required_free_kilobytes KiloBytes." + echo "::: You only have ${existing_free_kilobytes} KiloBytes free." + echo "::: If this is a new install on a Raspberry Pi you may need to expand your disk." + echo "::: Try running 'sudo raspi-config', and choose the 'expand file system option'" + echo "::: After rebooting, run this installation again. (curl -L https://install.pivpn.io | bash)" + + echo "Insufficient free space, exiting..." + exit 1 + fi +} + +updatePackageCache(){ + #Running apt-get update/upgrade with minimal output can cause some issues with + #requiring user input + + #Check to see if apt-get update has already been run today + #it needs to have been run at least once on new installs! + timestamp=$(stat -c %Y ${PKG_CACHE}) + timestampAsDate=$(date -d @"${timestamp}" "+%b %e") + today=$(date "+%b %e") + + + if [ ! "${today}" == "${timestampAsDate}" ]; then + #update package lists + echo ":::" + echo -ne "::: ${PKG_MANAGER} update has not been run today. Running now...\n" + $SUDO ${UPDATE_PKG_CACHE} &> /dev/null + echo " done!" + fi +} + +notifyPackageUpdatesAvailable(){ + # Let user know if they have outdated packages on their system and + # advise them to run a package update at soonest possible. + echo ":::" + echo -n "::: Checking ${PKG_MANAGER} for upgraded packages...." + updatesToInstall=$(eval "${PKG_COUNT}") + echo " done!" + echo ":::" + if [[ ${updatesToInstall} -eq "0" ]]; then + echo "::: Your system is up to date! Continuing with PiVPN installation..." + else + echo "::: There are ${updatesToInstall} updates available for your system!" + echo "::: We recommend you update your OS after installing PiVPN! " + echo ":::" + fi +} + +packageCheckInstall(){ + dpkg-query -W -f='${Status}' "${1}" 2>/dev/null | grep -c "ok installed" || ${PKG_INSTALL} "${1}" +} + +preconfigurePackages(){ + # Add support for https repositories if there are any that use it otherwise the installation will silently fail + if grep -q https /etc/apt/sources.list; then + BASE_DEPS+=("apt-transport-https") + fi + + if [[ ${OSCN} == "buster" ]]; then + $SUDO update-alternatives --set iptables /usr/sbin/iptables-legacy + $SUDO update-alternatives --set ip6tables /usr/sbin/ip6tables-legacy + fi + + echo iptables-persistent iptables-persistent/autosave_v4 boolean true | $SUDO debconf-set-selections + echo iptables-persistent iptables-persistent/autosave_v6 boolean false | $SUDO debconf-set-selections +} + +installDependentPackages(){ + # Install packages passed in via argument array + # No spinner - conflicts with set -e + declare -a argArray1=("${!1}") + + if command -v debconf-apt-progress &> /dev/null; then + $SUDO debconf-apt-progress -- ${PKG_INSTALL} "${argArray1[@]}" + else + for i in "${argArray1[@]}"; do + echo -n "::: Checking for $i..." + $SUDO packageCheckInstall "${i}" &> /dev/null + echo " installed!" + done + fi +} + +welcomeDialogs(){ + # Display the welcome dialog + whiptail --msgbox --backtitle "Welcome" --title "PiVPN Automated Installer" "This installer will transform your Raspberry Pi into an OpenVPN or WireGuard server!" ${r} ${c} + + # Explain the need for a static address + whiptail --msgbox --backtitle "Initiating network interface" --title "Static IP Needed" "The PiVPN is a SERVER so it needs a STATIC IP ADDRESS to function properly. In the next section, you can choose to use your current network settings (DHCP) or to manually edit them." ${r} ${c} } -chooseUser() { - # Explain the local user - whiptail --msgbox --backtitle "Parsing User List" --title "Local Users" "Choose a local user that will hold your ovpn configurations." ${r} ${c} - # First, let's check if there is a user available. - numUsers=$(awk -F':' 'BEGIN {count=0} $3>=1000 && $3<=60000 { count++ } END{ print count }' /etc/passwd) - if [ "$numUsers" -eq 0 ] - then - # We don't have a user, let's ask to add one. - if userToAdd=$(whiptail --title "Choose A User" --inputbox "No non-root user account was found. Please type a new username." ${r} ${c} 3>&1 1>&2 2>&3) - then - # See http://askubuntu.com/a/667842/459815 - PASSWORD=$(whiptail --title "password dialog" --passwordbox "Please enter the new user password" ${r} ${c} 3>&1 1>&2 2>&3) - CRYPT=$(perl -e 'printf("%s\n", crypt($ARGV[0], "password"))' "${PASSWORD}") - $SUDO useradd -m -p "${CRYPT}" -s /bin/bash "${userToAdd}" - if [[ $? = 0 ]]; then - echo "Succeeded" - ((numUsers+=1)) - else - exit 1 - fi - else - exit 1 - fi - fi - availableUsers=$(awk -F':' '$3>=1000 && $3<=60000 {print $1}' /etc/passwd) - local userArray=() - local firstloop=1 +chooseInterface(){ + # Turn the available interfaces into an array so it can be used with a whiptail dialog + local interfacesArray=() + # Number of available interfaces + local interfaceCount + # Whiptail variable storage + local chooseInterfaceCmd + # Temporary Whiptail options storage + local chooseInterfaceOptions + # Loop sentinel variable + local firstloop=1 - while read -r line - do - mode="OFF" - if [[ $firstloop -eq 1 ]]; then - firstloop=0 - mode="ON" - fi - userArray+=("${line}" "" "${mode}") - done <<< "${availableUsers}" - chooseUserCmd=(whiptail --title "Choose A User" --separate-output --radiolist "Choose (press space to select):" ${r} ${c} ${numUsers}) - chooseUserOptions=$("${chooseUserCmd[@]}" "${userArray[@]}" 2>&1 >/dev/tty) - if [[ $? = 0 ]]; then - for desiredUser in ${chooseUserOptions}; do - INSTALL_USER=${desiredUser} - echo "::: Using User: $INSTALL_USER" - echo "${INSTALL_USER}" > /tmp/INSTALL_USER - done - else - echo "::: Cancel selected, exiting...." - exit 1 - fi -} + if [[ $(echo "${availableInterfaces}" | wc -l) -eq 1 ]]; then + PHYS_INT="${availableInterfaces}" + echo "PHYS_INT=${PHYS_INT}" >> /tmp/setupVars.conf + return + fi -verifyFreeDiskSpace() { - # If user installs unattended-upgrades we'd need about 60MB so will check for 75MB free - echo "::: Verifying free disk space..." - local required_free_kilobytes=76800 - local existing_free_kilobytes=$(df -Pk | grep -m1 '\/$' | awk '{print $4}') + while read -r line; do + mode="OFF" + if [[ ${firstloop} -eq 1 ]]; then + firstloop=0 + mode="ON" + fi + interfacesArray+=("${line}" "available" "${mode}") + done <<< "${availableInterfaces}" - # - Unknown free disk space , not a integer - if ! [[ "${existing_free_kilobytes}" =~ ^([0-9])+$ ]]; then - echo "::: Unknown free disk space!" - echo "::: We were unable to determine available free disk space on this system." - echo "::: You may continue with the installation, however, it is not recommended." - read -r -p "::: If you are sure you want to continue, type YES and press enter :: " response - case $response in - [Y][E][S]) - ;; - *) - echo "::: Confirmation not received, exiting..." - exit 1 - ;; - esac - # - Insufficient free disk space - elif [[ ${existing_free_kilobytes} -lt ${required_free_kilobytes} ]]; then - echo "::: Insufficient Disk Space!" - echo "::: Your system appears to be low on disk space. PiVPN recommends a minimum of $required_free_kilobytes KiloBytes." - echo "::: You only have ${existing_free_kilobytes} KiloBytes free." - echo "::: If this is a new install on a Raspberry Pi you may need to expand your disk." - echo "::: Try running 'sudo raspi-config', and choose the 'expand file system option'" - echo "::: After rebooting, run this installation again. (curl -L https://install.pivpn.io | bash)" - - echo "Insufficient free space, exiting..." - exit 1 - fi -} - - -chooseInterface() { - # Turn the available interfaces into an array so it can be used with a whiptail dialog - local interfacesArray=() - # Number of available interfaces - local interfaceCount - # Whiptail variable storage - local chooseInterfaceCmd - # Temporary Whiptail options storage - local chooseInterfaceOptions - # Loop sentinel variable - local firstloop=1 - - if [[ $(echo "${availableInterfaces}" | wc -l) -eq 1 ]]; then - pivpnInterface="${availableInterfaces}" - echo "${pivpnInterface}" > /tmp/pivpnINT - return - fi - - while read -r line; do - mode="OFF" - if [[ ${firstloop} -eq 1 ]]; then - firstloop=0 - mode="ON" - fi - interfacesArray+=("${line}" "available" "${mode}") - done <<< "${availableInterfaces}" - - # Find out how many interfaces are available to choose from - interfaceCount=$(echo "${availableInterfaces}" | wc -l) - chooseInterfaceCmd=(whiptail --separate-output --radiolist "Choose An Interface (press space to select):" ${r} ${c} ${interfaceCount}) - chooseInterfaceOptions=$("${chooseInterfaceCmd[@]}" "${interfacesArray[@]}" 2>&1 >/dev/tty) - if [[ $? = 0 ]]; then - for desiredInterface in ${chooseInterfaceOptions}; do - pivpnInterface=${desiredInterface} - echo "::: Using interface: $pivpnInterface" - echo "${pivpnInterface}" > /tmp/pivpnINT - done - else - echo "::: Cancel selected, exiting...." - exit 1 - fi -} - -avoidStaticIPv4Ubuntu() { - # If we are in Ubuntu then they need to have previously set their network, so just use what you have. - whiptail --msgbox --backtitle "IP Information" --title "IP Information" "Since we think you are not using Raspbian, we will not configure a static IP for you. -If you are in Amazon then you can not configure a static IP anyway. Just ensure before this installer started you had set an elastic IP on your instance." ${r} ${c} + # Find out how many interfaces are available to choose from + interfaceCount=$(echo "${availableInterfaces}" | wc -l) + chooseInterfaceCmd=(whiptail --separate-output --radiolist "Choose An Interface (press space to select):" ${r} ${c} ${interfaceCount}) + chooseInterfaceOptions=$("${chooseInterfaceCmd[@]}" "${interfacesArray[@]}" 2>&1 >/dev/tty) + if [[ $? = 0 ]]; then + for desiredInterface in ${chooseInterfaceOptions}; do + PHYS_INT=${desiredInterface} + echo "::: Using interface: $PHYS_INT" + echo "PHYS_INT=${PHYS_INT}" >> /tmp/setupVars.conf + done + else + echo "::: Cancel selected, exiting...." + exit 1 + fi } getStaticIPv4Settings() { - local ipSettingsCorrect - # Grab their current DNS Server - IPv4dns=$(nslookup 127.0.0.1 | grep Server: | awk '{print $2}') - # Ask if the user wants to use DHCP settings as their static IP - if (whiptail --backtitle "Calibrating network interface" --title "Static IP Address" --yesno "Do you want to use your current network settings as a static address? - IP address: ${IPv4addr} - Gateway: ${IPv4gw}" ${r} ${c}); then - # If they choose yes, let the user know that the IP address will not be available via DHCP and may cause a conflict. - whiptail --msgbox --backtitle "IP information" --title "FYI: IP Conflict" "It is possible your router could still try to assign this IP to a device, which would cause a conflict. But in most cases the router is smart enough to not do that. + local ipSettingsCorrect + # Grab their current DNS Server + IPv4dns=$(nslookup 127.0.0.1 | grep Server: | awk '{print $2}') + # Ask if the user wants to use DHCP settings as their static IP + if (whiptail --backtitle "Calibrating network interface" --title "Static IP Address" --yesno "Do you want to use your current network settings as a static address? + IP address: ${IPv4addr} + Gateway: ${IPv4gw}" ${r} ${c}); then + # If they choose yes, let the user know that the IP address will not be available via DHCP and may cause a conflict. + whiptail --msgbox --backtitle "IP information" --title "FYI: IP Conflict" "It is possible your router could still try to assign this IP to a device, which would cause a conflict. But in most cases the router is smart enough to not do that. If you are worried, either manually set the address, or modify the DHCP reservation pool so it does not include the IP you want. It is also possible to use a DHCP reservation, but if you are going to do that, you might as well set a static address." ${r} ${c} - # Nothing else to do since the variables are already set above - else - # Otherwise, we need to ask the user to input their desired settings. - # Start by getting the IPv4 address (pre-filling it with info gathered from DHCP) - # Start a loop to let the user enter their information with the chance to go back and edit it if necessary - until [[ ${ipSettingsCorrect} = True ]]; do - # Ask for the IPv4 address - IPv4addr=$(whiptail --backtitle "Calibrating network interface" --title "IPv4 address" --inputbox "Enter your desired IPv4 address" ${r} ${c} "${IPv4addr}" 3>&1 1>&2 2>&3) - if [[ $? = 0 ]]; then - echo "::: Your static IPv4 address: ${IPv4addr}" - # Ask for the gateway - IPv4gw=$(whiptail --backtitle "Calibrating network interface" --title "IPv4 gateway (router)" --inputbox "Enter your desired IPv4 default gateway" ${r} ${c} "${IPv4gw}" 3>&1 1>&2 2>&3) - if [[ $? = 0 ]]; then - echo "::: Your static IPv4 gateway: ${IPv4gw}" - # Give the user a chance to review their settings before moving on - if (whiptail --backtitle "Calibrating network interface" --title "Static IP Address" --yesno "Are these settings correct? - IP address: ${IPv4addr} - Gateway: ${IPv4gw}" ${r} ${c}); then - # If the settings are correct, then we need to set the pivpnIP - echo "${IPv4addr%/*}" > /tmp/pivpnIP - echo "$pivpnInterface" > /tmp/pivpnINT - # After that's done, the loop ends and we move on - ipSettingsCorrect=True - else - # If the settings are wrong, the loop continues - ipSettingsCorrect=False - fi - else - # Cancelling gateway settings window - ipSettingsCorrect=False - echo "::: Cancel selected. Exiting..." - exit 1 - fi - else - # Cancelling IPv4 settings window - ipSettingsCorrect=False - echo "::: Cancel selected. Exiting..." - exit 1 - fi - done - # End the if statement for DHCP vs. static - fi + # Nothing else to do since the variables are already set above + else + # Otherwise, we need to ask the user to input their desired settings. + # Start by getting the IPv4 address (pre-filling it with info gathered from DHCP) + # Start a loop to let the user enter their information with the chance to go back and edit it if necessary + until [[ ${ipSettingsCorrect} = True ]]; do + # Ask for the IPv4 address + IPv4addr=$(whiptail --backtitle "Calibrating network interface" --title "IPv4 address" --inputbox "Enter your desired IPv4 address" ${r} ${c} "${IPv4addr}" 3>&1 1>&2 2>&3) + if [[ $? = 0 ]]; then + echo "::: Your static IPv4 address: ${IPv4addr}" + # Ask for the gateway + IPv4gw=$(whiptail --backtitle "Calibrating network interface" --title "IPv4 gateway (router)" --inputbox "Enter your desired IPv4 default gateway" ${r} ${c} "${IPv4gw}" 3>&1 1>&2 2>&3) + if [[ $? = 0 ]]; then + echo "::: Your static IPv4 gateway: ${IPv4gw}" + # Give the user a chance to review their settings before moving on + if (whiptail --backtitle "Calibrating network interface" --title "Static IP Address" --yesno "Are these settings correct? + IP address: ${IPv4addr} + Gateway: ${IPv4gw}" ${r} ${c}); then + # If the settings are correct, then we need to set the pivpnIP + echo "pivpnIP=${IPv4addr%/*}" >> /tmp/setupVars.conf + # After that's done, the loop ends and we move on + ipSettingsCorrect=True + else + # If the settings are wrong, the loop continues + ipSettingsCorrect=False + fi + else + # Cancelling gateway settings window + ipSettingsCorrect=False + echo "::: Cancel selected. Exiting..." + exit 1 + fi + else + # Cancelling IPv4 settings window + ipSettingsCorrect=False + echo "::: Cancel selected. Exiting..." + exit 1 + fi + done + # End the if statement for DHCP vs. static + fi } -setDHCPCD() { - # Append these lines to dhcpcd.conf to enable a static IP - echo "interface ${pivpnInterface} - static ip_address=${IPv4addr} - static routers=${IPv4gw} - static domain_name_servers=${IPv4dns}" | $SUDO tee -a ${dhcpcdFile} >/dev/null +setDHCPCD(){ + # Append these lines to dhcpcd.conf to enable a static IP + echo "interface ${PHYS_INT} + static ip_address=${IPv4addr} + static routers=${IPv4gw} + static domain_name_servers=${IPv4dns}" | $SUDO tee -a ${dhcpcdFile} >/dev/null } -setStaticIPv4() { - # Tries to set the IPv4 address - if [[ -f /etc/dhcpcd.conf ]]; then - if grep -q "${IPv4addr}" ${dhcpcdFile}; then - echo "::: Static IP already configured." - else - setDHCPCD - $SUDO ip addr replace dev "${pivpnInterface}" "${IPv4addr}" - echo ":::" - echo "::: Setting IP to ${IPv4addr}. You may need to restart after the install is complete." - echo ":::" - fi - else - echo "::: Critical: Unable to locate configuration file to set static IPv4 address!" - exit 1 - fi +setStaticIPv4(){ + # Tries to set the IPv4 address + if [[ -f /etc/dhcpcd.conf ]]; then + if grep -q "${IPv4addr}" ${dhcpcdFile}; then + echo "::: Static IP already configured." + else + setDHCPCD + $SUDO ip addr replace dev "${PHYS_INT}" "${IPv4addr}" + echo ":::" + echo "::: Setting IP to ${IPv4addr}. You may need to restart after the install is complete." + echo ":::" + fi + else + echo "::: Critical: Unable to locate configuration file to set static IPv4 address!" + exit 1 + fi } -function valid_ip() -{ - local ip=$1 - local stat=1 +chooseUser(){ + # Explain the local user + whiptail --msgbox --backtitle "Parsing User List" --title "Local Users" "Choose a local user that will hold your ovpn configurations." ${r} ${c} + # First, let's check if there is a user available. + numUsers=$(awk -F':' 'BEGIN {count=0} $3>=1000 && $3<=60000 { count++ } END{ print count }' /etc/passwd) + if [ "$numUsers" -eq 0 ] + then + # We don't have a user, let's ask to add one. + if userToAdd=$(whiptail --title "Choose A User" --inputbox "No non-root user account was found. Please type a new username." ${r} ${c} 3>&1 1>&2 2>&3) + then + # See http://askubuntu.com/a/667842/459815 + PASSWORD=$(whiptail --title "password dialog" --passwordbox "Please enter the new user password" ${r} ${c} 3>&1 1>&2 2>&3) + CRYPT=$(perl -e 'printf("%s\n", crypt($ARGV[0], "password"))' "${PASSWORD}") + $SUDO useradd -m -p "${CRYPT}" -s /bin/bash "${userToAdd}" + if [[ $? = 0 ]]; then + echo "Succeeded" + ((numUsers+=1)) + else + exit 1 + fi + else + exit 1 + fi + fi + availableUsers=$(awk -F':' '$3>=1000 && $3<=60000 {print $1}' /etc/passwd) + local userArray=() + local firstloop=1 - if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then - OIFS=$IFS - IFS='.' - ip=($ip) - IFS=$OIFS - [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \ - && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] - stat=$? - fi - return $stat + while read -r line + do + mode="OFF" + if [[ $firstloop -eq 1 ]]; then + firstloop=0 + mode="ON" + fi + userArray+=("${line}" "" "${mode}") + done <<< "${availableUsers}" + chooseUserCmd=(whiptail --title "Choose A User" --separate-output --radiolist "Choose (press space to select):" ${r} ${c} ${numUsers}) + chooseUserOptions=$("${chooseUserCmd[@]}" "${userArray[@]}" 2>&1 >/dev/tty) + if [[ $? = 0 ]]; then + for desiredUser in ${chooseUserOptions}; do + install_user=${desiredUser} + echo "::: Using User: $install_user" + install_home=$(grep -m1 "^${install_user}:" /etc/passwd | cut -d: -f6) + install_home=${install_home%/} # remove possible trailing slash + echo "install_user=${install_user}" >> /tmp/setupVars.conf + echo "install_home=${install_home}" >> /tmp/setupVars.conf + done + else + echo "::: Cancel selected, exiting...." + exit 1 + fi + + +} + +isRepo(){ + # If the directory does not have a .git folder it is not a repo + echo -n "::: Checking $1 is a repo..." + cd "${1}" &> /dev/null || return 1 + $SUDO git status &> /dev/null && echo " OK!"; return 0 || echo " not found!"; return 1 +} + +updateRepo(){ + # Pull the latest commits + echo -n "::: Updating repo in $1..." + $SUDO rm -rf "${1}" + # Go back to /etc otherwhise git will complain when the current working + # directory has just been deleted (/etc/.pivpn). + cd /etc + $SUDO git clone -q --depth 1 --no-single-branch "${2}" "${1}" > /dev/null & spinner $! + cd "${1}" || exit 1 + if [ -z "${TESTING}" ]; then + : + elif [ "${TESTING}" = "test" ]; then + ${SUDOE} git checkout test + elif [ "${TESTING}" = "test-wireguard" ]; then + ${SUDOE} git checkout test-wireguard + fi + echo " done!" +} + +makeRepo(){ + # Remove the non-repos interface and clone the interface + echo -n "::: Cloning $2 into $1..." + $SUDO rm -rf "${1}" + $SUDO git clone -q --depth 1 --no-single-branch "${2}" "${1}" > /dev/null & spinner $! + if [ -z "${TESTING}" ]; then + : + elif [ "${TESTING}" = "test" ]; then + ${SUDOE} git checkout test + elif [ "${TESTING}" = "test-wireguard" ]; then + ${SUDOE} git checkout test-wireguard + fi + echo " done!" +} + +getGitFiles(){ + # Setup git repos for base files + echo ":::" + echo "::: Checking for existing base files..." + if isRepo "${1}"; then + updateRepo "${1}" "${2}" + else + makeRepo "${1}" "${2}" + fi +} + +cloneOrUpdateRepos(){ + # Get Git files + getGitFiles ${pivpnFilesDir} ${pivpnGitUrl} || \ + { echo "!!! Unable to clone ${pivpnGitUrl} into ${pivpnFilesDir}, unable to continue."; \ + exit 1; \ +} +} + +askWhichVPN(){ + if (whiptail --backtitle "Setup PiVPN" --title "Installation mode" --yesno "WireGuard is a new kind of VPN that provides near-istantaneous connection speed, high performance, modern cryptography.\n\nIt's the recommended choise expecially if you use mobile devices where WireGuard is easier on battery than OpenVPN.\n\nOpenVPN is still available if you need the traditional, flexible, trusted VPN protocol. Or if you need features like TCP and custom search domain.\n\nChoose 'Yes' to use WireGuard of 'No' to use OpenVPN." ${r} ${c}); + then + VPN="WireGuard" + pivpnINT="wg0" + else + VPN="OpenVPN" + pivpnINT="tun0" + fi + + echo "VPN=${VPN}" >> /tmp/setupVars.conf + echo "pivpnINT=${pivpnINT}" >> /tmp/setupVars.conf +} + +installOpenVPN(){ + echo "::: Installing OpenVPN from Debian package... " + # grepcidr is used to redact IPs in the debug log, whereas expect is used + # to feed easy-rsa with passwords + PIVPN_DEPS=(openvpn grepcidr expect) + installDependentPackages PIVPN_DEPS[@] +} + +installWireGuard(){ + # If this Raspberry Pi uses armv7l we can use the package from the repo + # https://lists.zx2c4.com/pipermail/wireguard/2017-November/001885.html + # Otherwhise compile and build the kernel module via DKMS (so it will + # be recompiled on kernel upgrades) + if [ "$(uname -m)" = "armv7l" ]; then + echo "::: Installing WireGuard from Debian package... " + # dirmngr is used to download repository keys, whereas qrencode is used to generate qrcodes + # from config file, for use with mobile clients + PIVPN_DEPS=(dirmngr qrencode) + installDependentPackages PIVPN_DEPS[@] + # Do not upgrade packages from the unstable repository except for wireguard + echo "::: Adding Debian repository... " + echo "deb http://deb.debian.org/debian/ unstable main" | $SUDO tee -a /etc/apt/sources.list.d/unstable.list > /dev/null + echo "Package: * +Pin: release a=unstable +Pin-Priority: 1 + +Package: wireguard wireguard-dkms wireguard-tools +Pin: release a=unstable +Pin-Priority: 500" | $SUDO tee -a /etc/apt/preferences.d/limit-unstable > /dev/null + + $SUDO apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 04EE7237B7D453EC 648ACFD622F3D138 + $SUDO ${UPDATE_PKG_CACHE} &> /dev/null + PIVPN_DEPS=(wireguard) + installDependentPackages PIVPN_DEPS[@] + elif [ "$(uname -m)" = "armv6l" ]; then + echo "::: Installing WireGuard from source... " + PIVPN_DEPS=(libmnl-dev libelf-dev raspberrypi-kernel-headers build-essential pkg-config qrencode) + installDependentPackages PIVPN_DEPS[@] + + # Delete any leftover code + $SUDO rm -rf /usr/src/wireguard-* + + echo -n "::: Downloading source code... " + wget -O- "${WG_SOURCE}" | $SUDO tar Jxf - --directory /usr/src + echo "done!" + + cd /usr/src + $SUDO mv WireGuard-"${WG_SNAPSHOT}" wireguard-"${WG_SNAPSHOT}" + cd wireguard-"${WG_SNAPSHOT}" + $SUDO mv src/* . + $SUDO rmdir src + + # We install the userspace tools manually since DKMS only compiles and + # installs the kernel module + echo -n "::: Compiling WireGuard tools... " + if $SUDO make tools; then + echo "done!" + else + echo "failed!" + exit 1 + fi + + echo -n "::: Installing WireGuard tools... " + if $SUDO make install tools; then + echo "done!" + else + echo "failed!" + exit 1 + fi + + echo -n "::: Adding WireGuard modules via DKMS... " + if $SUDO dkms add wireguard/"${WG_SNAPSHOT}"; then + echo "done!" + else + echo "failed!" + $SUDO dkms remove wireguard/"${WG_SNAPSHOT}" --all + exit 1 + fi + + echo -n "::: Compiling WireGuard modules via DKMS... " + if $SUDO dkms build wireguard/"${WG_SNAPSHOT}"; then + echo "done!" + else + echo "failed!" + $SUDO dkms remove wireguard/"${WG_SNAPSHOT}" --all + exit 1 + fi + + echo -n "::: Installing WireGuard modules via DKMS... " + if $SUDO dkms install wireguard/"${WG_SNAPSHOT}"; then + echo "done!" + else + echo "failed!" + $SUDO dkms remove wireguard/"${WG_SNAPSHOT}" --all + exit 1 + fi + fi +} + +validIP(){ + local ip=$1 + local stat=1 + + if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then + OIFS=$IFS + IFS='.' + ip=($ip) + IFS=$OIFS + [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \ + && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] + stat=$? + fi + return $stat } #Call this function to use a regex to check user input for a valid custom domain -function valid_domain() -{ - local domain=$1 - local stat=1 +validDomain(){ + local domain=$1 + local stat=1 - - if [[ $domain =~ ^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}\.[a-zA-Z]{2,}$ ]]; then - stat=$? - fi + if [[ $domain =~ ^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}\.[a-zA-Z]{2,}$ ]]; then + stat=$? + fi return $stat } -installScripts() { - # Install the scripts from /etc/.pivpn to their various locations - $SUDO echo ":::" - $SUDO echo -n "::: Installing scripts to /opt/pivpn..." - if [ ! -d /opt/pivpn ]; then - $SUDO mkdir /opt/pivpn - $SUDO chown "$INSTALL_USER":root /opt/pivpn - $SUDO chmod 0755 /opt/pivpn - fi - $SUDO cp /etc/.pivpn/scripts/*.sh /opt/pivpn/ - $SUDO chmod 0755 /opt/pivpn/*.sh - $SUDO cp /etc/.pivpn/pivpn /usr/local/bin/pivpn - $SUDO chmod 0755 /usr/local/bin/pivpn - $SUDO cp /etc/.pivpn/scripts/bash-completion /etc/bash_completion.d/pivpn - . /etc/bash_completion.d/pivpn - # Copy interface setting for debug - $SUDO cp /tmp/pivpnINT /etc/pivpn/pivpnINTERFACE - - $SUDO echo " done." +askCustomProto(){ + # Set the available protocols into an array so it can be used with a whiptail dialog + if protocol=$(whiptail --title "Protocol" --radiolist \ + "Choose a protocol (press space to select). Please only choose TCP if you know why you need TCP." ${r} ${c} 2 \ + "UDP" "" ON \ + "TCP" "" OFF 3>&1 1>&2 2>&3) + then + # Convert option into lowercase (UDP->udp) + pivpnPROTO="${protocol,,}" + echo "::: Using protocol: $pivpnPROTO" + echo "pivpnPROTO=${pivpnPROTO}" >> /tmp/setupVars.conf + else + echo "::: Cancel selected, exiting...." + exit 1 + fi } -package_check_install() { - dpkg-query -W -f='${Status}' "${1}" 2>/dev/null | grep -c "ok installed" || ${PKG_INSTALL} "${1}" +askCustomPort(){ + until [[ $PORTNumCorrect = True ]] + do + portInvalid="Invalid" + + if [ "$VPN" = "WireGuard" ]; then + DEFAULT_PORT=51820 + elif [ "$VPN" = "OpenVPN" ]; then + if [ "$pivpnPROTO" = "udp" ]; then + DEFAULT_PORT=1194 + else + DEFAULT_PORT=443 + fi + fi + + if pivpnPORT=$(whiptail --title "Default $VPN Port" --inputbox "You can modify the default $VPN port. \nEnter a new value or hit 'Enter' to retain the default" ${r} ${c} $DEFAULT_PORT 3>&1 1>&2 2>&3) + then + if [[ "$pivpnPORT" =~ ^[0-9]+$ ]] && [ "$pivpnPORT" -ge 1 ] && [ "$pivpnPORT" -le 65535 ]; then + : + else + pivpnPORT=$portInvalid + fi + else + echo "::: Cancel selected, exiting...." + exit 1 + fi + + if [[ $pivpnPORT == "$portInvalid" ]]; then + whiptail --msgbox --backtitle "Invalid Port" --title "Invalid Port" "You entered an invalid Port number.\n Please enter a number from 1 - 65535.\n If you are not sure, please just keep the default." ${r} ${c} + PORTNumCorrect=False + else + if (whiptail --backtitle "Specify Custom Port" --title "Confirm Custom Port Number" --yesno "Are these settings correct?\n PORT: $pivpnPORT" ${r} ${c}) then + PORTNumCorrect=True + else + # If the settings are wrong, the loop continues + PORTNumCorrect=False + fi + fi + done + # write out the port + echo "pivpnPORT=${pivpnPORT}" >> /tmp/setupVars.conf } -addSoftwareRepo() { - # Add the official OpenVPN repo for distros that don't have the latest version in their default repos - case ${PLAT} in - Ubuntu|Debian|Devuan) - case ${OSCN} in - trusty|xenial|wheezy|jessie) - wget -qO- https://swupdate.openvpn.net/repos/repo-public.gpg | $SUDO apt-key add - - echo "deb http://build.openvpn.net/debian/openvpn/stable $OSCN main" | $SUDO tee /etc/apt/sources.list.d/swupdate.openvpn.net.list > /dev/null - echo -n "::: Adding OpenVPN repo for $PLAT $OSCN ..." - $SUDO $PKG_MANAGER -qq update & spinner $! - echo " done!" - ;; - esac - ;; - esac -} +askClientDNS() { + DNSChoseCmd=(whiptail --separate-output --radiolist "Select the DNS Provider for your VPN Clients (press space to select). To use your own, select Custom." ${r} ${c} 6) + DNSChooseOptions=(Google "" on + OpenDNS "" off + Level3 "" off + DNS.WATCH "" off + Norton "" off + FamilyShield "" off + CloudFlare "" off + Custom "" off) -update_package_cache() { - #Running apt-get update/upgrade with minimal output can cause some issues with - #requiring user input + if DNSchoices=$("${DNSChoseCmd[@]}" "${DNSChooseOptions[@]}" 2>&1 >/dev/tty) + then - #Check to see if apt-get update has already been run today - #it needs to have been run at least once on new installs! - timestamp=$(stat -c %Y ${PKG_CACHE}) - timestampAsDate=$(date -d @"${timestamp}" "+%b %e") - today=$(date "+%b %e") + if [[ ${DNSchoices} != "Custom" ]]; then + echo "::: Using ${DNSchoices} servers." + declare -A DNS_MAP=(["Google"]="8.8.8.8 8.8.4.4" + ["OpenDNS"]="208.67.222.222 208.67.220.220" + ["Level3"]="209.244.0.3 209.244.0.4" + ["DNS.WATCH"]="84.200.69.80 84.200.70.40" + ["Norton"]="199.85.126.10 199.85.127.10" + ["FamilyShield"]="208.67.222.123 208.67.220.123" + ["CloudFlare"]="1.1.1.1 1.0.0.1") - if [ ! "${today}" == "${timestampAsDate}" ]; then - #update package lists - echo ":::" - echo -ne "::: ${PKG_MANAGER} update has not been run today. Running now...\n" - $SUDO ${UPDATE_PKG_CACHE} &> /dev/null - echo " done!" - fi -} + pivpnDNS1=$(awk '{print $1}' <<< "${DNS_MAP["${DNSchoices}"]}") + pivpnDNS2=$(awk '{print $2}' <<< "${DNS_MAP["${DNSchoices}"]}") -notify_package_updates_available() { - # Let user know if they have outdated packages on their system and - # advise them to run a package update at soonest possible. - echo ":::" - echo -n "::: Checking ${PKG_MANAGER} for upgraded packages...." - updatesToInstall=$(eval "${PKG_COUNT}") - echo " done!" - echo ":::" - if [[ ${updatesToInstall} -eq "0" ]]; then - echo "::: Your system is up to date! Continuing with PiVPN installation..." - else - echo "::: There are ${updatesToInstall} updates available for your system!" - echo "::: We recommend you update your OS after installing PiVPN! " - echo ":::" - fi -} + else -install_dependent_packages() { - # Install packages passed in via argument array - # No spinner - conflicts with set -e - declare -a argArray1=("${!1}") + until [[ $DNSSettingsCorrect = True ]]; do + strInvalid="Invalid" - if [[ ${OSCN} == "buster" ]]; then - $SUDO update-alternatives --set iptables /usr/sbin/iptables-legacy - $SUDO update-alternatives --set ip6tables /usr/sbin/ip6tables-legacy - fi - echo iptables-persistent iptables-persistent/autosave_v4 boolean true | $SUDO debconf-set-selections - echo iptables-persistent iptables-persistent/autosave_v6 boolean false | $SUDO debconf-set-selections + if pivpnDNS=$(whiptail --backtitle "Specify Upstream DNS Provider(s)" --inputbox "Enter your desired upstream DNS provider(s), separated by a comma.\n\nFor example '8.8.8.8, 8.8.4.4'" ${r} ${c} "" 3>&1 1>&2 2>&3) + then + pivpnDNS1=$(echo "$pivpnDNS" | sed 's/[, \t]\+/,/g' | awk -F, '{print$1}') + pivpnDNS2=$(echo "$pivpnDNS" | sed 's/[, \t]\+/,/g' | awk -F, '{print$2}') + if ! validIP "$pivpnDNS1" || [ ! "$pivpnDNS1" ]; then + pivpnDNS1=$strInvalid + fi + if ! validIP "$pivpnDNS2" && [ "$pivpnDNS2" ]; then + pivpnDNS2=$strInvalid + fi + else + echo "::: Cancel selected, exiting...." + exit 1 + fi - # Add support for https repositories if there are any that use it otherwise the installation will silently fail - if grep -q https /etc/apt/sources.list; then - PIVPN_DEPS+=("apt-transport-https") - fi + if [[ $pivpnDNS1 == "$strInvalid" ]] || [[ $pivpnDNS2 == "$strInvalid" ]]; then + whiptail --msgbox --backtitle "Invalid IP" --title "Invalid IP" "One or both entered IP addresses were invalid. Please try again.\n\n DNS Server 1: $pivpnDNS1\n DNS Server 2: $pivpnDNS2" ${r} ${c} + if [[ $pivpnDNS1 == "$strInvalid" ]]; then + pivpnDNS1="" + fi + if [[ $pivpnDNS2 == "$strInvalid" ]]; then + pivpnDNS2="" + fi + DNSSettingsCorrect=False + else + if (whiptail --backtitle "Specify Upstream DNS Provider(s)" --title "Upstream DNS Provider(s)" --yesno "Are these settings correct?\n DNS Server 1: $pivpnDNS1\n DNS Server 2: $pivpnDNS2" ${r} ${c}) then + DNSSettingsCorrect=True + else + # If the settings are wrong, the loop continues + DNSSettingsCorrect=False + fi + fi + done + fi - if command -v debconf-apt-progress &> /dev/null; then - $SUDO debconf-apt-progress -- ${PKG_INSTALL} "${argArray1[@]}" - else - for i in "${argArray1[@]}"; do - echo -n "::: Checking for $i..." - $SUDO package_check_install "${i}" &> /dev/null - echo " installed!" - done - fi -} + else + echo "::: Cancel selected. Exiting..." + exit 1 + fi -unattendedUpgrades() { - whiptail --msgbox --backtitle "Security Updates" --title "Unattended Upgrades" "Since this server will have at least one port open to the internet, it is recommended you enable unattended-upgrades.\nThis feature will check daily for security package updates only and apply them when necessary.\nIt will NOT automatically reboot the server so to fully apply some updates you should periodically reboot." ${r} ${c} - - if (whiptail --backtitle "Security Updates" --title "Unattended Upgrades" --yesno "Do you want to enable unattended upgrades of security patches to this server?" ${r} ${c}) then - UNATTUPG="unattended-upgrades" - else - UNATTUPG="" - fi -} - -stopServices() { - # Stop openvpn - $SUDO echo ":::" - $SUDO echo -n "::: Stopping OpenVPN service..." - case ${PLAT} in - Ubuntu|Debian|*vuan) - $SUDO service openvpn stop || true - ;; - *) - $SUDO systemctl stop openvpn.service || true - ;; - esac - $SUDO echo " done." -} - -getGitFiles() { - # Setup git repos for base files - echo ":::" - echo "::: Checking for existing base files..." - if is_repo "${1}"; then - update_repo "${1}" "${2}" - else - make_repo "${1}" "${2}" - fi -} - -is_repo() { - # If the directory does not have a .git folder it is not a repo - echo -n "::: Checking $1 is a repo..." - cd "${1}" &> /dev/null || return 1 - $SUDO git status &> /dev/null && echo " OK!"; return 0 || echo " not found!"; return 1 -} - -make_repo() { - # Remove the non-repos interface and clone the interface - echo -n "::: Cloning $2 into $1..." - $SUDO rm -rf "${1}" - $SUDO git clone -q --depth 1 --no-single-branch "${2}" "${1}" > /dev/null & spinner $! - if [ -z "${TESTING+x}" ]; then - : - else - $SUDO git -C "${1}" checkout test - fi - echo " done!" -} - -update_repo() { - if [[ "${reconfigure}" == true ]]; then - echo "::: --reconfigure passed to install script. Not downloading/updating local repos" - else - # Pull the latest commits - echo -n "::: Updating repo in $1..." - $SUDO rm -rf "${1}" - # Go back to /etc otherwhise git will complain when the current working directory has - # just been deleted (/etc/.pivpn). - cd /etc - $SUDO git clone -q --depth 1 --no-single-branch "${2}" "${1}" > /dev/null & spinner $! - cd "${1}" || exit 1 - if [ -z "${TESTING+x}" ]; then - : - else - ${SUDOE} git checkout test - fi - echo " done!" - fi -} - -setCustomProto() { - # Set the available protocols into an array so it can be used with a whiptail dialog - if protocol=$(whiptail --title "Protocol" --radiolist \ - "Choose a protocol (press space to select). Please only choose TCP if you know why you need TCP." ${r} ${c} 2 \ - "UDP" "" ON \ - "TCP" "" OFF 3>&1 1>&2 2>&3) - then - # Convert option into lowercase (UDP->udp) - pivpnProto="${protocol,,}" - echo "::: Using protocol: $pivpnProto" - echo "${pivpnProto}" > /tmp/pivpnPROTO - else - echo "::: Cancel selected, exiting...." - exit 1 - fi - # write out the PROTO - PROTO=$pivpnProto - $SUDO cp /tmp/pivpnPROTO /etc/pivpn/INSTALL_PROTO -} - - -setCustomPort() { - until [[ $PORTNumCorrect = True ]] - do - portInvalid="Invalid" - - PROTO=$(cat /etc/pivpn/INSTALL_PROTO) - if [ "$PROTO" = "udp" ]; then - DEFAULT_PORT=1194 - else - DEFAULT_PORT=443 - fi - if PORT=$(whiptail --title "Default OpenVPN Port" --inputbox "You can modify the default OpenVPN port. \nEnter a new value or hit 'Enter' to retain the default" ${r} ${c} $DEFAULT_PORT 3>&1 1>&2 2>&3) - then - if [[ "$PORT" =~ ^[0-9]+$ ]] && [ "$PORT" -ge 1 ] && [ "$PORT" -le 65535 ]; then - : - else - PORT=$portInvalid - fi - else - echo "::: Cancel selected, exiting...." - exit 1 - fi - - if [[ $PORT == "$portInvalid" ]]; then - whiptail --msgbox --backtitle "Invalid Port" --title "Invalid Port" "You entered an invalid Port number.\n Please enter a number from 1 - 65535.\n If you are not sure, please just keep the default." ${r} ${c} - PORTNumCorrect=False - else - if (whiptail --backtitle "Specify Custom Port" --title "Confirm Custom Port Number" --yesno "Are these settings correct?\n PORT: $PORT" ${r} ${c}) then - PORTNumCorrect=True - else - # If the settings are wrong, the loop continues - PORTNumCorrect=False - fi - fi - done - # write out the port - echo ${PORT} > /tmp/INSTALL_PORT - $SUDO cp /tmp/INSTALL_PORT /etc/pivpn/INSTALL_PORT -} - -setClientDNS() { - DNSChoseCmd=(whiptail --separate-output --radiolist "Select the DNS Provider for your VPN Clients (press space to select). To use your own, select Custom." ${r} ${c} 6) - DNSChooseOptions=(Google "" on - OpenDNS "" off - Level3 "" off - DNS.WATCH "" off - Norton "" off - FamilyShield "" off - CloudFlare "" off - Custom "" off) - - if DNSchoices=$("${DNSChoseCmd[@]}" "${DNSChooseOptions[@]}" 2>&1 >/dev/tty) - then - - if [[ ${DNSchoices} != "Custom" ]]; then - - echo "::: Using ${DNSchoices} servers." - declare -A DNS_MAP=(["Google"]="8.8.8.8 8.8.4.4" ["OpenDNS"]="208.67.222.222 208.67.220.220" ["Level3"]="209.244.0.3 209.244.0.4" ["DNS.WATCH"]="84.200.69.80 84.200.70.40" ["Norton"]="199.85.126.10 199.85.127.10" ["FamilyShield"]="208.67.222.123 208.67.220.123" ["CloudFlare"]="1.1.1.1 1.0.0.1") - - OVPNDNS1=$(awk '{print $1}' <<< "${DNS_MAP["${DNSchoices}"]}") - OVPNDNS2=$(awk '{print $2}' <<< "${DNS_MAP["${DNSchoices}"]}") - - $SUDO sed -i '0,/\(dhcp-option DNS \)/ s/\(dhcp-option DNS \).*/\1'${OVPNDNS1}'\"/' /etc/openvpn/server.conf - $SUDO sed -i '0,/\(dhcp-option DNS \)/! s/\(dhcp-option DNS \).*/\1'${OVPNDNS2}'\"/' /etc/openvpn/server.conf - - else - - until [[ $DNSSettingsCorrect = True ]] - do - strInvalid="Invalid" - - if OVPNDNS=$(whiptail --backtitle "Specify Upstream DNS Provider(s)" --inputbox "Enter your desired upstream DNS provider(s), separated by a comma.\n\nFor example '8.8.8.8, 8.8.4.4'" ${r} ${c} "" 3>&1 1>&2 2>&3) - then - OVPNDNS1=$(echo "$OVPNDNS" | sed 's/[, \t]\+/,/g' | awk -F, '{print$1}') - OVPNDNS2=$(echo "$OVPNDNS" | sed 's/[, \t]\+/,/g' | awk -F, '{print$2}') - if ! valid_ip "$OVPNDNS1" || [ ! "$OVPNDNS1" ]; then - OVPNDNS1=$strInvalid - fi - if ! valid_ip "$OVPNDNS2" && [ "$OVPNDNS2" ]; then - OVPNDNS2=$strInvalid - fi - else - echo "::: Cancel selected, exiting...." - exit 1 - fi - if [[ $OVPNDNS1 == "$strInvalid" ]] || [[ $OVPNDNS2 == "$strInvalid" ]]; then - whiptail --msgbox --backtitle "Invalid IP" --title "Invalid IP" "One or both entered IP addresses were invalid. Please try again.\n\n DNS Server 1: $OVPNDNS1\n DNS Server 2: $OVPNDNS2" ${r} ${c} - if [[ $OVPNDNS1 == "$strInvalid" ]]; then - OVPNDNS1="" - fi - if [[ $OVPNDNS2 == "$strInvalid" ]]; then - OVPNDNS2="" - fi - DNSSettingsCorrect=False - else - if (whiptail --backtitle "Specify Upstream DNS Provider(s)" --title "Upstream DNS Provider(s)" --yesno "Are these settings correct?\n DNS Server 1: $OVPNDNS1\n DNS Server 2: $OVPNDNS2" ${r} ${c}) then - DNSSettingsCorrect=True - $SUDO sed -i '0,/\(dhcp-option DNS \)/ s/\(dhcp-option DNS \).*/\1'${OVPNDNS1}'\"/' /etc/openvpn/server.conf - if [ -z ${OVPNDNS2} ]; then - $SUDO sed -i '/\(dhcp-option DNS \)/{n;N;d}' /etc/openvpn/server.conf - else - $SUDO sed -i '0,/\(dhcp-option DNS \)/! s/\(dhcp-option DNS \).*/\1'${OVPNDNS2}'\"/' /etc/openvpn/server.conf - fi - else - # If the settings are wrong, the loop continues - DNSSettingsCorrect=False - fi - fi - done - fi - - else - echo "::: Cancel selected. Exiting..." - exit 1 - fi + echo "pivpnDNS1=${pivpnDNS1}" >> /tmp/setupVars.conf + echo "pivpnDNS2=${pivpnDNS2}" >> /tmp/setupVars.conf } #This procedure allows a user to specify a custom search domain if they have one. -setCustomDomain() { - DomainSettingsCorrect=False +askCustomDomain(){ + DomainSettingsCorrect=False - if (whiptail --backtitle "Custom Search Domain" --title "Custom Search Domain" --yesno "Would you like to add a custom search domain? \n (This is only for advanced users who have their own domain)\n" ${r} ${c}); then + if (whiptail --backtitle "Custom Search Domain" --title "Custom Search Domain" --yesno "Would you like to add a custom search domain? \n (This is only for advanced users who have their own domain)\n" ${r} ${c}); then - until [[ $DomainSettingsCorrect = True ]] - do - if CUSTOMDomain=$(whiptail --inputbox "Enter Custom Domain\nFormat: mydomain.com" ${r} ${c} --title "Custom Domain" 3>&1 1>&2 2>&3); then - if valid_domain "$CUSTOMDomain"; then - if (whiptail --backtitle "Custom Search Domain" --title "Custom Search Domain" --yesno "Are these settings correct?\n Custom Search Domain: $CUSTOMDomain" ${r} ${c}); then - DomainSettingsCorrect=True + until [[ $DomainSettingsCorrect = True ]] + do + if pivpnDOMAIN=$(whiptail --inputbox "Enter Custom Domain\nFormat: mydomain.com" ${r} ${c} --title "Custom Domain" 3>&1 1>&2 2>&3); then + if validDomain "$pivpnDOMAIN"; then + if (whiptail --backtitle "Custom Search Domain" --title "Custom Search Domain" --yesno "Are these settings correct?\n Custom Search Domain: $pivpnDOMAIN" ${r} ${c}); then + DomainSettingsCorrect=True + echo "pivpnDOMAIN=${pivpnDOMAIN}" >> /tmp/setupVars.conf + else + # If the settings are wrong, the loop continues + DomainSettingsCorrect=False + fi + else + whiptail --msgbox --backtitle "Invalid Domain" --title "Invalid Domain" "Domain is invalid. Please try again.\n\n DOMAIN: $pivpnDOMAIN\n" ${r} ${c} + DomainSettingsCorrect=False + fi + else + echo "::: Cancel selected. Exiting..." + exit 1 + fi + done - $SUDO sed -i '0,/\(.*dhcp-option.*\)/s//\push "dhcp-option DOMAIN '${CUSTOMDomain}'" \n&/' /etc/openvpn/server.conf - - else - # If the settings are wrong, the loop continues - DomainSettingsCorrect=False - fi - else - whiptail --msgbox --backtitle "Invalid Domain" --title "Invalid Domain" "Domain is invalid. Please try again.\n\n DOMAIN: $CUSTOMDomain\n" ${r} ${c} - DomainSettingsCorrect=False - fi - else - echo "::: Cancel selected. Exiting..." - exit 1 - fi - done - - else - echo sleep 0.1 - fi + else + echo sleep 0.1 + fi } -confOpenVPN() { - # Grab the existing Hostname - host_name=$(hostname -s) - # Generate a random UUID for this server so that we can use verify-x509-name later that is unique for this server installation. - NEW_UUID=$(&1 1>&2 2>&3) - if [[ ${useUpdateVars} == false ]]; then - # Ask user for desired level of encryption + exitstatus=$? + if [ $exitstatus != 0 ]; then + echo "::: Cancel selected. Exiting..." + exit 1 + fi - if [[ ${useUpdateVars} == false ]]; then + if [ "$METH" == "$IPv4pub" ]; then + pivpnHOST="${IPv4pub}" + else + until [[ $publicDNSCorrect = True ]] + do + PUBLICDNS=$(whiptail --title "PiVPN Setup" --inputbox "What is the public DNS name of this Server?" ${r} ${c} 3>&1 1>&2 2>&3) + exitstatus=$? + if [ $exitstatus != 0 ]; then + echo "::: Cancel selected. Exiting..." + exit 1 + fi + if (whiptail --backtitle "Confirm DNS Name" --title "Confirm DNS Name" --yesno "Is this correct?\n\n Public DNS Name: $PUBLICDNS" ${r} ${c}) then + publicDNSCorrect=True + pivpnHOST="${PUBLICDNS}" + else + publicDNSCorrect=False + fi + done + fi - if [[ ${PLAT} == "Raspbian" ]] && [[ ${OSCN} != "stretch" ]] && [[ ${OSCN} != "buster" ]] ; then + echo "pivpnHOST=${pivpnHOST}" >> /tmp/setupVars.conf +} - APPLY_TWO_POINT_FOUR=false - else - if (whiptail --backtitle "Setup OpenVPN" --title "Installation mode" --yesno "OpenVPN 2.4 brings support for stronger authentication and key exchange using Elliptic Curves, along with encrypted control channel.\n\nIf your clients do run OpenVPN 2.4 or later you can enable these features, otherwise choose 'No' for best compatibility.\n\nNOTE: Current mobile app, that is OpenVPN connect, is supported." ${r} ${c}); then - APPLY_TWO_POINT_FOUR=true - $SUDO touch /etc/pivpn/TWO_POINT_FOUR - else - APPLY_TWO_POINT_FOUR=false - fi - fi - fi +askEncryption(){ + pivpnENCRYPT=$(whiptail --backtitle "Setup OpenVPN" --title "RSA certificate size" --radiolist \ + "Choose the desired size of your certificate (press space to select):\nThis is a certificate that will be generated on your system. The larger the certificate, the more time this will take. For most applications, it is recommended to use 2048 bits. If you are paranoid about ... things... then grab a cup of joe and pick 4096 bits." ${r} ${c} 3 \ + "2048" "Use a 2048-bit certificate (recommended level)" ON \ + "3072" "Use a 3072-bit certificate " OFF \ + "4096" "Use a 4096-bit certificate (paranoid level)" OFF 3>&1 1>&2 2>&3) - if [[ ${runUnattended} == true ]] && [[ ${APPLY_TWO_POINT_FOUR} == true ]]; then - $SUDO touch /etc/pivpn/TWO_POINT_FOUR - fi + exitstatus=$? + if [ $exitstatus != 0 ]; then + echo "::: Cancel selected. Exiting..." + exit 1 + fi - if [[ ${APPLY_TWO_POINT_FOUR} == false ]]; then + if ([ "$pivpnENCRYPT" -ge "3072" ] && whiptail --backtitle "Setup OpenVPN" --title "Download Diffie-Hellman Parameters" --yesno --defaultno "Download Diffie-Hellman parameters from a public DH parameter generation service?\n\nGenerating DH parameters for a $pivpnENCRYPT-bit key can take many hours on a Raspberry Pi. You can instead download DH parameters from \"2 Ton Digital\" that are generated at regular intervals as part of a public service. Downloaded DH parameters will be randomly selected from their database.\nMore information about this service can be found here: https://2ton.com.au/safeprimes/\n\nIf you're paranoid, choose 'No' and Diffie-Hellman parameters will be generated on your device." ${r} ${c}); then + DOWNLOAD_DH_PARAM=true + else + DOWNLOAD_DH_PARAM=false + fi - ENCRYPT=$(whiptail --backtitle "Setup OpenVPN" --title "RSA certificate size" --radiolist \ - "Choose the desired size of your certificate (press space to select):\n This is a certificate that will be generated on your system. The larger the certificate, the more time this will take. For most applications, it is recommended to use 2048 bits. If you are testing, you can use 1024 bits to speed things up, but do not use this for normal use! If you are paranoid about ... things... then grab a cup of joe and pick 4096 bits." ${r} ${c} 3 \ - "1024" "Use a 1024-bit certificate (testing only)" OFF \ - "2048" "Use a 2048-bit certificate (recommended level)" ON \ - "4096" "Use a 4096-bit certificate (paranoid level)" OFF 3>&1 1>&2 2>&3) + echo "pivpnENCRYPT=${pivpnENCRYPT}" >> /tmp/setupVars.conf + echo "DOWNLOAD_DH_PARAM=${DOWNLOAD_DH_PARAM}" >> /tmp/setupVars.conf +} - else +confOpenVPN(){ + # Grab the existing Hostname + host_name=$(hostname -s) + # Generate a random UUID for this server so that we can use verify-x509-name later that is unique for this server installation. + NEW_UUID=$(&1 1>&2 2>&3) + # If easy-rsa exists, remove it + if [[ -d /etc/openvpn/easy-rsa/ ]]; then + $SUDO rm -rf /etc/openvpn/easy-rsa/ + fi - fi + # Get easy-rsa + wget -q -O - "${easyrsaRel}" | $SUDO tar xz -C /etc/openvpn && $SUDO mv /etc/openvpn/EasyRSA-v${easyrsaVer} /etc/openvpn/easy-rsa + # fix ownership + $SUDO chown -R root:root /etc/openvpn/easy-rsa + $SUDO mkdir /etc/openvpn/easy-rsa/pki - exitstatus=$? - if [ $exitstatus != 0 ]; then - echo "::: Cancel selected. Exiting..." - exit 1 - fi - fi + cd /etc/openvpn/easy-rsa || exit - # If easy-rsa exists, remove it - if [[ -d /etc/openvpn/easy-rsa/ ]]; then - $SUDO rm -rf /etc/openvpn/easy-rsa/ - fi - - - # Get easy-rsa - wget -q -O - "${easyrsaRel}" | $SUDO tar xz -C /etc/openvpn && $SUDO mv /etc/openvpn/EasyRSA-v${easyrsaVer} /etc/openvpn/easy-rsa - # fix ownership - $SUDO chown -R root:root /etc/openvpn/easy-rsa - $SUDO mkdir /etc/openvpn/easy-rsa/pki - - cd /etc/openvpn/easy-rsa || exit - - # Write out new vars file - set +e - IFS= read -d '' String <<"EOF" -if [ -z "$EASYRSA_CALLER" ]; then - echo "Nope." >&2 - return 1 + # Write out new vars file + echo "if [ -z \"\$EASYRSA_CALLER\" ]; then + echo \"Nope.\" >&2 + return 1 fi -set_var EASYRSA "/etc/openvpn/easy-rsa" -set_var EASYRSA_PKI "$EASYRSA/pki" +set_var EASYRSA \"/etc/openvpn/easy-rsa\" +set_var EASYRSA_PKI \"\$EASYRSA/pki\" set_var EASYRSA_CRL_DAYS 3650 -EOF - echo "${String}" | $SUDO tee vars >/dev/null - set -e +set_var EASYRSA_ALGO rsa +set_var EASYRSA_KEY_SIZE ${pivpnENCRYPT}" | $SUDO tee vars >/dev/null - # Set certificate type - if [[ ${APPLY_TWO_POINT_FOUR} == false ]]; then - echo "set_var EASYRSA_ALGO rsa" | $SUDO tee -a vars - echo "set_var EASYRSA_KEY_SIZE ${ENCRYPT}" | $SUDO tee -a vars - else - echo "set_var EASYRSA_ALGO ec" | $SUDO tee -a vars - echo "set_var EASYRSA_CURVE ${ECDSA_MAP["${ENCRYPT}"]}" | $SUDO tee -a vars - fi + # Remove any previous keys + ${SUDOE} ./easyrsa --batch init-pki - # Remove any previous keys - ${SUDOE} ./easyrsa --batch init-pki + # Build the certificate authority + printf "::: Building CA...\n" + ${SUDOE} ./easyrsa --batch build-ca nopass + printf "\n::: CA Complete.\n" - # Build the certificate authority - printf "::: Building CA...\n" - ${SUDOE} ./easyrsa --batch build-ca nopass - printf "\n::: CA Complete.\n" + whiptail --msgbox --backtitle "Setup OpenVPN" --title "Server Information" "The server key, Diffie-Hellman parameters, and HMAC key will now be generated." ${r} ${c} - if [[ ${useUpdateVars} == false ]]; then - if [[ ${APPLY_TWO_POINT_FOUR} == false ]]; then - whiptail --msgbox --backtitle "Setup OpenVPN" --title "Server Information" "The server key, Diffie-Hellman parameters, and HMAC key will now be generated." ${r} ${c} - fi - fi + # Build the server + EASYRSA_CERT_EXPIRE=3650 ${SUDOE} ./easyrsa build-server-full ${SERVER_NAME} nopass - # Build the server - EASYRSA_CERT_EXPIRE=3650 ${SUDOE} ./easyrsa build-server-full ${SERVER_NAME} nopass + if [[ ${DOWNLOAD_DH_PARAM} == true ]]; then + # Downloading parameters + ${SUDOE} curl "https://2ton.com.au/getprimes/random/dhparam/${pivpnENCRYPT}" -o "/etc/openvpn/easy-rsa/pki/dh${pivpnENCRYPT}.pem" + else + # Generate Diffie-Hellman key exchange + ${SUDOE} ./easyrsa gen-dh + ${SUDOE} mv pki/dh.pem pki/dh${pivpnENCRYPT}.pem + fi - if [[ ${useUpdateVars} == false ]]; then - if [[ ${APPLY_TWO_POINT_FOUR} == false ]]; then - if ([ "$ENCRYPT" -ge "4096" ] && whiptail --backtitle "Setup OpenVPN" --title "Download Diffie-Hellman Parameters" --yesno --defaultno "Download Diffie-Hellman parameters from a public DH parameter generation service?\n\nGenerating DH parameters for a $ENCRYPT-bit key can take many hours on a Raspberry Pi. You can instead download DH parameters from \"2 Ton Digital\" that are generated at regular intervals as part of a public service. Downloaded DH parameters will be randomly selected from their database.\nMore information about this service can be found here: https://2ton.com.au/safeprimes/\n\nIf you're paranoid, choose 'No' and Diffie-Hellman parameters will be generated on your device." ${r} ${c}); then - DOWNLOAD_DH_PARAM=true - else - DOWNLOAD_DH_PARAM=false - fi - else - DOWNLOAD_DH_PARAM=false - fi - fi + # Generate static HMAC key to defend against DDoS + ${SUDOE} openvpn --genkey --secret pki/ta.key - if [[ ${APPLY_TWO_POINT_FOUR} == false ]]; then - if [ "$ENCRYPT" -ge "4096" ] && [[ ${DOWNLOAD_DH_PARAM} == true ]]; then - # Downloading parameters - ${SUDOE} curl "https://2ton.com.au/getprimes/random/dhparam/${ENCRYPT}" -o "/etc/openvpn/easy-rsa/pki/dh${ENCRYPT}.pem" - else - # Generate Diffie-Hellman key exchange - ${SUDOE} ./easyrsa gen-dh - ${SUDOE} mv pki/dh.pem pki/dh${ENCRYPT}.pem - fi - fi + # Generate an empty Certificate Revocation List + ${SUDOE} ./easyrsa gen-crl + ${SUDOE} cp pki/crl.pem /etc/openvpn/crl.pem + ${SUDOE} chown nobody:nogroup /etc/openvpn/crl.pem - # Generate static HMAC key to defend against DDoS - ${SUDOE} openvpn --genkey --secret pki/ta.key + # Write config file for server using the template.txt file + $SUDO cp /etc/.pivpn/server_config.txt /etc/openvpn/server.conf - # Generate an empty Certificate Revocation List - ${SUDOE} ./easyrsa gen-crl - ${SUDOE} cp pki/crl.pem /etc/openvpn/crl.pem - ${SUDOE} chown nobody:nogroup /etc/openvpn/crl.pem + # Apply client DNS settings + ${SUDOE} sed -i '0,/\(dhcp-option DNS \)/ s/\(dhcp-option DNS \).*/\1'${pivpnDNS1}'\"/' /etc/openvpn/server.conf - # Write config file for server using the template.txt file - $SUDO cp /etc/.pivpn/server_config.txt /etc/openvpn/server.conf + if [ -z ${pivpnDNS2} ]; then + ${SUDOE} sed -i '/\(dhcp-option DNS \)/{n;N;d}' /etc/openvpn/server.conf + else + ${SUDOE} sed -i '0,/\(dhcp-option DNS \)/! s/\(dhcp-option DNS \).*/\1'${pivpnDNS2}'\"/' /etc/openvpn/server.conf + fi - if [[ ${APPLY_TWO_POINT_FOUR} == true ]]; then - #If they enabled 2.4 use tls-crypt instead of tls-auth to encrypt control channel - $SUDO sed -i "s/tls-auth \/etc\/openvpn\/easy-rsa\/pki\/ta.key 0/tls-crypt \/etc\/openvpn\/easy-rsa\/pki\/ta.key/" /etc/openvpn/server.conf - fi + # Set the user encryption key size + $SUDO sed -i "s/\(dh \/etc\/openvpn\/easy-rsa\/pki\/dh\).*/\1${pivpnENCRYPT}.pem/" /etc/openvpn/server.conf - if [[ ${APPLY_TWO_POINT_FOUR} == true ]]; then - #If they enabled 2.4 disable dh parameters since the key exchange will use the matching curve from the ECDSA certificate - $SUDO sed -i "s/\(dh \/etc\/openvpn\/easy-rsa\/pki\/dh\).*/dh none/" /etc/openvpn/server.conf - else - # Otherwise set the user encryption key size - $SUDO sed -i "s/\(dh \/etc\/openvpn\/easy-rsa\/pki\/dh\).*/\1${ENCRYPT}.pem/" /etc/openvpn/server.conf - fi + # if they modified port put value in server.conf + if [ "$pivpnPORT" != 1194 ]; then + $SUDO sed -i "s/1194/${pivpnPORT}/g" /etc/openvpn/server.conf + fi - # if they modified port put value in server.conf - if [ $PORT != 1194 ]; then - $SUDO sed -i "s/1194/${PORT}/g" /etc/openvpn/server.conf - fi + # if they modified protocol put value in server.conf + if [ "$pivpnPROTO" != "udp" ]; then + $SUDO sed -i "s/proto udp/proto tcp/g" /etc/openvpn/server.conf + fi - # if they modified protocol put value in server.conf - if [ "$PROTO" != "udp" ]; then - $SUDO sed -i "s/proto udp/proto tcp/g" /etc/openvpn/server.conf - fi - - # write out server certs to conf file - $SUDO sed -i "s/\(key \/etc\/openvpn\/easy-rsa\/pki\/private\/\).*/\1${SERVER_NAME}.key/" /etc/openvpn/server.conf - $SUDO sed -i "s/\(cert \/etc\/openvpn\/easy-rsa\/pki\/issued\/\).*/\1${SERVER_NAME}.crt/" /etc/openvpn/server.conf + # write out server certs to conf file + $SUDO sed -i "s/\(key \/etc\/openvpn\/easy-rsa\/pki\/private\/\).*/\1${SERVER_NAME}.key/" /etc/openvpn/server.conf + $SUDO sed -i "s/\(cert \/etc\/openvpn\/easy-rsa\/pki\/issued\/\).*/\1${SERVER_NAME}.crt/" /etc/openvpn/server.conf } -confUnattendedUpgrades() { - cd /etc/apt/apt.conf.d +confOVPN(){ + $SUDO cp /etc/.pivpn/Default.txt /etc/openvpn/easy-rsa/pki/Default.txt - if [[ $UNATTUPG == "unattended-upgrades" ]]; then - $SUDO $PKG_MANAGER --yes --quiet --no-install-recommends install "$UNATTUPG" > /dev/null & spinner $! - if [[ $PLAT == "Ubuntu" ]]; then - # Ubuntu 50unattended-upgrades should already just have security enabled - # so we just need to configure the 10periodic file - cat << EOT | $SUDO tee 10periodic >/dev/null - APT::Periodic::Update-Package-Lists "1"; - APT::Periodic::Download-Upgradeable-Packages "1"; - APT::Periodic::AutocleanInterval "5"; - APT::Periodic::Unattended-Upgrade "1"; -EOT - else - # Fix Raspbian config - if [[ $PLAT == "Raspbian" ]]; then - wget -q -O - "$UNATTUPG_CONFIG" | $SUDO tar xz - $SUDO cp "unattended-upgrades-$UNATTUPG_RELEASE/data/50unattended-upgrades.Raspbian" 50unattended-upgrades - $SUDO rm -rf "unattended-upgrades-$UNATTUPG_RELEASE" - fi + $SUDO sed -i 's/IPv4pub/'"$pivpnHOST"'/' /etc/openvpn/easy-rsa/pki/Default.txt - # Add the remaining settings for all other distributions - cat << EOT | $SUDO tee 02periodic >/dev/null - APT::Periodic::Enable "1"; - APT::Periodic::Update-Package-Lists "1"; - APT::Periodic::Download-Upgradeable-Packages "1"; - APT::Periodic::Unattended-Upgrade "1"; - APT::Periodic::AutocleanInterval "7"; - APT::Periodic::Verbose "0"; -EOT - fi - fi + # if they modified port put value in Default.txt for clients to use + if [ "$pivpnPORT" != 1194 ]; then + $SUDO sed -i -e "s/1194/${pivpnPORT}/g" /etc/openvpn/easy-rsa/pki/Default.txt + fi + # if they modified protocol put value in Default.txt for clients to use + if [ "$pivpnPROTO" != "udp" ]; then + $SUDO sed -i -e "s/proto udp/proto tcp/g" /etc/openvpn/easy-rsa/pki/Default.txt + fi + + # verify server name to strengthen security + $SUDO sed -i "s/SRVRNAME/${SERVER_NAME}/" /etc/openvpn/easy-rsa/pki/Default.txt + + if [ ! -d "$install_home/ovpns" ]; then + $SUDO mkdir "$install_home/ovpns" + fi + $SUDO chmod 0750 "$install_home/ovpns" + $SUDO chown $install_user:$install_user "$install_home/ovpns" } -confNetwork() { - # Enable forwarding of internet traffic - $SUDO sed -i '/net.ipv4.ip_forward=1/s/^#//g' /etc/sysctl.conf - $SUDO sysctl -p +confWireGuard(){ + whiptail --title "Server Information" --msgbox "The Server Keys and Pre-Shared key will now be generated." "${r}" "${c}" + $SUDO mkdir /etc/wireguard/configs + $SUDO touch /etc/wireguard/configs/clients.txt + $SUDO mkdir /etc/wireguard/keys - # if ufw enabled, configure that (running as root because sometimes the executable is not in the user's $PATH, on Debian for example) - if $SUDO bash -c 'hash ufw' 2>/dev/null; then - if LANG=en_US.UTF-8 $SUDO ufw status | grep -q inactive - then - noUFW=1 - else - echo "::: Detected UFW is enabled." - echo "::: Adding UFW rules..." - $SUDO sed "/delete these required/i *nat\n:POSTROUTING ACCEPT [0:0]\n-I POSTROUTING -s 10.8.0.0/24 -o $IPv4dev -j MASQUERADE\nCOMMIT\n" -i /etc/ufw/before.rules - # Insert rules at the beginning of the chain (in case there are other rules that may drop the traffic) - $SUDO ufw insert 1 allow "$PORT"/"$PROTO" >/dev/null + # Generate private key and derive public key from it + wg genkey | $SUDO tee /etc/wireguard/keys/server_priv &> /dev/null + wg genpsk | $SUDO tee /etc/wireguard/keys/psk &> /dev/null + $SUDO cat /etc/wireguard/keys/server_priv | wg pubkey | $SUDO tee /etc/wireguard/keys/server_pub &> /dev/null - # https://askubuntu.com/a/712202 - INSTALLED_UFW=$(dpkg-query --showformat='${Version}' --show ufw) - MINIMUM_UFW=0.34 + echo "::: Server Keys and Pre-Shared Key have been generated." - if $SUDO dpkg --compare-versions "$INSTALLED_UFW" ge "$MINIMUM_UFW"; then - # Don't forward everything, just the traffic originated from the VPN subnet - $SUDO ufw route insert 1 allow in on tun0 from 10.8.0.0/24 out on "$IPv4dev" to any >/dev/null - echo 0 > /tmp/OLD_UFW - else - # This ufw version does not support route command, fallback to policy change - $SUDO sed -i "s/\(DEFAULT_FORWARD_POLICY=\).*/\1\"ACCEPT\"/" /etc/default/ufw - echo 1 > /tmp/OLD_UFW - fi - - $SUDO ufw reload >/dev/null - echo "::: UFW configuration completed." - fi - else - noUFW=1 - fi - # else configure iptables - if [[ $noUFW -eq 1 ]]; then - echo 1 > /tmp/noUFW - - # Now some checks to detect which rules we need to add. On a newly installed system all policies - # should be ACCEPT, so the only required rule would be the MASQUERADE one. - - $SUDO iptables -t nat -I POSTROUTING -s 10.8.0.0/24 -o "$IPv4dev" -j MASQUERADE - - # Count how many rules are in the INPUT and FORWARD chain. When parsing input from - # iptables -S, '^-P' skips the policies and 'ufw-' skips ufw chains (in case ufw was found - # installed but not enabled). - - # Grep returns non 0 exit code where there are no matches, however that would make the script exit, - # for this reasons we use '|| true' to force exit code 0 - INPUT_RULES_COUNT="$($SUDO iptables -S INPUT | grep -vcE '(^-P|ufw-)' || true)" - FORWARD_RULES_COUNT="$($SUDO iptables -S FORWARD | grep -vcE '(^-P|ufw-)' || true)" - - INPUT_POLICY="$($SUDO iptables -S INPUT | grep '^-P' | awk '{print $3}')" - FORWARD_POLICY="$($SUDO iptables -S FORWARD | grep '^-P' | awk '{print $3}')" - - # If rules count is not zero, we assume we need to explicitly allow traffic. Same conclusion if - # there are no rules and the policy is not ACCEPT. Note that rules are being added to the top of the - # chain (using -I). - - if [ "$INPUT_RULES_COUNT" -ne 0 ] || [ "$INPUT_POLICY" != "ACCEPT" ]; then - $SUDO iptables -I INPUT 1 -i "$IPv4dev" -p "$PROTO" --dport "$PORT" -j ACCEPT - INPUT_CHAIN_EDITED=1 - else - INPUT_CHAIN_EDITED=0 - fi - - if [ "$FORWARD_RULES_COUNT" -ne 0 ] || [ "$FORWARD_POLICY" != "ACCEPT" ]; then - $SUDO iptables -I FORWARD 1 -d 10.8.0.0/24 -i "$IPv4dev" -o tun0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT - $SUDO iptables -I FORWARD 2 -s 10.8.0.0/24 -i tun0 -o "$IPv4dev" -j ACCEPT - FORWARD_CHAIN_EDITED=1 - else - FORWARD_CHAIN_EDITED=0 - fi - - case ${PLAT} in - Ubuntu|Debian|Devuan) - $SUDO iptables-save | $SUDO tee /etc/iptables/rules.v4 > /dev/null - ;; - *) - $SUDO netfilter-persistent save - ;; - esac - else - echo 0 > /tmp/noUFW - fi - - echo "$INPUT_CHAIN_EDITED" > /tmp/INPUT_CHAIN_EDITED - echo "$FORWARD_CHAIN_EDITED" > /tmp/FORWARD_CHAIN_EDITED - - $SUDO cp /tmp/noUFW /etc/pivpn/NO_UFW - $SUDO cp /tmp/OLD_UFW /etc/pivpn/OLD_UFW - $SUDO cp /tmp/INPUT_CHAIN_EDITED /etc/pivpn/INPUT_CHAIN_EDITED - $SUDO cp /tmp/FORWARD_CHAIN_EDITED /etc/pivpn/FORWARD_CHAIN_EDITED + echo "[Interface] +PrivateKey = $($SUDO cat /etc/wireguard/keys/server_priv) +Address = 10.6.0.1/24 +ListenPort = ${pivpnPORT}" | $SUDO tee /etc/wireguard/wg0.conf &> /dev/null + echo "::: Server config generated." } -confOVPN() { - if ! IPv4pub=$(dig +short myip.opendns.com @208.67.222.222) || ! valid_ip "$IPv4pub"; then - echo "dig failed, now trying to curl checkip.amazonaws.com" - if ! IPv4pub=$(curl -s https://checkip.amazonaws.com) || ! valid_ip "$IPv4pub"; then - echo "checkip.amazonaws.com failed, please check your internet connection/DNS" - exit 1 - fi - fi - $SUDO cp /tmp/INSTALL_USER /etc/pivpn/INSTALL_USER - $SUDO cp /tmp/DET_PLATFORM /etc/pivpn/DET_PLATFORM +confNetwork(){ + # Enable forwarding of internet traffic + $SUDO sed -i '/net.ipv4.ip_forward=1/s/^#//g' /etc/sysctl.conf + $SUDO sysctl -p - $SUDO cp /etc/.pivpn/Default.txt /etc/openvpn/easy-rsa/pki/Default.txt + # if ufw enabled, configure that (running as root because sometimes the executable is not in the user's $PATH, on Debian for example) + if $SUDO bash -c 'hash ufw' 2>/dev/null; then + if LANG=en_US.UTF-8 $SUDO ufw status | grep -q inactive + then + USING_UFW=0 + else + USING_UFW=1 + echo "::: Detected UFW is enabled." + echo "::: Adding UFW rules..." + $SUDO sed "/delete these required/i *nat\n:POSTROUTING ACCEPT [0:0]\n-I POSTROUTING -s 10.8.0.0/24 -o $PHYS_INT -j MASQUERADE\nCOMMIT\n" -i /etc/ufw/before.rules + # Insert rules at the beginning of the chain (in case there are other rules that may drop the traffic) + $SUDO ufw insert 1 allow "$PORT"/"$PROTO" >/dev/null + $SUDO ufw route insert 1 allow in on "$pivpnINT" from 10.8.0.0/24 out on "$PHYS_INT" to any >/dev/null - if [[ ${APPLY_TWO_POINT_FOUR} == true ]]; then - #If they enabled 2.4 remove key-direction options since it's not required - $SUDO sed -i "/key-direction 1/d" /etc/openvpn/easy-rsa/pki/Default.txt - fi + $SUDO ufw reload >/dev/null + echo "::: UFW configuration completed." + fi + else + USING_UFW=0 + fi + # else configure iptables + if [[ $USING_UFW -eq 0 ]]; then + # Now some checks to detect which rules we need to add. On a newly installed system all policies + # should be ACCEPT, so the only required rule would be the MASQUERADE one. - if [[ ${useUpdateVars} == false ]]; then - METH=$(whiptail --title "Public IP or DNS" --radiolist "Will clients use a Public IP or DNS Name to connect to your server (press space to select)?" ${r} ${c} 2 \ - "$IPv4pub" "Use this public IP" "ON" \ - "DNS Entry" "Use a public DNS" "OFF" 3>&1 1>&2 2>&3) + $SUDO iptables -t nat -I POSTROUTING -s 10.8.0.0/24 -o "$PHYS_INT" -j MASQUERADE - exitstatus=$? - if [ $exitstatus != 0 ]; then - echo "::: Cancel selected. Exiting..." - exit 1 - fi + # Count how many rules are in the INPUT and FORWARD chain. When parsing input from + # iptables -S, '^-P' skips the policies and 'ufw-' skips ufw chains (in case ufw was found + # installed but not enabled). - if [ "$METH" == "$IPv4pub" ]; then - $SUDO sed -i 's/IPv4pub/'"$IPv4pub"'/' /etc/openvpn/easy-rsa/pki/Default.txt - else - until [[ $publicDNSCorrect = True ]] - do - PUBLICDNS=$(whiptail --title "PiVPN Setup" --inputbox "What is the public DNS name of this Server?" ${r} ${c} 3>&1 1>&2 2>&3) - exitstatus=$? - if [ $exitstatus != 0 ]; then - echo "::: Cancel selected. Exiting..." - exit 1 - fi - if (whiptail --backtitle "Confirm DNS Name" --title "Confirm DNS Name" --yesno "Is this correct?\n\n Public DNS Name: $PUBLICDNS" ${r} ${c}) then - publicDNSCorrect=True - $SUDO sed -i 's/IPv4pub/'"$PUBLICDNS"'/' /etc/openvpn/easy-rsa/pki/Default.txt - else - publicDNSCorrect=False - fi - done - fi - else - $SUDO sed -i 's/IPv4pub/'"$PUBLICDNS"'/' /etc/openvpn/easy-rsa/pki/Default.txt - fi + # Grep returns non 0 exit code where there are no matches, however that would make the script exit, + # for this reasons we use '|| true' to force exit code 0 + INPUT_RULES_COUNT="$($SUDO iptables -S INPUT | grep -vcE '(^-P|ufw-)')" + FORWARD_RULES_COUNT="$($SUDO iptables -S FORWARD | grep -vcE '(^-P|ufw-)')" - # if they modified port put value in Default.txt for clients to use - if [ $PORT != 1194 ]; then - $SUDO sed -i -e "s/1194/${PORT}/g" /etc/openvpn/easy-rsa/pki/Default.txt - fi + INPUT_POLICY="$($SUDO iptables -S INPUT | grep '^-P' | awk '{print $3}')" + FORWARD_POLICY="$($SUDO iptables -S FORWARD | grep '^-P' | awk '{print $3}')" - # if they modified protocol put value in Default.txt for clients to use - if [ "$PROTO" != "udp" ]; then - $SUDO sed -i -e "s/proto udp/proto tcp/g" /etc/openvpn/easy-rsa/pki/Default.txt - fi + # If rules count is not zero, we assume we need to explicitly allow traffic. Same conclusion if + # there are no rules and the policy is not ACCEPT. Note that rules are being added to the top of the + # chain (using -I). - # verify server name to strengthen security - $SUDO sed -i "s/SRVRNAME/${SERVER_NAME}/" /etc/openvpn/easy-rsa/pki/Default.txt + if [ "$INPUT_RULES_COUNT" -ne 0 ] || [ "$INPUT_POLICY" != "ACCEPT" ]; then + $SUDO iptables -I INPUT 1 -i "$PHYS_INT" -p "$PROTO" --dport "$PORT" -j ACCEPT + INPUT_CHAIN_EDITED=1 + else + INPUT_CHAIN_EDITED=0 + fi - INSTALL_HOME=$(grep -m1 "^${INSTALL_USER}:" /etc/passwd | cut -d: -f6) - INSTALL_HOME=${INSTALL_HOME%/} # remove possible trailing slash - if [ ! -d "$INSTALL_HOME/ovpns" ]; then - $SUDO mkdir "$INSTALL_HOME/ovpns" - fi - $SUDO chmod 0750 "$INSTALL_HOME/ovpns" - $SUDO chown $INSTALL_USER:$INSTALL_USER "$INSTALL_HOME/ovpns" + if [ "$FORWARD_RULES_COUNT" -ne 0 ] || [ "$FORWARD_POLICY" != "ACCEPT" ]; then + $SUDO iptables -I FORWARD 1 -d 10.8.0.0/24 -i "$PHYS_INT" -o "$pivpnINT" -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT + $SUDO iptables -I FORWARD 2 -s 10.8.0.0/24 -i "$pivpnINT" -o "$PHYS_INT" -j ACCEPT + FORWARD_CHAIN_EDITED=1 + else + FORWARD_CHAIN_EDITED=0 + fi + + case ${PLAT} in + Raspbian) + $SUDO iptables-save | $SUDO tee /etc/iptables/rules.v4 > /dev/null + ;; + esac + + echo "INPUT_CHAIN_EDITED=${INPUT_CHAIN_EDITED}" >> /tmp/setupVars.conf + echo "FORWARD_CHAIN_EDITED=${FORWARD_CHAIN_EDITED}" >> /tmp/setupVars.conf + fi + + echo "USING_UFW=${USING_UFW}" >> /tmp/setupVars.conf } confLogging() { @@ -1139,361 +1090,232 @@ if \$programname == 'ovpn-server' then stop" | $SUDO tee /etc/rsyslog.d/30-openv echo "/var/log/openvpn.log { - rotate 4 - weekly - missingok - notifempty - compress - delaycompress - sharedscripts - postrotate - invoke-rc.d rsyslog rotate >/dev/null 2>&1 || true - endscript + rotate 4 + weekly + missingok + notifempty + compress + delaycompress + sharedscripts + postrotate + invoke-rc.d rsyslog rotate >/dev/null 2>&1 || true + endscript }" | $SUDO tee /etc/logrotate.d/openvpn > /dev/null # Restart the logging service - case ${PLAT} in - Ubuntu|Debian|*vuan) - $SUDO service rsyslog restart || true - ;; - *) - $SUDO systemctl restart rsyslog.service || true - ;; - esac + case ${PLAT} in + Raspbian) + $SUDO systemctl restart rsyslog.service || true + ;; + esac } -finalExports() { - # Update variables in setupVars.conf file - if [ -e "${setupVars}" ]; then - $SUDO sed -i.update.bak '/INSTALL_USER/d;/UNATTUPG/d;/pivpnInterface/d;/IPv4dns/d;/IPv4addr/d;/IPv4gw/d;/pivpnProto/d;/PORT/d;/ENCRYPT/d;/DOWNLOAD_DH_PARAM/d;/PUBLICDNS/d;/OVPNDNS1/d;/OVPNDNS2/d;' "${setupVars}" - fi - { - echo "INSTALL_USER=${INSTALL_USER}" - echo "UNATTUPG=${UNATTUPG}" - echo "pivpnInterface=${pivpnInterface}" - echo "IPv4dns=${IPv4dns}" - echo "IPv4addr=${IPv4addr}" - echo "IPv4gw=${IPv4gw}" - echo "pivpnProto=${pivpnProto}" - echo "PORT=${PORT}" - echo "ENCRYPT=${ENCRYPT}" - echo "APPLY_TWO_POINT_FOUR=${APPLY_TWO_POINT_FOUR}" - echo "DOWNLOAD_DH_PARAM=${DOWNLOAD_DH_PARAM}" - echo "PUBLICDNS=${PUBLICDNS}" - echo "OVPNDNS1=${OVPNDNS1}" - echo "OVPNDNS2=${OVPNDNS2}" - } | $SUDO tee "${setupVars}" > /dev/null +installPiVPN(){ + $SUDO mkdir -p /etc/pivpn/ + askWhichVPN + + if [ "$VPN" = "OpenVPN" ]; then + installOpenVPN + askCustomProto + askCustomPort + askClientDNS + askCustomDomain + askPublicIPOrDNS + askEncryption + confOpenVPN + confOVPN + confNetwork + confLogging + elif [ "$VPN" = "WireGuard" ]; then + installWireGuard + askCustomPort + askClientDNS + askPublicIPOrDNS + confWireGuard + confNetwork + fi } +askUnattendedUpgrades(){ + whiptail --msgbox --backtitle "Security Updates" --title "Unattended Upgrades" "Since this server will have at least one port open to the internet, it is recommended you enable unattended-upgrades.\nThis feature will check daily for security package updates only and apply them when necessary.\nIt will NOT automatically reboot the server so to fully apply some updates you should periodically reboot." ${r} ${c} -# I suggest replacing some of these names. + if (whiptail --backtitle "Security Updates" --title "Unattended Upgrades" --yesno "Do you want to enable unattended upgrades of security patches to this server?" ${r} ${c}); then + UNATTUPG=1 + PIVPN_DEPS=(unattended-upgrades) + installDependentPackages PIVPN_DEPS[@] + else + UNATTUPG=0 + fi -#accountForRefactor() { -# # At some point in the future this list can be pruned, for now we'll need it to ensure updates don't break. -# -# # Refactoring of install script has changed the name of a couple of variables. Sort them out here. -# sed -i 's/INSTALL_USER/PIVPN_USER/g' ${setupVars} -# #sed -i 's/UNATTUPG/UNATTUPG/g' ${setupVars} -# sed -i 's/pivpnInterface/PIVPN_INTERFACE/g' ${setupVars} -# sed -i 's/IPv4dns/IPV4_DNS/g' ${setupVars} -# sed -i 's/IPv4addr/IPV4_ADDRESS/g' ${setupVars} -# sed -i 's/IPv4gw/IPV4_GATEWAY/g' ${setupVars} -# sed -i 's/pivpnProto/TRANSPORT_LAYER/g' ${setupVars} -# #sed -i 's/PORT/PORT/g' ${setupVars} -# #sed -i 's/ENCRYPT/ENCRYPT/g' ${setupVars} -# #sed -i 's/DOWNLOAD_DH_PARAM/DOWNLOAD_DH_PARAM/g' ${setupVars} -# sed -i 's/PUBLICDNS/PUBLIC_DNS/g' ${setupVars} -# sed -i 's/OVPNDNS1/OVPN_DNS_1/g' ${setupVars} -# sed -i 's/OVPNDNS2/OVPN_DNS_2/g' ${setupVars} -#} - -installPiVPN() { - stopServices - $SUDO mkdir -p /etc/pivpn/ - confUnattendedUpgrades - installScripts - setCustomProto - setCustomPort - confOpenVPN - confNetwork - confOVPN - setClientDNS - setCustomDomain - confLogging - finalExports + echo "UNATTUPG=${UNATTUPG}" >> /tmp/setupVars.conf } -updatePiVPN() { - #accountForRefactor - stopServices - confUnattendedUpgrades - installScripts +confUnattendedUpgrades(){ + cd /etc/apt/apt.conf.d - # setCustomProto - # write out the PROTO - PROTO=$pivpnProto - $SUDO cp /tmp/pivpnPROTO /etc/pivpn/INSTALL_PROTO + wget -q -O- "$UNATTUPG_CONFIG" | $SUDO tar xz + $SUDO cp "unattended-upgrades-$UNATTUPG_RELEASE/data/50unattended-upgrades.Raspbian" 50unattended-upgrades + $SUDO rm -rf "unattended-upgrades-$UNATTUPG_RELEASE" - #setCustomPort - # write out the port - $SUDO cp /tmp/INSTALL_PORT /etc/pivpn/INSTALL_PORT + if [ "$VPN" = "WireGuard" ] && [ "$(uname -m)" = "armv7l" ]; then + sed -i '/Unattended-Upgrade::Origins-Pattern {/a"o=Debian,a=unstable";' 50unattended-upgrades + fi - confOpenVPN - confNetwork - confOVPN - - # ?? Is this always OK? Also if you only select one DNS server ?? - $SUDO sed -i '0,/\(dhcp-option DNS \)/ s/\(dhcp-option DNS \).*/\1'${OVPNDNS1}'\"/' /etc/openvpn/server.conf - $SUDO sed -i '0,/\(dhcp-option DNS \)/! s/\(dhcp-option DNS \).*/\1'${OVPNDNS2}'\"/' /etc/openvpn/server.conf - - finalExports #re-export setupVars.conf to account for any new vars added in new versions + # Add the remaining settings for all other distributions + echo "APT::Periodic::Enable \"1\"; + APT::Periodic::Update-Package-Lists \"1\"; + APT::Periodic::Download-Upgradeable-Packages \"1\"; + APT::Periodic::Unattended-Upgrade \"1\"; + APT::Periodic::AutocleanInterval \"7\"; + APT::Periodic::Verbose \"0\";" | $SUDO tee 02periodic > /dev/null } +installScripts() { + # Install the scripts from /etc/.pivpn to their various locations + echo ":::" + echo -n "::: Installing scripts to /opt/pivpn..." + if [ ! -d /opt/pivpn ]; then + $SUDO mkdir /opt/pivpn + $SUDO chown root:root /opt/pivpn + $SUDO chmod 0755 /opt/pivpn + fi -displayFinalMessage() { - # Final completion message to user - whiptail --msgbox --backtitle "Make it so." --title "Installation Complete!" "Now run 'pivpn add' to create the ovpn profiles. + FOLDER=$(tr '[:upper:]' '[:lower:]' <<< "$VPN") + $SUDO cp /etc/.pivpn/scripts/$FOLDER/*.sh /opt/pivpn/ + $SUDO chmod 0755 /opt/pivpn/*.sh + $SUDO cp /etc/.pivpn/$FOLDER/pivpn /usr/local/bin/pivpn + $SUDO chmod 0755 /usr/local/bin/pivpn + $SUDO cp /etc/.pivpn/scripts/$FOLDER/bash-completion /etc/bash_completion.d/pivpn + . /etc/bash_completion.d/pivpn + echo " done." +} + +displayFinalMessage(){ + # Final completion message to user + whiptail --msgbox --backtitle "Make it so." --title "Installation Complete!" "Now run 'pivpn add' to create the ovpn profiles. Run 'pivpn help' to see what else you can do!\n\nIf you run into any issue, please read all our documentation carefully. All incomplete posts or bug reports will be ignored or deleted.\n\nThank you for using PiVPN." ${r} ${c} - if (whiptail --title "Reboot" --yesno --defaultno "It is strongly recommended you reboot after installation. Would you like to reboot now?" ${r} ${c}); then - whiptail --title "Rebooting" --msgbox "The system will now reboot." ${r} ${c} - jkkprintf "\nRebooting system...\n" - $SUDO sleep 3 - $SUDO shutdown -r now - fi + if (whiptail --title "Reboot" --yesno --defaultno "It is strongly recommended you reboot after installation. Would you like to reboot now?" ${r} ${c}); then + whiptail --title "Rebooting" --msgbox "The system will now reboot." ${r} ${c} + printf "\nRebooting system...\n" + $SUDO sleep 3 + $SUDO shutdown -r now + fi } -update_dialogs() { - # reconfigure - if [ "${reconfigure}" = true ]; then - opt1a="Repair" - opt1b="This will retain existing settings" - strAdd="You will remain on the same version" - else - opt1a="Update" - opt1b="This will retain existing settings." - strAdd="You will be updated to the latest version." - fi - opt2a="Reconfigure" - opt2b="This will allow you to enter new settings" - - UpdateCmd=$(whiptail --title "Existing Install Detected!" --menu "\n\nWe have detected an existing install.\n\nPlease choose from the following options: \n($strAdd)" ${r} ${c} 2 \ - "${opt1a}" "${opt1b}" \ - "${opt2a}" "${opt2b}" 3>&2 2>&1 1>&3) || \ - { echo "::: Cancel selected. Exiting"; exit 1; } - - case ${UpdateCmd} in - ${opt1a}) - echo "::: ${opt1a} option selected." - useUpdateVars=true - ;; - ${opt2a}) - echo "::: ${opt2a} option selected" - useUpdateVars=false - ;; - esac -} - -clone_or_update_repos() { - if [[ "${reconfigure}" == true ]]; then - echo "::: --reconfigure passed to install script. Not downloading/updating local repos" - else - # Get Git files - getGitFiles ${pivpnFilesDir} ${pivpnGitUrl} || \ - { echo "!!! Unable to clone ${pivpnGitUrl} into ${pivpnFilesDir}, unable to continue."; \ - exit 1; \ - } - fi -} - -checkhostname(){ -###Checks for hostnamesize - host_name=$(hostname -s) - if [[ ! ${#host_name} -le 28 ]]; then - until [[ ${#host_name} -le 28 && $host_name =~ ^[a-zA-Z0-9][a-zA-Z0-9-]{1,28}$ ]]; do - host_name=$(whiptail --inputbox "Your hostname is too long.\nEnter new hostname with less then 28 characters\nNo special characters allowed." \ - --title "Hostname too long" ${r} ${c} 3>&1 1>&2 2>&3) - $SUDO hostnamectl set-hostname "${host_name}" - if [[ ${#host_name} -le 28 && $host_name =~ ^[a-zA-Z0-9][a-zA-Z0-9-]{1,28}$ ]]; then - echo "::: Hostname valid and length OK, proceeding..." - fi - - done - else - echo "::: Hostname length OK" - fi - -} - - ######## SCRIPT ############ -main() { +main(){ - ######## FIRST CHECK ######## - # Must be root to install - echo ":::" - if [[ $EUID -eq 0 ]];then - echo "::: You are root." - else - echo "::: sudo will be used for the install." - # Check if it is actually installed - # If it isn't, exit because the install cannot complete - if [[ $(dpkg-query -s sudo) ]];then - export SUDO="sudo" - export SUDOE="sudo -E" - else - echo "::: Please install sudo or run this as root." - exit 1 - fi - fi + ######## FIRST CHECK ######## + # Must be root to install + echo ":::" + if [[ $EUID -eq 0 ]];then + echo "::: You are root." + else + echo "::: sudo will be used for the install." + # Check if it is actually installed + # If it isn't, exit because the install cannot complete + if [[ $(dpkg-query -s sudo) ]];then + export SUDO="sudo" + export SUDOE="sudo -E" + else + echo "::: Please install sudo or run this as root." + exit 1 + fi + fi + # Check for supported distribution + distroCheck - # Check for supported distribution - distro_check + # Checks for hostname Length + checkHostname - # Checks for hostname Length - checkhostname + # Check arguments for the undocumented flags + for var in "$@"; do + case "$var" in + "--i_do_not_follow_recommendations" ) skipSpaceCheck=false;; + "--unattended" ) runUnattended=true;; + esac + done - # Check arguments for the undocumented flags - for var in "$@"; do - case "$var" in - "--reconfigure" ) reconfigure=true;; - "--i_do_not_follow_recommendations" ) skipSpaceCheck=false;; - "--unattended" ) runUnattended=true;; - esac - done + if [[ "${runUnattended}" == true ]]; then + echo "::: --unattended passed to install script, no whiptail dialogs will be displayed" + fi - if [[ -f ${setupVars} ]]; then - if [[ "${runUnattended}" == true ]]; then - echo "::: --unattended passed to install script, no whiptail dialogs will be displayed" - useUpdateVars=true - else - update_dialogs - fi - fi + # Start the installer + # Verify there is enough disk space for the install + if [[ "${skipSpaceCheck}" == true ]]; then + echo "::: --i_do_not_follow_recommendations passed to script, skipping free disk space verification!" + else + verifyFreeDiskSpace + fi - # Start the installer - # Verify there is enough disk space for the install - if [[ "${skipSpaceCheck}" == true ]]; then - echo "::: --i_do_not_follow_recommendations passed to script, skipping free disk space verification!" - else - verifyFreeDiskSpace - fi + updatePackageCache - # Install the packages (we do this first because we need whiptail) - addSoftwareRepo + # Notify user of package availability + notifyPackageUpdatesAvailable - update_package_cache + # Install packages used by this installation script + preconfigurePackages + installDependentPackages BASE_DEPS[@] - # Notify user of package availability - notify_package_updates_available + # Display welcome dialogs + welcomeDialogs + # Find interfaces and let the user choose one + chooseInterface - # Install packages used by this installation script - install_dependent_packages PIVPN_DEPS[@] + getStaticIPv4Settings + setStaticIPv4 - if [[ ${useUpdateVars} == false ]]; then - # Display welcome dialogs - welcomeDialogs + # Choose the user for the ovpns + chooseUser - # Find interfaces and let the user choose one - chooseInterface + # Clone/Update the repos + cloneOrUpdateRepos - # Only try to set static on Raspbian, otherwise let user do it - if [[ $PLAT != "Raspbian" ]]; then - avoidStaticIPv4Ubuntu - else - getStaticIPv4Settings - setStaticIPv4 - fi + # Install + if installPiVPN; then + echo "::: Install Complete..." + else + exit 1 + fi - # Choose the user for the ovpns - chooseUser + echo "::: Restarting services..." + # Start services + case ${PLAT} in + Raspbian) + if [ "$VPN" = "OpenVPN" ]; then + $SUDO systemctl enable openvpn.service + $SUDO systemctl start openvpn.service + elif [ "$VPN" = "WireGuard" ]; then + $SUDO systemctl enable wg-quick@wg0.service + $SUDO systemctl start wg-quick@wg0.service + fi + ;; + esac - # Ask if unattended-upgrades will be enabled - unattendedUpgrades + # Ask if unattended-upgrades will be enabled + askUnattendedUpgrades + confUnattendedUpgrades - # Clone/Update the repos - clone_or_update_repos + $SUDO cp /tmp/setupVars.conf /etc/pivpn/setupVars.conf + installScripts - # Install - if installPiVPN; then - echo "::: Install Complete..." - else - exit 1 - fi - else - # Source ${setupVars} for use in the rest of the functions. - source ${setupVars} + # Ensure that cached writes reach persistent storage + echo "::: Flushing writes to disk..." + sync + echo "::: done." - echo "::: Using IP address: $IPv4addr" - echo "${IPv4addr%/*}" > /tmp/pivpnIP - echo "::: Using interface: $pivpnInterface" - echo "${pivpnInterface}" > /tmp/pivpnINT - echo "::: Using User: $INSTALL_USER" - echo "${INSTALL_USER}" > /tmp/INSTALL_USER - echo "::: Using protocol: $pivpnProto" - echo "${pivpnProto}" > /tmp/pivpnPROTO - echo "::: Using port: $PORT" - echo ${PORT} > /tmp/INSTALL_PORT - echo ":::" + displayFinalMessage - # Only try to set static on Raspbian - case ${PLAT} in - Rasp*) - setStaticIPv4 # This might be a problem if a user tries to modify the ip in the config file and then runs an update because of the way we check for previous configuration in /etc/dhcpcd.conf - ;; - *) - echo "::: IP Information" - echo "::: Since we think you are not using Raspbian, we will not configure a static IP for you." - echo "::: If you are in Amazon then you can not configure a static IP anyway." - echo "::: Just ensure before this installer started you had set an elastic IP on your instance." - ;; - esac - - # Clone/Update the repos - clone_or_update_repos - - - updatePiVPN - fi - - echo "::: Restarting services..." - # Start services - case ${PLAT} in - Ubuntu|Debian|*vuan) - $SUDO service openvpn start - ;; - *) - $SUDO systemctl enable openvpn.service - $SUDO systemctl start openvpn.service - ;; - esac - - # Ensure that cached writes reach persistent storage - echo "::: Flushing writes to disk..." - sync - - echo "::: done." - - if [[ "${useUpdateVars}" == false ]]; then - displayFinalMessage - fi - - echo ":::" - if [[ "${useUpdateVars}" == false ]]; then - echo "::: Installation Complete!" - echo "::: Now run 'pivpn add' to create an ovpn profile for each of your devices." - echo "::: Run 'pivpn help' to see what else you can do!" - echo "::: It is strongly recommended you reboot after installation." - else - echo "::: Update complete!" - fi - - echo ":::" + echo ":::" + echo "::: Installation Complete!" + echo "::: Now run 'pivpn add' to create an ovpn profile for each of your devices." + echo "::: Run 'pivpn help' to see what else you can do!" + echo "::: It is strongly recommended you reboot after installation." + echo ":::" } -if [[ "${PIVPN_TEST}" != true ]] ; then - main "$@" -fi +main "$@" diff --git a/pivpn b/pivpn deleted file mode 100644 index de55586..0000000 --- a/pivpn +++ /dev/null @@ -1,106 +0,0 @@ -#!/bin/bash - -# Must be root to use this tool -if [[ ! $EUID -eq 0 ]];then - if [[ $(dpkg-query -s sudo) ]];then - export SUDO="sudo" - else - echo "::: Please install sudo or run this as root." - exit 0 - fi -fi - -function makeOVPNFunc { - shift - $SUDO /opt/pivpn/makeOVPN.sh "$@" - exit 0 -} - -function listClientsFunc { - $SUDO /opt/pivpn/clientStat.sh - exit 0 -} - -function listOVPNFunc { - $SUDO /opt/pivpn/listOVPN.sh - exit 0 -} - -function debugFunc { - echo "::: Generating Debug Output" - $SUDO /opt/pivpn/pivpnDebug.sh | tee /tmp/debug.txt - echo "::: " - echo "::: Debug output completed above." - echo "::: Copy saved to /tmp/debug.txt" - echo "::: " - exit 0 -} - -function removeOVPNFunc { - shift - $SUDO /opt/pivpn/removeOVPN.sh "$@" - exit 0 -} - -function uninstallFunc { - $SUDO /opt/pivpn/uninstall.sh - exit 0 -} - -function versionFunc { - printf "\e[1mVersion 1.9\e[0m\n" -} - -function update { - - shift - $SUDO /opt/pivpn/update.sh "$@" - exit 0 - - -} - -function backup { - - $SUDO /opt/pivpn/backup.sh - exit 0 - -} - - -function helpFunc { - echo "::: Control all PiVPN specific functions!" - echo ":::" - echo "::: Usage: pivpn [option]" - echo ":::" - echo "::: Commands:" - echo "::: -a, add [nopass] Create a client ovpn profile, optional nopass" - echo "::: -c, clients List any connected clients to the server" - echo "::: -d, debug Start a debugging session if having trouble" - echo "::: -l, list List all valid and revoked certificates" - echo "::: -r, revoke Revoke a client ovpn profile" - echo "::: -h, help Show this help dialog" - echo "::: -u, uninstall Uninstall PiVPN from your system!" - echo "::: -up, update Updates PiVPN Scripts" - echo "::: -bk, backup Backup Openvpn and ovpns dir" - exit 0 -} - -if [[ $# = 0 ]]; then - helpFunc -fi - -# Handle redirecting to specific functions based on arguments -case "$1" in -"-a" | "add" ) makeOVPNFunc "$@";; -"-c" | "clients" ) listClientsFunc;; -"-d" | "debug" ) debugFunc;; -"-l" | "list" ) listOVPNFunc;; -"-r" | "revoke" ) removeOVPNFunc "$@";; -"-h" | "help" ) helpFunc;; -"-u" | "uninstall" ) uninstallFunc;; -"-v" ) versionFunc;; -"-up"| "update" ) update "$@" ;; -"-bk"| "backup" ) backup;; -* ) helpFunc;; -esac diff --git a/scripts/backup.sh b/scripts/backup.sh deleted file mode 100755 index 61cc6cf..0000000 --- a/scripts/backup.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/bash -install_user=$(1 - backupzip=$date-pivpnbackup.tgz - tar -czf $backupzip -C ${install_home} $backupdir 2&>1 - echo -e "Backup crated to $install_home/$backupdir/$backupzip \nTo restore the backup, follow instructions at:\nhttps://github.com/pivpn/pivpn/wiki/FAQ#how-can-i-migrate-my-configs-to-another-pivpn-instance" -} - - -if [[ ! $EUID -eq 0 ]];then - if [[ $(dpkg-query -s sudo) ]];then - export SUDO="sudo" - else - echo "::: Please install sudo or run this as root." - exit 0 - fi -fi - -backup_openvpn - diff --git a/scripts/bash-completion b/scripts/bash-completion deleted file mode 100644 index f317bc4..0000000 --- a/scripts/bash-completion +++ /dev/null @@ -1,22 +0,0 @@ -_pivpn() -{ - local cur prev opts - COMPREPLY=() - cur="${COMP_WORDS[COMP_CWORD]}" - prev="${COMP_WORDS[COMP_CWORD-1]}" - dashopts="-a -c -d -l -r -h -u -up" - opts="debug add clients list revoke uninstall help update" - if [ "${#COMP_WORDS[@]}" -eq 2 ] - then - if [[ ${cur} == -* ]] ; then - COMPREPLY=( $(compgen -W "${dashopts}" -- "${cur}") ) - else - COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") ) - fi - elif [[ ( "$prev" == "add" || "$prev" == "-a" ) && "${#COMP_WORDS[@]}" -eq 3 ]] - then - COMPREPLY=( $(compgen -W "nopass" -- "${cur}") ) - fi - return 0 -} -complete -F _pivpn pivpn diff --git a/scripts/clientStat.sh b/scripts/clientStat.sh deleted file mode 100755 index 2af420f..0000000 --- a/scripts/clientStat.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env bash -# PiVPN: client status script - -STATUS_LOG="/var/log/openvpn-status.log" - -function hr() { - numfmt --to=iec-i --suffix=B "$1" -} - -printf "\n" -if [ ! -f "${STATUS_LOG}" ]; then - echo "The file: $STATUS_LOG was not found!" - exit 1 -fi - -printf ": NOTE : The output below is NOT real-time!\n" -printf ": : It may be off by a few minutes.\n" -printf "\n" -printf "\e[1m::: Client Status List :::\e[0m\n" -printf "\t\t\t\t\t\t\t\tBytes\t\tBytes\t\n" -printf "\e[4mName\e[0m\t\t\t\e[4mRemote IP\e[0m\t\t\e[4mVirtual IP\e[0m\t\e[4mReceived\e[0m\t\e[4mSent\e[0m\t\t\e[4mConnected Since\e[0m \n" -if grep -q "^CLIENT_LIST" "${STATUS_LOG}"; then - if [ -n "$(type -t numfmt)" ]; then - while read -r line; do - read -r -a array <<< $line - [[ ${array[0]} = CLIENT_LIST ]] || continue - printf "%s\t\t%s\t%s\t%s\t\t%s\t\t%s %s %s - %s\n" ${array[1]} ${array[2]} ${array[3]} $(hr ${array[4]}) $(hr ${array[5]}) ${array[7]} ${array[8]} ${array[10]} ${array[9]} - done <$STATUS_LOG - else - awk -F' ' -v s='CLIENT_LIST' '$1 == s {print $2"\t\t"$3"\t"$4"\t"$5"\t\t"$6"\t\t"$8" "$9" "$11" - "$10"\n"}' ${STATUS_LOG} - fi -else - printf "\nNo Clients Connected!\n" -fi -printf "\n" diff --git a/scripts/listOVPN.sh b/scripts/listOVPN.sh deleted file mode 100755 index ec0ffd7..0000000 --- a/scripts/listOVPN.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env bash -# PiVPN: list clients script - -INDEX="/etc/openvpn/easy-rsa/pki/index.txt" -printf "\n" -if [ ! -f "${INDEX}" ]; then - echo "The file: $INDEX was not found!" - exit 1 -fi - -printf ": NOTE : The first entry should always be your valid server!\n" -printf "\n" -printf "\e[1m::: Certificate Status List :::\e[0m\n" -printf " ::\e[4m Status \e[0m||\e[4m Name \e[0m:: \n" - -while read -r line || [ -n "$line" ]; do - STATUS=$(echo "$line" | awk '{print $1}') - NAME=$(echo "$line" | sed -e 's:.*/CN=::') - if [ "${STATUS}" == "V" ]; then - printf " Valid :: %s\n" "$NAME" - elif [ "${STATUS}" == "R" ]; then - printf " Revoked :: %s\n" "$NAME" - else - printf " Unknown :: %s\n" "$NAME" - fi -done <${INDEX} -printf "\n" diff --git a/scripts/makeOVPN.sh b/scripts/makeOVPN.sh deleted file mode 100755 index 406aff0..0000000 --- a/scripts/makeOVPN.sh +++ /dev/null @@ -1,415 +0,0 @@ -#!/bin/bash -# Create OVPN Client -# Default Variable Declarations -DEFAULT="Default.txt" -FILEEXT=".ovpn" -CRT=".crt" -KEY=".key" -CA="ca.crt" -TA="ta.key" -INDEX="/etc/openvpn/easy-rsa/pki/index.txt" -INSTALL_USER=$( [-n|--name ] [-p|--password ]|[nopass] [-d|--days ] [-b|--bitwarden] [-i|--iOS] [-h|--help]" - echo ":::" - echo "::: Commands:" - echo "::: [none] Interactive mode" - echo "::: nopass Create a client without a password" - echo "::: -n,--name Name for the Client (default: '"$(hostname)"')" - echo "::: -p,--password Password for the Client (no default)" - echo "::: -d,--days Expire the certificate after specified number of days (default: 1080)" - echo "::: -b,--bitwarden Create and save a client through Bitwarden" - echo "::: -i,--iOS Generate a certificate that leverages iOS keychain" - echo "::: -h,--help Show this help dialog" -} - -if [ ! -f /etc/pivpn/HELP_SHOWN ]; then - helpFunc - echo - touch /etc/pivpn/HELP_SHOWN -fi - -# Parse input arguments -while test $# -gt 0 -do - _key="$1" - case "$_key" in - -n|--name|--name=*) - _val="${_key##--name=}" - if test "$_val" = "$_key" - then - test $# -lt 2 && echo "Missing value for the optional argument '$_key'." && exit 1 - _val="$2" - shift - fi - NAME="$_val" - ;; - -p|--password|--password=*) - _val="${_key##--password=}" - if test "$_val" = "$_key" - then - test $# -lt 2 && echo "Missing value for the optional argument '$_key'." && exit 1 - _val="$2" - shift - fi - PASSWD="$_val" - ;; - -d|--days|--days=*) - _val="${_key##--days=}" - if test "$_val" = "$_key" - then - test $# -lt 2 && echo "Missing value for the optional argument '$_key'." && exit 1 - _val="$2" - shift - fi - DAYS="$_val" - ;; - -i|--iOS) - iOS=1 - ;; - -h|--help) - helpFunc - exit 0 - ;; - nopass) - NO_PASS="1" - ;; - -b|--bitwarden) - if which bw; then - BITWARDEN="2" - else - echo "Bitwarden not found, please install bitwarden" - exit 1 - fi - - ;; - *) - echo "Error: Got an unexpected argument '$1'" - helpFunc - exit 1 - ;; - esac - shift -done - -# Functions def - -function keynoPASS() { - - #Build the client key - expect << EOF - set timeout -1 - set env(EASYRSA_CERT_EXPIRE) "${DAYS}" - spawn ./easyrsa build-client-full "${NAME}" nopass - expect eof -EOF - - cd pki || exit - -} - -function useBitwarden() { - - # login and unlock vault - printf "****Bitwarden Login****" - printf "\n" - SESSION_KEY=`bw login --raw` - export BW_SESSION=$SESSION_KEY - printf "Successfully Logged in!" - printf "\n" - - # ask user for username - printf "Enter the username: " - read -r NAME - - # check name - until [[ "$NAME" =~ ^[a-zA-Z0-9.@_-]+$ && ${NAME::1} != "." && ${NAME::1} != "-" ]] - do - echo "Name can only contain alphanumeric characters and these characters (.-@_). The name also cannot start with a dot (.) or a dash (-). Please try again." - # ask user for username again - printf "Enter the username: " - read -r NAME - done - - - # ask user for length of password - printf "Please enter the length of characters you want your password to be (minimum 12): " - read -r LENGTH - - # check length - until [[ "$LENGTH" -gt 11 && "$LENGTH" -lt 129 ]] - do - echo "Password must be between from 12 to 128 characters, please try again." - # ask user for length of password - printf "Enter the length of characters you want your password to be (minimum 12): " - read -r LENGTH - done - - printf "Creating a PiVPN item for your vault..." - printf "\n" - # create a new item for your PiVPN Password - PASSWD=`bw generate -usln --length $LENGTH` - bw get template item | jq '.login.type = "1"'| jq '.name = "PiVPN"' | jq -r --arg NAME "$NAME" '.login.username = $NAME' | jq -r --arg PASSWD "$PASSWD" '.login.password = $PASSWD' | bw encode | bw create item - bw logout - -} - -function keyPASS() { - - if [[ -z "${PASSWD}" ]]; then - stty -echo - while true - do - printf "Enter the password for the client: " - read -r PASSWD - printf "\n" - printf "Enter the password again to verify: " - read -r PASSWD2 - printf "\n" - [ "${PASSWD}" = "${PASSWD2}" ] && break - printf "Passwords do not match! Please try again.\n" - done - stty echo - if [[ -z "${PASSWD}" ]]; then - echo "You left the password blank" - echo "If you don't want a password, please run:" - echo "pivpn add nopass" - exit 1 - fi - fi - if [ ${#PASSWD} -lt 4 ] || [ ${#PASSWD} -gt 1024 ] - then - echo "Password must be between from 4 to 1024 characters" - exit 1 - fi - - #Escape chars in PASSWD - PASSWD=$(echo -n ${PASSWD} | sed -e 's/\\/\\\\/g' -e 's/\//\\\//g' -e 's/\$/\\\$/g' -e 's/!/\\!/g' -e 's/\./\\\./g' -e "s/'/\\\'/g" -e 's/"/\\"/g' -e 's/\*/\\\*/g' -e 's/\@/\\\@/g' -e 's/\#/\\\#/g' -e 's/£/\\£/g' -e 's/%/\\%/g' -e 's/\^/\\\^/g' -e 's/\&/\\\&/g' -e 's/(/\\(/g' -e 's/)/\\)/g' -e 's/-/\\-/g' -e 's/_/\\_/g' -e 's/\+/\\\+/g' -e 's/=/\\=/g' -e 's/\[/\\\[/g' -e 's/\]/\\\]/g' -e 's/;/\\;/g' -e 's/:/\\:/g' -e 's/|/\\|/g' -e 's//\\>/g' -e 's/,/\\,/g' -e 's/?/\\?/g' -e 's/~/\\~/g' -e 's/{/\\{/g' -e 's/}/\\}/g') - - #Build the client key and then encrypt the key - - expect << EOF - set timeout -1 - set env(EASYRSA_CERT_EXPIRE) "${DAYS}" - spawn ./easyrsa build-client-full "${NAME}" - expect "Enter PEM pass phrase" { send -- "${PASSWD}\r" } - expect "Verifying - Enter PEM pass phrase" { send -- "${PASSWD}\r" } - expect eof -EOF - cd pki || exit - -} - -#make sure ovpns dir exists -if [ ! -d "$INSTALL_HOME/ovpns" ]; then - mkdir "$INSTALL_HOME/ovpns" - chmod 0750 "$INSTALL_HOME/ovpns" -fi - -#bitWarden -if [[ "${BITWARDEN}" =~ "2" ]]; then - useBitwarden -fi - -if [ -z "${NAME}" ]; then - printf "Enter a Name for the Client: " - read -r NAME -fi - -if [[ ${NAME::1} == "." ]] || [[ ${NAME::1} == "-" ]]; then - echo "Names cannot start with a dot (.) or a dash (-)." - exit 1 -fi - -if [[ "${NAME}" =~ [^a-zA-Z0-9.@_-] ]]; then - echo "Name can only contain alphanumeric characters and these characters (.-@_)." - exit 1 -fi - -if [[ -z "${NAME}" ]]; then - echo "You cannot leave the name blank." - exit 1 -fi - -# Check if name is already in use -while read -r line || [ -n "${line}" ]; do - STATUS=$(echo "$line" | awk '{print $1}') - - if [ "${STATUS}" == "V" ]; then - CERT=$(echo "$line" | sed -e 's:.*/CN=::') - if [ "${CERT}" == "${NAME}" ]; then - INUSE="1" - break - fi - fi -done <${INDEX} - -if [ "${INUSE}" == "1" ]; then - printf "\n!! This name is already in use by a Valid Certificate." - printf "\nPlease choose another name or revoke this certificate first.\n" - exit 1 -fi - -# Check if name is reserved -if [ "${NAME}" == "ta" ] || [ "${NAME}" == "server" ] || [ "${NAME}" == "ca" ]; then - echo "Sorry, this is in use by the server and cannot be used by clients." - exit 1 -fi - -#As of EasyRSA 3.0.6, by default certificates last 1080 days, see https://github.com/OpenVPN/easy-rsa/blob/6b7b6bf1f0d3c9362b5618ad18c66677351cacd1/easyrsa3/vars.example -if [ -z "${DAYS}" ]; then - read -r -e -p "How many days should the certificate last? " -i 1080 DAYS -fi - -if [[ ! "$DAYS" =~ ^[0-9]+$ ]] || [ "$DAYS" -lt 1 ] || [ "$DAYS" -gt 3650 ]; then - #The CRL lasts 3650 days so it doesn't make much sense that certificates would last longer - echo "Please input a valid number of days, between 1 and 3650 inclusive." - exit 1 - -fi - -cd /etc/openvpn/easy-rsa || exit - -if [[ "${NO_PASS}" =~ "1" ]]; then - if [[ -n "${PASSWD}" ]]; then - echo "Both nopass and password arguments passed to the script. Please use either one." - exit 1 - else - keynoPASS - fi -else - keyPASS -fi - -#1st Verify that clients Public Key Exists -if [ ! -f "issued/${NAME}${CRT}" ]; then - echo "[ERROR]: Client Public Key Certificate not found: $NAME$CRT" - exit -fi -echo "Client's cert found: $NAME$CRT" - -#Then, verify that there is a private key for that client -if [ ! -f "private/${NAME}${KEY}" ]; then - echo "[ERROR]: Client Private Key not found: $NAME$KEY" - exit -fi -echo "Client's Private Key found: $NAME$KEY" - -#Confirm the CA public key exists -if [ ! -f "${CA}" ]; then - echo "[ERROR]: CA Public Key not found: $CA" - exit -fi -echo "CA public Key found: $CA" - -#Confirm the tls key file exists -if [ ! -f "${TA}" ]; then - echo "[ERROR]: tls Private Key not found: $TA" - exit -fi -echo "tls Private Key found: $TA" - - -## Added new step to create an .ovpn12 file that can be stored on iOS keychain -## This step is more secure method and does not require the end-user to keep entering passwords, or storing the client private cert where it can be easily tampered -## https://openvpn.net/faq/how-do-i-use-a-client-certificate-and-private-key-from-the-ios-keychain/ -if [ "$iOS" = "1" ]; then - #Generates the .ovpn file WITHOUT the client private key - { - # Start by populating with the default file - cat "${DEFAULT}" - - #Now, append the CA Public Cert - echo "" - cat "${CA}" - echo "" - - #Next append the client Public Cert - echo "" - sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' < "issued/${NAME}${CRT}" - echo "" - - #Finally, append the TA Private Key - if [ -f /etc/pivpn/TWO_POINT_FOUR ]; then - echo "" - cat "${TA}" - echo "" - else - echo "" - cat "${TA}" - echo "" - fi - - } > "${NAME}${FILEEXT}" - - # Copy the .ovpn profile to the home directory for convenient remote access - - printf "========================================================\n" - printf "Generating an .ovpn12 file for use with iOS devices\n" - printf "Please remember the export password\n" - printf "as you will need this import the certificate on your iOS device\n" - printf "========================================================\n" - openssl pkcs12 -passin pass:"$PASSWD" -export -in "issued/${NAME}${CRT}" -inkey "private/${NAME}${KEY}" -certfile ${CA} -name "${NAME}" -out "/home/$INSTALL_USER/ovpns/$NAME.ovpn12" - chown "$INSTALL_USER" "/home/$INSTALL_USER/ovpns/$NAME.ovpn12" - chmod 600 "/home/$INSTALL_USER/ovpns/$NAME.ovpn12" - printf "========================================================\n" - printf "\e[1mDone! %s successfully created!\e[0m \n" "$NAME.ovpn12" - printf "You will need to transfer both the .ovpn and .ovpn12 files\n" - printf "to your iOS device.\n" - printf "========================================================\n\n" -else - #This is the standard non-iOS configuration -#Ready to make a new .ovpn file - { - # Start by populating with the default file - cat "${DEFAULT}" - - #Now, append the CA Public Cert - echo "" - cat "${CA}" - echo "" - - #Next append the client Public Cert - echo "" - sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' < "issued/${NAME}${CRT}" - echo "" - - #Then, append the client Private Key - echo "" - cat "private/${NAME}${KEY}" - echo "" - - #Finally, append the tls Private Key - if [ -f /etc/pivpn/TWO_POINT_FOUR ]; then - echo "" - cat "${TA}" - echo "" - else - echo "" - cat "${TA}" - echo "" - fi - - } > "${NAME}${FILEEXT}" - -fi - - -# Copy the .ovpn profile to the home directory for convenient remote access -cp "/etc/openvpn/easy-rsa/pki/$NAME$FILEEXT" "$INSTALL_HOME/ovpns/$NAME$FILEEXT" -chown "$INSTALL_USER" "$INSTALL_HOME/ovpns/$NAME$FILEEXT" -chmod 640 "/etc/openvpn/easy-rsa/pki/$NAME$FILEEXT" -chmod 640 "$INSTALL_HOME/ovpns/$NAME$FILEEXT" -printf "\n\n" -printf "========================================================\n" -printf "\e[1mDone! %s successfully created!\e[0m \n" "$NAME$FILEEXT" -printf "%s was copied to:\n" "$NAME$FILEEXT" -printf " %s/ovpns\n" "$INSTALL_HOME" -printf "for easy transfer. Please use this profile only on one\n" -printf "device and create additional profiles for other devices.\n" -printf "========================================================\n\n" diff --git a/scripts/pivpnDebug.sh b/scripts/pivpnDebug.sh deleted file mode 100755 index 25a4bf1..0000000 --- a/scripts/pivpnDebug.sh +++ /dev/null @@ -1,230 +0,0 @@ -#!/usr/bin/env bash -# This scripts runs as root - -PORT=$(cat /etc/pivpn/INSTALL_PORT) -PROTO=$(cat /etc/pivpn/INSTALL_PROTO) -IPv4dev="$(cat /etc/pivpn/pivpnINTERFACE)" -REMOTE="$(grep 'remote ' /etc/openvpn/easy-rsa/pki/Default.txt | awk '{print $2}')" -NO_UFW=$(cat /etc/pivpn/NO_UFW) -OLD_UFW=$(cat /etc/pivpn/NO_UFW) -INPUT_CHAIN_EDITED="$(cat /etc/pivpn/INPUT_CHAIN_EDITED)" -FORWARD_CHAIN_EDITED="$(cat /etc/pivpn/FORWARD_CHAIN_EDITED)" -ERR=0 - -echo -e "::::\t\t\e[4mPiVPN debug\e[0m\t\t ::::" -printf "=============================================\n" -echo -e "::::\t\t\e[4mLatest commit\e[0m\t\t ::::" -git --git-dir /etc/.pivpn/.git log -n 1 -printf "=============================================\n" -echo -e "::::\t \e[4mInstallation settings\e[0m \t ::::" -# Use the wildcard so setupVars.conf.update.bak from the previous install is not shown -for filename in /etc/pivpn/*; do - if [[ "$filename" != "/etc/pivpn/setupVars.conf"* ]]; then - echo "$filename -> $(cat "$filename")" - fi -done -printf "=============================================\n" -echo -e "::::\t\e[4msetupVars file shown below\e[0m\t ::::" -sed "s/$REMOTE/REMOTE/" < /etc/pivpn/setupVars.conf -printf "=============================================\n" -echo -e ":::: \e[4mServer configuration shown below\e[0m ::::" -cat /etc/openvpn/server.conf -printf "=============================================\n" -echo -e ":::: \e[4mClient template file shown below\e[0m ::::" -sed "s/$REMOTE/REMOTE/" < /etc/openvpn/easy-rsa/pki/Default.txt -printf "=============================================\n" -echo -e ":::: \t\e[4mRecursive list of files in\e[0m\t ::::\n::: \e[4m/etc/openvpn/easy-rsa/pki shows below\e[0m :::" -ls -LR /etc/openvpn/easy-rsa/pki/ -Ireqs -Icerts_by_serial -printf "=============================================\n" -echo -e "::::\t\t\e[4mSelf check\e[0m\t\t ::::" - -if [ "$(cat /proc/sys/net/ipv4/ip_forward)" -eq 1 ]; then - echo ":: [OK] IP forwarding is enabled" -else - ERR=1 - read -r -p ":: [ERR] IP forwarding is not enabled, attempt fix now? [Y/n] " REPLY - if [[ ${REPLY} =~ ^[Yy]$ ]]; then - sed -i '/net.ipv4.ip_forward=1/s/^#//g' /etc/sysctl.conf - sysctl -p - echo "Done" - fi -fi - -if [ "$NO_UFW" -eq 1 ]; then - - if iptables -t nat -C POSTROUTING -s 10.8.0.0/24 -o "${IPv4dev}" -j MASQUERADE &> /dev/null; then - echo ":: [OK] Iptables MASQUERADE rule set" - else - ERR=1 - read -r -p ":: [ERR] Iptables MASQUERADE rule is not set, attempt fix now? [Y/n] " REPLY - if [[ ${REPLY} =~ ^[Yy]$ ]]; then - iptables -t nat -F - iptables -t nat -I POSTROUTING -s 10.8.0.0/24 -o "${IPv4dev}" -j MASQUERADE - iptables-save > /etc/iptables/rules.v4 - echo "Done" - fi - fi - - - if [ "$INPUT_CHAIN_EDITED" -eq 1 ]; then - - if iptables -C INPUT -i "$IPv4dev" -p "$PROTO" --dport "$PORT" -j ACCEPT &> /dev/null; then - echo ":: [OK] Iptables INPUT rule set" - else - ERR=1 - read -r -p ":: [ERR] Iptables INPUT rule is not set, attempt fix now? [Y/n] " REPLY - if [[ ${REPLY} =~ ^[Yy]$ ]]; then - iptables -I INPUT 1 -i "$IPv4dev" -p "$PROTO" --dport "$PORT" -j ACCEPT - iptables-save > /etc/iptables/rules.v4 - echo "Done" - fi - fi - fi - - if [ "$FORWARD_CHAIN_EDITED" -eq 1 ]; then - - if iptables -C FORWARD -s 10.8.0.0/24 -i tun0 -o "$IPv4dev" -j ACCEPT &> /dev/null; then - echo ":: [OK] Iptables FORWARD rule set" - else - ERR=1 - read -r -p ":: [ERR] Iptables FORWARD rule is not set, attempt fix now? [Y/n] " REPLY - if [[ ${REPLY} =~ ^[Yy]$ ]]; then - iptables -I FORWARD 1 -d 10.8.0.0/24 -i "$IPv4dev" -o tun0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT - iptables -I FORWARD 2 -s 10.8.0.0/24 -i tun0 -o "$IPv4dev" -j ACCEPT - iptables-save > /etc/iptables/rules.v4 - echo "Done" - fi - fi - fi - -else - - if LANG="en_US.UTF-8" ufw status | grep -qw 'active'; then - echo ":: [OK] Ufw is enabled" - else - ERR=1 - read -r -p ":: [ERR] Ufw is not enabled, try to enable now? [Y/n] " REPLY - if [[ ${REPLY} =~ ^[Yy]$ ]]; then - ufw enable - fi - fi - - if iptables -t nat -C POSTROUTING -s 10.8.0.0/24 -o "${IPv4dev}" -j MASQUERADE &> /dev/null; then - echo ":: [OK] Iptables MASQUERADE rule set" - else - ERR=1 - read -r -p ":: [ERR] Iptables MASQUERADE rule is not set, attempt fix now? [Y/n] " REPLY - if [[ ${REPLY} =~ ^[Yy]$ ]]; then - sed "/delete these required/i *nat\n:POSTROUTING ACCEPT [0:0]\n-I POSTROUTING -s 10.8.0.0/24 -o $IPv4dev -j MASQUERADE\nCOMMIT\n" -i /etc/ufw/before.rules - ufw reload - echo "Done" - fi - fi - - if iptables -C ufw-user-input -p "${PROTO}" --dport "${PORT}" -j ACCEPT &> /dev/null; then - echo ":: [OK] Ufw input rule set" - else - ERR=1 - read -r -p ":: [ERR] Ufw input rule is not set, attempt fix now? [Y/n] " REPLY - if [[ ${REPLY} =~ ^[Yy]$ ]]; then - ufw insert 1 allow "$PORT"/"$PROTO" - ufw reload - echo "Done" - fi - fi - - if [ "$OLD_UFW" -eq 1 ]; then - FORWARD_POLICY="$(iptables -S FORWARD | grep '^-P' | awk '{print $3}')" - if [ "$FORWARD_POLICY" = "ACCEPT" ]; then - echo ":: [OK] Ufw forwarding policy is accept" - else - ERR=1 - read -r -p ":: [ERR] Ufw forwarding policy is not 'ACCEPT', attempt fix now? [Y/n] " REPLY - if [[ ${REPLY} =~ ^[Yy]$ ]]; then - sed -i "s/\(DEFAULT_FORWARD_POLICY=\).*/\1\"ACCEPT\"/" /etc/default/ufw - ufw reload > /dev/null - echo "Done" - fi - fi - else - if iptables -C ufw-user-forward -i tun0 -o "${IPv4dev}" -s 10.8.0.0/24 -j ACCEPT &> /dev/null; then - echo ":: [OK] Ufw forwarding rule set" - else - ERR=1 - read -r -p ":: [ERR] Ufw forwarding rule is not set, attempt fix now? [Y/n] " REPLY - if [[ ${REPLY} =~ ^[Yy]$ ]]; then - ufw route insert 1 allow in on tun0 from 10.8.0.0/24 out on "$IPv4dev" to any - ufw reload - echo "Done" - fi - fi - fi - -fi - -if systemctl is-active -q openvpn; then - echo ":: [OK] OpenVPN is running" -else - ERR=1 - read -r -p ":: [ERR] OpenVPN is not running, try to start now? [Y/n] " REPLY - if [[ ${REPLY} =~ ^[Yy]$ ]]; then - systemctl start openvpn - echo "Done" - fi -fi - -if systemctl is-enabled -q openvpn; then - echo ":: [OK] OpenVPN is enabled (it will automatically start on reboot)" -else - ERR=1 - read -r -p ":: [ERR] OpenVPN is not enabled, try to enable now? [Y/n] " REPLY - if [[ ${REPLY} =~ ^[Yy]$ ]]; then - systemctl enable openvpn - echo "Done" - fi -fi - -# grep -w (whole word) is used so port 111940 with now match when looking for 1194 -if netstat -uanpt | grep openvpn | grep -w "${PORT}" | grep -q "${PROTO}"; then - echo ":: [OK] OpenVPN is listening on port ${PORT}/${PROTO}" -else - ERR=1 - read -r -p ":: [ERR] OpenVPN is not listening, try to restart now? [Y/n] " REPLY - if [[ ${REPLY} =~ ^[Yy]$ ]]; then - systemctl restart openvpn - echo "Done" - fi -fi - -if [ "$ERR" -eq 1 ]; then - echo -e "[INFO] Run \e[1mpivpn -d\e[0m again to see if we detect issues" -fi - -printf "=============================================\n" -echo -e ":::: \e[4mSnippet of the server log\e[0m ::::" -tail -20 /var/log/openvpn.log > /tmp/snippet - -# Regular expession taken from https://superuser.com/a/202835, it will match invalid IPs -# like 123.456.789.012 but it's fine because the log only contains valid ones. -declare -a IPS_TO_HIDE=($(grepcidr -v 10.0.0.0/8,172.16.0.0/12,192.168.0.0/16 /tmp/snippet | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | uniq)) -for IP in "${IPS_TO_HIDE[@]}"; do - sed -i "s/$IP/REDACTED/g" /tmp/snippet -done - -cat /tmp/snippet -rm /tmp/snippet -printf "=============================================\n" -echo -e "::::\t\t\e[4mDebug complete\e[0m\t\t ::::" - -# Telekom Hybrid Check -wget -O /tmp/hybcheck http://speedport.ip &>/dev/null -if grep -Fq "Speedport Pro" /tmp/hybcheck || grep -Fq "Speedport Hybrid" /tmp/hybcheck -then - printf ":::\t\t\t\t\t:::\n::\tTelekom Hybrid Check\t\t ::\n:::\t\t\t\t\t:::\n" - echo "Are you using Telekom Hybrid (found a hybrid compatible router)?" - echo "If yes and you have problems with the connections you can test the following:" - echo "Add 'tun-mtu 1316' in /etc/openvpn/easy-rsa/pki/Default.txt to set a hybrid compatible MTU size (new .ovpn files)." - echo "For already existing .ovpn files 'tun-mtu 1316' can also be inserted there manually." - echo "With Telekom hybrid connections, you may have to experiment a little with MTU (tun-mtu, link-mtu and mssfix)." -fi -rm /tmp/hybcheck diff --git a/scripts/removeOVPN.sh b/scripts/removeOVPN.sh deleted file mode 100755 index b2d726f..0000000 --- a/scripts/removeOVPN.sh +++ /dev/null @@ -1,123 +0,0 @@ -#!/usr/bin/env bash -# PiVPN: revoke client script - -INSTALL_USER=$( [-h|--help] [] ... [] ..." - echo ":::" - echo "::: Commands:" - echo "::: [none] Interactive mode" - echo "::: Client(s) to to revoke" - echo "::: -h,--help Show this help dialog" -} - -# Parse input arguments -while test $# -gt 0 -do - _key="$1" - case "$_key" in - -h|--help) - helpFunc - exit 0 - ;; - *) - CERTS_TO_REVOKE+=("$1") - ;; - esac - shift -done - -if [ ! -f "${INDEX}" ]; then - printf "The file: %s was not found\n" "$INDEX" - exit 1 -fi - -if [[ -z "${CERTS_TO_REVOKE}" ]]; then - printf "\n" - printf " ::\e[4m Certificate List \e[0m:: \n" - - i=0 - while read -r line || [ -n "$line" ]; do - STATUS=$(echo "$line" | awk '{print $1}') - if [[ "${STATUS}" = "V" ]]; then - NAME=$(echo "$line" | sed -e 's:.*/CN=::') - CERTS[$i]=${NAME} - if [ "$i" != 0 ]; then - # Prevent printing "server" certificate - printf " %s\n" "$NAME" - fi - let i=i+1 - fi - done <${INDEX} - printf "\n" - - echo "::: Please enter the Name of the client to be revoked from the list above:" - read -r NAME - - if [[ -z "${NAME}" ]]; then - echo "You can not leave this blank!" - exit 1 - fi - - for((x=1;x<=i;++x)); do - if [ "${CERTS[$x]}" = "${NAME}" ]; then - VALID=1 - fi - done - - if [ -z "${VALID}" ]; then - printf "You didn't enter a valid cert name!\n" - exit 1 - fi - - CERTS_TO_REVOKE=( "${NAME}" ) -else - i=0 - while read -r line || [ -n "$line" ]; do - STATUS=$(echo "$line" | awk '{print $1}') - if [[ "${STATUS}" = "V" ]]; then - NAME=$(echo "$line" | sed -e 's:.*/CN=::') - CERTS[$i]=${NAME} - let i=i+1 - fi - done <${INDEX} - - for (( ii = 0; ii < ${#CERTS_TO_REVOKE[@]}; ii++)); do - VALID=0 - for((x=1;x<=i;++x)); do - if [ "${CERTS[$x]}" = "${CERTS_TO_REVOKE[ii]}" ]; then - VALID=1 - fi - done - - if [ "${VALID}" != 1 ]; then - printf "You passed an invalid cert name: '"%s"'!\n" "${CERTS_TO_REVOKE[ii]}" - exit 1 - fi - done -fi - -cd /etc/openvpn/easy-rsa || exit - -INSTALL_HOME=$(grep -m1 "^${INSTALL_USER}:" /etc/passwd | cut -d: -f6) -INSTALL_HOME=${INSTALL_HOME%/} # remove possible trailing slash -for (( ii = 0; ii < ${#CERTS_TO_REVOKE[@]}; ii++)); do - printf "\n::: Revoking certificate '"%s"'.\n" "${CERTS_TO_REVOKE[ii]}" - ./easyrsa --batch revoke "${CERTS_TO_REVOKE[ii]}" - ./easyrsa gen-crl - printf "\n::: Certificate revoked, and CRL file updated.\n" - printf "::: Removing certs and client configuration for this profile.\n" - rm -rf "pki/reqs/${CERTS_TO_REVOKE[ii]}.req" - rm -rf "pki/private/${CERTS_TO_REVOKE[ii]}.key" - rm -rf "pki/issued/${CERTS_TO_REVOKE[ii]}.crt" - - rm -rf "${INSTALL_HOME}/ovpns/${CERTS_TO_REVOKE[ii]}.ovpn" - rm -rf "/etc/openvpn/easy-rsa/pki/${CERTS_TO_REVOKE[ii]}.ovpn" - cp /etc/openvpn/easy-rsa/pki/crl.pem /etc/openvpn/crl.pem -done -printf "::: Completed!\n" diff --git a/scripts/uninstall.sh b/scripts/uninstall.sh deleted file mode 100755 index b06aaa4..0000000 --- a/scripts/uninstall.sh +++ /dev/null @@ -1,153 +0,0 @@ -#!/usr/bin/env bash -# PiVPN: Uninstall Script - -PKG_MANAGER="apt-get" -INSTALL_USER=$(cat /etc/pivpn/INSTALL_USER) -INSTALL_HOME=$(grep -m1 "^${INSTALL_USER}:" /etc/passwd | cut -d: -f6) -INSTALL_HOME=${INSTALL_HOME%/} # remove possible trailing slash -PLAT=$(cat /etc/pivpn/DET_PLATFORM) -NO_UFW=$(cat /etc/pivpn/NO_UFW) -OLD_UFW=$(cat /etc/pivpn/NO_UFW) -PORT=$(cat /etc/pivpn/INSTALL_PORT) -PROTO=$(cat /etc/pivpn/INSTALL_PROTO) -IPv4dev="$(cat /etc/pivpn/pivpnINTERFACE)" -INPUT_CHAIN_EDITED="$(cat /etc/pivpn/INPUT_CHAIN_EDITED)" -FORWARD_CHAIN_EDITED="$(cat /etc/pivpn/FORWARD_CHAIN_EDITED)" - -# Find the rows and columns. Will default to 80x24 if it can not be detected. -screen_size=$(stty size 2>/dev/null || echo 24 80) -rows=$(echo $screen_size | awk '{print $1}') -columns=$(echo $screen_size | awk '{print $2}') - -# Divide by two so the dialogs take up half of the screen, which looks nice. -r=$(( rows / 2 )) -c=$(( columns / 2 )) -# Unless the screen is tiny -r=$(( r < 20 ? 20 : r )) -c=$(( c < 70 ? 70 : c )) - -spinner() -{ - local pid=$1 - local delay=0.50 - local spinstr='/-\|' - while [ "$(ps a | awk '{print $1}' | grep "$pid")" ]; do - local temp=${spinstr#?} - printf " [%c] " "$spinstr" - local spinstr=$temp${spinstr%"$temp"} - sleep $delay - printf "\b\b\b\b\b\b" - done - printf " \b\b\b\b" -} - -function removeAll { - # Purge dependencies -echo ":::" - dependencies=( openvpn easy-rsa git iptables-persistent dnsutils expect unattended-upgrades ) - for i in "${dependencies[@]}"; do - if [ "$(dpkg-query -W --showformat='${Status}\n' "$i" 2> /dev/null | grep -c "ok installed")" -eq 1 ]; then - while true; do - read -rp "::: Do you wish to remove $i from your system? [y/n]: " yn - case $yn in - [Yy]* ) printf ":::\tRemoving %s..." "$i"; $PKG_MANAGER -y remove --purge "$i" &> /dev/null & spinner $!; printf "done!\n"; - if [ "$i" == "openvpn" ]; then UINST_OVPN=1 ; fi - if [ "$i" == "unattended-upgrades" ]; then UINST_UNATTUPG=1 ; fi - break;; - [Nn]* ) printf ":::\tSkipping %s\n" "$i"; break;; - * ) printf "::: You must answer yes or no!\n";; - esac - done - else - printf ":::\tPackage %s not installed... Not removing.\n" "$i" - fi - done - - # Take care of any additional package cleaning - printf "::: Auto removing remaining dependencies..." - $PKG_MANAGER -y autoremove &> /dev/null & spinner $!; printf "done!\n"; - printf "::: Auto cleaning remaining dependencies..." - $PKG_MANAGER -y autoclean &> /dev/null & spinner $!; printf "done!\n"; - - echo ":::" - # Removing pivpn files - echo "::: Removing pivpn system files..." - - $SUDO rm -rf /opt/pivpn &> /dev/null - $SUDO rm -rf /etc/.pivpn &> /dev/null - $SUDO rm -rf $INSTALL_HOME/ovpns &> /dev/null - - rm -rf /var/log/*pivpn* &> /dev/null - rm -rf /var/log/*openvpn* &> /dev/null - if [[ $UINST_OVPN = 1 ]]; then - rm -rf /etc/openvpn &> /dev/null - if [[ $PLAT == "Ubuntu" || $PLAT == "Debian" ]]; then - printf "::: Removing openvpn apt source..." - rm -rf /etc/apt/sources.list.d/swupdate.openvpn.net.list &> /dev/null - $PKG_MANAGER -qq update & spinner $!; printf "done!\n"; - fi - fi - if [[ $UINST_UNATTUPG = 1 ]]; then - rm -rf /var/log/unattended-upgrades - rm -rf /etc/apt/apt.conf.d/*periodic - fi - rm -rf /etc/pivpn &> /dev/null - rm /usr/local/bin/pivpn &> /dev/null - rm /etc/bash_completion.d/pivpn - - # Disable IPv4 forwarding - sed -i '/net.ipv4.ip_forward=1/c\#net.ipv4.ip_forward=1' /etc/sysctl.conf - sysctl -p - - if [[ $NO_UFW -eq 0 ]]; then - - sed -z "s/*nat\n:POSTROUTING ACCEPT \[0:0\]\n-I POSTROUTING -s 10.8.0.0\/24 -o $IPv4dev -j MASQUERADE\nCOMMIT\n\n//" -i /etc/ufw/before.rules - ufw delete allow "$PORT"/"$PROTO" >/dev/null - if [ "$OLD_UFW" -eq 1 ]; then - sed -i "s/\(DEFAULT_FORWARD_POLICY=\).*/\1\"DROP\"/" /etc/default/ufw - else - ufw route delete allow in on tun0 from 10.8.0.0/24 out on "$IPv4dev" to any >/dev/null - fi - ufw reload >/dev/null - else - iptables -t nat -D POSTROUTING -s 10.8.0.0/24 -o "${IPv4dev}" -j MASQUERADE - - if [ "$INPUT_CHAIN_EDITED" -eq 1 ]; then - iptables -D INPUT -i "$IPv4dev" -p "$PROTO" --dport "$PORT" -j ACCEPT - fi - - if [ "$FORWARD_CHAIN_EDITED" -eq 1 ]; then - iptables -D FORWARD -d 10.8.0.0/24 -i "$IPv4dev" -o tun0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT - iptables -D FORWARD -s 10.8.0.0/24 -i tun0 -o "$IPv4dev" -j ACCEPT - fi - - iptables-save > /etc/iptables/rules.v4 - fi - - echo ":::" - printf "::: Finished removing PiVPN from your system.\n" - printf "::: Reinstall by simpling running\n:::\n:::\tcurl -L https://install.pivpn.io | bash\n:::\n::: at any time!\n:::\n" -} - -function askreboot() { - printf "It is \e[1mstrongly\e[0m recommended to reboot after un-installation.\n" - read -p "Would you like to reboot now? [y/n]: " -n 1 -r - echo - if [[ ${REPLY} =~ ^[Yy]$ ]]; then - printf "\nRebooting system...\n" - sleep 3 - shutdown -r now - fi -} - -######### SCRIPT ########### -echo "::: Preparing to remove packages, be sure that each may be safely removed depending on your operating system." -echo "::: (SAFE TO REMOVE ALL ON RASPBIAN)" -while true; do - read -rp "::: Do you wish to completely remove PiVPN configuration and installed packages from your system? (You will be prompted for each package) [y/n]: " yn - case $yn in - [Yy]* ) removeAll; askreboot; break;; - - [Nn]* ) printf "::: Not removing anything, exiting...\n"; break;; - esac -done diff --git a/scripts/update.sh b/scripts/update.sh deleted file mode 100755 index fb74450..0000000 --- a/scripts/update.sh +++ /dev/null @@ -1,99 +0,0 @@ -#/bin/bash - -###Updates pivpn scripts (Not PiVPN) -###Main Vars -pivpnrepo="https://github.com/pivpn/pivpn.git" -pivpnlocalpath="/etc/.pivpn" -pivpnscripts="/opt/pivpn/scripts" -bashcompletiondir="/etc/bash_completion.d/pivpn" - - -###Functions -##Updates scripts -updatepivpnscripts(){ - ##We don't know what sort of changes users have made. - ##Lets remove first /etc/.pivpn dir then clone it back again - echo "going do update PiVPN Scripts" - if [[ -d $pivpnlocalpath ]]; then - - sudo rm -rf $pivpnlocalpath - cloneandupdate - - else - cloneandupdate - fi - echo "PiVPN Scripts have been updated" -} - -##Updates scripts using test branch -updatefromtest(){ - ##We don't know what sort of changes users have made. - ##Lets remove first /etc/.pivpn dir then clone it back again - echo "PiVPN Scripts updating from test branch" - if [[ -d /etc/.pivpn ]]; then - - rm -rf /etc/.pivpn - cloneupdttest - - else - - cloneupdttest - - fi - echo "PiVPN Scripts updated have been updated from test branch" - } - -##Clone and copy pivpn scripts to /op/ -cloneandupdate(){ - - sudo git clone $pivpnrepo $pivpnlocalpath - sudo cp -r $pivpnlocalpath/scripts $pivpnscripts - sudo cp $pivpnlocalpath/scripts/bash-completion $bashcompletiondir - -} - -##same as cloneandupdate() but from test branch -##and falls back to master branch again after updating -cloneupdttest(){ - - sudo git clone $pivpnrepo $pivpnlocalpath - sudo git -C $pivpnlocalpath checkout test - sudo git -C $pivpnlocalpath pull origin test - sudo cp -r $pivpnlocalpath/scripts $pivpnscripts - sudo cp $pivpnlocalpath/scripts/bash-completion $bashcompletiondir - sudo git -C $pivpnlocalpath checkout master - -} - -scriptusage(){ - echo -e "Updates pivpn scripts,\n - Usage: - pivpn update | updates from master branch - pivpn update -t or --test | updates from test branch" - -} - -## SCRIPT - -if [[ $# -eq 0 ]]; then - updatepivpnscripts - -else - while true; do - case "$1" in - -t | --test | test ) - updatefromtest - exit 0 - ;; - -h | --help | help ) - scriptusage - exit 0 - ;; - * ) - updatepivpnscripts - exit 0 - ;; - esac - done -fi - From 5e16322f9edefd49609fee9686a0d33029836bcd Mon Sep 17 00:00:00 2001 From: Orazio Date: Mon, 14 Oct 2019 12:27:28 +0200 Subject: [PATCH 2/6] Added missing script folder --- scripts/openvpn/backup.sh | 36 +++ scripts/openvpn/bash-completion | 22 ++ scripts/openvpn/clientStat.sh | 35 +++ scripts/openvpn/listOVPN.sh | 27 +++ scripts/openvpn/makeOVPN.sh | 414 ++++++++++++++++++++++++++++++++ scripts/openvpn/pivpn | 106 ++++++++ scripts/openvpn/pivpnDebug.sh | 230 ++++++++++++++++++ scripts/openvpn/removeOVPN.sh | 123 ++++++++++ scripts/openvpn/update.sh | 99 ++++++++ scripts/wireguard/listCONF.sh | 23 ++ scripts/wireguard/makeCONF.sh | 130 ++++++++++ scripts/wireguard/pivpn | 83 +++++++ scripts/wireguard/pivpnDEBUG.sh | 173 +++++++++++++ scripts/wireguard/qrcodeCONF.sh | 63 +++++ scripts/wireguard/removeCONF.sh | 117 +++++++++ 15 files changed, 1681 insertions(+) create mode 100755 scripts/openvpn/backup.sh create mode 100644 scripts/openvpn/bash-completion create mode 100755 scripts/openvpn/clientStat.sh create mode 100755 scripts/openvpn/listOVPN.sh create mode 100755 scripts/openvpn/makeOVPN.sh create mode 100755 scripts/openvpn/pivpn create mode 100755 scripts/openvpn/pivpnDebug.sh create mode 100755 scripts/openvpn/removeOVPN.sh create mode 100755 scripts/openvpn/update.sh create mode 100755 scripts/wireguard/listCONF.sh create mode 100755 scripts/wireguard/makeCONF.sh create mode 100755 scripts/wireguard/pivpn create mode 100755 scripts/wireguard/pivpnDEBUG.sh create mode 100755 scripts/wireguard/qrcodeCONF.sh create mode 100755 scripts/wireguard/removeCONF.sh diff --git a/scripts/openvpn/backup.sh b/scripts/openvpn/backup.sh new file mode 100755 index 0000000..8ef6006 --- /dev/null +++ b/scripts/openvpn/backup.sh @@ -0,0 +1,36 @@ +#!/bin/bash +setupVars="/etc/pivpn/setupVars.conf" +backupdir=pivpnbackup +openvpndir=/etc/openvpn +ovpnsdir=${install_home}/ovpns +date=$(date +%Y-%m-%d-%H%M%S) + +if [ ! -f "${setupVars}" ]; then + echo "::: Missing setup vars file!" + exit 1 +fi + +source "${setupVars}" + +backup_openvpn(){ + if [[ ! -d $install_home/$backupdir ]]; then + mkdir $install_home/$backupdir + fi + cp -r $openvpndir $ovpnsdir $backupdir 2&>1 + backupzip=$date-pivpnbackup.tgz + tar -czf $backupzip -C ${install_home} $backupdir 2&>1 + echo -e "Backup crated to $install_home/$backupdir/$backupzip \nTo restore the backup, follow instructions at:\nhttps://github.com/pivpn/pivpn/wiki/FAQ#how-can-i-migrate-my-configs-to-another-pivpn-instance" +} + + +if [[ ! $EUID -eq 0 ]];then + if [[ $(dpkg-query -s sudo) ]];then + export SUDO="sudo" + else + echo "::: Please install sudo or run this as root." + exit 0 + fi +fi + +backup_openvpn + diff --git a/scripts/openvpn/bash-completion b/scripts/openvpn/bash-completion new file mode 100644 index 0000000..f317bc4 --- /dev/null +++ b/scripts/openvpn/bash-completion @@ -0,0 +1,22 @@ +_pivpn() +{ + local cur prev opts + COMPREPLY=() + cur="${COMP_WORDS[COMP_CWORD]}" + prev="${COMP_WORDS[COMP_CWORD-1]}" + dashopts="-a -c -d -l -r -h -u -up" + opts="debug add clients list revoke uninstall help update" + if [ "${#COMP_WORDS[@]}" -eq 2 ] + then + if [[ ${cur} == -* ]] ; then + COMPREPLY=( $(compgen -W "${dashopts}" -- "${cur}") ) + else + COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") ) + fi + elif [[ ( "$prev" == "add" || "$prev" == "-a" ) && "${#COMP_WORDS[@]}" -eq 3 ]] + then + COMPREPLY=( $(compgen -W "nopass" -- "${cur}") ) + fi + return 0 +} +complete -F _pivpn pivpn diff --git a/scripts/openvpn/clientStat.sh b/scripts/openvpn/clientStat.sh new file mode 100755 index 0000000..2af420f --- /dev/null +++ b/scripts/openvpn/clientStat.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# PiVPN: client status script + +STATUS_LOG="/var/log/openvpn-status.log" + +function hr() { + numfmt --to=iec-i --suffix=B "$1" +} + +printf "\n" +if [ ! -f "${STATUS_LOG}" ]; then + echo "The file: $STATUS_LOG was not found!" + exit 1 +fi + +printf ": NOTE : The output below is NOT real-time!\n" +printf ": : It may be off by a few minutes.\n" +printf "\n" +printf "\e[1m::: Client Status List :::\e[0m\n" +printf "\t\t\t\t\t\t\t\tBytes\t\tBytes\t\n" +printf "\e[4mName\e[0m\t\t\t\e[4mRemote IP\e[0m\t\t\e[4mVirtual IP\e[0m\t\e[4mReceived\e[0m\t\e[4mSent\e[0m\t\t\e[4mConnected Since\e[0m \n" +if grep -q "^CLIENT_LIST" "${STATUS_LOG}"; then + if [ -n "$(type -t numfmt)" ]; then + while read -r line; do + read -r -a array <<< $line + [[ ${array[0]} = CLIENT_LIST ]] || continue + printf "%s\t\t%s\t%s\t%s\t\t%s\t\t%s %s %s - %s\n" ${array[1]} ${array[2]} ${array[3]} $(hr ${array[4]}) $(hr ${array[5]}) ${array[7]} ${array[8]} ${array[10]} ${array[9]} + done <$STATUS_LOG + else + awk -F' ' -v s='CLIENT_LIST' '$1 == s {print $2"\t\t"$3"\t"$4"\t"$5"\t\t"$6"\t\t"$8" "$9" "$11" - "$10"\n"}' ${STATUS_LOG} + fi +else + printf "\nNo Clients Connected!\n" +fi +printf "\n" diff --git a/scripts/openvpn/listOVPN.sh b/scripts/openvpn/listOVPN.sh new file mode 100755 index 0000000..ec0ffd7 --- /dev/null +++ b/scripts/openvpn/listOVPN.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# PiVPN: list clients script + +INDEX="/etc/openvpn/easy-rsa/pki/index.txt" +printf "\n" +if [ ! -f "${INDEX}" ]; then + echo "The file: $INDEX was not found!" + exit 1 +fi + +printf ": NOTE : The first entry should always be your valid server!\n" +printf "\n" +printf "\e[1m::: Certificate Status List :::\e[0m\n" +printf " ::\e[4m Status \e[0m||\e[4m Name \e[0m:: \n" + +while read -r line || [ -n "$line" ]; do + STATUS=$(echo "$line" | awk '{print $1}') + NAME=$(echo "$line" | sed -e 's:.*/CN=::') + if [ "${STATUS}" == "V" ]; then + printf " Valid :: %s\n" "$NAME" + elif [ "${STATUS}" == "R" ]; then + printf " Revoked :: %s\n" "$NAME" + else + printf " Unknown :: %s\n" "$NAME" + fi +done <${INDEX} +printf "\n" diff --git a/scripts/openvpn/makeOVPN.sh b/scripts/openvpn/makeOVPN.sh new file mode 100755 index 0000000..e0c8891 --- /dev/null +++ b/scripts/openvpn/makeOVPN.sh @@ -0,0 +1,414 @@ +#!/bin/bash +# Create OVPN Client +# Default Variable Declarations +setupVars="/etc/pivpn/setupVars.conf" +DEFAULT="Default.txt" +FILEEXT=".ovpn" +CRT=".crt" +KEY=".key" +CA="ca.crt" +TA="ta.key" +INDEX="/etc/openvpn/easy-rsa/pki/index.txt" + +if [ ! -f "${setupVars}" ]; then + echo "::: Missing setup vars file!" + exit 1 +fi + +source "${setupVars}" + +helpFunc() { + echo "::: Create a client ovpn profile, optional nopass" + echo ":::" + echo "::: Usage: pivpn <-a|add> [-n|--name ] [-p|--password ]|[nopass] [-d|--days ] [-b|--bitwarden] [-i|--iOS] [-h|--help]" + echo ":::" + echo "::: Commands:" + echo "::: [none] Interactive mode" + echo "::: nopass Create a client without a password" + echo "::: -n,--name Name for the Client (default: '"$(hostname)"')" + echo "::: -p,--password Password for the Client (no default)" + echo "::: -d,--days Expire the certificate after specified number of days (default: 1080)" + echo "::: -b,--bitwarden Create and save a client through Bitwarden" + echo "::: -i,--iOS Generate a certificate that leverages iOS keychain" + echo "::: -h,--help Show this help dialog" +} + +if [ -z "$HELP_SHOWN" ]; then + helpFunc + echo + echo "HELP_SHOWN=1" >> "$setupVars" +fi + +# Parse input arguments +while test $# -gt 0 +do + _key="$1" + case "$_key" in + -n|--name|--name=*) + _val="${_key##--name=}" + if test "$_val" = "$_key" + then + test $# -lt 2 && echo "Missing value for the optional argument '$_key'." && exit 1 + _val="$2" + shift + fi + NAME="$_val" + ;; + -p|--password|--password=*) + _val="${_key##--password=}" + if test "$_val" = "$_key" + then + test $# -lt 2 && echo "Missing value for the optional argument '$_key'." && exit 1 + _val="$2" + shift + fi + PASSWD="$_val" + ;; + -d|--days|--days=*) + _val="${_key##--days=}" + if test "$_val" = "$_key" + then + test $# -lt 2 && echo "Missing value for the optional argument '$_key'." && exit 1 + _val="$2" + shift + fi + DAYS="$_val" + ;; + -i|--iOS) + iOS=1 + ;; + -h|--help) + helpFunc + exit 0 + ;; + nopass) + NO_PASS="1" + ;; + -b|--bitwarden) + if which bw; then + BITWARDEN="2" + else + echo "Bitwarden not found, please install bitwarden" + exit 1 + fi + + ;; + *) + echo "Error: Got an unexpected argument '$1'" + helpFunc + exit 1 + ;; + esac + shift +done + +# Functions def + +function keynoPASS() { + + #Build the client key + expect << EOF + set timeout -1 + set env(EASYRSA_CERT_EXPIRE) "${DAYS}" + spawn ./easyrsa build-client-full "${NAME}" nopass + expect eof +EOF + + cd pki || exit + +} + +function useBitwarden() { + + # login and unlock vault + printf "****Bitwarden Login****" + printf "\n" + SESSION_KEY=`bw login --raw` + export BW_SESSION=$SESSION_KEY + printf "Successfully Logged in!" + printf "\n" + + # ask user for username + printf "Enter the username: " + read -r NAME + + # check name + until [[ "$NAME" =~ ^[a-zA-Z0-9.@_-]+$ && ${NAME::1} != "." && ${NAME::1} != "-" ]] + do + echo "Name can only contain alphanumeric characters and these characters (.-@_). The name also cannot start with a dot (.) or a dash (-). Please try again." + # ask user for username again + printf "Enter the username: " + read -r NAME + done + + + # ask user for length of password + printf "Please enter the length of characters you want your password to be (minimum 12): " + read -r LENGTH + + # check length + until [[ "$LENGTH" -gt 11 && "$LENGTH" -lt 129 ]] + do + echo "Password must be between from 12 to 128 characters, please try again." + # ask user for length of password + printf "Enter the length of characters you want your password to be (minimum 12): " + read -r LENGTH + done + + printf "Creating a PiVPN item for your vault..." + printf "\n" + # create a new item for your PiVPN Password + PASSWD=`bw generate -usln --length $LENGTH` + bw get template item | jq '.login.type = "1"'| jq '.name = "PiVPN"' | jq -r --arg NAME "$NAME" '.login.username = $NAME' | jq -r --arg PASSWD "$PASSWD" '.login.password = $PASSWD' | bw encode | bw create item + bw logout + +} + +function keyPASS() { + + if [[ -z "${PASSWD}" ]]; then + stty -echo + while true + do + printf "Enter the password for the client: " + read -r PASSWD + printf "\n" + printf "Enter the password again to verify: " + read -r PASSWD2 + printf "\n" + [ "${PASSWD}" = "${PASSWD2}" ] && break + printf "Passwords do not match! Please try again.\n" + done + stty echo + if [[ -z "${PASSWD}" ]]; then + echo "You left the password blank" + echo "If you don't want a password, please run:" + echo "pivpn add nopass" + exit 1 + fi + fi + if [ ${#PASSWD} -lt 4 ] || [ ${#PASSWD} -gt 1024 ] + then + echo "Password must be between from 4 to 1024 characters" + exit 1 + fi + + #Escape chars in PASSWD + PASSWD=$(echo -n ${PASSWD} | sed -e 's/\\/\\\\/g' -e 's/\//\\\//g' -e 's/\$/\\\$/g' -e 's/!/\\!/g' -e 's/\./\\\./g' -e "s/'/\\\'/g" -e 's/"/\\"/g' -e 's/\*/\\\*/g' -e 's/\@/\\\@/g' -e 's/\#/\\\#/g' -e 's/£/\\£/g' -e 's/%/\\%/g' -e 's/\^/\\\^/g' -e 's/\&/\\\&/g' -e 's/(/\\(/g' -e 's/)/\\)/g' -e 's/-/\\-/g' -e 's/_/\\_/g' -e 's/\+/\\\+/g' -e 's/=/\\=/g' -e 's/\[/\\\[/g' -e 's/\]/\\\]/g' -e 's/;/\\;/g' -e 's/:/\\:/g' -e 's/|/\\|/g' -e 's//\\>/g' -e 's/,/\\,/g' -e 's/?/\\?/g' -e 's/~/\\~/g' -e 's/{/\\{/g' -e 's/}/\\}/g') + + #Build the client key and then encrypt the key + + expect << EOF + set timeout -1 + set env(EASYRSA_CERT_EXPIRE) "${DAYS}" + spawn ./easyrsa build-client-full "${NAME}" + expect "Enter PEM pass phrase" { send -- "${PASSWD}\r" } + expect "Verifying - Enter PEM pass phrase" { send -- "${PASSWD}\r" } + expect eof +EOF + cd pki || exit + +} + +#make sure ovpns dir exists +if [ ! -d "$install_home/ovpns" ]; then + mkdir "$install_home/ovpns" + chmod 0750 "$install_home/ovpns" +fi + +#bitWarden +if [[ "${BITWARDEN}" =~ "2" ]]; then + useBitwarden +fi + +if [ -z "${NAME}" ]; then + printf "Enter a Name for the Client: " + read -r NAME +fi + +if [[ ${NAME::1} == "." ]] || [[ ${NAME::1} == "-" ]]; then + echo "Names cannot start with a dot (.) or a dash (-)." + exit 1 +fi + +if [[ "${NAME}" =~ [^a-zA-Z0-9.@_-] ]]; then + echo "Name can only contain alphanumeric characters and these characters (.-@_)." + exit 1 +fi + +if [[ -z "${NAME}" ]]; then + echo "You cannot leave the name blank." + exit 1 +fi + +# Check if name is already in use +while read -r line || [ -n "${line}" ]; do + STATUS=$(echo "$line" | awk '{print $1}') + + if [ "${STATUS}" == "V" ]; then + CERT=$(echo "$line" | sed -e 's:.*/CN=::') + if [ "${CERT}" == "${NAME}" ]; then + INUSE="1" + break + fi + fi +done <${INDEX} + +if [ "${INUSE}" == "1" ]; then + printf "\n!! This name is already in use by a Valid Certificate." + printf "\nPlease choose another name or revoke this certificate first.\n" + exit 1 +fi + +# Check if name is reserved +if [ "${NAME}" == "ta" ] || [ "${NAME}" == "server" ] || [ "${NAME}" == "ca" ]; then + echo "Sorry, this is in use by the server and cannot be used by clients." + exit 1 +fi + +#As of EasyRSA 3.0.6, by default certificates last 1080 days, see https://github.com/OpenVPN/easy-rsa/blob/6b7b6bf1f0d3c9362b5618ad18c66677351cacd1/easyrsa3/vars.example +if [ -z "${DAYS}" ]; then + read -r -e -p "How many days should the certificate last? " -i 1080 DAYS +fi + +if [[ ! "$DAYS" =~ ^[0-9]+$ ]] || [ "$DAYS" -lt 1 ] || [ "$DAYS" -gt 3650 ]; then + #The CRL lasts 3650 days so it doesn't make much sense that certificates would last longer + echo "Please input a valid number of days, between 1 and 3650 inclusive." + exit 1 + +fi + +cd /etc/openvpn/easy-rsa || exit + +if [[ "${NO_PASS}" =~ "1" ]]; then + if [[ -n "${PASSWD}" ]]; then + echo "Both nopass and password arguments passed to the script. Please use either one." + exit 1 + else + keynoPASS + fi +else + keyPASS +fi + +#1st Verify that clients Public Key Exists +if [ ! -f "issued/${NAME}${CRT}" ]; then + echo "[ERROR]: Client Public Key Certificate not found: $NAME$CRT" + exit +fi +echo "Client's cert found: $NAME$CRT" + +#Then, verify that there is a private key for that client +if [ ! -f "private/${NAME}${KEY}" ]; then + echo "[ERROR]: Client Private Key not found: $NAME$KEY" + exit +fi +echo "Client's Private Key found: $NAME$KEY" + +#Confirm the CA public key exists +if [ ! -f "${CA}" ]; then + echo "[ERROR]: CA Public Key not found: $CA" + exit +fi +echo "CA public Key found: $CA" + +#Confirm the tls key file exists +if [ ! -f "${TA}" ]; then + echo "[ERROR]: tls Private Key not found: $TA" + exit +fi +echo "tls Private Key found: $TA" + + +## Added new step to create an .ovpn12 file that can be stored on iOS keychain +## This step is more secure method and does not require the end-user to keep entering passwords, or storing the client private cert where it can be easily tampered +## https://openvpn.net/faq/how-do-i-use-a-client-certificate-and-private-key-from-the-ios-keychain/ +if [ "$iOS" = "1" ]; then + #Generates the .ovpn file WITHOUT the client private key + { + # Start by populating with the default file + cat "${DEFAULT}" + + #Now, append the CA Public Cert + echo "" + cat "${CA}" + echo "" + + #Next append the client Public Cert + echo "" + sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' < "issued/${NAME}${CRT}" + echo "" + + #Finally, append the TA Private Key + if [ -f /etc/pivpn/TWO_POINT_FOUR ]; then + echo "" + cat "${TA}" + echo "" + else + echo "" + cat "${TA}" + echo "" + fi + + } > "${NAME}${FILEEXT}" + + # Copy the .ovpn profile to the home directory for convenient remote access + + printf "========================================================\n" + printf "Generating an .ovpn12 file for use with iOS devices\n" + printf "Please remember the export password\n" + printf "as you will need this import the certificate on your iOS device\n" + printf "========================================================\n" + openssl pkcs12 -passin pass:"$PASSWD" -export -in "issued/${NAME}${CRT}" -inkey "private/${NAME}${KEY}" -certfile ${CA} -name "${NAME}" -out "$install_home/ovpns/$NAME.ovpn12" + chown "$install_user" "$install_home/ovpns/$NAME.ovpn12" + chmod 600 "$install_home/ovpns/$NAME.ovpn12" + printf "========================================================\n" + printf "\e[1mDone! %s successfully created!\e[0m \n" "$NAME.ovpn12" + printf "You will need to transfer both the .ovpn and .ovpn12 files\n" + printf "to your iOS device.\n" + printf "========================================================\n\n" +else + #This is the standard non-iOS configuration +#Ready to make a new .ovpn file + { + # Start by populating with the default file + cat "${DEFAULT}" + + #Now, append the CA Public Cert + echo "" + cat "${CA}" + echo "" + + #Next append the client Public Cert + echo "" + sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' < "issued/${NAME}${CRT}" + echo "" + + #Then, append the client Private Key + echo "" + cat "private/${NAME}${KEY}" + echo "" + + #Finally, append the tls Private Key + echo "" + cat "${TA}" + echo "" + + } > "${NAME}${FILEEXT}" + +fi + + +# Copy the .ovpn profile to the home directory for convenient remote access +cp "/etc/openvpn/easy-rsa/pki/$NAME$FILEEXT" "$install_home/ovpns/$NAME$FILEEXT" +chown "$install_user" "$install_home/ovpns/$NAME$FILEEXT" +chmod 640 "/etc/openvpn/easy-rsa/pki/$NAME$FILEEXT" +chmod 640 "$install_home/ovpns/$NAME$FILEEXT" +printf "\n\n" +printf "========================================================\n" +printf "\e[1mDone! %s successfully created!\e[0m \n" "$NAME$FILEEXT" +printf "%s was copied to:\n" "$NAME$FILEEXT" +printf " %s/ovpns\n" "$install_home" +printf "for easy transfer. Please use this profile only on one\n" +printf "device and create additional profiles for other devices.\n" +printf "========================================================\n\n" diff --git a/scripts/openvpn/pivpn b/scripts/openvpn/pivpn new file mode 100755 index 0000000..de55586 --- /dev/null +++ b/scripts/openvpn/pivpn @@ -0,0 +1,106 @@ +#!/bin/bash + +# Must be root to use this tool +if [[ ! $EUID -eq 0 ]];then + if [[ $(dpkg-query -s sudo) ]];then + export SUDO="sudo" + else + echo "::: Please install sudo or run this as root." + exit 0 + fi +fi + +function makeOVPNFunc { + shift + $SUDO /opt/pivpn/makeOVPN.sh "$@" + exit 0 +} + +function listClientsFunc { + $SUDO /opt/pivpn/clientStat.sh + exit 0 +} + +function listOVPNFunc { + $SUDO /opt/pivpn/listOVPN.sh + exit 0 +} + +function debugFunc { + echo "::: Generating Debug Output" + $SUDO /opt/pivpn/pivpnDebug.sh | tee /tmp/debug.txt + echo "::: " + echo "::: Debug output completed above." + echo "::: Copy saved to /tmp/debug.txt" + echo "::: " + exit 0 +} + +function removeOVPNFunc { + shift + $SUDO /opt/pivpn/removeOVPN.sh "$@" + exit 0 +} + +function uninstallFunc { + $SUDO /opt/pivpn/uninstall.sh + exit 0 +} + +function versionFunc { + printf "\e[1mVersion 1.9\e[0m\n" +} + +function update { + + shift + $SUDO /opt/pivpn/update.sh "$@" + exit 0 + + +} + +function backup { + + $SUDO /opt/pivpn/backup.sh + exit 0 + +} + + +function helpFunc { + echo "::: Control all PiVPN specific functions!" + echo ":::" + echo "::: Usage: pivpn [option]" + echo ":::" + echo "::: Commands:" + echo "::: -a, add [nopass] Create a client ovpn profile, optional nopass" + echo "::: -c, clients List any connected clients to the server" + echo "::: -d, debug Start a debugging session if having trouble" + echo "::: -l, list List all valid and revoked certificates" + echo "::: -r, revoke Revoke a client ovpn profile" + echo "::: -h, help Show this help dialog" + echo "::: -u, uninstall Uninstall PiVPN from your system!" + echo "::: -up, update Updates PiVPN Scripts" + echo "::: -bk, backup Backup Openvpn and ovpns dir" + exit 0 +} + +if [[ $# = 0 ]]; then + helpFunc +fi + +# Handle redirecting to specific functions based on arguments +case "$1" in +"-a" | "add" ) makeOVPNFunc "$@";; +"-c" | "clients" ) listClientsFunc;; +"-d" | "debug" ) debugFunc;; +"-l" | "list" ) listOVPNFunc;; +"-r" | "revoke" ) removeOVPNFunc "$@";; +"-h" | "help" ) helpFunc;; +"-u" | "uninstall" ) uninstallFunc;; +"-v" ) versionFunc;; +"-up"| "update" ) update "$@" ;; +"-bk"| "backup" ) backup;; +* ) helpFunc;; +esac diff --git a/scripts/openvpn/pivpnDebug.sh b/scripts/openvpn/pivpnDebug.sh new file mode 100755 index 0000000..847bcdc --- /dev/null +++ b/scripts/openvpn/pivpnDebug.sh @@ -0,0 +1,230 @@ +#!/usr/bin/env bash +# This scripts runs as root + +setupVars="/etc/pivpn/setupVars.conf" +ERR=0 + +if [ ! -f "${setupVars}" ]; then + echo "::: Missing setup vars file!" + exit 1 +fi + +source "${setupVars}" + +echo -e "::::\t\t\e[4mPiVPN debug\e[0m\t\t ::::" +printf "=============================================\n" +echo -e "::::\t\t\e[4mLatest commit\e[0m\t\t ::::" +git --git-dir /etc/.pivpn/.git log -n 1 +printf "=============================================\n" +echo -e "::::\t \e[4mInstallation settings\e[0m \t ::::" +# Use the wildcard so setupVars.conf.update.bak from the previous install is not shown +for filename in /etc/pivpn/*; do + if [[ "$filename" != "/etc/pivpn/setupVars.conf"* ]]; then + echo "$filename -> $(cat "$filename")" + fi +done +printf "=============================================\n" +echo -e "::::\t\e[4msetupVars file shown below\e[0m\t ::::" +sed "s/$pivpnHOST/REDACTED/" < /etc/pivpn/setupVars.conf +printf "=============================================\n" +echo -e ":::: \e[4mServer configuration shown below\e[0m ::::" +cat /etc/openvpn/server.conf +printf "=============================================\n" +echo -e ":::: \e[4mClient template file shown below\e[0m ::::" +sed "s/$pivpnHOST/REDACTED/" < /etc/openvpn/easy-rsa/pki/Default.txt +printf "=============================================\n" +echo -e ":::: \t\e[4mRecursive list of files in\e[0m\t ::::\n::: \e[4m/etc/openvpn/easy-rsa/pki shows below\e[0m :::" +ls -LR /etc/openvpn/easy-rsa/pki/ -Ireqs -Icerts_by_serial +printf "=============================================\n" +echo -e "::::\t\t\e[4mSelf check\e[0m\t\t ::::" + +if [ "$(cat /proc/sys/net/ipv4/ip_forward)" -eq 1 ]; then + echo ":: [OK] IP forwarding is enabled" +else + ERR=1 + read -r -p ":: [ERR] IP forwarding is not enabled, attempt fix now? [Y/n] " REPLY + if [[ ${REPLY} =~ ^[Yy]$ ]]; then + sed -i '/net.ipv4.ip_forward=1/s/^#//g' /etc/sysctl.conf + sysctl -p + echo "Done" + fi +fi + +if [ "$USING_UFW" -eq 0 ]; then + + if iptables -t nat -C POSTROUTING -s 10.8.0.0/24 -o "${PHYS_INT}" -j MASQUERADE &> /dev/null; then + echo ":: [OK] Iptables MASQUERADE rule set" + else + ERR=1 + read -r -p ":: [ERR] Iptables MASQUERADE rule is not set, attempt fix now? [Y/n] " REPLY + if [[ ${REPLY} =~ ^[Yy]$ ]]; then + iptables -t nat -F + iptables -t nat -I POSTROUTING -s 10.8.0.0/24 -o "${PHYS_INT}" -j MASQUERADE + iptables-save > /etc/iptables/rules.v4 + echo "Done" + fi + fi + + + if [ "$INPUT_CHAIN_EDITED" -eq 1 ]; then + + if iptables -C INPUT -i "$PHYS_INT" -p "$pivpnPROTO" --dport "$pivpnPORT" -j ACCEPT &> /dev/null; then + echo ":: [OK] Iptables INPUT rule set" + else + ERR=1 + read -r -p ":: [ERR] Iptables INPUT rule is not set, attempt fix now? [Y/n] " REPLY + if [[ ${REPLY} =~ ^[Yy]$ ]]; then + iptables -I INPUT 1 -i "$PHYS_INT" -p "$pivpnPROTO" --dport "$pivpnPORT" -j ACCEPT + iptables-save > /etc/iptables/rules.v4 + echo "Done" + fi + fi + fi + + if [ "$FORWARD_CHAIN_EDITED" -eq 1 ]; then + + if iptables -C FORWARD -s 10.8.0.0/24 -i tun0 -o "$PHYS_INT" -j ACCEPT &> /dev/null; then + echo ":: [OK] Iptables FORWARD rule set" + else + ERR=1 + read -r -p ":: [ERR] Iptables FORWARD rule is not set, attempt fix now? [Y/n] " REPLY + if [[ ${REPLY} =~ ^[Yy]$ ]]; then + iptables -I FORWARD 1 -d 10.8.0.0/24 -i "$PHYS_INT" -o tun0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT + iptables -I FORWARD 2 -s 10.8.0.0/24 -i tun0 -o "$PHYS_INT" -j ACCEPT + iptables-save > /etc/iptables/rules.v4 + echo "Done" + fi + fi + fi + +else + + if LANG="en_US.UTF-8" ufw status | grep -qw 'active'; then + echo ":: [OK] Ufw is enabled" + else + ERR=1 + read -r -p ":: [ERR] Ufw is not enabled, try to enable now? [Y/n] " REPLY + if [[ ${REPLY} =~ ^[Yy]$ ]]; then + ufw enable + fi + fi + + if iptables -t nat -C POSTROUTING -s 10.8.0.0/24 -o "${PHYS_INT}" -j MASQUERADE &> /dev/null; then + echo ":: [OK] Iptables MASQUERADE rule set" + else + ERR=1 + read -r -p ":: [ERR] Iptables MASQUERADE rule is not set, attempt fix now? [Y/n] " REPLY + if [[ ${REPLY} =~ ^[Yy]$ ]]; then + sed "/delete these required/i *nat\n:POSTROUTING ACCEPT [0:0]\n-I POSTROUTING -s 10.8.0.0/24 -o $PHYS_INT -j MASQUERADE\nCOMMIT\n" -i /etc/ufw/before.rules + ufw reload + echo "Done" + fi + fi + + if iptables -C ufw-user-input -p "${pivpnPROTO}" --dport "${pivpnPORT}" -j ACCEPT &> /dev/null; then + echo ":: [OK] Ufw input rule set" + else + ERR=1 + read -r -p ":: [ERR] Ufw input rule is not set, attempt fix now? [Y/n] " REPLY + if [[ ${REPLY} =~ ^[Yy]$ ]]; then + ufw insert 1 allow "$pivpnPORT"/"$pivpnPROTO" + ufw reload + echo "Done" + fi + fi + + if [ "$OLD_UFW" -eq 1 ]; then + FORWARD_POLICY="$(iptables -S FORWARD | grep '^-P' | awk '{print $3}')" + if [ "$FORWARD_POLICY" = "ACCEPT" ]; then + echo ":: [OK] Ufw forwarding policy is accept" + else + ERR=1 + read -r -p ":: [ERR] Ufw forwarding policy is not 'ACCEPT', attempt fix now? [Y/n] " REPLY + if [[ ${REPLY} =~ ^[Yy]$ ]]; then + sed -i "s/\(DEFAULT_FORWARD_POLICY=\).*/\1\"ACCEPT\"/" /etc/default/ufw + ufw reload > /dev/null + echo "Done" + fi + fi + else + if iptables -C ufw-user-forward -i tun0 -o "${PHYS_INT}" -s 10.8.0.0/24 -j ACCEPT &> /dev/null; then + echo ":: [OK] Ufw forwarding rule set" + else + ERR=1 + read -r -p ":: [ERR] Ufw forwarding rule is not set, attempt fix now? [Y/n] " REPLY + if [[ ${REPLY} =~ ^[Yy]$ ]]; then + ufw route insert 1 allow in on tun0 from 10.8.0.0/24 out on "$PHYS_INT" to any + ufw reload + echo "Done" + fi + fi + fi + +fi + +if systemctl is-active -q openvpn; then + echo ":: [OK] OpenVPN is running" +else + ERR=1 + read -r -p ":: [ERR] OpenVPN is not running, try to start now? [Y/n] " REPLY + if [[ ${REPLY} =~ ^[Yy]$ ]]; then + systemctl start openvpn + echo "Done" + fi +fi + +if systemctl is-enabled -q openvpn; then + echo ":: [OK] OpenVPN is enabled (it will automatically start on reboot)" +else + ERR=1 + read -r -p ":: [ERR] OpenVPN is not enabled, try to enable now? [Y/n] " REPLY + if [[ ${REPLY} =~ ^[Yy]$ ]]; then + systemctl enable openvpn + echo "Done" + fi +fi + +# grep -w (whole word) is used so port 111940 with now match when looking for 1194 +if netstat -uanpt | grep openvpn | grep -w "${pivpnPORT}" | grep -q "${pivpnPROTO}"; then + echo ":: [OK] OpenVPN is listening on port ${pivpnPORT}/${pivpnPROTO}" +else + ERR=1 + read -r -p ":: [ERR] OpenVPN is not listening, try to restart now? [Y/n] " REPLY + if [[ ${REPLY} =~ ^[Yy]$ ]]; then + systemctl restart openvpn + echo "Done" + fi +fi + +if [ "$ERR" -eq 1 ]; then + echo -e "[INFO] Run \e[1mpivpn -d\e[0m again to see if we detect issues" +fi + +printf "=============================================\n" +echo -e ":::: \e[4mSnippet of the server log\e[0m ::::" +tail -20 /var/log/openvpn.log > /tmp/snippet + +# Regular expession taken from https://superuser.com/a/202835, it will match invalid IPs +# like 123.456.789.012 but it's fine because the log only contains valid ones. +declare -a IPS_TO_HIDE=($(grepcidr -v 10.0.0.0/8,172.16.0.0/12,192.168.0.0/16 /tmp/snippet | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | uniq)) +for IP in "${IPS_TO_HIDE[@]}"; do + sed -i "s/$IP/REDACTED/g" /tmp/snippet +done + +cat /tmp/snippet +rm /tmp/snippet +printf "=============================================\n" +echo -e "::::\t\t\e[4mDebug complete\e[0m\t\t ::::" + +# Telekom Hybrid Check +wget -O /tmp/hybcheck http://speedport.ip &>/dev/null +if grep -Fq "Speedport Pro" /tmp/hybcheck || grep -Fq "Speedport Hybrid" /tmp/hybcheck +then + printf ":::\t\t\t\t\t:::\n::\tTelekom Hybrid Check\t\t ::\n:::\t\t\t\t\t:::\n" + echo "Are you using Telekom Hybrid (found a hybrid compatible router)?" + echo "If yes and you have problems with the connections you can test the following:" + echo "Add 'tun-mtu 1316' in /etc/openvpn/easy-rsa/pki/Default.txt to set a hybrid compatible MTU size (new .ovpn files)." + echo "For already existing .ovpn files 'tun-mtu 1316' can also be inserted there manually." + echo "With Telekom hybrid connections, you may have to experiment a little with MTU (tun-mtu, link-mtu and mssfix)." +fi +rm /tmp/hybcheck diff --git a/scripts/openvpn/removeOVPN.sh b/scripts/openvpn/removeOVPN.sh new file mode 100755 index 0000000..0d79eaf --- /dev/null +++ b/scripts/openvpn/removeOVPN.sh @@ -0,0 +1,123 @@ +#!/usr/bin/env bash +# PiVPN: revoke client script + +install_user=$( [-h|--help] [] ... [] ..." + echo ":::" + echo "::: Commands:" + echo "::: [none] Interactive mode" + echo "::: Client(s) to to revoke" + echo "::: -h,--help Show this help dialog" +} + +# Parse input arguments +while test $# -gt 0 +do + _key="$1" + case "$_key" in + -h|--help) + helpFunc + exit 0 + ;; + *) + CERTS_TO_REVOKE+=("$1") + ;; + esac + shift +done + +if [ ! -f "${INDEX}" ]; then + printf "The file: %s was not found\n" "$INDEX" + exit 1 +fi + +if [[ -z "${CERTS_TO_REVOKE}" ]]; then + printf "\n" + printf " ::\e[4m Certificate List \e[0m:: \n" + + i=0 + while read -r line || [ -n "$line" ]; do + STATUS=$(echo "$line" | awk '{print $1}') + if [[ "${STATUS}" = "V" ]]; then + NAME=$(echo "$line" | sed -e 's:.*/CN=::') + CERTS[$i]=${NAME} + if [ "$i" != 0 ]; then + # Prevent printing "server" certificate + printf " %s\n" "$NAME" + fi + let i=i+1 + fi + done <${INDEX} + printf "\n" + + echo "::: Please enter the Name of the client to be revoked from the list above:" + read -r NAME + + if [[ -z "${NAME}" ]]; then + echo "You can not leave this blank!" + exit 1 + fi + + for((x=1;x<=i;++x)); do + if [ "${CERTS[$x]}" = "${NAME}" ]; then + VALID=1 + fi + done + + if [ -z "${VALID}" ]; then + printf "You didn't enter a valid cert name!\n" + exit 1 + fi + + CERTS_TO_REVOKE=( "${NAME}" ) +else + i=0 + while read -r line || [ -n "$line" ]; do + STATUS=$(echo "$line" | awk '{print $1}') + if [[ "${STATUS}" = "V" ]]; then + NAME=$(echo "$line" | sed -e 's:.*/CN=::') + CERTS[$i]=${NAME} + let i=i+1 + fi + done <${INDEX} + + for (( ii = 0; ii < ${#CERTS_TO_REVOKE[@]}; ii++)); do + VALID=0 + for((x=1;x<=i;++x)); do + if [ "${CERTS[$x]}" = "${CERTS_TO_REVOKE[ii]}" ]; then + VALID=1 + fi + done + + if [ "${VALID}" != 1 ]; then + printf "You passed an invalid cert name: '"%s"'!\n" "${CERTS_TO_REVOKE[ii]}" + exit 1 + fi + done +fi + +cd /etc/openvpn/easy-rsa || exit + +install_home=$(grep -m1 "^${install_user}:" /etc/passwd | cut -d: -f6) +install_home=${install_home%/} # remove possible trailing slash +for (( ii = 0; ii < ${#CERTS_TO_REVOKE[@]}; ii++)); do + printf "\n::: Revoking certificate '"%s"'.\n" "${CERTS_TO_REVOKE[ii]}" + ./easyrsa --batch revoke "${CERTS_TO_REVOKE[ii]}" + ./easyrsa gen-crl + printf "\n::: Certificate revoked, and CRL file updated.\n" + printf "::: Removing certs and client configuration for this profile.\n" + rm -rf "pki/reqs/${CERTS_TO_REVOKE[ii]}.req" + rm -rf "pki/private/${CERTS_TO_REVOKE[ii]}.key" + rm -rf "pki/issued/${CERTS_TO_REVOKE[ii]}.crt" + + rm -rf "${install_home}/ovpns/${CERTS_TO_REVOKE[ii]}.ovpn" + rm -rf "/etc/openvpn/easy-rsa/pki/${CERTS_TO_REVOKE[ii]}.ovpn" + cp /etc/openvpn/easy-rsa/pki/crl.pem /etc/openvpn/crl.pem +done +printf "::: Completed!\n" diff --git a/scripts/openvpn/update.sh b/scripts/openvpn/update.sh new file mode 100755 index 0000000..fb74450 --- /dev/null +++ b/scripts/openvpn/update.sh @@ -0,0 +1,99 @@ +#/bin/bash + +###Updates pivpn scripts (Not PiVPN) +###Main Vars +pivpnrepo="https://github.com/pivpn/pivpn.git" +pivpnlocalpath="/etc/.pivpn" +pivpnscripts="/opt/pivpn/scripts" +bashcompletiondir="/etc/bash_completion.d/pivpn" + + +###Functions +##Updates scripts +updatepivpnscripts(){ + ##We don't know what sort of changes users have made. + ##Lets remove first /etc/.pivpn dir then clone it back again + echo "going do update PiVPN Scripts" + if [[ -d $pivpnlocalpath ]]; then + + sudo rm -rf $pivpnlocalpath + cloneandupdate + + else + cloneandupdate + fi + echo "PiVPN Scripts have been updated" +} + +##Updates scripts using test branch +updatefromtest(){ + ##We don't know what sort of changes users have made. + ##Lets remove first /etc/.pivpn dir then clone it back again + echo "PiVPN Scripts updating from test branch" + if [[ -d /etc/.pivpn ]]; then + + rm -rf /etc/.pivpn + cloneupdttest + + else + + cloneupdttest + + fi + echo "PiVPN Scripts updated have been updated from test branch" + } + +##Clone and copy pivpn scripts to /op/ +cloneandupdate(){ + + sudo git clone $pivpnrepo $pivpnlocalpath + sudo cp -r $pivpnlocalpath/scripts $pivpnscripts + sudo cp $pivpnlocalpath/scripts/bash-completion $bashcompletiondir + +} + +##same as cloneandupdate() but from test branch +##and falls back to master branch again after updating +cloneupdttest(){ + + sudo git clone $pivpnrepo $pivpnlocalpath + sudo git -C $pivpnlocalpath checkout test + sudo git -C $pivpnlocalpath pull origin test + sudo cp -r $pivpnlocalpath/scripts $pivpnscripts + sudo cp $pivpnlocalpath/scripts/bash-completion $bashcompletiondir + sudo git -C $pivpnlocalpath checkout master + +} + +scriptusage(){ + echo -e "Updates pivpn scripts,\n + Usage: + pivpn update | updates from master branch + pivpn update -t or --test | updates from test branch" + +} + +## SCRIPT + +if [[ $# -eq 0 ]]; then + updatepivpnscripts + +else + while true; do + case "$1" in + -t | --test | test ) + updatefromtest + exit 0 + ;; + -h | --help | help ) + scriptusage + exit 0 + ;; + * ) + updatepivpnscripts + exit 0 + ;; + esac + done +fi + diff --git a/scripts/wireguard/listCONF.sh b/scripts/wireguard/listCONF.sh new file mode 100755 index 0000000..02e5224 --- /dev/null +++ b/scripts/wireguard/listCONF.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +cd /etc/wireguard/configs +if [ ! -s clients.txt ]; then + echo "::: There are no clients to list" + exit 1 +fi + +# Present the user with a summary of the clients, fetching info from dates. +FORMATTED+=": \e[4mClient\e[0m&\e[4mCreation date\e[0m :\n" + +while read -r LINE; do + CLIENT_NAME="$(awk '{print $1}' <<< "$LINE")" + + CREATION_DATE="$(awk '{print $2}' <<< "$LINE")" + + # Dates are converted from UNIX time to human readable. + CD_FORMAT="$(date -d @"$CREATION_DATE" +'%d %b %Y, %H:%M, %Z')" + + FORMATTED+="• $CLIENT_NAME&$CD_FORMAT\n" +done < clients.txt + +echo -e "$FORMATTED" | column -t -s '&' \ No newline at end of file diff --git a/scripts/wireguard/makeCONF.sh b/scripts/wireguard/makeCONF.sh new file mode 100755 index 0000000..cbfd9b4 --- /dev/null +++ b/scripts/wireguard/makeCONF.sh @@ -0,0 +1,130 @@ +#!/bin/bash + +setupVars="/etc/pivpn/setupVars.conf" + +helpFunc(){ + echo "::: Create a client conf profile" + echo ":::" + echo "::: Usage: pivpn <-a|add> [-n|--name ] [-h|--help]" + echo ":::" + echo "::: Commands:" + echo "::: [none] Interactive mode" + echo "::: -n,--name Name for the Client (default: '$HOSTNAME')" + echo "::: -h,--help Show this help dialog" +} + +# Parse input arguments +while test $# -gt 0; do + _key="$1" + case "$_key" in + -n|--name|--name=*) + _val="${_key##--name=}" + if test "$_val" = "$_key"; then + test $# -lt 2 && echo "::: Missing value for the optional argument '$_key'." && exit 1 + _val="$2" + shift + fi + CLIENT_NAME="$_val" + ;; + -h|--help) + helpFunc + exit 0 + ;; + *) + echo "::: Error: Got an unexpected argument '$1'" + helpFunc + exit 1 + ;; + esac + shift +done + +if [ ! -f "${setupVars}" ]; then + echo "::: Missing setup vars file!" + exit 1 +fi + +source "${setupVars}" + +# The home folder variable was sourced from the settings file. +if [ ! -d "${install_home}/configs" ]; then + mkdir "${install_home}/configs" + chown "${install_user}":"${install_user}" "${install_home}/configs" +fi + +cd /etc/wireguard + +if [ -z "${CLIENT_NAME}" ]; then + read -r -p "Enter a Name for the Client: " CLIENT_NAME +fi + +if [[ "${CLIENT_NAME}" =~ [^a-zA-Z0-9.@_-] ]]; then + echo "Name can only contain alphanumeric characters and these characters (.-@_)." + exit 1 +fi + +if [ -z "${CLIENT_NAME}" ]; then + echo "::: You cannot leave the name blank." + exit 1 +fi + +if [ -f "configs/${CLIENT_NAME}.conf" ]; then + echo "::: A client with this name already exists" + exit 1 +fi + +wg genkey | tee "keys/${CLIENT_NAME}_priv" | wg pubkey > "keys/${CLIENT_NAME}_pub" +echo "::: Client Keys generated" + +# Find an unused number for the last octet of the client IP +for i in {2..254}; do + if ! grep -q " $i" configs/clients.txt; then + COUNT="$i" + echo "${CLIENT_NAME} $(date +%s) ${COUNT}" >> configs/clients.txt + break + fi +done + +echo -n "[Interface] +PrivateKey = $(cat "keys/${CLIENT_NAME}_priv") +Address = 10.6.0.${COUNT}/24 +DNS = ${pivpnDNS1}" > "configs/${CLIENT_NAME}.conf" + +if [ -n "${pivpnDNS2}" ]; then + echo ", ${pivpnDNS2}" >> "configs/${CLIENT_NAME}.conf" +else + echo >> "configs/${CLIENT_NAME}.conf" +fi +echo >> "configs/${CLIENT_NAME}.conf" + +echo "[Peer] +PublicKey = $(cat keys/server_pub) +PresharedKey = $(cat keys/psk) +Endpoint = ${pivpnHOST}:${pivpnPORT} +AllowedIPs = 0.0.0.0/0" >> "configs/${CLIENT_NAME}.conf" +echo "::: Client config generated" + +echo "# begin ${CLIENT_NAME} +[Peer] +PublicKey = $(cat "keys/${CLIENT_NAME}_pub") +PresharedKey = $(cat keys/psk) +AllowedIPs = 10.6.0.${COUNT}/32 +# end ${CLIENT_NAME}" >> wg0.conf +echo "::: Updated server config" + +if systemctl restart wg-quick@wg0; then + echo "::: WireGuard restarted" +else + echo "::: Failed to restart WireGuard" +fi + +cp "configs/${CLIENT_NAME}.conf" "${install_home}/configs/${CLIENT_NAME}.conf" +chown "${install_user}":"${install_user}" "${install_home}/configs/${CLIENT_NAME}.conf" + +echo "======================================================================" +echo -e "::: Done! \e[1m${CLIENT_NAME}.conf successfully created!\e[0m" +echo "::: ${CLIENT_NAME}.conf was copied to ${install_home}/configs for easy transfer." +echo "::: Please use this profile only on one device and create additional" +echo -e "::: profiles for other devices. You can also use \e[1mpivpn -qr\e[0m" +echo "::: to generate a QR Code you can scan with the mobile app." +echo "======================================================================" diff --git a/scripts/wireguard/pivpn b/scripts/wireguard/pivpn new file mode 100755 index 0000000..f4bcfd9 --- /dev/null +++ b/scripts/wireguard/pivpn @@ -0,0 +1,83 @@ +#!/bin/bash + +# Must be root to use this tool +if [ $EUID -ne 0 ];then + if dpkg-query -s sudo &> /dev/null; then + export SUDO="sudo" + else + echo "::: Please install sudo or run this as root." + exit 1 + fi +fi + +makeConf(){ + shift + $SUDO /opt/pivpn/makeCONF.sh "$@" + exit 1 +} + +listConnected(){ + $SUDO wg show + exit 1 +} + +debug(){ + $SUDO /opt/pivpn/pivpnDEBUG.sh + exit 1 +} + +listClients(){ + $SUDO /opt/pivpn/listCONF.sh + exit 1 +} + +showQrcode(){ + shift + $SUDO /opt/pivpn/qrcodeCONF.sh "$@" + exit 1 +} + +removeClient(){ + shift + $SUDO /opt/pivpn/removeCONF.sh "$@" + exit 1 +} + +uninstallServer(){ + $SUDO /opt/pivpn/uninstall.sh + exit 1 +} + +showHelp(){ + echo "::: Control all PiVPN specific functions!" + echo ":::" + echo "::: Usage: pivpn [option]" + echo ":::" + echo "::: Commands:" + echo "::: -a, add Create a client conf profile" + echo "::: -c, clients List any connected clients to the server" + echo "::: -d, debug Start a debugging session if having trouble" + echo "::: -l, list List all clients" + echo "::: -qr, qrcode Show the qrcode of a client for use with the mobile app" + echo "::: -r, remove Remove a client" + echo "::: -h, help Show this help dialog" + echo "::: -u, uninstall Uninstall pivpn from your system!" + exit 1 +} + +if [ $# = 0 ]; then + showHelp +fi + +# Handle redirecting to specific functions based on arguments +case "$1" in +"-a" | "add" ) makeConf "$@";; +"-c" | "clients" ) listConnected;; +"-d" | "debug" ) debug;; +"-l" | "list" ) listClients;; +"-qr" | "qrcode" ) showQrcode "$@";; +"-r" | "remove" ) removeClient "$@";; +"-h" | "help" ) showHelp;; +"-u" | "uninstall" ) uninstallServer;; +* ) showHelp;; +esac diff --git a/scripts/wireguard/pivpnDEBUG.sh b/scripts/wireguard/pivpnDEBUG.sh new file mode 100755 index 0000000..761cc49 --- /dev/null +++ b/scripts/wireguard/pivpnDEBUG.sh @@ -0,0 +1,173 @@ +#!/usr/bin/env bash +# This scripts runs as root + +setupVars="/etc/pivpn/setupVars.conf" + +if [ ! -f "${setupVars}" ]; then + echo "::: Missing setup vars file!" + exit 1 +fi + +source "${setupVars}" + +EXAMPLE="$(head -1 /etc/wireguard/configs/clients.txt | awk '{print $1}')" +ERR=0 + +echo -e "::::\t\t\e[4mPiVPN debug\e[0m\t\t ::::" +printf "=============================================\n" +echo -e "::::\t\t\e[4mLatest commit\e[0m\t\t ::::" +git --git-dir /etc/.pivpn/.git log -n 1 +printf "=============================================\n" +echo -e "::::\t \e[4mInstallation settings\e[0m \t ::::" +sed "s/$pivpnHOST/REDACTED/" < /etc/pivpn/setupVars.conf +printf "=============================================\n" +echo -e ":::: \e[4mServer configuration shown below\e[0m ::::" +cd /etc/wireguard/keys +cp ../wg0.conf ../wg0.tmp +for k in *; do + sed "s#$(cat "$k")#$k#" -i ../wg0.tmp +done +cat ../wg0.tmp +rm ../wg0.tmp +printf "=============================================\n" +echo -e ":::: \e[4mClient configuration shown below\e[0m ::::" +if [ -n "$EXAMPLE" ]; then + cp ../configs/"$EXAMPLE".conf ../configs/"$EXAMPLE".tmp + for k in *; do + sed "s#$(cat "$k")#$k#" -i ../configs/"$EXAMPLE".tmp + done + sed "s/$pivpnHOST/REDACTED/" < ../configs/"$EXAMPLE".tmp + rm ../configs/"$EXAMPLE".tmp +else + echo "::: There are no clients yet" +fi + +printf "=============================================\n" +echo -e ":::: \t\e[4mRecursive list of files in\e[0m\t ::::\n::::\e\t[4m/etc/wireguard shown below\e[0m\t ::::" +ls -LR /etc/wireguard +printf "=============================================\n" +echo -e "::::\t\t\e[4mSelf check\e[0m\t\t ::::" + +if [ "$(cat /proc/sys/net/ipv4/ip_forward)" -eq 1 ]; then + echo ":: [OK] IP forwarding is enabled" +else + ERR=1 + read -r -p ":: [ERR] IP forwarding is not enabled, attempt fix now? [Y/n] " REPLY + if [[ ${REPLY} =~ ^[Yy]$ ]]; then + sed -i '/net.ipv4.ip_forward=1/s/^#//g' /etc/sysctl.conf + sysctl -p + echo "Done" + fi +fi + +if [ "$USING_UFW" -eq 0 ]; then + + if iptables -t nat -C POSTROUTING -s 10.6.0.0/24 -o "${PHYS_INT}" -j MASQUERADE &> /dev/null; then + echo ":: [OK] Iptables MASQUERADE rule set" + else + ERR=1 + read -r -p ":: [ERR] Iptables MASQUERADE rule is not set, attempt fix now? [Y/n] " REPLY + if [[ ${REPLY} =~ ^[Yy]$ ]]; then + iptables -t nat -F + iptables -t nat -I POSTROUTING -s 10.6.0.0/24 -o "${PHYS_INT}" -j MASQUERADE + iptables-save > /etc/iptables/rules.v4 + iptables-restore < /etc/iptables/rules.v4 + echo "Done" + fi + fi + +else + + if LANG="en_US.UTF-8" ufw status | grep -qw 'active'; then + echo ":: [OK] Ufw is enabled" + else + ERR=1 + read -r -p ":: [ERR] Ufw is not enabled, try to enable now? [Y/n] " REPLY + if [[ ${REPLY} =~ ^[Yy]$ ]]; then + ufw enable + fi + fi + + if iptables -t nat -C POSTROUTING -s 10.6.0.0/24 -o "${PHYS_INT}" -j MASQUERADE &> /dev/null; then + echo ":: [OK] Iptables MASQUERADE rule set" + else + ERR=1 + read -r -p ":: [ERR] Iptables MASQUERADE rule is not set, attempt fix now? [Y/n] " REPLY + if [[ ${REPLY} =~ ^[Yy]$ ]]; then + sed "/delete these required/i *nat\n:POSTROUTING ACCEPT [0:0]\n-I POSTROUTING -s 10.6.0.0/24 -o $PHYS_INT -j MASQUERADE\nCOMMIT\n" -i /etc/ufw/before.rules + ufw reload + echo "Done" + fi + fi + + if iptables -C ufw-user-input -p udp --dport "${pivpnPORT}" -j ACCEPT &> /dev/null; then + echo ":: [OK] Ufw input rule set" + else + ERR=1 + read -r -p ":: [ERR] Ufw input rule is not set, attempt fix now? [Y/n] " REPLY + if [[ ${REPLY} =~ ^[Yy]$ ]]; then + ufw insert 1 allow "$pivpnPORT"/udp + ufw reload + echo "Done" + fi + fi + + if iptables -C ufw-user-forward -i wg0 -o "${PHYS_INT}" -s 10.6.0.0/24 -j ACCEPT &> /dev/null; then + echo ":: [OK] Ufw forwarding rule set" + else + ERR=1 + read -r -p ":: [ERR] Ufw forwarding rule is not set, attempt fix now? [Y/n] " REPLY + if [[ ${REPLY} =~ ^[Yy]$ ]]; then + ufw route insert 1 allow in on wg0 from 10.6.0.0/24 out on "$PHYS_INT" to any + ufw reload + echo "Done" + fi + fi + +fi + +if systemctl is-active -q wg-quick@wg0; then + echo ":: [OK] WireGuard is running" +else + ERR=1 + read -r -p ":: [ERR] WireGuard is not running, try to start now? [Y/n] " REPLY + if [[ ${REPLY} =~ ^[Yy]$ ]]; then + systemctl start wg-quick@wg0 + echo "Done" + fi +fi + +if systemctl is-enabled -q wg-quick@wg0; then + echo ":: [OK] WireGuard is enabled (it will automatically start on reboot)" +else + ERR=1 + read -r -p ":: [ERR] WireGuard is not enabled, try to enable now? [Y/n] " REPLY + if [[ ${REPLY} =~ ^[Yy]$ ]]; then + systemctl enable wg-quick@wg0 + echo "Done" + fi +fi + +# grep -w (whole word) is used so port 111940 with now match when looking for 1194 +if netstat -uanp | grep -w "${pivpnPORT}" | grep -q 'udp'; then + echo ":: [OK] WireGuard is listening on port ${pivpnPORT}/udp" +else + ERR=1 + read -r -p ":: [ERR] WireGuard is not listening, try to restart now? [Y/n] " REPLY + if [[ ${REPLY} =~ ^[Yy]$ ]]; then + systemctl restart wg-quick@wg0 + echo "Done" + fi +fi + +if [ "$ERR" -eq 1 ]; then + echo -e "[INFO] Run \e[1mpivpn -d\e[0m again to see if we detect issues" +fi +printf "=============================================\n" +echo -e ":::: \e[1mWARNING\e[0m: This script should have automatically masked sensitive ::::" +echo -e ":::: information, however, still make sure that \e[4mPrivateKey\e[0m, \e[4mPublicKey\e[0m ::::" +echo -e ":::: and \e[4mPresharedKey\e[0m are masked before reporting an issue. An example key ::::" +echo ":::: that you should NOT see in this log looks like this: ::::" +echo ":::: WJhKKx+Uk1l1TxaH2KcEGeBdPBTp/k/Qy4EpBig5UnI= ::::" +printf "=============================================\n" +echo -e "::::\t\t\e[4mDebug complete\e[0m\t\t ::::" diff --git a/scripts/wireguard/qrcodeCONF.sh b/scripts/wireguard/qrcodeCONF.sh new file mode 100755 index 0000000..40fce8f --- /dev/null +++ b/scripts/wireguard/qrcodeCONF.sh @@ -0,0 +1,63 @@ +#!/bin/bash + +helpFunc(){ + echo "::: Show the qrcode of a client for use with the mobile app" + echo ":::" + echo "::: Usage: pivpn <-qr|qrcode> [-h|--help] [] ... [] ..." + echo ":::" + echo "::: Commands:" + echo "::: [none] Interactive mode" + echo "::: Client(s) to show" + echo "::: -h,--help Show this help dialog" +} + +# Parse input arguments +while test $# -gt 0 +do + _key="$1" + case "$_key" in + -h|--help) + helpFunc + exit 0 + ;; + *) + CLIENTS_TO_SHOW+=("$1") + ;; + esac + shift +done + +cd /etc/wireguard/configs +if [ ! -s clients.txt ]; then + echo "::: There are no clients to remove" + exit 1 +fi + +if [ "${#CLIENTS_TO_SHOW[@]}" -eq 0 ]; then + + echo -e "::\e[4m Client list \e[0m::" + LIST=($(awk '{print $1}' clients.txt)) + COUNTER=1 + while [ $COUNTER -le ${#LIST[@]} ]; do + echo "• ${LIST[(($COUNTER-1))]}" + ((COUNTER++)) + done + + read -r -p "Please enter the Name of the Client to show: " CLIENTS_TO_SHOW + + if [ -z "${CLIENTS_TO_SHOW}" ]; then + echo "::: You can not leave this blank!" + exit 1 + fi +fi + +for CLIENT_NAME in "${CLIENTS_TO_SHOW[@]}"; do + if grep -qw "${CLIENT_NAME}" clients.txt; then + echo -e "::: Showing client \e[1m${CLIENT_NAME}\e[0m below" + echo "=====================================================================" + qrencode -t ansiutf8 < "${CLIENT_NAME}.conf" + echo "=====================================================================" + else + echo -e "::: \e[1m${CLIENT_NAME}\e[0m does not exist" + fi +done \ No newline at end of file diff --git a/scripts/wireguard/removeCONF.sh b/scripts/wireguard/removeCONF.sh new file mode 100755 index 0000000..403da3c --- /dev/null +++ b/scripts/wireguard/removeCONF.sh @@ -0,0 +1,117 @@ +#!/bin/bash + +setupVars="/etc/pivpn/setupVars.conf" + +helpFunc(){ + echo "::: Remove a client conf profile" + echo ":::" + echo "::: Usage: pivpn <-r|remove> [-h|--help] [] ... [] ..." + echo ":::" + echo "::: Commands:" + echo "::: [none] Interactive mode" + echo "::: Client(s) to remove" + echo "::: -h,--help Show this help dialog" +} + +# Parse input arguments +while test $# -gt 0 +do + _key="$1" + case "$_key" in + -h|--help) + helpFunc + exit 0 + ;; + *) + CLIENTS_TO_REMOVE+=("$1") + ;; + esac + shift +done + +if [ ! -f "${setupVars}" ]; then + echo "::: Missing setup vars file!" + exit 1 +fi + +source "${setupVars}" + +cd /etc/wireguard +if [ ! -s configs/clients.txt ]; then + echo "::: There are no clients to remove" + exit 1 +fi + +if [ "${#CLIENTS_TO_REMOVE[@]}" -eq 0 ]; then + + echo -e "::\e[4m Client list \e[0m::" + LIST=($(awk '{print $1}' configs/clients.txt)) + COUNTER=1 + while [ $COUNTER -le ${#LIST[@]} ]; do + echo "• ${LIST[(($COUNTER-1))]}" + ((COUNTER++)) + done + + read -r -p "Please enter the Name of the Client to be removed from the list above: " CLIENTS_TO_REMOVE + + if [ -z "${CLIENTS_TO_REMOVE}" ]; then + echo "::: You can not leave this blank!" + exit 1 + fi +fi + +DELETED_COUNT=0 + +for CLIENT_NAME in "${CLIENTS_TO_REMOVE[@]}"; do + + if ! grep -qw "${CLIENT_NAME}" configs/clients.txt; then + echo -e "::: \e[1m${CLIENT_NAME}\e[0m does not exist" + else + REQUESTED="$(sha256sum "configs/${CLIENT_NAME}.conf" | cut -c 1-64)" + read -r -p "Do you really want to delete $CLIENT_NAME? [Y/n] " + + if [[ $REPLY =~ ^[Yy]$ ]]; then + + # Grab the least significant octed of the client IP address + COUNT=$(grep "${CLIENT_NAME}" configs/clients.txt | awk '{print $3}') + # And the creation date of the client + CREATION_DATE="$(grep "${CLIENT_NAME}" configs/clients.txt | awk '{print $2}')" + + # Then remove the client matching the variables above + sed "/${CLIENT_NAME} ${CREATION_DATE} ${COUNT}/d" -i configs/clients.txt + + # Remove the peer section from the server config + sed "/# begin ${CLIENT_NAME}/,/# end ${CLIENT_NAME}/d" -i wg0.conf + echo "::: Updated server config" + + rm "configs/${CLIENT_NAME}.conf" + echo "::: Client config for ${CLIENT_NAME} removed" + + rm "keys/${CLIENT_NAME}_priv" + rm "keys/${CLIENT_NAME}_pub" + echo "::: Client Keys for ${CLIENT_NAME} removed" + + # Find all .conf files in the home folder of the user matching the checksum of the + # config and delete them. '-maxdepth 3' is used to avoid traversing too many folders. + find "${install_home}" -maxdepth 3 -type f -name '*.conf' -print0 | while IFS= read -r -d '' CONFIG; do + if sha256sum -c <<< "${REQUESTED} ${CONFIG}" &> /dev/null; then + rm "${CONFIG}" + fi + done + + echo "::: Successfully deleted ${CLIENT_NAME}" + + ((DELETED_COUNT++)) + fi + fi + +done + +# Restart WireGuard only if some clients were actually deleted +if [ "${DELETED_COUNT}" -gt 0 ]; then + if systemctl restart wg-quick@wg0; then + echo "::: WireGuard restarted" + else + echo "::: Failed to restart WireGuard" + fi +fi From 1777d5c2390bbb2f66943d5175407f9a466ab9c2 Mon Sep 17 00:00:00 2001 From: Orazio Date: Mon, 14 Oct 2019 15:06:34 +0200 Subject: [PATCH 3/6] Added back Debian 10 support --- auto_install/install.sh | 73 ++++++++++++++++++++++----------- scripts/openvpn/removeOVPN.sh | 14 ++++--- scripts/wireguard/pivpnDEBUG.sh | 3 +- 3 files changed, 60 insertions(+), 30 deletions(-) diff --git a/auto_install/install.sh b/auto_install/install.sh index 653b017..079cd1f 100755 --- a/auto_install/install.sh +++ b/auto_install/install.sh @@ -91,7 +91,7 @@ distroCheck(){ fi case ${PLAT} in - Raspbian) + Debian|Raspbian) case ${OSCN} in buster) ;; @@ -120,7 +120,7 @@ checkHostname(){ if [[ ${#host_name} -le 28 && $host_name =~ ^[a-zA-Z0-9][a-zA-Z0-9-]{1,28}$ ]]; then echo "::: Hostname valid and length OK, proceeding..." fi - done + done else echo "::: Hostname length OK" fi @@ -525,6 +525,7 @@ installWireGuard(){ # Otherwhise compile and build the kernel module via DKMS (so it will # be recompiled on kernel upgrades) if [ "$(uname -m)" = "armv7l" ]; then + echo "::: Installing WireGuard from Debian package... " # dirmngr is used to download repository keys, whereas qrencode is used to generate qrcodes # from config file, for use with mobile clients @@ -532,20 +533,22 @@ installWireGuard(){ installDependentPackages PIVPN_DEPS[@] # Do not upgrade packages from the unstable repository except for wireguard echo "::: Adding Debian repository... " - echo "deb http://deb.debian.org/debian/ unstable main" | $SUDO tee -a /etc/apt/sources.list.d/unstable.list > /dev/null + echo "deb http://deb.debian.org/debian/ unstable main" | $SUDO tee /etc/apt/sources.list.d/unstable.list > /dev/null echo "Package: * Pin: release a=unstable Pin-Priority: 1 Package: wireguard wireguard-dkms wireguard-tools Pin: release a=unstable -Pin-Priority: 500" | $SUDO tee -a /etc/apt/preferences.d/limit-unstable > /dev/null +Pin-Priority: 500" | $SUDO tee /etc/apt/preferences.d/limit-unstable > /dev/null $SUDO apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 04EE7237B7D453EC 648ACFD622F3D138 $SUDO ${UPDATE_PKG_CACHE} &> /dev/null PIVPN_DEPS=(wireguard) installDependentPackages PIVPN_DEPS[@] + elif [ "$(uname -m)" = "armv6l" ]; then + echo "::: Installing WireGuard from source... " PIVPN_DEPS=(libmnl-dev libelf-dev raspberrypi-kernel-headers build-essential pkg-config qrencode) installDependentPackages PIVPN_DEPS[@] @@ -553,8 +556,8 @@ Pin-Priority: 500" | $SUDO tee -a /etc/apt/preferences.d/limit-unstable > /dev/n # Delete any leftover code $SUDO rm -rf /usr/src/wireguard-* - echo -n "::: Downloading source code... " - wget -O- "${WG_SOURCE}" | $SUDO tar Jxf - --directory /usr/src + echo "::: Downloading source code... " + wget -qO- "${WG_SOURCE}" | $SUDO tar Jxf - --directory /usr/src echo "done!" cd /usr/src @@ -565,7 +568,7 @@ Pin-Priority: 500" | $SUDO tee -a /etc/apt/preferences.d/limit-unstable > /dev/n # We install the userspace tools manually since DKMS only compiles and # installs the kernel module - echo -n "::: Compiling WireGuard tools... " + echo "::: Compiling WireGuard tools... " if $SUDO make tools; then echo "done!" else @@ -573,7 +576,7 @@ Pin-Priority: 500" | $SUDO tee -a /etc/apt/preferences.d/limit-unstable > /dev/n exit 1 fi - echo -n "::: Installing WireGuard tools... " + echo "::: Installing WireGuard tools... " if $SUDO make install tools; then echo "done!" else @@ -581,7 +584,7 @@ Pin-Priority: 500" | $SUDO tee -a /etc/apt/preferences.d/limit-unstable > /dev/n exit 1 fi - echo -n "::: Adding WireGuard modules via DKMS... " + echo "::: Adding WireGuard modules via DKMS... " if $SUDO dkms add wireguard/"${WG_SNAPSHOT}"; then echo "done!" else @@ -590,7 +593,7 @@ Pin-Priority: 500" | $SUDO tee -a /etc/apt/preferences.d/limit-unstable > /dev/n exit 1 fi - echo -n "::: Compiling WireGuard modules via DKMS... " + echo "::: Compiling WireGuard modules via DKMS... " if $SUDO dkms build wireguard/"${WG_SNAPSHOT}"; then echo "done!" else @@ -599,7 +602,7 @@ Pin-Priority: 500" | $SUDO tee -a /etc/apt/preferences.d/limit-unstable > /dev/n exit 1 fi - echo -n "::: Installing WireGuard modules via DKMS... " + echo "::: Installing WireGuard modules via DKMS... " if $SUDO dkms install wireguard/"${WG_SNAPSHOT}"; then echo "done!" else @@ -607,6 +610,17 @@ Pin-Priority: 500" | $SUDO tee -a /etc/apt/preferences.d/limit-unstable > /dev/n $SUDO dkms remove wireguard/"${WG_SNAPSHOT}" --all exit 1 fi + + elif [ "$(uname -m)" = "x86_64" ] || [ "$(uname -m)" = "i686" ]; then + + echo "deb http://deb.debian.org/debian/ unstable main" | $SUDO tee /etc/apt/sources.list.d/unstable.list > /dev/null + echo "Package: * +Pin: release a=unstable +Pin-Priority: 90" | $SUDO tee /etc/apt/preferences.d/limit-unstable > /dev/null + $SUDO ${UPDATE_PKG_CACHE} &> /dev/null + PIVPN_DEPS=(qrencode wireguard) + installDependentPackages PIVPN_DEPS[@] + fi } @@ -862,9 +876,9 @@ askEncryption(){ fi if ([ "$pivpnENCRYPT" -ge "3072" ] && whiptail --backtitle "Setup OpenVPN" --title "Download Diffie-Hellman Parameters" --yesno --defaultno "Download Diffie-Hellman parameters from a public DH parameter generation service?\n\nGenerating DH parameters for a $pivpnENCRYPT-bit key can take many hours on a Raspberry Pi. You can instead download DH parameters from \"2 Ton Digital\" that are generated at regular intervals as part of a public service. Downloaded DH parameters will be randomly selected from their database.\nMore information about this service can be found here: https://2ton.com.au/safeprimes/\n\nIf you're paranoid, choose 'No' and Diffie-Hellman parameters will be generated on your device." ${r} ${c}); then - DOWNLOAD_DH_PARAM=true + DOWNLOAD_DH_PARAM=1 else - DOWNLOAD_DH_PARAM=false + DOWNLOAD_DH_PARAM=0 fi echo "pivpnENCRYPT=${pivpnENCRYPT}" >> /tmp/setupVars.conf @@ -885,7 +899,7 @@ confOpenVPN(){ fi # Get easy-rsa - wget -q -O - "${easyrsaRel}" | $SUDO tar xz -C /etc/openvpn && $SUDO mv /etc/openvpn/EasyRSA-v${easyrsaVer} /etc/openvpn/easy-rsa + wget -qO- "${easyrsaRel}" | $SUDO tar xz -C /etc/openvpn && $SUDO mv /etc/openvpn/EasyRSA-v${easyrsaVer} /etc/openvpn/easy-rsa # fix ownership $SUDO chown -R root:root /etc/openvpn/easy-rsa $SUDO mkdir /etc/openvpn/easy-rsa/pki @@ -916,9 +930,9 @@ set_var EASYRSA_KEY_SIZE ${pivpnENCRYPT}" | $SUDO tee vars >/dev/null # Build the server EASYRSA_CERT_EXPIRE=3650 ${SUDOE} ./easyrsa build-server-full ${SERVER_NAME} nopass - if [[ ${DOWNLOAD_DH_PARAM} == true ]]; then + if [ ${DOWNLOAD_DH_PARAM} -eq 1 ]; then # Downloading parameters - ${SUDOE} curl "https://2ton.com.au/getprimes/random/dhparam/${pivpnENCRYPT}" -o "/etc/openvpn/easy-rsa/pki/dh${pivpnENCRYPT}.pem" + ${SUDOE} curl -s "https://2ton.com.au/getprimes/random/dhparam/${pivpnENCRYPT}" -o "/etc/openvpn/easy-rsa/pki/dh${pivpnENCRYPT}.pem" else # Generate Diffie-Hellman key exchange ${SUDOE} ./easyrsa gen-dh @@ -989,6 +1003,13 @@ confOVPN(){ } confWireGuard(){ + if [ -d /etc/wireguard ]; then + $SUDO rm -r /etc/wireguard + $SUDO mkdir /etc/wireguard + $SUDO chown root:root /etc/wireguard + $SUDO chmod 700 /etc/wireguard + fi + whiptail --title "Server Information" --msgbox "The Server Keys and Pre-Shared key will now be generated." "${r}" "${c}" $SUDO mkdir /etc/wireguard/configs $SUDO touch /etc/wireguard/configs/clients.txt @@ -1072,7 +1093,7 @@ confNetwork(){ fi case ${PLAT} in - Raspbian) + Debian|Raspbian) $SUDO iptables-save | $SUDO tee /etc/iptables/rules.v4 > /dev/null ;; esac @@ -1104,7 +1125,7 @@ if \$programname == 'ovpn-server' then stop" | $SUDO tee /etc/rsyslog.d/30-openv # Restart the logging service case ${PLAT} in - Raspbian) + Debian|Raspbian) $SUDO systemctl restart rsyslog.service || true ;; esac @@ -1153,11 +1174,15 @@ askUnattendedUpgrades(){ confUnattendedUpgrades(){ cd /etc/apt/apt.conf.d - wget -q -O- "$UNATTUPG_CONFIG" | $SUDO tar xz - $SUDO cp "unattended-upgrades-$UNATTUPG_RELEASE/data/50unattended-upgrades.Raspbian" 50unattended-upgrades - $SUDO rm -rf "unattended-upgrades-$UNATTUPG_RELEASE" + if [ "$PLAT" = "Raspbian" ]; then + wget -qO- "$UNATTUPG_CONFIG" | $SUDO tar xz + $SUDO cp "unattended-upgrades-$UNATTUPG_RELEASE/data/50unattended-upgrades.Raspbian" 50unattended-upgrades + $SUDO rm -rf "unattended-upgrades-$UNATTUPG_RELEASE" + fi - if [ "$VPN" = "WireGuard" ] && [ "$(uname -m)" = "armv7l" ]; then + # On architectures different from armv6l, where we install wireguard from source, enable + # automatic updates via the unstable repository + if [ "$VPN" = "WireGuard" ] && [ "$(uname -m)" != "armv6l" ]; then sed -i '/Unattended-Upgrade::Origins-Pattern {/a"o=Debian,a=unstable";' 50unattended-upgrades fi @@ -1183,7 +1208,7 @@ installScripts() { FOLDER=$(tr '[:upper:]' '[:lower:]' <<< "$VPN") $SUDO cp /etc/.pivpn/scripts/$FOLDER/*.sh /opt/pivpn/ $SUDO chmod 0755 /opt/pivpn/*.sh - $SUDO cp /etc/.pivpn/$FOLDER/pivpn /usr/local/bin/pivpn + $SUDO cp /etc/.pivpn/$FOLDER/scripts/pivpn /usr/local/bin/pivpn $SUDO chmod 0755 /usr/local/bin/pivpn $SUDO cp /etc/.pivpn/scripts/$FOLDER/bash-completion /etc/bash_completion.d/pivpn . /etc/bash_completion.d/pivpn @@ -1285,7 +1310,7 @@ main(){ echo "::: Restarting services..." # Start services case ${PLAT} in - Raspbian) + Debian|Raspbian) if [ "$VPN" = "OpenVPN" ]; then $SUDO systemctl enable openvpn.service $SUDO systemctl start openvpn.service diff --git a/scripts/openvpn/removeOVPN.sh b/scripts/openvpn/removeOVPN.sh index 0d79eaf..86457c2 100755 --- a/scripts/openvpn/removeOVPN.sh +++ b/scripts/openvpn/removeOVPN.sh @@ -1,10 +1,16 @@ #!/usr/bin/env bash # PiVPN: revoke client script -install_user=$( Date: Mon, 14 Oct 2019 16:51:43 +0200 Subject: [PATCH 4/6] Bugfixes --- auto_install/install.sh | 26 ++++++++++++++++++++------ scripts/wireguard/makeCONF.sh | 2 ++ 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/auto_install/install.sh b/auto_install/install.sh index 079cd1f..de5ec6e 100755 --- a/auto_install/install.sh +++ b/auto_install/install.sh @@ -300,6 +300,12 @@ chooseInterface(){ fi } +avoidStaticIPv4Ubuntu() { + # If we are in Ubuntu then they need to have previously set their network, so just use what you have. + whiptail --msgbox --backtitle "IP Information" --title "IP Information" "Since we think you are not using Raspbian, we will not configure a static IP for you. +If you are in Amazon then you can not configure a static IP anyway. Just ensure before this installer started you had set an elastic IP on your instance." ${r} ${c} +} + getStaticIPv4Settings() { local ipSettingsCorrect # Grab their current DNS Server @@ -467,7 +473,11 @@ makeRepo(){ # Remove the non-repos interface and clone the interface echo -n "::: Cloning $2 into $1..." $SUDO rm -rf "${1}" + # Go back to /etc otherwhise git will complain when the current working + # directory has just been deleted (/etc/.pivpn). + cd /etc $SUDO git clone -q --depth 1 --no-single-branch "${2}" "${1}" > /dev/null & spinner $! + cd "${1}" || exit 1 if [ -z "${TESTING}" ]; then : elif [ "${TESTING}" = "test" ]; then @@ -618,7 +628,7 @@ Pin-Priority: 500" | $SUDO tee /etc/apt/preferences.d/limit-unstable > /dev/null Pin: release a=unstable Pin-Priority: 90" | $SUDO tee /etc/apt/preferences.d/limit-unstable > /dev/null $SUDO ${UPDATE_PKG_CACHE} &> /dev/null - PIVPN_DEPS=(qrencode wireguard) + PIVPN_DEPS=(linux-headers-amd64 qrencode wireguard) installDependentPackages PIVPN_DEPS[@] fi @@ -1183,7 +1193,7 @@ confUnattendedUpgrades(){ # On architectures different from armv6l, where we install wireguard from source, enable # automatic updates via the unstable repository if [ "$VPN" = "WireGuard" ] && [ "$(uname -m)" != "armv6l" ]; then - sed -i '/Unattended-Upgrade::Origins-Pattern {/a"o=Debian,a=unstable";' 50unattended-upgrades + $SUDO sed -i '/Unattended-Upgrade::Origins-Pattern {/a"o=Debian,a=unstable";' 50unattended-upgrades fi # Add the remaining settings for all other distributions @@ -1195,7 +1205,7 @@ confUnattendedUpgrades(){ APT::Periodic::Verbose \"0\";" | $SUDO tee 02periodic > /dev/null } -installScripts() { +installScripts(){ # Install the scripts from /etc/.pivpn to their various locations echo ":::" echo -n "::: Installing scripts to /opt/pivpn..." @@ -1208,7 +1218,7 @@ installScripts() { FOLDER=$(tr '[:upper:]' '[:lower:]' <<< "$VPN") $SUDO cp /etc/.pivpn/scripts/$FOLDER/*.sh /opt/pivpn/ $SUDO chmod 0755 /opt/pivpn/*.sh - $SUDO cp /etc/.pivpn/$FOLDER/scripts/pivpn /usr/local/bin/pivpn + $SUDO cp /etc/.pivpn/scripts/$FOLDER/pivpn /usr/local/bin/pivpn $SUDO chmod 0755 /usr/local/bin/pivpn $SUDO cp /etc/.pivpn/scripts/$FOLDER/bash-completion /etc/bash_completion.d/pivpn . /etc/bash_completion.d/pivpn @@ -1291,8 +1301,12 @@ main(){ # Find interfaces and let the user choose one chooseInterface - getStaticIPv4Settings - setStaticIPv4 + if [ "$PLAT" != "Raspbian" ]; then + avoidStaticIPv4Ubuntu + else + getStaticIPv4Settings + setStaticIPv4 + fi # Choose the user for the ovpns chooseUser diff --git a/scripts/wireguard/makeCONF.sh b/scripts/wireguard/makeCONF.sh index cbfd9b4..e0378cd 100755 --- a/scripts/wireguard/makeCONF.sh +++ b/scripts/wireguard/makeCONF.sh @@ -50,6 +50,7 @@ source "${setupVars}" if [ ! -d "${install_home}/configs" ]; then mkdir "${install_home}/configs" chown "${install_user}":"${install_user}" "${install_home}/configs" + chmod 0750 "${install_home}/configs" fi cd /etc/wireguard @@ -120,6 +121,7 @@ fi cp "configs/${CLIENT_NAME}.conf" "${install_home}/configs/${CLIENT_NAME}.conf" chown "${install_user}":"${install_user}" "${install_home}/configs/${CLIENT_NAME}.conf" +chmod 640 "${install_home}/configs/${CLIENT_NAME}.conf" echo "======================================================================" echo -e "::: Done! \e[1m${CLIENT_NAME}.conf successfully created!\e[0m" From 5c97221d3f5f7191abd73b16e89fd3e54b89194a Mon Sep 17 00:00:00 2001 From: Orazio Date: Wed, 16 Oct 2019 12:01:50 +0200 Subject: [PATCH 5/6] Revert some variable names and fix iptables rules --- auto_install/install.sh | 39 +++++++++++++++++++-------------- scripts/openvpn/pivpnDebug.sh | 22 +++++++++---------- scripts/wireguard/pivpnDEBUG.sh | 12 +++++----- 3 files changed, 39 insertions(+), 34 deletions(-) diff --git a/auto_install/install.sh b/auto_install/install.sh index de5ec6e..458815d 100755 --- a/auto_install/install.sh +++ b/auto_install/install.sh @@ -270,8 +270,8 @@ chooseInterface(){ local firstloop=1 if [[ $(echo "${availableInterfaces}" | wc -l) -eq 1 ]]; then - PHYS_INT="${availableInterfaces}" - echo "PHYS_INT=${PHYS_INT}" >> /tmp/setupVars.conf + IPv4dev="${availableInterfaces}" + echo "IPv4dev=${IPv4dev}" >> /tmp/setupVars.conf return fi @@ -290,9 +290,9 @@ chooseInterface(){ chooseInterfaceOptions=$("${chooseInterfaceCmd[@]}" "${interfacesArray[@]}" 2>&1 >/dev/tty) if [[ $? = 0 ]]; then for desiredInterface in ${chooseInterfaceOptions}; do - PHYS_INT=${desiredInterface} - echo "::: Using interface: $PHYS_INT" - echo "PHYS_INT=${PHYS_INT}" >> /tmp/setupVars.conf + IPv4dev=${desiredInterface} + echo "::: Using interface: $IPv4dev" + echo "IPv4dev=${IPv4dev}" >> /tmp/setupVars.conf done else echo "::: Cancel selected, exiting...." @@ -314,6 +314,9 @@ getStaticIPv4Settings() { if (whiptail --backtitle "Calibrating network interface" --title "Static IP Address" --yesno "Do you want to use your current network settings as a static address? IP address: ${IPv4addr} Gateway: ${IPv4gw}" ${r} ${c}); then + + echo "IPv4addr=${IPv4addr%/*}" >> /tmp/setupVars.conf + echo "IPv4gw=${IPv4gw}" >> /tmp/setupVars.conf # If they choose yes, let the user know that the IP address will not be available via DHCP and may cause a conflict. whiptail --msgbox --backtitle "IP information" --title "FYI: IP Conflict" "It is possible your router could still try to assign this IP to a device, which would cause a conflict. But in most cases the router is smart enough to not do that. If you are worried, either manually set the address, or modify the DHCP reservation pool so it does not include the IP you want. @@ -337,7 +340,8 @@ It is also possible to use a DHCP reservation, but if you are going to do that, IP address: ${IPv4addr} Gateway: ${IPv4gw}" ${r} ${c}); then # If the settings are correct, then we need to set the pivpnIP - echo "pivpnIP=${IPv4addr%/*}" >> /tmp/setupVars.conf + echo "IPv4addr=${IPv4addr%/*}" >> /tmp/setupVars.conf + echo "IPv4gw=${IPv4gw}" >> /tmp/setupVars.conf # After that's done, the loop ends and we move on ipSettingsCorrect=True else @@ -363,7 +367,7 @@ It is also possible to use a DHCP reservation, but if you are going to do that, setDHCPCD(){ # Append these lines to dhcpcd.conf to enable a static IP - echo "interface ${PHYS_INT} + echo "interface ${IPv4dev} static ip_address=${IPv4addr} static routers=${IPv4gw} static domain_name_servers=${IPv4dns}" | $SUDO tee -a ${dhcpcdFile} >/dev/null @@ -376,7 +380,7 @@ setStaticIPv4(){ echo "::: Static IP already configured." else setDHCPCD - $SUDO ip addr replace dev "${PHYS_INT}" "${IPv4addr}" + $SUDO ip addr replace dev "${IPv4dev}" "${IPv4addr}" echo ":::" echo "::: Setting IP to ${IPv4addr}. You may need to restart after the install is complete." echo ":::" @@ -511,14 +515,15 @@ askWhichVPN(){ if (whiptail --backtitle "Setup PiVPN" --title "Installation mode" --yesno "WireGuard is a new kind of VPN that provides near-istantaneous connection speed, high performance, modern cryptography.\n\nIt's the recommended choise expecially if you use mobile devices where WireGuard is easier on battery than OpenVPN.\n\nOpenVPN is still available if you need the traditional, flexible, trusted VPN protocol. Or if you need features like TCP and custom search domain.\n\nChoose 'Yes' to use WireGuard of 'No' to use OpenVPN." ${r} ${c}); then VPN="WireGuard" - pivpnINT="wg0" + pivpnDEV="wg0" + pivpnNET="10.6.0.0/24" else VPN="OpenVPN" - pivpnINT="tun0" + pivpnDEV="tun0" + pivpnNET="10.8.0.0/24" fi echo "VPN=${VPN}" >> /tmp/setupVars.conf - echo "pivpnINT=${pivpnINT}" >> /tmp/setupVars.conf } installOpenVPN(){ @@ -1053,10 +1058,10 @@ confNetwork(){ USING_UFW=1 echo "::: Detected UFW is enabled." echo "::: Adding UFW rules..." - $SUDO sed "/delete these required/i *nat\n:POSTROUTING ACCEPT [0:0]\n-I POSTROUTING -s 10.8.0.0/24 -o $PHYS_INT -j MASQUERADE\nCOMMIT\n" -i /etc/ufw/before.rules + $SUDO sed "/delete these required/i *nat\n:POSTROUTING ACCEPT [0:0]\n-I POSTROUTING -s $pivpnNET -o $IPv4dev -j MASQUERADE\nCOMMIT\n" -i /etc/ufw/before.rules # Insert rules at the beginning of the chain (in case there are other rules that may drop the traffic) $SUDO ufw insert 1 allow "$PORT"/"$PROTO" >/dev/null - $SUDO ufw route insert 1 allow in on "$pivpnINT" from 10.8.0.0/24 out on "$PHYS_INT" to any >/dev/null + $SUDO ufw route insert 1 allow in on "$pivpnDEV" from "$pivpnNET" out on "$IPv4dev" to any >/dev/null $SUDO ufw reload >/dev/null echo "::: UFW configuration completed." @@ -1069,7 +1074,7 @@ confNetwork(){ # Now some checks to detect which rules we need to add. On a newly installed system all policies # should be ACCEPT, so the only required rule would be the MASQUERADE one. - $SUDO iptables -t nat -I POSTROUTING -s 10.8.0.0/24 -o "$PHYS_INT" -j MASQUERADE + $SUDO iptables -t nat -I POSTROUTING -s "$pivpnNET" -o "$IPv4dev" -j MASQUERADE # Count how many rules are in the INPUT and FORWARD chain. When parsing input from # iptables -S, '^-P' skips the policies and 'ufw-' skips ufw chains (in case ufw was found @@ -1088,15 +1093,15 @@ confNetwork(){ # chain (using -I). if [ "$INPUT_RULES_COUNT" -ne 0 ] || [ "$INPUT_POLICY" != "ACCEPT" ]; then - $SUDO iptables -I INPUT 1 -i "$PHYS_INT" -p "$PROTO" --dport "$PORT" -j ACCEPT + $SUDO iptables -I INPUT 1 -i "$IPv4dev" -p "$PROTO" --dport "$PORT" -j ACCEPT INPUT_CHAIN_EDITED=1 else INPUT_CHAIN_EDITED=0 fi if [ "$FORWARD_RULES_COUNT" -ne 0 ] || [ "$FORWARD_POLICY" != "ACCEPT" ]; then - $SUDO iptables -I FORWARD 1 -d 10.8.0.0/24 -i "$PHYS_INT" -o "$pivpnINT" -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT - $SUDO iptables -I FORWARD 2 -s 10.8.0.0/24 -i "$pivpnINT" -o "$PHYS_INT" -j ACCEPT + $SUDO iptables -I FORWARD 1 -d "$pivpnNET" -i "$IPv4dev" -o "$pivpnDEV" -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT + $SUDO iptables -I FORWARD 2 -s "$pivpnNET" -i "$pivpnDEV" -o "$IPv4dev" -j ACCEPT FORWARD_CHAIN_EDITED=1 else FORWARD_CHAIN_EDITED=0 diff --git a/scripts/openvpn/pivpnDebug.sh b/scripts/openvpn/pivpnDebug.sh index 847bcdc..348e7de 100755 --- a/scripts/openvpn/pivpnDebug.sh +++ b/scripts/openvpn/pivpnDebug.sh @@ -52,14 +52,14 @@ fi if [ "$USING_UFW" -eq 0 ]; then - if iptables -t nat -C POSTROUTING -s 10.8.0.0/24 -o "${PHYS_INT}" -j MASQUERADE &> /dev/null; then + if iptables -t nat -C POSTROUTING -s 10.8.0.0/24 -o "${IPv4dev}" -j MASQUERADE &> /dev/null; then echo ":: [OK] Iptables MASQUERADE rule set" else ERR=1 read -r -p ":: [ERR] Iptables MASQUERADE rule is not set, attempt fix now? [Y/n] " REPLY if [[ ${REPLY} =~ ^[Yy]$ ]]; then iptables -t nat -F - iptables -t nat -I POSTROUTING -s 10.8.0.0/24 -o "${PHYS_INT}" -j MASQUERADE + iptables -t nat -I POSTROUTING -s 10.8.0.0/24 -o "${IPv4dev}" -j MASQUERADE iptables-save > /etc/iptables/rules.v4 echo "Done" fi @@ -68,13 +68,13 @@ if [ "$USING_UFW" -eq 0 ]; then if [ "$INPUT_CHAIN_EDITED" -eq 1 ]; then - if iptables -C INPUT -i "$PHYS_INT" -p "$pivpnPROTO" --dport "$pivpnPORT" -j ACCEPT &> /dev/null; then + if iptables -C INPUT -i "$IPv4dev" -p "$pivpnPROTO" --dport "$pivpnPORT" -j ACCEPT &> /dev/null; then echo ":: [OK] Iptables INPUT rule set" else ERR=1 read -r -p ":: [ERR] Iptables INPUT rule is not set, attempt fix now? [Y/n] " REPLY if [[ ${REPLY} =~ ^[Yy]$ ]]; then - iptables -I INPUT 1 -i "$PHYS_INT" -p "$pivpnPROTO" --dport "$pivpnPORT" -j ACCEPT + iptables -I INPUT 1 -i "$IPv4dev" -p "$pivpnPROTO" --dport "$pivpnPORT" -j ACCEPT iptables-save > /etc/iptables/rules.v4 echo "Done" fi @@ -83,14 +83,14 @@ if [ "$USING_UFW" -eq 0 ]; then if [ "$FORWARD_CHAIN_EDITED" -eq 1 ]; then - if iptables -C FORWARD -s 10.8.0.0/24 -i tun0 -o "$PHYS_INT" -j ACCEPT &> /dev/null; then + if iptables -C FORWARD -s 10.8.0.0/24 -i tun0 -o "$IPv4dev" -j ACCEPT &> /dev/null; then echo ":: [OK] Iptables FORWARD rule set" else ERR=1 read -r -p ":: [ERR] Iptables FORWARD rule is not set, attempt fix now? [Y/n] " REPLY if [[ ${REPLY} =~ ^[Yy]$ ]]; then - iptables -I FORWARD 1 -d 10.8.0.0/24 -i "$PHYS_INT" -o tun0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT - iptables -I FORWARD 2 -s 10.8.0.0/24 -i tun0 -o "$PHYS_INT" -j ACCEPT + iptables -I FORWARD 1 -d 10.8.0.0/24 -i "$IPv4dev" -o tun0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT + iptables -I FORWARD 2 -s 10.8.0.0/24 -i tun0 -o "$IPv4dev" -j ACCEPT iptables-save > /etc/iptables/rules.v4 echo "Done" fi @@ -109,13 +109,13 @@ else fi fi - if iptables -t nat -C POSTROUTING -s 10.8.0.0/24 -o "${PHYS_INT}" -j MASQUERADE &> /dev/null; then + if iptables -t nat -C POSTROUTING -s 10.8.0.0/24 -o "${IPv4dev}" -j MASQUERADE &> /dev/null; then echo ":: [OK] Iptables MASQUERADE rule set" else ERR=1 read -r -p ":: [ERR] Iptables MASQUERADE rule is not set, attempt fix now? [Y/n] " REPLY if [[ ${REPLY} =~ ^[Yy]$ ]]; then - sed "/delete these required/i *nat\n:POSTROUTING ACCEPT [0:0]\n-I POSTROUTING -s 10.8.0.0/24 -o $PHYS_INT -j MASQUERADE\nCOMMIT\n" -i /etc/ufw/before.rules + sed "/delete these required/i *nat\n:POSTROUTING ACCEPT [0:0]\n-I POSTROUTING -s 10.8.0.0/24 -o $IPv4dev -j MASQUERADE\nCOMMIT\n" -i /etc/ufw/before.rules ufw reload echo "Done" fi @@ -147,13 +147,13 @@ else fi fi else - if iptables -C ufw-user-forward -i tun0 -o "${PHYS_INT}" -s 10.8.0.0/24 -j ACCEPT &> /dev/null; then + if iptables -C ufw-user-forward -i tun0 -o "${IPv4dev}" -s 10.8.0.0/24 -j ACCEPT &> /dev/null; then echo ":: [OK] Ufw forwarding rule set" else ERR=1 read -r -p ":: [ERR] Ufw forwarding rule is not set, attempt fix now? [Y/n] " REPLY if [[ ${REPLY} =~ ^[Yy]$ ]]; then - ufw route insert 1 allow in on tun0 from 10.8.0.0/24 out on "$PHYS_INT" to any + ufw route insert 1 allow in on tun0 from 10.8.0.0/24 out on "$IPv4dev" to any ufw reload echo "Done" fi diff --git a/scripts/wireguard/pivpnDEBUG.sh b/scripts/wireguard/pivpnDEBUG.sh index d339c39..bdd7f3e 100755 --- a/scripts/wireguard/pivpnDEBUG.sh +++ b/scripts/wireguard/pivpnDEBUG.sh @@ -63,14 +63,14 @@ fi if [ "$USING_UFW" -eq 0 ]; then - if iptables -t nat -C POSTROUTING -s 10.6.0.0/24 -o "${PHYS_INT}" -j MASQUERADE &> /dev/null; then + if iptables -t nat -C POSTROUTING -s 10.6.0.0/24 -o "${IPv4dev}" -j MASQUERADE &> /dev/null; then echo ":: [OK] Iptables MASQUERADE rule set" else ERR=1 read -r -p ":: [ERR] Iptables MASQUERADE rule is not set, attempt fix now? [Y/n] " REPLY if [[ ${REPLY} =~ ^[Yy]$ ]]; then iptables -t nat -F - iptables -t nat -I POSTROUTING -s 10.6.0.0/24 -o "${PHYS_INT}" -j MASQUERADE + iptables -t nat -I POSTROUTING -s 10.6.0.0/24 -o "${IPv4dev}" -j MASQUERADE iptables-save > /etc/iptables/rules.v4 iptables-restore < /etc/iptables/rules.v4 echo "Done" @@ -89,13 +89,13 @@ else fi fi - if iptables -t nat -C POSTROUTING -s 10.6.0.0/24 -o "${PHYS_INT}" -j MASQUERADE &> /dev/null; then + if iptables -t nat -C POSTROUTING -s 10.6.0.0/24 -o "${IPv4dev}" -j MASQUERADE &> /dev/null; then echo ":: [OK] Iptables MASQUERADE rule set" else ERR=1 read -r -p ":: [ERR] Iptables MASQUERADE rule is not set, attempt fix now? [Y/n] " REPLY if [[ ${REPLY} =~ ^[Yy]$ ]]; then - sed "/delete these required/i *nat\n:POSTROUTING ACCEPT [0:0]\n-I POSTROUTING -s 10.6.0.0/24 -o $PHYS_INT -j MASQUERADE\nCOMMIT\n" -i /etc/ufw/before.rules + sed "/delete these required/i *nat\n:POSTROUTING ACCEPT [0:0]\n-I POSTROUTING -s 10.6.0.0/24 -o $IPv4dev -j MASQUERADE\nCOMMIT\n" -i /etc/ufw/before.rules ufw reload echo "Done" fi @@ -113,13 +113,13 @@ else fi fi - if iptables -C ufw-user-forward -i wg0 -o "${PHYS_INT}" -s 10.6.0.0/24 -j ACCEPT &> /dev/null; then + if iptables -C ufw-user-forward -i wg0 -o "${IPv4dev}" -s 10.6.0.0/24 -j ACCEPT &> /dev/null; then echo ":: [OK] Ufw forwarding rule set" else ERR=1 read -r -p ":: [ERR] Ufw forwarding rule is not set, attempt fix now? [Y/n] " REPLY if [[ ${REPLY} =~ ^[Yy]$ ]]; then - ufw route insert 1 allow in on wg0 from 10.6.0.0/24 out on "$PHYS_INT" to any + ufw route insert 1 allow in on wg0 from 10.6.0.0/24 out on "$IPv4dev" to any ufw reload echo "Done" fi From e77f668021e1dbd9ef6c064bb5b3fc075754c749 Mon Sep 17 00:00:00 2001 From: Orazio Date: Wed, 16 Oct 2019 18:17:16 +0200 Subject: [PATCH 6/6] Kernel headers are required when installing from package too --- auto_install/install.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/auto_install/install.sh b/auto_install/install.sh index 458815d..ff9200c 100755 --- a/auto_install/install.sh +++ b/auto_install/install.sh @@ -559,7 +559,7 @@ Pin-Priority: 500" | $SUDO tee /etc/apt/preferences.d/limit-unstable > /dev/null $SUDO apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 04EE7237B7D453EC 648ACFD622F3D138 $SUDO ${UPDATE_PKG_CACHE} &> /dev/null - PIVPN_DEPS=(wireguard) + PIVPN_DEPS=(raspberrypi-kernel-headers wireguard) installDependentPackages PIVPN_DEPS[@] elif [ "$(uname -m)" = "armv6l" ]; then @@ -1344,7 +1344,7 @@ main(){ askUnattendedUpgrades confUnattendedUpgrades - $SUDO cp /tmp/setupVars.conf /etc/pivpn/setupVars.conf + $SUDO cp /tmp/setupVars.conf "$setupVars" installScripts # Ensure that cached writes reach persistent storage