pivpn/scripts/wireguard/makeCONF.sh

211 lines
5.5 KiB
Bash
Raw Normal View History

2019-10-14 10:27:28 +00:00
#!/bin/bash
2022-07-27 12:53:36 +00:00
# Some vars that might be empty but need to be defined for checks
pivpnPERSISTENTKEEPALIVE=""
pivpnDNS2=""
2020-04-28 22:44:56 +00:00
setupVars="/etc/pivpn/wireguard/setupVars.conf"
2022-07-27 12:53:36 +00:00
# shellcheck disable=SC2154
userGroup="${install_user}:${install_user}"
2019-10-14 10:27:28 +00:00
err() {
echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')]: $*" >&2
}
2022-07-27 12:53:36 +00:00
if [[ ! -f "${setupVars}" ]]; then
err "::: Missing setup vars file!"
exit 1
Merge test (#929) * added link to server status dashboard * Replaced Header with bold instead * More safeguards, some fixes, standardized some code, WireGuard update script, removed redundant code - Add curl as a dependency for those who run the script without 'curl URL | bash'. - Use POSIX 'command -v' instead of 'hash'. - Check if packages have actually been installed and abort execution if they have not. - Fixed issue with getStaticIPv4Settings() that prevented existing network settings to be used as static IP settings when running the script unattended with empty $IPv4addr and $IPv4gw variables. - Exit if processing wireguard-linux-compat fails. - Exit if 50unattended-upgrades fails to extract. - Exit clientSTAT.sh if the wg0 interface is not available. - Moved the Self Check to a single script since dedicated versions were very similar. - Add 'pivpn -wg' to update WireGuard for users running Raspbian with armv6l kernel. * Fixed cosmetic issue with spinner, added missing spinner to some APT commands * Detect current netmask, validate user input when configuring a static IP * Inform the user when updating the package cache, which can be slow on some RPis * Invalidate $IPv4Addr and $IPv4gw when the user claims those settings are not correct * Restart pihole in the more appropriate restartServices() function * Improve static IP selection, validate public DNS name of the server - Default to 'No' when asking if the RPi has DHCP reservation, considered that the user may not be fully aware, furthermore, setting a static IP anyways doesn't do harm. - Validate existing IPv4 settings (address, gateway, DNS) to avoid filling '/etc/dhcpcd.conf' with invalid data. - Validate public DNS name of the server inside askPublicIPOrDNS() function * Check DH parameters, fix 'pivpn -c', improvements when dealing with external repositories - Added a basic sanity check to downloaded DH paramenters, which doubles as a check for missing .pem file. - Fix 'pivpn -c' showing the month number instead of the day of the month when using WireGuard. - Removing APT keys is risky, it would break APT update/upgrade if the user already was already using the unstable repo. - Replaced 'Checking for $i... installed' in favor of a more clear 'Checking for $i... already installed'. - Check whether the OpenVPN repo and the Debian unstable repo are already used. * Improvements to getStaticIPv4Settings() - Use a regular expression to extract IPs from the 'ip' command. With this, there is a little need to validate output. Even though the regex will match invalid IPs like 192.168.23.444, 'ip' can't return them, and even if it did, the script would not have reached this function due to previous functions using the network with broken routes and addresses. - Get the IP address from the selected interface rather then from the 'ip route' command as it's not guaranteed that such IP is the same of the interface the user decided to use (though on a Raspberry Pi inside a home LAN, most likely it is, but it also maskes easier to get the IP in the CIDR notation with a single 'ip | grep' pipe). * Moved command substitution to specific functions to avoid unnecessary execution - Moved $availableInterfaces and $CurrentIPv4gw from the script header to their relevant function, considered that if the OS is not Raspbian a static IP is not set, so those variables are not used. * Copy files from git repo using the 'install' command, switch DH params from 2ton.com.au to RFC 7919 - Now using DH parameters suggested by the RFC 7919 for use by TLS servers (the user can still generate his own if he wishes). https://wiki.mozilla.org/Security/Archive/Server_Side_TLS_4.0#Pre-defined_DHE_groups
2020-01-31 15:40:09 +00:00
fi
# shellcheck disable=SC1090
Merge test (#929) * added link to server status dashboard * Replaced Header with bold instead * More safeguards, some fixes, standardized some code, WireGuard update script, removed redundant code - Add curl as a dependency for those who run the script without 'curl URL | bash'. - Use POSIX 'command -v' instead of 'hash'. - Check if packages have actually been installed and abort execution if they have not. - Fixed issue with getStaticIPv4Settings() that prevented existing network settings to be used as static IP settings when running the script unattended with empty $IPv4addr and $IPv4gw variables. - Exit if processing wireguard-linux-compat fails. - Exit if 50unattended-upgrades fails to extract. - Exit clientSTAT.sh if the wg0 interface is not available. - Moved the Self Check to a single script since dedicated versions were very similar. - Add 'pivpn -wg' to update WireGuard for users running Raspbian with armv6l kernel. * Fixed cosmetic issue with spinner, added missing spinner to some APT commands * Detect current netmask, validate user input when configuring a static IP * Inform the user when updating the package cache, which can be slow on some RPis * Invalidate $IPv4Addr and $IPv4gw when the user claims those settings are not correct * Restart pihole in the more appropriate restartServices() function * Improve static IP selection, validate public DNS name of the server - Default to 'No' when asking if the RPi has DHCP reservation, considered that the user may not be fully aware, furthermore, setting a static IP anyways doesn't do harm. - Validate existing IPv4 settings (address, gateway, DNS) to avoid filling '/etc/dhcpcd.conf' with invalid data. - Validate public DNS name of the server inside askPublicIPOrDNS() function * Check DH parameters, fix 'pivpn -c', improvements when dealing with external repositories - Added a basic sanity check to downloaded DH paramenters, which doubles as a check for missing .pem file. - Fix 'pivpn -c' showing the month number instead of the day of the month when using WireGuard. - Removing APT keys is risky, it would break APT update/upgrade if the user already was already using the unstable repo. - Replaced 'Checking for $i... installed' in favor of a more clear 'Checking for $i... already installed'. - Check whether the OpenVPN repo and the Debian unstable repo are already used. * Improvements to getStaticIPv4Settings() - Use a regular expression to extract IPs from the 'ip' command. With this, there is a little need to validate output. Even though the regex will match invalid IPs like 192.168.23.444, 'ip' can't return them, and even if it did, the script would not have reached this function due to previous functions using the network with broken routes and addresses. - Get the IP address from the selected interface rather then from the 'ip route' command as it's not guaranteed that such IP is the same of the interface the user decided to use (though on a Raspberry Pi inside a home LAN, most likely it is, but it also maskes easier to get the IP in the CIDR notation with a single 'ip | grep' pipe). * Moved command substitution to specific functions to avoid unnecessary execution - Moved $availableInterfaces and $CurrentIPv4gw from the script header to their relevant function, considered that if the OS is not Raspbian a static IP is not set, so those variables are not used. * Copy files from git repo using the 'install' command, switch DH params from 2ton.com.au to RFC 7919 - Now using DH parameters suggested by the RFC 7919 for use by TLS servers (the user can still generate his own if he wishes). https://wiki.mozilla.org/Security/Archive/Server_Side_TLS_4.0#Pre-defined_DHE_groups
2020-01-31 15:40:09 +00:00
source "${setupVars}"
2022-07-27 12:53:36 +00:00
helpFunc() {
echo "::: Create a client conf profile"
echo ":::"
echo "::: Usage: pivpn <-a|add> [-n|--name <arg>] [-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"
2019-10-14 10:27:28 +00:00
}
# Parse input arguments
2022-07-27 12:53:36 +00:00
while [[ "$#" -gt 0 ]]; do
_key="${1}"
case "${_key}" in
-n | --name | --name=*)
_val="${_key##--name=}"
if [[ "${_val}" == "${_key}" ]]; then
[[ "$#" -lt 2 ]] \
&& err "::: Missing value for the optional argument '${_key}'." \
&& exit 1
2022-07-27 12:53:36 +00:00
_val="${2}"
shift
fi
CLIENT_NAME="${_val}"
;;
-h | --help)
helpFunc
exit 0
;;
*)
err "::: Error: Got an unexpected argument '${1}'"
helpFunc
exit 1
;;
esac
shift
2019-10-14 10:27:28 +00:00
done
# Disabling SC2154, variables sourced externaly
# shellcheck disable=SC2154
2019-10-14 10:27:28 +00:00
# The home folder variable was sourced from the settings file.
2022-07-27 12:53:36 +00:00
if [[ ! -d "${install_home}/configs" ]]; then
mkdir "${install_home}/configs"
chown "${userGroup}" "${install_home}/configs"
chmod 0750 "${install_home}/configs"
2019-10-14 10:27:28 +00:00
fi
cd /etc/wireguard || exit
2019-10-14 10:27:28 +00:00
2022-07-27 12:53:36 +00:00
if [[ -z "${CLIENT_NAME}" ]]; then
read -r -p "Enter a Name for the Client: " CLIENT_NAME
elif [[ "${CLIENT_NAME}" =~ [^a-zA-Z0-9.@_-] ]]; then
err "Name can only contain alphanumeric characters and these symbols (.-@_)."
exit 1
elif [[ "${CLIENT_NAME:0:1}" == "-" ]]; then
err "Name cannot start with -"
exit 1
elif [[ "${CLIENT_NAME}" =~ ^[0-9]+$ ]]; then
err "Names cannot be integers."
exit 1
elif [[ -z "${CLIENT_NAME}" ]]; then
err "::: You cannot leave the name blank."
exit 1
elif [[ -f "configs/${CLIENT_NAME}.conf" ]]; then
err "::: A client with this name already exists"
exit 1
fi
wg genkey \
| tee "keys/${CLIENT_NAME}_priv" \
| wg pubkey > "keys/${CLIENT_NAME}_pub"
wg genpsk | tee "keys/${CLIENT_NAME}_psk" &> /dev/null
2019-10-14 10:27:28 +00:00
echo "::: Client Keys generated"
# Find an unused number for the last octet of the client IP
for i in {2..254}; do
2022-07-27 12:53:36 +00:00
if ! grep -q " ${i}$" configs/clients.txt; then
COUNT="${i}"
echo "${CLIENT_NAME} $(< keys/"${CLIENT_NAME}"_pub) $(date +%s) ${COUNT}" \
| tee -a configs/clients.txt > /dev/null
2022-07-27 12:53:36 +00:00
break
fi
2019-10-14 10:27:28 +00:00
done
# Disabling SC2154, variables sourced externaly
# shellcheck disable=SC2154
NET_REDUCED="${pivpnNET::-2}"
# shellcheck disable=SC2154
2022-07-27 12:53:36 +00:00
{
echo '[Interface]'
echo "PrivateKey = $(cat "keys/${CLIENT_NAME}_priv")"
echo -n "Address = ${NET_REDUCED}.${COUNT}/${subnetClass}"
if [[ "${pivpnenableipv6}" == 1 ]]; then
echo ",${pivpnNETv6}${COUNT}/${subnetClassv6}"
else
echo
fi
echo -n "DNS = ${pivpnDNS1}"
if [[ -n "${pivpnDNS2}" ]]; then
echo ", ${pivpnDNS2}"
else
echo
fi
echo
echo '[Peer]'
echo "PublicKey = $(cat keys/server_pub)"
echo "PresharedKey = $(cat "keys/${CLIENT_NAME}_psk")"
echo "Endpoint = ${pivpnHOST}:${pivpnPORT}"
echo "AllowedIPs = ${ALLOWED_IPS}"
if [[ -n "${pivpnPERSISTENTKEEPALIVE}" ]]; then
echo "PersistentKeepalive = ${pivpnPERSISTENTKEEPALIVE}"
fi
} > "configs/${CLIENT_NAME}.conf"
2019-10-14 10:27:28 +00:00
echo "::: Client config generated"
2022-07-27 12:53:36 +00:00
{
echo "### begin ${CLIENT_NAME} ###"
echo '[Peer]'
echo "PublicKey = $(cat "keys/${CLIENT_NAME}_pub")"
echo "PresharedKey = $(cat "keys/${CLIENT_NAME}_psk")"
echo -n "AllowedIPs = ${NET_REDUCED}.${COUNT}/32"
if [[ "${pivpnenableipv6}" == 1 ]]; then
echo ",${pivpnNETv6}${COUNT}/128"
else
echo
fi
echo "### end ${CLIENT_NAME} ###"
} >> wg0.conf
2019-10-14 10:27:28 +00:00
echo "::: Updated server config"
2022-07-27 12:53:36 +00:00
if [[ -f /etc/pivpn/hosts.wireguard ]]; then
echo "${NET_REDUCED}.${COUNT} ${CLIENT_NAME}.pivpn" \
| tee -a /etc/pivpn/hosts.wireguard > /dev/null
2022-07-27 12:53:36 +00:00
if [[ "${pivpnenableipv6}" == 1 ]]; then
echo "${pivpnNETv6}${COUNT} ${CLIENT_NAME}.pivpn" \
| tee -a /etc/pivpn/hosts.wireguard > /dev/null
2022-07-27 12:53:36 +00:00
fi
if killall -SIGHUP pihole-FTL; then
echo "::: Updated hosts file for Pi-hole"
else
err "::: Failed to reload pihole-FTL configuration"
fi
fi
2022-07-27 12:53:36 +00:00
if [[ "${PLAT}" == 'Alpine' ]]; then
if rc-service wg-quick restart; then
echo "::: WireGuard reloaded"
else
err "::: Failed to reload WireGuard"
fi
2019-10-14 10:27:28 +00:00
else
2022-07-27 12:53:36 +00:00
if systemctl reload wg-quick@wg0; then
echo "::: WireGuard reloaded"
else
err "::: Failed to reload WireGuard"
fi
2019-10-14 10:27:28 +00:00
fi
cp "configs/${CLIENT_NAME}.conf" "${install_home}/configs/${CLIENT_NAME}.conf"
2022-07-27 12:53:36 +00:00
chown "${userGroup}" "${install_home}/configs/${CLIENT_NAME}.conf"
2019-10-14 14:51:43 +00:00
chmod 640 "${install_home}/configs/${CLIENT_NAME}.conf"
2019-10-14 10:27:28 +00:00
echo "======================================================================"
echo -e "::: Done! \e[1m${CLIENT_NAME}.conf successfully created!\e[0m"
2022-07-27 12:53:36 +00:00
echo -n "::: ${CLIENT_NAME}.conf was copied to ${install_home}/configs for easy"
echo "transfer."
2019-10-14 10:27:28 +00:00
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 "======================================================================"