Advertisement
Guest User

Untitled

a guest
Nov 4th, 2017
361
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 53.01 KB | None | 0 0
  1. #!/usr/bin/env bash
  2. # PiVPN: Trivial OpenVPN setup and configuration
  3. # Easiest setup and mangement of OpenVPN on Raspberry Pi
  4. # http://pivpn.io
  5. # Heavily adapted from the pi-hole.net project and...
  6. # https://github.com/StarshipEngineer/OpenVPN-Setup/
  7. #
  8. # Install with this command (from your Pi):
  9. #
  10. # curl -L https://install.pivpn.io | bash
  11. # Make sure you have `curl` installed
  12.  
  13. set -e
  14. ######## VARIABLES #########
  15.  
  16. tmpLog="/tmp/pivpn-install.log"
  17. instalLogLoc="/etc/pivpn/install.log"
  18. setupVars=/etc/pivpn/setupVars.conf
  19. useUpdateVars=false
  20.  
  21. ### PKG Vars ###
  22. PKG_MANAGER="apt-get"
  23. PKG_CACHE="/var/lib/apt/lists/"
  24. UPDATE_PKG_CACHE="${PKG_MANAGER} update"
  25. PKG_INSTALL="${PKG_MANAGER} --yes --no-install-recommends install"
  26. PKG_COUNT="${PKG_MANAGER} -s -o Debug::NoLocking=true upgrade | grep -c ^Inst || true"
  27. PIVPN_DEPS=( openvpn git dhcpcd5 tar wget grep iptables-persistent dnsutils expect whiptail net-tools)
  28. ### ###
  29.  
  30. pivpnGitUrl="https://github.com/pivpn/pivpn.git"
  31. pivpnFilesDir="/etc/.pivpn"
  32. easyrsaVer="3.0.1-pivpn1"
  33. easyrsaRel="https://github.com/pivpn/easy-rsa/releases/download/${easyrsaVer}/EasyRSA-${easyrsaVer}.tgz"
  34.  
  35. # Find the rows and columns. Will default to 80x24 if it can not be detected.
  36. screen_size=$(stty size 2>/dev/null || echo 24 80)
  37. rows=$(echo $screen_size | awk '{print $1}')
  38. columns=$(echo $screen_size | awk '{print $2}')
  39.  
  40. # Divide by two so the dialogs take up half of the screen, which looks nice.
  41. r=$(( rows / 2 ))
  42. c=$(( columns / 2 ))
  43. # Unless the screen is tiny
  44. r=$(( r < 20 ? 20 : r ))
  45. c=$(( c < 70 ? 70 : c ))
  46.  
  47. ######## Undocumented Flags. Shhh ########
  48. skipSpaceCheck=false
  49. reconfigure=false
  50. runUnattended=false
  51.  
  52. # Find IP used to route to outside world
  53.  
  54. IPv4dev=$(ip route get 8.8.8.8 | awk '{for(i=1;i<=NF;i++)if($i~/dev/)print $(i+1)}')
  55. IPv4addr=$(ip route get 8.8.8.8| awk '{print $7}')
  56. IPv4gw=$(ip route get 8.8.8.8 | awk '{print $3}')
  57.  
  58. availableInterfaces=$(ip -o link | grep "state UP" | awk '{print $2}' | cut -d':' -f1 | cut -d'@' -f1)
  59. dhcpcdFile=/etc/dhcpcd.conf
  60.  
  61. # Next see if we are on a tested and supported OS
  62. function noOS_Support() {
  63. whiptail --msgbox --backtitle "INVALID OS DETECTED" --title "Invalid OS" "We have not been able to detect a supported OS.
  64. Currently this installer supports Raspbian and Debian (Jessie and Stretch), Devuan (Jessie) and Ubuntu from 14.04 (trusty) to 17.04 (zesty).
  65. 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}
  66. exit 1
  67. }
  68.  
  69. function maybeOS_Support() {
  70. if (whiptail --backtitle "Not Supported OS" --title "Not Supported OS" --yesno "You are on an OS that we have not tested but MAY work.
  71. Currently this installer supports Raspbian and Debian (Jessie and Stretch), Devuan (Jessie) and Ubuntu from 14.04 (trusty) to 17.04 (zesty).
  72. Would you like to continue anyway?" ${r} ${c}) then
  73. echo "::: Did not detect perfectly supported OS but,"
  74. echo "::: Continuing installation at user's own risk..."
  75. else
  76. echo "::: Exiting due to unsupported OS"
  77. exit 1
  78. fi
  79. }
  80.  
  81. # Compatibility
  82. distro_check() {
  83. # if lsb_release command is on their system
  84. if hash lsb_release 2>/dev/null; then
  85. PLAT=$(lsb_release -si)
  86. OSCN=$(lsb_release -sc) # We want this to be trusty xenial or jessie
  87.  
  88. case ${PLAT} in
  89. Ubuntu|Raspbian|Debian|Devuan)
  90. case ${OSCN} in
  91. trusty|xenial|jessie|stretch)
  92. ;;
  93. *)
  94. maybeOS_Support
  95. ;;
  96. esac
  97. ;;
  98. *)
  99. noOS_Support
  100. ;;
  101. esac
  102. # else get info from os-release
  103. elif grep -q devuan /etc/os-release; then
  104. if grep -q jessie /etc/os-release; then
  105. PLAT="Raspvuan"
  106. OSCN="jessie"
  107. else
  108. noOS_Support
  109. fi
  110. elif grep -q debian /etc/os-release; then
  111. if grep -q jessie /etc/os-release; then
  112. PLAT="Raspbian"
  113. OSCN="jessie"
  114. elif grep -q stretch /etc/os-release; then
  115. PLAT="Raspbian"
  116. OSCN="stretch"
  117. else
  118. PLAT="Ubuntu"
  119. OSCN="unknown"
  120. maybeOS_Support
  121. fi
  122. # else we prob don't want to install
  123. else
  124. noOS_Support
  125. fi
  126.  
  127. echo "${PLAT}" > /tmp/DET_PLATFORM
  128. }
  129.  
  130. ####### FUNCTIONS ##########
  131. spinner()
  132. {
  133. local pid=$1
  134. local delay=0.50
  135. local spinstr='/-\|'
  136. while [ "$(ps a | awk '{print $1}' | grep "${pid}")" ]; do
  137. local temp=${spinstr#?}
  138. printf " [%c] " "${spinstr}"
  139. local spinstr=${temp}${spinstr%"$temp"}
  140. sleep ${delay}
  141. printf "\b\b\b\b\b\b"
  142. done
  143. printf " \b\b\b\b"
  144. }
  145.  
  146. welcomeDialogs() {
  147. # Display the welcome dialog
  148. whiptail --msgbox --backtitle "Welcome" --title "PiVPN Automated Installer" "This installer will transform your Raspberry Pi into an OpenVPN server!" ${r} ${c}
  149.  
  150. # Explain the need for a static address
  151. 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.
  152.  
  153. In the next section, you can choose to use your current network settings (DHCP) or to manually edit them." ${r} ${c}
  154. }
  155.  
  156. chooseUser() {
  157. # Explain the local user
  158. whiptail --msgbox --backtitle "Parsing User List" --title "Local Users" "Choose a local user that will hold your ovpn configurations." ${r} ${c}
  159. # First, let's check if there is a user available.
  160. numUsers=$(awk -F':' 'BEGIN {count=0} $3>=500 && $3<=60000 { count++ } END{ print count }' /etc/passwd)
  161. if [ "$numUsers" -eq 0 ]
  162. then
  163. # We don't have a user, let's ask to add one.
  164. 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)
  165. then
  166. # See http://askubuntu.com/a/667842/459815
  167. PASSWORD=$(whiptail --title "password dialog" --passwordbox "Please enter the new user password" ${r} ${c} 3>&1 1>&2 2>&3)
  168. CRYPT=$(perl -e 'printf("%s\n", crypt($ARGV[0], "password"))' "${PASSWORD}")
  169. $SUDO useradd -m -p "${CRYPT}" -s /bin/bash "${userToAdd}"
  170. if [[ $? = 0 ]]; then
  171. echo "Succeeded"
  172. ((numUsers+=1))
  173. else
  174. exit 1
  175. fi
  176. else
  177. exit 1
  178. fi
  179. fi
  180. availableUsers=$(awk -F':' '$3>=500 && $3<=60000 {print $1}' /etc/passwd)
  181. local userArray=()
  182. local firstloop=1
  183.  
  184. while read -r line
  185. do
  186. mode="OFF"
  187. if [[ $firstloop -eq 1 ]]; then
  188. firstloop=0
  189. mode="ON"
  190. fi
  191. userArray+=("${line}" "" "${mode}")
  192. done <<< "${availableUsers}"
  193. chooseUserCmd=(whiptail --title "Choose A User" --separate-output --radiolist "Choose (press space to select):" ${r} ${c} ${numUsers})
  194. chooseUserOptions=$("${chooseUserCmd[@]}" "${userArray[@]}" 2>&1 >/dev/tty)
  195. if [[ $? = 0 ]]; then
  196. for desiredUser in ${chooseUserOptions}; do
  197. pivpnUser=${desiredUser}
  198. echo "::: Using User: $pivpnUser"
  199. echo "${pivpnUser}" > /tmp/pivpnUSR
  200. done
  201. else
  202. echo "::: Cancel selected, exiting...."
  203. exit 1
  204. fi
  205. }
  206.  
  207. verifyFreeDiskSpace() {
  208. # If user installs unattended-upgrades we'd need about 60MB so will check for 75MB free
  209. echo "::: Verifying free disk space..."
  210. local required_free_kilobytes=76800
  211. local existing_free_kilobytes=$(df -Pk | grep -m1 '\/$' | awk '{print $4}')
  212.  
  213. # - Unknown free disk space , not a integer
  214. if ! [[ "${existing_free_kilobytes}" =~ ^([0-9])+$ ]]; then
  215. echo "::: Unknown free disk space!"
  216. echo "::: We were unable to determine available free disk space on this system."
  217. echo "::: You may continue with the installation, however, it is not recommended."
  218. read -r -p "::: If you are sure you want to continue, type YES and press enter :: " response
  219. case $response in
  220. [Y][E][S])
  221. ;;
  222. *)
  223. echo "::: Confirmation not received, exiting..."
  224. exit 1
  225. ;;
  226. esac
  227. # - Insufficient free disk space
  228. elif [[ ${existing_free_kilobytes} -lt ${required_free_kilobytes} ]]; then
  229. echo "::: Insufficient Disk Space!"
  230. echo "::: Your system appears to be low on disk space. PiVPN recommends a minimum of $required_free_kilobytes KiloBytes."
  231. echo "::: You only have ${existing_free_kilobytes} KiloBytes free."
  232. echo "::: If this is a new install on a Raspberry Pi you may need to expand your disk."
  233. echo "::: Try running 'sudo raspi-config', and choose the 'expand file system option'"
  234. echo "::: After rebooting, run this installation again. (curl -L https://install.pivpn.io | bash)"
  235.  
  236. echo "Insufficient free space, exiting..."
  237. exit 1
  238. fi
  239. }
  240.  
  241.  
  242. chooseInterface() {
  243. # Turn the available interfaces into an array so it can be used with a whiptail dialog
  244. local interfacesArray=()
  245. # Number of available interfaces
  246. local interfaceCount
  247. # Whiptail variable storage
  248. local chooseInterfaceCmd
  249. # Temporary Whiptail options storage
  250. local chooseInterfaceOptions
  251. # Loop sentinel variable
  252. local firstLoop=1
  253.  
  254. if [[ $(echo "${availableInterfaces}" | wc -l) -eq 1 ]]; then
  255. pivpnInterface="${availableInterfaces}"
  256. echo "${pivpnInterface}" > /tmp/pivpnINT
  257. return
  258. fi
  259.  
  260. while read -r line; do
  261. mode="OFF"
  262. if [[ ${firstloop} -eq 1 ]]; then
  263. firstloop=0
  264. mode="ON"
  265. fi
  266. interfacesArray+=("${line}" "available" "${mode}")
  267. done <<< "${availableInterfaces}"
  268.  
  269. # Find out how many interfaces are available to choose from
  270. interfaceCount=$(echo "${availableInterfaces}" | wc -l)
  271. chooseInterfaceCmd=(whiptail --separate-output --radiolist "Choose An Interface (press space to select):" ${r} ${c} ${interfaceCount})
  272. chooseInterfaceOptions=$("${chooseInterfaceCmd[@]}" "${interfacesArray[@]}" 2>&1 >/dev/tty)
  273. if [[ $? = 0 ]]; then
  274. for desiredInterface in ${chooseInterfaceOptions}; do
  275. pivpnInterface=${desiredInterface}
  276. echo "::: Using interface: $pivpnInterface"
  277. echo "${pivpnInterface}" > /tmp/pivpnINT
  278. done
  279. else
  280. echo "::: Cancel selected, exiting...."
  281. exit 1
  282. fi
  283. }
  284.  
  285. avoidStaticIPv4Ubuntu() {
  286. # If we are in Ubuntu then they need to have previously set their network, so just use what you have.
  287. 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.
  288. 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}
  289. }
  290.  
  291. getStaticIPv4Settings() {
  292. local ipSettingsCorrect
  293. # Grab their current DNS Server
  294. IPv4dns=$(nslookup 127.0.0.1 | grep Server: | awk '{print $2}')
  295. # Ask if the user wants to use DHCP settings as their static IP
  296. if (whiptail --backtitle "Calibrating network interface" --title "Static IP Address" --yesno "Do you want to use your current network settings as a static address?
  297. IP address: ${IPv4addr}
  298. Gateway: ${IPv4gw}" ${r} ${c}); then
  299. # If they choose yes, let the user know that the IP address will not be available via DHCP and may cause a conflict.
  300. 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.
  301. If you are worried, either manually set the address, or modify the DHCP reservation pool so it does not include the IP you want.
  302. 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}
  303. # Nothing else to do since the variables are already set above
  304. else
  305. # Otherwise, we need to ask the user to input their desired settings.
  306. # Start by getting the IPv4 address (pre-filling it with info gathered from DHCP)
  307. # Start a loop to let the user enter their information with the chance to go back and edit it if necessary
  308. until [[ ${ipSettingsCorrect} = True ]]; do
  309. # Ask for the IPv4 address
  310. IPv4addr=$(whiptail --backtitle "Calibrating network interface" --title "IPv4 address" --inputbox "Enter your desired IPv4 address" ${r} ${c} "${IPv4addr}" 3>&1 1>&2 2>&3)
  311. if [[ $? = 0 ]]; then
  312. echo "::: Your static IPv4 address: ${IPv4addr}"
  313. # Ask for the gateway
  314. 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)
  315. if [[ $? = 0 ]]; then
  316. echo "::: Your static IPv4 gateway: ${IPv4gw}"
  317. # Give the user a chance to review their settings before moving on
  318. if (whiptail --backtitle "Calibrating network interface" --title "Static IP Address" --yesno "Are these settings correct?
  319. IP address: ${IPv4addr}
  320. Gateway: ${IPv4gw}" ${r} ${c}); then
  321. # If the settings are correct, then we need to set the pivpnIP
  322. echo "${IPv4addr%/*}" > /tmp/pivpnIP
  323. echo "$pivpnInterface" > /tmp/pivpnINT
  324. # After that's done, the loop ends and we move on
  325. ipSettingsCorrect=True
  326. else
  327. # If the settings are wrong, the loop continues
  328. ipSettingsCorrect=False
  329. fi
  330. else
  331. # Cancelling gateway settings window
  332. ipSettingsCorrect=False
  333. echo "::: Cancel selected. Exiting..."
  334. exit 1
  335. fi
  336. else
  337. # Cancelling IPv4 settings window
  338. ipSettingsCorrect=False
  339. echo "::: Cancel selected. Exiting..."
  340. exit 1
  341. fi
  342. done
  343. # End the if statement for DHCP vs. static
  344. fi
  345. }
  346.  
  347. setDHCPCD() {
  348. # Append these lines to dhcpcd.conf to enable a static IP
  349. echo "interface ${pivpnInterface}
  350. static ip_address=${IPv4addr}
  351. static routers=${IPv4gw}
  352. static domain_name_servers=${IPv4dns}" | $SUDO tee -a ${dhcpcdFile} >/dev/null
  353. }
  354.  
  355. setStaticIPv4() {
  356.  
  357. fi
  358. }
  359.  
  360. setNetwork() {
  361. # Sets the Network IP and Mask correctly
  362. export PATH=${PATH}:/sbin:/usr/sbin
  363. LOCALMASK=$(ifconfig "${pivpnInterface}" | awk '/Mask:/{ print $4;} ' | cut -c6-)
  364. LOCALIP=$(ifconfig "${pivpnInterface}" | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*')
  365. IFS=. read -r i1 i2 i3 i4 <<< "$LOCALIP"
  366. IFS=. read -r m1 m2 m3 m4 <<< "$LOCALMASK"
  367. LOCALNET=$(printf "%d.%d.%d.%d\n" "$((i1 & m1))" "$((i2 & m2))" "$((i3 & m3))" "$((i4 & m4))")
  368. }
  369.  
  370. function valid_ip()
  371. {
  372. local ip=$1
  373. local stat=1
  374.  
  375. if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
  376. OIFS=$IFS
  377. IFS='.'
  378. ip=($ip)
  379. IFS=$OIFS
  380. [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
  381. && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
  382. stat=$?
  383. fi
  384. return $stat
  385. }
  386.  
  387. installScripts() {
  388. # Install the scripts from /etc/.pivpn to their various locations
  389. $SUDO echo ":::"
  390. $SUDO echo -n "::: Installing scripts to /opt/pivpn..."
  391. if [ ! -d /opt/pivpn ]; then
  392. $SUDO mkdir /opt/pivpn
  393. $SUDO chown "$pivpnUser":root /opt/pivpn
  394. $SUDO chmod u+srwx /opt/pivpn
  395. fi
  396. $SUDO cp /etc/.pivpn/scripts/makeOVPN.sh /opt/pivpn/makeOVPN.sh
  397. $SUDO cp /etc/.pivpn/scripts/clientStat.sh /opt/pivpn/clientStat.sh
  398. $SUDO cp /etc/.pivpn/scripts/listOVPN.sh /opt/pivpn/listOVPN.sh
  399. $SUDO cp /etc/.pivpn/scripts/removeOVPN.sh /opt/pivpn/removeOVPN.sh
  400. $SUDO cp /etc/.pivpn/scripts/uninstall.sh /opt/pivpn/uninstall.sh
  401. $SUDO cp /etc/.pivpn/scripts/pivpnDebug.sh /opt/pivpn/pivpnDebug.sh
  402. $SUDO cp /etc/.pivpn/scripts/fix_iptables.sh /opt/pivpn/fix_iptables.sh
  403. $SUDO chmod 0755 /opt/pivpn/{makeOVPN,clientStat,listOVPN,removeOVPN,uninstall,pivpnDebug,fix_iptables}.sh
  404. $SUDO cp /etc/.pivpn/pivpn /usr/local/bin/pivpn
  405. $SUDO chmod 0755 /usr/local/bin/pivpn
  406. $SUDO cp /etc/.pivpn/scripts/bash-completion /etc/bash_completion.d/pivpn
  407. . /etc/bash_completion.d/pivpn
  408. # Copy interface setting for debug
  409. $SUDO cp /tmp/pivpnINT /etc/pivpn/pivpnINTERFACE
  410.  
  411. $SUDO echo " done."
  412. }
  413.  
  414. package_check_install() {
  415. dpkg-query -W -f='${Status}' "${1}" 2>/dev/null | grep -c "ok installed" || ${PKG_INSTALL} "${1}"
  416. }
  417.  
  418. update_package_cache() {
  419. #Running apt-get update/upgrade with minimal output can cause some issues with
  420. #requiring user input
  421.  
  422. #Check to see if apt-get update has already been run today
  423. #it needs to have been run at least once on new installs!
  424. timestamp=$(stat -c %Y ${PKG_CACHE})
  425. timestampAsDate=$(date -d @"${timestamp}" "+%b %e")
  426. today=$(date "+%b %e")
  427.  
  428.  
  429. if [ ! "${today}" == "${timestampAsDate}" ]; then
  430. #update package lists
  431. echo ":::"
  432. echo -n "::: ${PKG_MANAGER} update has not been run today. Running now..."
  433. $SUDO ${UPDATE_PKG_CACHE} &> /dev/null
  434. echo " done!"
  435. fi
  436. }
  437.  
  438. notify_package_updates_available() {
  439. # Let user know if they have outdated packages on their system and
  440. # advise them to run a package update at soonest possible.
  441. echo ":::"
  442. echo -n "::: Checking ${PKG_MANAGER} for upgraded packages...."
  443. updatesToInstall=$(eval "${PKG_COUNT}")
  444. echo " done!"
  445. echo ":::"
  446. if [[ ${updatesToInstall} -eq "0" ]]; then
  447. echo "::: Your system is up to date! Continuing with PiVPN installation..."
  448. else
  449. echo "::: There are ${updatesToInstall} updates available for your system!"
  450. echo "::: We recommend you update your OS after installing PiVPN! "
  451. echo ":::"
  452. fi
  453. }
  454.  
  455. install_dependent_packages() {
  456. # Install packages passed in via argument array
  457. # No spinner - conflicts with set -e
  458. declare -a argArray1=("${!1}")
  459.  
  460. echo iptables-persistent iptables-persistent/autosave_v4 boolean true | $SUDO debconf-set-selections
  461. echo iptables-persistent iptables-persistent/autosave_v6 boolean false | $SUDO debconf-set-selections
  462.  
  463. if command -v debconf-apt-progress &> /dev/null; then
  464. $SUDO debconf-apt-progress -- ${PKG_INSTALL} "${argArray1[@]}"
  465. else
  466. for i in "${argArray1[@]}"; do
  467. echo -n "::: Checking for $i..."
  468. $SUDO package_check_install "${i}" &> /dev/null
  469. echo " installed!"
  470. done
  471. fi
  472. }
  473.  
  474. unattendedUpgrades() {
  475. 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}
  476.  
  477. 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
  478. UNATTUPG="unattended-upgrades"
  479. else
  480. UNATTUPG=""
  481. fi
  482. }
  483.  
  484. stopServices() {
  485. # Stop openvpn
  486. $SUDO echo ":::"
  487. $SUDO echo -n "::: Stopping OpenVPN service..."
  488. case ${PLAT} in
  489. Ubuntu|Debian|*vuan)
  490. $SUDO service openvpn stop || true
  491. ;;
  492. *)
  493. $SUDO systemctl stop openvpn.service || true
  494. ;;
  495. esac
  496. $SUDO echo " done."
  497. }
  498.  
  499. checkForDependencies() {
  500. #Running apt-get update/upgrade with minimal output can cause some issues with
  501. #requiring user input (e.g password for phpmyadmin see #218)
  502. #We'll change the logic up here, to check to see if there are any updates available and
  503. # if so, advise the user to run apt-get update/upgrade at their own discretion
  504. #Check to see if apt-get update has already been run today
  505. # it needs to have been run at least once on new installs!
  506.  
  507. timestamp=$(stat -c %Y /var/cache/apt/)
  508. timestampAsDate=$(date -d @"$timestamp" "+%b %e")
  509. today=$(date "+%b %e")
  510.  
  511. case ${PLAT} in
  512. Ubuntu|Debian|Devuan)
  513. case ${OSCN} in
  514. trusty|jessie|wheezy|stretch)
  515. wget -O - https://swupdate.openvpn.net/repos/repo-public.gpg| $SUDO apt-key add -
  516. echo "deb http://swupdate.openvpn.net/apt $OSCN main" | $SUDO tee /etc/apt/sources.list.d/swupdate.openvpn.net.list > /dev/null
  517. echo -n "::: Adding OpenVPN repo for $PLAT $OSCN ..."
  518. $SUDO apt-get -qq update & spinner $!
  519. echo " done!"
  520. ;;
  521. esac
  522. ;;
  523. esac
  524. if [[ $PLAT == "Ubuntu" || $PLAT == "Debian" ]]; then
  525. if [[ $OSCN == "trusty" || $OSCN == "jessie" || $OSCN == "wheezy" || $OSCN == "stretch" ]]; then
  526. wget -O - https://swupdate.openvpn.net/repos/repo-public.gpg| $SUDO apt-key add -
  527. echo "deb http://build.openvpn.net/debian/openvpn/stable $OSCN main" | $SUDO tee /etc/apt/sources.list.d/swupdate.openvpn.net.list > /dev/null
  528. echo -n "::: Adding OpenVPN repo for $PLAT $OSCN ..."
  529. $SUDO apt-get -qq update & spinner $!
  530. echo " done!"
  531. fi
  532. fi
  533.  
  534. if [ ! "$today" == "$timestampAsDate" ]; then
  535. #update package lists
  536. echo ":::"
  537. echo -n "::: apt-get update has not been run today. Running now..."
  538. $SUDO apt-get -qq update & spinner $!
  539. echo " done!"
  540. fi
  541. echo ":::"
  542. echo -n "::: Checking apt-get for upgraded packages...."
  543. updatesToInstall=$($SUDO apt-get -s -o Debug::NoLocking=true upgrade | grep -c ^Inst)
  544. echo " done!"
  545. echo ":::"
  546. if [[ $updatesToInstall -eq "0" ]]; then
  547. echo "::: Your pi is up to date! Continuing with PiVPN installation..."
  548. else
  549. echo "::: There are $updatesToInstall updates availible for your pi!"
  550. echo "::: We recommend you run 'sudo apt-get upgrade' after installing PiVPN! "
  551. echo ":::"
  552. fi
  553. echo ":::"
  554. echo "::: Checking dependencies:"
  555.  
  556. dependencies=( openvpn git dhcpcd5 tar wget grep iptables-persistent dnsutils expect whiptail net-tools)
  557. for i in "${dependencies[@]}"; do
  558. echo -n "::: Checking for $i..."
  559. if [ "$(dpkg-query -W -f='${Status}' "$i" 2>/dev/null | grep -c "ok installed")" -eq 0 ]; then
  560. echo -n " Not found! Installing...."
  561. #Supply answers to the questions so we don't prompt user
  562. if [[ $i = "iptables-persistent" ]]; then
  563. echo iptables-persistent iptables-persistent/autosave_v4 boolean true | $SUDO debconf-set-selections
  564. echo iptables-persistent iptables-persistent/autosave_v6 boolean false | $SUDO debconf-set-selections
  565. fi
  566. if [[ $i == "expect" ]] || [[ $i == "openvpn" ]]; then
  567. ($SUDO apt-get --yes --quiet --no-install-recommends install "$i" > /dev/null || echo "Installation Failed!" && fixApt) & spinner $!
  568. else
  569. ($SUDO apt-get --yes --quiet install "$i" > /dev/null || echo "Installation Failed!" && fixApt) & spinner $!
  570. fi
  571. echo " done!"
  572. else
  573. echo " already installed!"
  574. fi
  575. done
  576. }
  577.  
  578. getGitFiles() {
  579. # Setup git repos for base files
  580. echo ":::"
  581. echo "::: Checking for existing base files..."
  582. if is_repo "${1}"; then
  583. update_repo "${1}"
  584. else
  585. make_repo "${1}" "${2}"
  586. fi
  587. }
  588.  
  589. is_repo() {
  590. # If the directory does not have a .git folder it is not a repo
  591. echo -n "::: Checking $1 is a repo..."
  592. cd "${1}" &> /dev/null || return 1
  593. $SUDO git status &> /dev/null && echo " OK!"; return 0 || echo " not found!"; return 1
  594. }
  595.  
  596. make_repo() {
  597. # Remove the non-repos interface and clone the interface
  598. echo -n "::: Cloning $2 into $1..."
  599. $SUDO rm -rf "${1}"
  600. $SUDO git clone -q "${2}" "${1}" > /dev/null & spinner $!
  601. if [ -z "${TESTING+x}" ]; then
  602. :
  603. else
  604. $SUDO git -C "${1}" checkout test
  605. fi
  606. echo " done!"
  607. }
  608.  
  609. update_repo() {
  610. if [[ "${reconfigure}" == true ]]; then
  611. echo "::: --reconfigure passed to install script. Not downloading/updating local repos"
  612. else
  613. # Pull the latest commits
  614. echo -n "::: Updating repo in $1..."
  615. cd "${1}" || exit 1
  616. $SUDO git stash -q > /dev/null & spinner $!
  617. $SUDO git pull -q > /dev/null & spinner $!
  618. if [ -z "${TESTING+x}" ]; then
  619. :
  620. else
  621. ${SUDOE} git checkout test
  622. fi
  623. echo " done!"
  624. fi
  625. }
  626.  
  627. setCustomProto() {
  628. # Set the available protocols into an array so it can be used with a whiptail dialog
  629. if protocol=$(whiptail --title "Protocol" --radiolist \
  630. "Choose a protocol (press space to select). Please only choose TCP if you know why you need TCP." ${r} ${c} 2 \
  631. "UDP" "" ON \
  632. "TCP" "" OFF 3>&1 1>&2 2>&3)
  633. then
  634. # Convert option into lowercase (UDP->udp)
  635. pivpnProto="${protocol,,}"
  636. echo "::: Using protocol: $pivpnProto"
  637. echo "${pivpnProto}" > /tmp/pivpnPROTO
  638. else
  639. echo "::: Cancel selected, exiting...."
  640. exit 1
  641. fi
  642. # write out the PROTO
  643. PROTO=$pivpnProto
  644. $SUDO cp /tmp/pivpnPROTO /etc/pivpn/INSTALL_PROTO
  645. }
  646.  
  647.  
  648. setCustomPort() {
  649. until [[ $PORTNumCorrect = True ]]
  650. do
  651. portInvalid="Invalid"
  652.  
  653. PROTO=$(cat /etc/pivpn/INSTALL_PROTO)
  654. if [ "$PROTO" = "udp" ]; then
  655. DEFAULT_PORT=1194
  656. else
  657. DEFAULT_PORT=443
  658. fi
  659. 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)
  660. then
  661. if [[ "$PORT" =~ ^[0-9]+$ ]] && [ "$PORT" -ge 1 ] && [ "$PORT" -le 65535 ]; then
  662. :
  663. else
  664. PORT=$portInvalid
  665. fi
  666. else
  667. echo "::: Cancel selected, exiting...."
  668. exit 1
  669. fi
  670.  
  671. if [[ $PORT == "$portInvalid" ]]; then
  672. 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}
  673. PORTNumCorrect=False
  674. else
  675. if (whiptail --backtitle "Specify Custom Port" --title "Confirm Custom Port Number" --yesno "Are these settings correct?\n PORT: $PORT" ${r} ${c}) then
  676. PORTNumCorrect=True
  677. else
  678. # If the settings are wrong, the loop continues
  679. PORTNumCorrect=False
  680. fi
  681. fi
  682. done
  683. # write out the port
  684. echo ${PORT} > /tmp/INSTALL_PORT
  685. $SUDO cp /tmp/INSTALL_PORT /etc/pivpn/INSTALL_PORT
  686. }
  687.  
  688. setClientDNS() {
  689. 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)
  690. DNSChooseOptions=(Google "" on
  691. OpenDNS "" off
  692. Level3 "" off
  693. DNS.WATCH "" off
  694. Norton "" off
  695. Custom "" off)
  696.  
  697. if DNSchoices=$("${DNSChoseCmd[@]}" "${DNSChooseOptions[@]}" 2>&1 >/dev/tty)
  698. then
  699. case ${DNSchoices} in
  700. Google)
  701. echo "::: Using Google DNS servers."
  702. OVPNDNS1="8.8.8.8"
  703. OVPNDNS2="8.8.4.4"
  704. # These are already in the file
  705. ;;
  706. OpenDNS)
  707. echo "::: Using OpenDNS servers."
  708. OVPNDNS1="208.67.222.222"
  709. OVPNDNS2="208.67.220.220"
  710. $SUDO sed -i '0,/\(dhcp-option DNS \)/ s/\(dhcp-option DNS \).*/\1'${OVPNDNS1}'\"/' /etc/openvpn/server.conf
  711. $SUDO sed -i '0,/\(dhcp-option DNS \)/! s/\(dhcp-option DNS \).*/\1'${OVPNDNS2}'\"/' /etc/openvpn/server.conf
  712. ;;
  713. Level3)
  714. echo "::: Using Level3 servers."
  715. OVPNDNS1="209.244.0.3"
  716. OVPNDNS2="209.244.0.4"
  717. $SUDO sed -i '0,/\(dhcp-option DNS \)/ s/\(dhcp-option DNS \).*/\1'${OVPNDNS1}'\"/' /etc/openvpn/server.conf
  718. $SUDO sed -i '0,/\(dhcp-option DNS \)/! s/\(dhcp-option DNS \).*/\1'${OVPNDNS2}'\"/' /etc/openvpn/server.conf
  719. ;;
  720. DNS.WATCH)
  721. echo "::: Using DNS.WATCH servers."
  722. OVPNDNS1="84.200.69.80"
  723. OVPNDNS2="84.200.70.40"
  724. $SUDO sed -i '0,/\(dhcp-option DNS \)/ s/\(dhcp-option DNS \).*/\1'${OVPNDNS1}'\"/' /etc/openvpn/server.conf
  725. $SUDO sed -i '0,/\(dhcp-option DNS \)/! s/\(dhcp-option DNS \).*/\1'${OVPNDNS2}'\"/' /etc/openvpn/server.conf
  726. ;;
  727. Norton)
  728. echo "::: Using Norton ConnectSafe servers."
  729. OVPNDNS1="199.85.126.10"
  730. OVPNDNS2="199.85.127.10"
  731. $SUDO sed -i '0,/\(dhcp-option DNS \)/ s/\(dhcp-option DNS \).*/\1'${OVPNDNS1}'\"/' /etc/openvpn/server.conf
  732. $SUDO sed -i '0,/\(dhcp-option DNS \)/! s/\(dhcp-option DNS \).*/\1'${OVPNDNS2}'\"/' /etc/openvpn/server.conf
  733. ;;
  734. Custom)
  735. until [[ $DNSSettingsCorrect = True ]]
  736. do
  737. strInvalid="Invalid"
  738.  
  739. if OVPNDNS=$(whiptail --backtitle "Specify Upstream DNS Provider(s)" --inputbox "Enter your desired upstream DNS provider(s), seperated by a comma.\n\nFor example '8.8.8.8, 8.8.4.4'" ${r} ${c} "" 3>&1 1>&2 2>&3)
  740. then
  741. OVPNDNS1=$(echo "$OVPNDNS" | sed 's/[, \t]\+/,/g' | awk -F, '{print$1}')
  742. OVPNDNS2=$(echo "$OVPNDNS" | sed 's/[, \t]\+/,/g' | awk -F, '{print$2}')
  743. if ! valid_ip "$OVPNDNS1" || [ ! "$OVPNDNS1" ]; then
  744. OVPNDNS1=$strInvalid
  745. fi
  746. if ! valid_ip "$OVPNDNS2" && [ "$OVPNDNS2" ]; then
  747. OVPNDNS2=$strInvalid
  748. fi
  749. else
  750. echo "::: Cancel selected, exiting...."
  751. exit 1
  752. fi
  753. if [[ $OVPNDNS1 == "$strInvalid" ]] || [[ $OVPNDNS2 == "$strInvalid" ]]; then
  754. 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}
  755. if [[ $OVPNDNS1 == "$strInvalid" ]]; then
  756. OVPNDNS1=""
  757. fi
  758. if [[ $OVPNDNS2 == "$strInvalid" ]]; then
  759. OVPNDNS2=""
  760. fi
  761. DNSSettingsCorrect=False
  762. else
  763. 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
  764. DNSSettingsCorrect=True
  765. $SUDO sed -i '0,/\(dhcp-option DNS \)/ s/\(dhcp-option DNS \).*/\1'${OVPNDNS1}'\"/' /etc/openvpn/server.conf
  766. if [ -z ${OVPNDNS2} ]; then
  767. $SUDO sed -i '/\(dhcp-option DNS \)/{n;N;d}' /etc/openvpn/server.conf
  768. else
  769. $SUDO sed -i '0,/\(dhcp-option DNS \)/! s/\(dhcp-option DNS \).*/\1'${OVPNDNS2}'\"/' /etc/openvpn/server.conf
  770. fi
  771. else
  772. # If the settings are wrong, the loop continues
  773. DNSSettingsCorrect=False
  774. fi
  775. fi
  776. done
  777. ;;
  778. esac
  779. else
  780. echo "::: Cancel selected. Exiting..."
  781. exit 1
  782. fi
  783. }
  784.  
  785. confOpenVPN() {
  786. # Generate a random, alphanumeric identifier of 16 characters for this server so that we can use verify-x509-name later that is unique for this server installation. Source: Earthgecko (https://gist.github.com/earthgecko/3089509)
  787. NEW_UUID=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 16 | head -n 1)
  788. SERVER_NAME="server_${NEW_UUID}"
  789.  
  790. if [[ ${useUpdateVars} == false ]]; then
  791. # Ask user for desired level of encryption
  792. ENCRYPT=$(whiptail --backtitle "Setup OpenVPN" --title "Encryption strength" --radiolist \
  793. "Choose your desired level of encryption (press space to select):\n This is an encryption key that will be generated on your system. The larger the key, 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 \
  794. "1024" "Use 1024-bit encryption (testing only)" OFF \
  795. "2048" "Use 2048-bit encryption (recommended level)" ON \
  796. "4096" "Use 4096-bit encryption (paranoid level)" OFF 3>&1 1>&2 2>&3)
  797.  
  798. exitstatus=$?
  799. if [ $exitstatus != 0 ]; then
  800. echo "::: Cancel selected. Exiting..."
  801. exit 1
  802. fi
  803. fi
  804.  
  805. # If easy-rsa exists, remove it
  806. if [[ -d /etc/openvpn/easy-rsa/ ]]; then
  807. $SUDO rm -rf /etc/openvpn/easy-rsa/
  808. fi
  809.  
  810. # Get the PiVPN easy-rsa
  811. wget -q -O - "${easyrsaRel}" | $SUDO tar xz -C /etc/openvpn && $SUDO mv /etc/openvpn/EasyRSA-${easyrsaVer} /etc/openvpn/easy-rsa
  812. # fix ownership
  813. $SUDO chown -R root:root /etc/openvpn/easy-rsa
  814. $SUDO mkdir /etc/openvpn/easy-rsa/pki
  815.  
  816. # Write out new vars file
  817. set +e
  818. IFS= read -d '' String <<"EOF"
  819. if [ -z "$EASYRSA_CALLER" ]; then
  820. echo "Nope." >&2
  821. return 1
  822. fi
  823. set_var EASYRSA "/etc/openvpn/easy-rsa"
  824. set_var EASYRSA_PKI "$EASYRSA/pki"
  825. set_var EASYRSA_KEY_SIZE 2048
  826. set_var EASYRSA_ALGO rsa
  827. set_var EASYRSA_CURVE secp384r1
  828. EOF
  829.  
  830. echo "${String}" | $SUDO tee /etc/openvpn/easy-rsa/vars >/dev/null
  831. set -e
  832.  
  833. # Edit the KEY_SIZE variable in the vars file to set user chosen key size
  834. cd /etc/openvpn/easy-rsa || exit
  835. $SUDO sed -i "s/\(KEY_SIZE\).*/\1 ${ENCRYPT}/" vars
  836.  
  837. # Remove any previous keys
  838. ${SUDOE} ./easyrsa --batch init-pki
  839.  
  840. # Build the certificate authority
  841. printf "::: Building CA...\n"
  842. ${SUDOE} ./easyrsa --batch build-ca nopass
  843. printf "\n::: CA Complete.\n"
  844.  
  845. if [[ ${useUpdateVars} == false ]]; then
  846. whiptail --msgbox --backtitle "Setup OpenVPN" --title "Server Information" "The server key, Diffie-Hellman key, and HMAC key will now be generated." ${r} ${c}
  847. fi
  848.  
  849. # Build the server
  850. ${SUDOE} ./easyrsa build-server-full ${SERVER_NAME} nopass
  851.  
  852. if [[ ${useUpdateVars} == false ]]; then
  853. 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 a pool of the last 128 generated.\nMore information about this service can be found here: https://2ton.com.au/dhtool/\n\nIf you're paranoid, choose 'No' and Diffie-Hellman parameters will be generated on your device." ${r} ${c})
  854. then
  855. DOWNLOAD_DH_PARAM=true
  856. else
  857. DOWNLOAD_DH_PARAM=false
  858. fi
  859. fi
  860.  
  861. if [ "$ENCRYPT" -ge "4096" ] && [[ ${DOWNLOAD_DH_PARAM} == true ]]
  862. then
  863. # Downloading parameters
  864. RANDOM_INDEX=$(( RANDOM % 128 ))
  865. ${SUDOE} curl "https://2ton.com.au/dhparam/${ENCRYPT}/${RANDOM_INDEX}" -o "/etc/openvpn/easy-rsa/pki/dh${ENCRYPT}.pem"
  866. else
  867. # Generate Diffie-Hellman key exchange
  868. ${SUDOE} ./easyrsa gen-dh
  869. ${SUDOE} mv pki/dh.pem pki/dh${ENCRYPT}.pem
  870. fi
  871.  
  872. # Generate static HMAC key to defend against DDoS
  873. ${SUDOE} openvpn --genkey --secret pki/ta.key
  874.  
  875. # Generate an empty Certificate Revocation List
  876. ${SUDOE} ./easyrsa gen-crl
  877. ${SUDOE} cp pki/crl.pem /etc/openvpn/crl.pem
  878. ${SUDOE} chown nobody:nogroup /etc/openvpn/crl.pem
  879.  
  880. # Write config file for server using the template .txt file
  881. $SUDO cp /etc/.pivpn/server_config.txt /etc/openvpn/server.conf
  882.  
  883. $SUDO sed -i "s/LOCALNET/${LOCALNET}/g" /etc/openvpn/server.conf
  884. $SUDO sed -i "s/LOCALMASK/${LOCALMASK}/g" /etc/openvpn/server.conf
  885.  
  886. # Set the user encryption key size
  887. $SUDO sed -i "s/\(dh \/etc\/openvpn\/easy-rsa\/pki\/dh\).*/\1${ENCRYPT}.pem/" /etc/openvpn/server.conf
  888.  
  889. # if they modified port put value in server.conf
  890. if [ $PORT != 1194 ]; then
  891. $SUDO sed -i "s/1194/${PORT}/g" /etc/openvpn/server.conf
  892. fi
  893.  
  894. # if they modified protocol put value in server.conf
  895. if [ "$PROTO" != "udp" ]; then
  896. $SUDO sed -i "s/proto udp/proto tcp/g" /etc/openvpn/server.conf
  897. fi
  898.  
  899. # write out server certs to conf file
  900. $SUDO sed -i "s/\(key \/etc\/openvpn\/easy-rsa\/pki\/private\/\).*/\1${SERVER_NAME}.key/" /etc/openvpn/server.conf
  901. $SUDO sed -i "s/\(cert \/etc\/openvpn\/easy-rsa\/pki\/issued\/\).*/\1${SERVER_NAME}.crt/" /etc/openvpn/server.conf
  902. }
  903.  
  904. confUnattendedUpgrades() {
  905. if [[ $UNATTUPG == "unattended-upgrades" ]]; then
  906. $SUDO apt-get --yes --quiet --no-install-recommends install "$UNATTUPG" > /dev/null & spinner $!
  907. if [[ $PLAT == "Ubuntu" ]]; then
  908. # Ubuntu 50unattended-upgrades should already just have security enabled
  909. # so we just need to configure the 10periodic file
  910. cat << EOT | $SUDO tee /etc/apt/apt.conf.d/10periodic >/dev/null
  911. APT::Periodic::Update-Package-Lists "1";
  912. APT::Periodic::Download-Upgradeable-Packages "1";
  913. APT::Periodic::AutocleanInterval "5";
  914. APT::Periodic::Unattended-Upgrade "1";
  915. EOT
  916. else
  917. $SUDO sed -i '/\(o=Raspbian,n=jessie\)/c\"o=Raspbian,n=jessie,l=Raspbian-Security";\' /etc/apt/apt.conf.d/50unattended-upgrades
  918. cat << EOT | $SUDO tee /etc/apt/apt.conf.d/02periodic >/dev/null
  919. APT::Periodic::Enable "1";
  920. APT::Periodic::Update-Package-Lists "1";
  921. APT::Periodic::Download-Upgradeable-Packages "1";
  922. APT::Periodic::Unattended-Upgrade "1";
  923. APT::Periodic::AutocleanInterval "7";
  924. APT::Periodic::Verbose "0";
  925. EOT
  926. fi
  927. fi
  928.  
  929. }
  930.  
  931. confNetwork() {
  932. # Enable forwarding of internet traffic
  933. $SUDO sed -i '/net.ipv4.ip_forward=1/s/^#//g' /etc/sysctl.conf
  934. $SUDO sysctl -p
  935.  
  936. # if ufw enabled, configure that
  937. if hash ufw 2>/dev/null; then
  938. if $SUDO ufw status | grep -q inactive
  939. then
  940. noUFW=1
  941. else
  942. echo "::: Detected UFW is enabled."
  943. echo "::: Adding UFW rules..."
  944. $SUDO cp /etc/.pivpn/ufw_add.txt /tmp/ufw_add.txt
  945. $SUDO sed -i 's/IPv4dev/'"$IPv4dev"'/' /tmp/ufw_add.txt
  946. $SUDO sed -i "s/\(DEFAULT_FORWARD_POLICY=\).*/\1\"ACCEPT\"/" /etc/default/ufw
  947. $SUDO sed -i -e '/delete these required/r /tmp/ufw_add.txt' -e//N /etc/ufw/before.rules
  948. $SUDO ufw allow "${PORT}/${PROTO}"
  949. $SUDO ufw allow from 10.8.0.0/24
  950. $SUDO ufw reload
  951. echo "::: UFW configuration completed."
  952. fi
  953. else
  954. noUFW=1
  955. fi
  956. # else configure iptables
  957. if [[ $noUFW -eq 1 ]]; then
  958. echo 1 > /tmp/noUFW
  959. $SUDO iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o "$IPv4dev" -j MASQUERADE
  960. case ${PLAT} in
  961. Ubuntu|Debian|Devuan)
  962. $SUDO iptables-save | $SUDO tee /etc/iptables/rules.v4 > /dev/null
  963. ;;
  964. *)
  965. $SUDO netfilter-persistent save
  966. ;;
  967. esac
  968. else
  969. echo 0 > /tmp/noUFW
  970. fi
  971.  
  972. $SUDO cp /tmp/noUFW /etc/pivpn/NO_UFW
  973. }
  974.  
  975. confOVPN() {
  976. if ! IPv4pub=$(dig +short myip.opendns.com @resolver1.opendns.com)
  977. then
  978. echo "dig failed, now trying to curl eth0.me"
  979. if ! IPv4pub=$(curl eth0.me)
  980. then
  981. echo "eth0.me failed, please check your internet connection/DNS"
  982. exit $?
  983. fi
  984. fi
  985. $SUDO cp /tmp/pivpnUSR /etc/pivpn/INSTALL_USER
  986. $SUDO cp /tmp/DET_PLATFORM /etc/pivpn/DET_PLATFORM
  987.  
  988. $SUDO cp /etc/.pivpn/Default.txt /etc/openvpn/easy-rsa/pki/Default.txt
  989.  
  990. if [[ ${useUpdateVars} == false ]]; then
  991. 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 \
  992. "$IPv4pub" "Use this public IP" "ON" \
  993. "DNS Entry" "Use a public DNS" "OFF" 3>&1 1>&2 2>&3)
  994.  
  995. exitstatus=$?
  996. if [ $exitstatus != 0 ]; then
  997. echo "::: Cancel selected. Exiting..."
  998. exit 1
  999. fi
  1000.  
  1001. if [ "$METH" == "$IPv4pub" ]; then
  1002. $SUDO sed -i 's/IPv4pub/'"$IPv4pub"'/' /etc/openvpn/easy-rsa/pki/Default.txt
  1003. else
  1004. until [[ $publicDNSCorrect = True ]]
  1005. do
  1006. PUBLICDNS=$(whiptail --title "PiVPN Setup" --inputbox "What is the public DNS name of this Server?" ${r} ${c} 3>&1 1>&2 2>&3)
  1007. exitstatus=$?
  1008. if [ $exitstatus != 0 ]; then
  1009. echo "::: Cancel selected. Exiting..."
  1010. exit 1
  1011. fi
  1012. if (whiptail --backtitle "Confirm DNS Name" --title "Confirm DNS Name" --yesno "Is this correct?\n\n Public DNS Name: $PUBLICDNS" ${r} ${c}) then
  1013. publicDNSCorrect=True
  1014. $SUDO sed -i 's/IPv4pub/'"$PUBLICDNS"'/' /etc/openvpn/easy-rsa/pki/Default.txt
  1015. else
  1016. publicDNSCorrect=False
  1017. fi
  1018. done
  1019. fi
  1020. else
  1021. $SUDO sed -i 's/IPv4pub/'"$PUBLICDNS"'/' /etc/openvpn/easy-rsa/pki/Default.txt
  1022. fi
  1023.  
  1024. # if they modified port put value in Default.txt for clients to use
  1025. if [ $PORT != 1194 ]; then
  1026. $SUDO sed -i -e "s/1194/${PORT}/g" /etc/openvpn/easy-rsa/pki/Default.txt
  1027. fi
  1028.  
  1029. # if they modified protocol put value in Default.txt for clients to use
  1030. if [ "$PROTO" != "udp" ]; then
  1031. $SUDO sed -i -e "s/proto udp/proto tcp/g" /etc/openvpn/easy-rsa/pki/Default.txt
  1032. fi
  1033.  
  1034. # verify server name to strengthen security
  1035. $SUDO sed -i "s/SRVRNAME/${SERVER_NAME}/" /etc/openvpn/easy-rsa/pki/Default.txt
  1036.  
  1037. if [ ! -d "/home/$pivpnUser/ovpns" ]; then
  1038. $SUDO mkdir "/home/$pivpnUser/ovpns"
  1039. fi
  1040. $SUDO chmod 0777 -R "/home/$pivpnUser/ovpns"
  1041. }
  1042.  
  1043. finalExports() {
  1044. # Update variables in setupVars.conf file
  1045. if [ -e "${setupVars}" ]; then
  1046. sed -i.update.bak '/pivpnUser/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}"
  1047. fi
  1048. {
  1049. echo "pivpnUser=${pivpnUser}"
  1050. echo "UNATTUPG=${UNATTUPG}"
  1051. echo "pivpnInterface=${pivpnInterface}"
  1052. echo "IPv4dns=${IPv4dns}"
  1053. echo "IPv4addr=${IPv4addr}"
  1054. echo "IPv4gw=${IPv4gw}"
  1055. echo "pivpnProto=${pivpnProto}"
  1056. echo "PORT=${PORT}"
  1057. echo "ENCRYPT=${ENCRYPT}"
  1058. echo "DOWNLOAD_DH_PARAM=${DOWNLOAD_DH_PARAM}"
  1059. echo "PUBLICDNS=${PUBLICDNS}"
  1060. echo "OVPNDNS1=${OVPNDNS1}"
  1061. echo "OVPNDNS2=${OVPNDNS2}"
  1062. }>> "${setupVars}"
  1063. }
  1064.  
  1065.  
  1066. # I suggest replacing some of these names.
  1067.  
  1068. #accountForRefactor() {
  1069. # # At some point in the future this list can be pruned, for now we'll need it to ensure updates don't break.
  1070. #
  1071. # # Refactoring of install script has changed the name of a couple of variables. Sort them out here.
  1072. # sed -i 's/pivpnUser/PIVPN_USER/g' ${setupVars}
  1073. # #sed -i 's/UNATTUPG/UNATTUPG/g' ${setupVars}
  1074. # sed -i 's/pivpnInterface/PIVPN_INTERFACE/g' ${setupVars}
  1075. # sed -i 's/IPv4dns/IPV4_DNS/g' ${setupVars}
  1076. # sed -i 's/IPv4addr/IPV4_ADDRESS/g' ${setupVars}
  1077. # sed -i 's/IPv4gw/IPV4_GATEWAY/g' ${setupVars}
  1078. # sed -i 's/pivpnProto/TRANSPORT_LAYER/g' ${setupVars}
  1079. # #sed -i 's/PORT/PORT/g' ${setupVars}
  1080. # #sed -i 's/ENCRYPT/ENCRYPT/g' ${setupVars}
  1081. # #sed -i 's/DOWNLOAD_DH_PARAM/DOWNLOAD_DH_PARAM/g' ${setupVars}
  1082. # sed -i 's/PUBLICDNS/PUBLIC_DNS/g' ${setupVars}
  1083. # sed -i 's/OVPNDNS1/OVPN_DNS_1/g' ${setupVars}
  1084. # sed -i 's/OVPNDNS2/OVPN_DNS_2/g' ${setupVars}
  1085. #}
  1086.  
  1087. installPiVPN() {
  1088. stopServices
  1089. $SUDO mkdir -p /etc/pivpn/
  1090. confUnattendedUpgrades
  1091. installScripts
  1092. setCustomProto
  1093. setCustomPort
  1094. confOpenVPN
  1095. confNetwork
  1096. confOVPN
  1097. setClientDNS
  1098. finalExports
  1099. }
  1100.  
  1101. updatePiVPN() {
  1102. #accountForRefactor
  1103. stopServices
  1104. confUnattendedUpgrades
  1105. installScripts
  1106.  
  1107. # setCustomProto
  1108. # write out the PROTO
  1109. PROTO=$pivpnProto
  1110. $SUDO cp /tmp/pivpnPROTO /etc/pivpn/INSTALL_PROTO
  1111.  
  1112. #setCustomPort
  1113. # write out the port
  1114. $SUDO cp /tmp/INSTALL_PORT /etc/pivpn/INSTALL_PORT
  1115.  
  1116. confOpenVPN
  1117. confNetwork
  1118. confOVPN
  1119.  
  1120. # ?? Is this always OK? Also if you only select one DNS server ??
  1121. $SUDO sed -i '0,/\(dhcp-option DNS \)/ s/\(dhcp-option DNS \).*/\1'${OVPNDNS1}'\"/' /etc/openvpn/server.conf
  1122. $SUDO sed -i '0,/\(dhcp-option DNS \)/! s/\(dhcp-option DNS \).*/\1'${OVPNDNS2}'\"/' /etc/openvpn/server.conf
  1123.  
  1124. finalExports #re-export setupVars.conf to account for any new vars added in new versions
  1125. }
  1126.  
  1127.  
  1128. displayFinalMessage() {
  1129. # Final completion message to user
  1130. whiptail --msgbox --backtitle "Make it so." --title "Installation Complete!" "Now run 'pivpn add' to create the ovpn profiles.
  1131. Run 'pivpn help' to see what else you can do!
  1132. The install log is in /etc/pivpn." ${r} ${c}
  1133. if (whiptail --title "Reboot" --yesno --defaultno "It is strongly recommended you reboot after installation. Would you like to reboot now?" ${r} ${c}); then
  1134. whiptail --title "Rebooting" --msgbox "The system will now reboot." ${r} ${c}
  1135. printf "\nRebooting system...\n"
  1136. $SUDO sleep 3
  1137. $SUDO shutdown -r now
  1138. fi
  1139. }
  1140.  
  1141. update_dialogs() {
  1142. # reconfigure
  1143. if [ "${reconfigure}" = true ]; then
  1144. opt1a="Repair"
  1145. opt1b="This will retain existing settings"
  1146. strAdd="You will remain on the same version"
  1147. else
  1148. opt1a="Update"
  1149. opt1b="This will retain existing settings."
  1150. strAdd="You will be updated to the latest version."
  1151. fi
  1152. opt2a="Reconfigure"
  1153. opt2b="This will allow you to enter new settings"
  1154.  
  1155. 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 \
  1156. "${opt1a}" "${opt1b}" \
  1157. "${opt2a}" "${opt2b}" 3>&2 2>&1 1>&3) || \
  1158. { echo "::: Cancel selected. Exiting"; exit 1; }
  1159.  
  1160. case ${UpdateCmd} in
  1161. ${opt1a})
  1162. echo "::: ${opt1a} option selected."
  1163. useUpdateVars=true
  1164. ;;
  1165. ${opt2a})
  1166. echo "::: ${opt2a} option selected"
  1167. useUpdateVars=false
  1168. ;;
  1169. esac
  1170. }
  1171.  
  1172. clone_or_update_repos() {
  1173. if [[ "${reconfigure}" == true ]]; then
  1174. echo "::: --reconfigure passed to install script. Not downloading/updating local repos"
  1175. else
  1176. # Get Git files
  1177. getGitFiles ${pivpnFilesDir} ${pivpnGitUrl} || \
  1178. { echo "!!! Unable to clone ${pivpnGitUrl} into ${pivpnFilesDir}, unable to continue."; \
  1179. exit 1; \
  1180. }
  1181. fi
  1182. }
  1183.  
  1184. ######## SCRIPT ############
  1185.  
  1186. main() {
  1187.  
  1188. ######## FIRST CHECK ########
  1189. # Must be root to install
  1190. echo ":::"
  1191. if [[ $EUID -eq 0 ]];then
  1192. echo "::: You are root."
  1193. else
  1194. echo "::: sudo will be used for the install."
  1195. # Check if it is actually installed
  1196. # If it isn't, exit because the install cannot complete
  1197. if [[ $(dpkg-query -s sudo) ]];then
  1198. export SUDO="sudo"
  1199. export SUDOE="sudo -E"
  1200. else
  1201. echo "::: Please install sudo or run this as root."
  1202. exit 1
  1203. fi
  1204. fi
  1205.  
  1206. # Check for supported distribution
  1207. distro_check
  1208.  
  1209. # Check arguments for the undocumented flags
  1210. for var in "$@"; do
  1211. case "$var" in
  1212. "--reconfigure" ) reconfigure=true;;
  1213. "--i_do_not_follow_recommendations" ) skipSpaceCheck=false;;
  1214. "--unattended" ) runUnattended=true;;
  1215. esac
  1216. done
  1217.  
  1218. if [[ -f ${setupVars} ]]; then
  1219. if [[ "${runUnattended}" == true ]]; then
  1220. echo "::: --unattended passed to install script, no whiptail dialogs will be displayed"
  1221. useUpdateVars=true
  1222. else
  1223. update_dialogs
  1224. fi
  1225. fi
  1226.  
  1227. # Start the installer
  1228. # Verify there is enough disk space for the install
  1229. if [[ "${skipSpaceCheck}" == true ]]; then
  1230. echo "::: --i_do_not_follow_recommendations passed to script, skipping free disk space verification!"
  1231. else
  1232. verifyFreeDiskSpace
  1233. fi
  1234.  
  1235. # Install the packages (we do this first because we need whiptail)
  1236. #checkForDependencies
  1237. update_package_cache
  1238.  
  1239. # Notify user of package availability
  1240. notify_package_updates_available
  1241.  
  1242. # Install packages used by this installation script
  1243. install_dependent_packages PIVPN_DEPS[@]
  1244.  
  1245. if [[ ${useUpdateVars} == false ]]; then
  1246. # Display welcome dialogs
  1247. welcomeDialogs
  1248.  
  1249. # Find interfaces and let the user choose one
  1250. chooseInterface
  1251.  
  1252. # Only try to set static on Raspbian, otherwise let user do it
  1253. if [[ $PLAT != "Raspbian" ]]; then
  1254. avoidStaticIPv4Ubuntu
  1255. else
  1256. getStaticIPv4Settings
  1257. setStaticIPv4
  1258. fi
  1259.  
  1260. # Set the Network IP and Mask correctly
  1261. setNetwork
  1262.  
  1263. # Choose the user for the ovpns
  1264. chooseUser
  1265.  
  1266. # Ask if unattended-upgrades will be enabled
  1267. unattendedUpgrades
  1268.  
  1269. # Clone/Update the repos
  1270. clone_or_update_repos
  1271.  
  1272. # Install and log everything to a file
  1273. installPiVPN | tee ${tmpLog}
  1274.  
  1275. echo "::: Install Complete..."
  1276. else
  1277. # Source ${setupVars} for use in the rest of the functions.
  1278. source ${setupVars}
  1279.  
  1280. echo "::: Using IP address: $IPv4addr"
  1281. echo "${IPv4addr%/*}" > /tmp/pivpnIP
  1282. echo "::: Using interface: $pivpnInterface"
  1283. echo "${pivpnInterface}" > /tmp/pivpnINT
  1284. echo "::: Using User: $pivpnUser"
  1285. echo "${pivpnUser}" > /tmp/pivpnUSR
  1286. echo "::: Using protocol: $pivpnProto"
  1287. echo "${pivpnProto}" > /tmp/pivpnPROTO
  1288. echo "::: Using port: $PORT"
  1289. echo ${PORT} > /tmp/INSTALL_PORT
  1290. echo ":::"
  1291.  
  1292. # Only try to set static on Raspbian
  1293. case ${PLAT} in
  1294. Rasp*)
  1295. 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
  1296. ;;
  1297. *)
  1298. echo "::: IP Information"
  1299. echo "::: Since we think you are not using Raspbian, we will not configure a static IP for you."
  1300. echo "::: If you are in Amazon then you can not configure a static IP anyway."
  1301. echo "::: Just ensure before this installer started you had set an elastic IP on your instance."
  1302. ;;
  1303. esac
  1304.  
  1305. # Clone/Update the repos
  1306. clone_or_update_repos
  1307.  
  1308.  
  1309. updatePiVPN | tee ${tmpLog}
  1310. fi
  1311.  
  1312. #Move the install log into /etc/pivpn for storage
  1313. $SUDO mv ${tmpLog} ${instalLogLoc}
  1314.  
  1315. echo "::: Restarting services..."
  1316. # Start services
  1317. case ${PLAT} in
  1318. Ubuntu|Debian|*vuan)
  1319. $SUDO service openvpn start
  1320. ;;
  1321. *)
  1322. $SUDO systemctl enable openvpn.service
  1323. $SUDO systemctl start openvpn.service
  1324. ;;
  1325. esac
  1326.  
  1327. echo "::: done."
  1328.  
  1329. if [[ "${useUpdateVars}" == false ]]; then
  1330. displayFinalMessage
  1331. fi
  1332.  
  1333. echo ":::"
  1334. if [[ "${useUpdateVars}" == false ]]; then
  1335. echo "::: Installation Complete!"
  1336. echo "::: Now run 'pivpn add' to create an ovpn profile for each of your devices."
  1337. echo "::: Run 'pivpn help' to see what else you can do!"
  1338. echo "::: It is strongly recommended you reboot after installation."
  1339. else
  1340. echo "::: Update complete!"
  1341. fi
  1342.  
  1343. echo ":::"
  1344. echo "::: The install log is located at: ${instalLogLoc}"
  1345. }
  1346.  
  1347. if [[ "${PIVPN_TEST}" != true ]] ; then
  1348. main "$@"
  1349. fi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement