Advertisement
Guest User

Untitled

a guest
Nov 4th, 2017
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 52.78 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.  
  356. setNetwork() {
  357. # Sets the Network IP and Mask correctly
  358. export PATH=${PATH}:/sbin:/usr/sbin
  359. LOCALMASK=$(ifconfig "${pivpnInterface}" | awk '/Mask:/{ print $4;} ' | cut -c6-)
  360. LOCALIP=$(ifconfig "${pivpnInterface}" | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*')
  361. IFS=. read -r i1 i2 i3 i4 <<< "$LOCALIP"
  362. IFS=. read -r m1 m2 m3 m4 <<< "$LOCALMASK"
  363. LOCALNET=$(printf "%d.%d.%d.%d\n" "$((i1 & m1))" "$((i2 & m2))" "$((i3 & m3))" "$((i4 & m4))")
  364. }
  365.  
  366. function valid_ip()
  367. {
  368. local ip=$1
  369. local stat=1
  370.  
  371. if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
  372. OIFS=$IFS
  373. IFS='.'
  374. ip=($ip)
  375. IFS=$OIFS
  376. [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
  377. && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
  378. stat=$?
  379. fi
  380. return $stat
  381. }
  382.  
  383. installScripts() {
  384. # Install the scripts from /etc/.pivpn to their various locations
  385. $SUDO echo ":::"
  386. $SUDO echo -n "::: Installing scripts to /opt/pivpn..."
  387. if [ ! -d /opt/pivpn ]; then
  388. $SUDO mkdir /opt/pivpn
  389. $SUDO chown "$pivpnUser":root /opt/pivpn
  390. $SUDO chmod u+srwx /opt/pivpn
  391. fi
  392. $SUDO cp /etc/.pivpn/scripts/makeOVPN.sh /opt/pivpn/makeOVPN.sh
  393. $SUDO cp /etc/.pivpn/scripts/clientStat.sh /opt/pivpn/clientStat.sh
  394. $SUDO cp /etc/.pivpn/scripts/listOVPN.sh /opt/pivpn/listOVPN.sh
  395. $SUDO cp /etc/.pivpn/scripts/removeOVPN.sh /opt/pivpn/removeOVPN.sh
  396. $SUDO cp /etc/.pivpn/scripts/uninstall.sh /opt/pivpn/uninstall.sh
  397. $SUDO cp /etc/.pivpn/scripts/pivpnDebug.sh /opt/pivpn/pivpnDebug.sh
  398. $SUDO cp /etc/.pivpn/scripts/fix_iptables.sh /opt/pivpn/fix_iptables.sh
  399. $SUDO chmod 0755 /opt/pivpn/{makeOVPN,clientStat,listOVPN,removeOVPN,uninstall,pivpnDebug,fix_iptables}.sh
  400. $SUDO cp /etc/.pivpn/pivpn /usr/local/bin/pivpn
  401. $SUDO chmod 0755 /usr/local/bin/pivpn
  402. $SUDO cp /etc/.pivpn/scripts/bash-completion /etc/bash_completion.d/pivpn
  403. . /etc/bash_completion.d/pivpn
  404. # Copy interface setting for debug
  405. $SUDO cp /tmp/pivpnINT /etc/pivpn/pivpnINTERFACE
  406.  
  407. $SUDO echo " done."
  408. }
  409.  
  410. package_check_install() {
  411. dpkg-query -W -f='${Status}' "${1}" 2>/dev/null | grep -c "ok installed" || ${PKG_INSTALL} "${1}"
  412. }
  413.  
  414. update_package_cache() {
  415. #Running apt-get update/upgrade with minimal output can cause some issues with
  416. #requiring user input
  417.  
  418. #Check to see if apt-get update has already been run today
  419. #it needs to have been run at least once on new installs!
  420. timestamp=$(stat -c %Y ${PKG_CACHE})
  421. timestampAsDate=$(date -d @"${timestamp}" "+%b %e")
  422. today=$(date "+%b %e")
  423.  
  424.  
  425. if [ ! "${today}" == "${timestampAsDate}" ]; then
  426. #update package lists
  427. echo ":::"
  428. echo -n "::: ${PKG_MANAGER} update has not been run today. Running now..."
  429. $SUDO ${UPDATE_PKG_CACHE} &> /dev/null
  430. echo " done!"
  431. fi
  432. }
  433.  
  434. notify_package_updates_available() {
  435. # Let user know if they have outdated packages on their system and
  436. # advise them to run a package update at soonest possible.
  437. echo ":::"
  438. echo -n "::: Checking ${PKG_MANAGER} for upgraded packages...."
  439. updatesToInstall=$(eval "${PKG_COUNT}")
  440. echo " done!"
  441. echo ":::"
  442. if [[ ${updatesToInstall} -eq "0" ]]; then
  443. echo "::: Your system is up to date! Continuing with PiVPN installation..."
  444. else
  445. echo "::: There are ${updatesToInstall} updates available for your system!"
  446. echo "::: We recommend you update your OS after installing PiVPN! "
  447. echo ":::"
  448. fi
  449. }
  450.  
  451. install_dependent_packages() {
  452. # Install packages passed in via argument array
  453. # No spinner - conflicts with set -e
  454. declare -a argArray1=("${!1}")
  455.  
  456. echo iptables-persistent iptables-persistent/autosave_v4 boolean true | $SUDO debconf-set-selections
  457. echo iptables-persistent iptables-persistent/autosave_v6 boolean false | $SUDO debconf-set-selections
  458.  
  459. if command -v debconf-apt-progress &> /dev/null; then
  460. $SUDO debconf-apt-progress -- ${PKG_INSTALL} "${argArray1[@]}"
  461. else
  462. for i in "${argArray1[@]}"; do
  463. echo -n "::: Checking for $i..."
  464. $SUDO package_check_install "${i}" &> /dev/null
  465. echo " installed!"
  466. done
  467. fi
  468. }
  469.  
  470. unattendedUpgrades() {
  471. 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}
  472.  
  473. 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
  474. UNATTUPG="unattended-upgrades"
  475. else
  476. UNATTUPG=""
  477. fi
  478. }
  479.  
  480. stopServices() {
  481. # Stop openvpn
  482. $SUDO echo ":::"
  483. $SUDO echo -n "::: Stopping OpenVPN service..."
  484. case ${PLAT} in
  485. Ubuntu|Debian|*vuan)
  486. $SUDO service openvpn stop || true
  487. ;;
  488. *)
  489. $SUDO systemctl stop openvpn.service || true
  490. ;;
  491. esac
  492. $SUDO echo " done."
  493. }
  494.  
  495. checkForDependencies() {
  496. #Running apt-get update/upgrade with minimal output can cause some issues with
  497. #requiring user input (e.g password for phpmyadmin see #218)
  498. #We'll change the logic up here, to check to see if there are any updates available and
  499. # if so, advise the user to run apt-get update/upgrade at their own discretion
  500. #Check to see if apt-get update has already been run today
  501. # it needs to have been run at least once on new installs!
  502.  
  503. timestamp=$(stat -c %Y /var/cache/apt/)
  504. timestampAsDate=$(date -d @"$timestamp" "+%b %e")
  505. today=$(date "+%b %e")
  506.  
  507. case ${PLAT} in
  508. Ubuntu|Debian|Devuan)
  509. case ${OSCN} in
  510. trusty|jessie|wheezy|stretch)
  511. wget -O - https://swupdate.openvpn.net/repos/repo-public.gpg| $SUDO apt-key add -
  512. echo "deb http://swupdate.openvpn.net/apt $OSCN main" | $SUDO tee /etc/apt/sources.list.d/swupdate.openvpn.net.list > /dev/null
  513. echo -n "::: Adding OpenVPN repo for $PLAT $OSCN ..."
  514. $SUDO apt-get -qq update & spinner $!
  515. echo " done!"
  516. ;;
  517. esac
  518. ;;
  519. esac
  520. if [[ $PLAT == "Ubuntu" || $PLAT == "Debian" ]]; then
  521. if [[ $OSCN == "trusty" || $OSCN == "jessie" || $OSCN == "wheezy" || $OSCN == "stretch" ]]; then
  522. wget -O - https://swupdate.openvpn.net/repos/repo-public.gpg| $SUDO apt-key add -
  523. echo "deb http://build.openvpn.net/debian/openvpn/stable $OSCN main" | $SUDO tee /etc/apt/sources.list.d/swupdate.openvpn.net.list > /dev/null
  524. echo -n "::: Adding OpenVPN repo for $PLAT $OSCN ..."
  525. $SUDO apt-get -qq update & spinner $!
  526. echo " done!"
  527. fi
  528. fi
  529.  
  530. if [ ! "$today" == "$timestampAsDate" ]; then
  531. #update package lists
  532. echo ":::"
  533. echo -n "::: apt-get update has not been run today. Running now..."
  534. $SUDO apt-get -qq update & spinner $!
  535. echo " done!"
  536. fi
  537. echo ":::"
  538. echo -n "::: Checking apt-get for upgraded packages...."
  539. updatesToInstall=$($SUDO apt-get -s -o Debug::NoLocking=true upgrade | grep -c ^Inst)
  540. echo " done!"
  541. echo ":::"
  542. if [[ $updatesToInstall -eq "0" ]]; then
  543. echo "::: Your pi is up to date! Continuing with PiVPN installation..."
  544. else
  545. echo "::: There are $updatesToInstall updates availible for your pi!"
  546. echo "::: We recommend you run 'sudo apt-get upgrade' after installing PiVPN! "
  547. echo ":::"
  548. fi
  549. echo ":::"
  550. echo "::: Checking dependencies:"
  551.  
  552. dependencies=( openvpn git dhcpcd5 tar wget grep iptables-persistent dnsutils expect whiptail net-tools)
  553. for i in "${dependencies[@]}"; do
  554. echo -n "::: Checking for $i..."
  555. if [ "$(dpkg-query -W -f='${Status}' "$i" 2>/dev/null | grep -c "ok installed")" -eq 0 ]; then
  556. echo -n " Not found! Installing...."
  557. #Supply answers to the questions so we don't prompt user
  558. if [[ $i = "iptables-persistent" ]]; then
  559. echo iptables-persistent iptables-persistent/autosave_v4 boolean true | $SUDO debconf-set-selections
  560. echo iptables-persistent iptables-persistent/autosave_v6 boolean false | $SUDO debconf-set-selections
  561. fi
  562. if [[ $i == "expect" ]] || [[ $i == "openvpn" ]]; then
  563. ($SUDO apt-get --yes --quiet --no-install-recommends install "$i" > /dev/null || echo "Installation Failed!" && fixApt) & spinner $!
  564. else
  565. ($SUDO apt-get --yes --quiet install "$i" > /dev/null || echo "Installation Failed!" && fixApt) & spinner $!
  566. fi
  567. echo " done!"
  568. else
  569. echo " already installed!"
  570. fi
  571. done
  572. }
  573.  
  574. getGitFiles() {
  575. # Setup git repos for base files
  576. echo ":::"
  577. echo "::: Checking for existing base files..."
  578. if is_repo "${1}"; then
  579. update_repo "${1}"
  580. else
  581. make_repo "${1}" "${2}"
  582. fi
  583. }
  584.  
  585. is_repo() {
  586. # If the directory does not have a .git folder it is not a repo
  587. echo -n "::: Checking $1 is a repo..."
  588. cd "${1}" &> /dev/null || return 1
  589. $SUDO git status &> /dev/null && echo " OK!"; return 0 || echo " not found!"; return 1
  590. }
  591.  
  592. make_repo() {
  593. # Remove the non-repos interface and clone the interface
  594. echo -n "::: Cloning $2 into $1..."
  595. $SUDO rm -rf "${1}"
  596. $SUDO git clone -q "${2}" "${1}" > /dev/null & spinner $!
  597. if [ -z "${TESTING+x}" ]; then
  598. :
  599. else
  600. $SUDO git -C "${1}" checkout test
  601. fi
  602. echo " done!"
  603. }
  604.  
  605. update_repo() {
  606. if [[ "${reconfigure}" == true ]]; then
  607. echo "::: --reconfigure passed to install script. Not downloading/updating local repos"
  608. else
  609. # Pull the latest commits
  610. echo -n "::: Updating repo in $1..."
  611. cd "${1}" || exit 1
  612. $SUDO git stash -q > /dev/null & spinner $!
  613. $SUDO git pull -q > /dev/null & spinner $!
  614. if [ -z "${TESTING+x}" ]; then
  615. :
  616. else
  617. ${SUDOE} git checkout test
  618. fi
  619. echo " done!"
  620. fi
  621. }
  622.  
  623. setCustomProto() {
  624. # Set the available protocols into an array so it can be used with a whiptail dialog
  625. if protocol=$(whiptail --title "Protocol" --radiolist \
  626. "Choose a protocol (press space to select). Please only choose TCP if you know why you need TCP." ${r} ${c} 2 \
  627. "UDP" "" ON \
  628. "TCP" "" OFF 3>&1 1>&2 2>&3)
  629. then
  630. # Convert option into lowercase (UDP->udp)
  631. pivpnProto="${protocol,,}"
  632. echo "::: Using protocol: $pivpnProto"
  633. echo "${pivpnProto}" > /tmp/pivpnPROTO
  634. else
  635. echo "::: Cancel selected, exiting...."
  636. exit 1
  637. fi
  638. # write out the PROTO
  639. PROTO=$pivpnProto
  640. $SUDO cp /tmp/pivpnPROTO /etc/pivpn/INSTALL_PROTO
  641. }
  642.  
  643.  
  644. setCustomPort() {
  645. until [[ $PORTNumCorrect = True ]]
  646. do
  647. portInvalid="Invalid"
  648.  
  649. PROTO=$(cat /etc/pivpn/INSTALL_PROTO)
  650. if [ "$PROTO" = "udp" ]; then
  651. DEFAULT_PORT=1194
  652. else
  653. DEFAULT_PORT=443
  654. fi
  655. 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)
  656. then
  657. if [[ "$PORT" =~ ^[0-9]+$ ]] && [ "$PORT" -ge 1 ] && [ "$PORT" -le 65535 ]; then
  658. :
  659. else
  660. PORT=$portInvalid
  661. fi
  662. else
  663. echo "::: Cancel selected, exiting...."
  664. exit 1
  665. fi
  666.  
  667. if [[ $PORT == "$portInvalid" ]]; then
  668. 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}
  669. PORTNumCorrect=False
  670. else
  671. if (whiptail --backtitle "Specify Custom Port" --title "Confirm Custom Port Number" --yesno "Are these settings correct?\n PORT: $PORT" ${r} ${c}) then
  672. PORTNumCorrect=True
  673. else
  674. # If the settings are wrong, the loop continues
  675. PORTNumCorrect=False
  676. fi
  677. fi
  678. done
  679. # write out the port
  680. echo ${PORT} > /tmp/INSTALL_PORT
  681. $SUDO cp /tmp/INSTALL_PORT /etc/pivpn/INSTALL_PORT
  682. }
  683.  
  684. setClientDNS() {
  685. 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)
  686. DNSChooseOptions=(Google "" on
  687. OpenDNS "" off
  688. Level3 "" off
  689. DNS.WATCH "" off
  690. Norton "" off
  691. Custom "" off)
  692.  
  693. if DNSchoices=$("${DNSChoseCmd[@]}" "${DNSChooseOptions[@]}" 2>&1 >/dev/tty)
  694. then
  695. case ${DNSchoices} in
  696. Google)
  697. echo "::: Using Google DNS servers."
  698. OVPNDNS1="8.8.8.8"
  699. OVPNDNS2="8.8.4.4"
  700. # These are already in the file
  701. ;;
  702. OpenDNS)
  703. echo "::: Using OpenDNS servers."
  704. OVPNDNS1="208.67.222.222"
  705. OVPNDNS2="208.67.220.220"
  706. $SUDO sed -i '0,/\(dhcp-option DNS \)/ s/\(dhcp-option DNS \).*/\1'${OVPNDNS1}'\"/' /etc/openvpn/server.conf
  707. $SUDO sed -i '0,/\(dhcp-option DNS \)/! s/\(dhcp-option DNS \).*/\1'${OVPNDNS2}'\"/' /etc/openvpn/server.conf
  708. ;;
  709. Level3)
  710. echo "::: Using Level3 servers."
  711. OVPNDNS1="209.244.0.3"
  712. OVPNDNS2="209.244.0.4"
  713. $SUDO sed -i '0,/\(dhcp-option DNS \)/ s/\(dhcp-option DNS \).*/\1'${OVPNDNS1}'\"/' /etc/openvpn/server.conf
  714. $SUDO sed -i '0,/\(dhcp-option DNS \)/! s/\(dhcp-option DNS \).*/\1'${OVPNDNS2}'\"/' /etc/openvpn/server.conf
  715. ;;
  716. DNS.WATCH)
  717. echo "::: Using DNS.WATCH servers."
  718. OVPNDNS1="84.200.69.80"
  719. OVPNDNS2="84.200.70.40"
  720. $SUDO sed -i '0,/\(dhcp-option DNS \)/ s/\(dhcp-option DNS \).*/\1'${OVPNDNS1}'\"/' /etc/openvpn/server.conf
  721. $SUDO sed -i '0,/\(dhcp-option DNS \)/! s/\(dhcp-option DNS \).*/\1'${OVPNDNS2}'\"/' /etc/openvpn/server.conf
  722. ;;
  723. Norton)
  724. echo "::: Using Norton ConnectSafe servers."
  725. OVPNDNS1="199.85.126.10"
  726. OVPNDNS2="199.85.127.10"
  727. $SUDO sed -i '0,/\(dhcp-option DNS \)/ s/\(dhcp-option DNS \).*/\1'${OVPNDNS1}'\"/' /etc/openvpn/server.conf
  728. $SUDO sed -i '0,/\(dhcp-option DNS \)/! s/\(dhcp-option DNS \).*/\1'${OVPNDNS2}'\"/' /etc/openvpn/server.conf
  729. ;;
  730. Custom)
  731. until [[ $DNSSettingsCorrect = True ]]
  732. do
  733. strInvalid="Invalid"
  734.  
  735. 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)
  736. then
  737. OVPNDNS1=$(echo "$OVPNDNS" | sed 's/[, \t]\+/,/g' | awk -F, '{print$1}')
  738. OVPNDNS2=$(echo "$OVPNDNS" | sed 's/[, \t]\+/,/g' | awk -F, '{print$2}')
  739. if ! valid_ip "$OVPNDNS1" || [ ! "$OVPNDNS1" ]; then
  740. OVPNDNS1=$strInvalid
  741. fi
  742. if ! valid_ip "$OVPNDNS2" && [ "$OVPNDNS2" ]; then
  743. OVPNDNS2=$strInvalid
  744. fi
  745. else
  746. echo "::: Cancel selected, exiting...."
  747. exit 1
  748. fi
  749. if [[ $OVPNDNS1 == "$strInvalid" ]] || [[ $OVPNDNS2 == "$strInvalid" ]]; then
  750. 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}
  751. if [[ $OVPNDNS1 == "$strInvalid" ]]; then
  752. OVPNDNS1=""
  753. fi
  754. if [[ $OVPNDNS2 == "$strInvalid" ]]; then
  755. OVPNDNS2=""
  756. fi
  757. DNSSettingsCorrect=False
  758. else
  759. 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
  760. DNSSettingsCorrect=True
  761. $SUDO sed -i '0,/\(dhcp-option DNS \)/ s/\(dhcp-option DNS \).*/\1'${OVPNDNS1}'\"/' /etc/openvpn/server.conf
  762. if [ -z ${OVPNDNS2} ]; then
  763. $SUDO sed -i '/\(dhcp-option DNS \)/{n;N;d}' /etc/openvpn/server.conf
  764. else
  765. $SUDO sed -i '0,/\(dhcp-option DNS \)/! s/\(dhcp-option DNS \).*/\1'${OVPNDNS2}'\"/' /etc/openvpn/server.conf
  766. fi
  767. else
  768. # If the settings are wrong, the loop continues
  769. DNSSettingsCorrect=False
  770. fi
  771. fi
  772. done
  773. ;;
  774. esac
  775. else
  776. echo "::: Cancel selected. Exiting..."
  777. exit 1
  778. fi
  779. }
  780.  
  781. confOpenVPN() {
  782. # 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)
  783. NEW_UUID=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 16 | head -n 1)
  784. SERVER_NAME="server_${NEW_UUID}"
  785.  
  786. if [[ ${useUpdateVars} == false ]]; then
  787. # Ask user for desired level of encryption
  788. ENCRYPT=$(whiptail --backtitle "Setup OpenVPN" --title "Encryption strength" --radiolist \
  789. "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 \
  790. "1024" "Use 1024-bit encryption (testing only)" OFF \
  791. "2048" "Use 2048-bit encryption (recommended level)" ON \
  792. "4096" "Use 4096-bit encryption (paranoid level)" OFF 3>&1 1>&2 2>&3)
  793.  
  794. exitstatus=$?
  795. if [ $exitstatus != 0 ]; then
  796. echo "::: Cancel selected. Exiting..."
  797. exit 1
  798. fi
  799. fi
  800.  
  801. # If easy-rsa exists, remove it
  802. if [[ -d /etc/openvpn/easy-rsa/ ]]; then
  803. $SUDO rm -rf /etc/openvpn/easy-rsa/
  804. fi
  805.  
  806. # Get the PiVPN easy-rsa
  807. wget -q -O - "${easyrsaRel}" | $SUDO tar xz -C /etc/openvpn && $SUDO mv /etc/openvpn/EasyRSA-${easyrsaVer} /etc/openvpn/easy-rsa
  808. # fix ownership
  809. $SUDO chown -R root:root /etc/openvpn/easy-rsa
  810. $SUDO mkdir /etc/openvpn/easy-rsa/pki
  811.  
  812. # Write out new vars file
  813. set +e
  814. IFS= read -d '' String <<"EOF"
  815. if [ -z "$EASYRSA_CALLER" ]; then
  816. echo "Nope." >&2
  817. return 1
  818. fi
  819. set_var EASYRSA "/etc/openvpn/easy-rsa"
  820. set_var EASYRSA_PKI "$EASYRSA/pki"
  821. set_var EASYRSA_KEY_SIZE 2048
  822. set_var EASYRSA_ALGO rsa
  823. set_var EASYRSA_CURVE secp384r1
  824. EOF
  825.  
  826. echo "${String}" | $SUDO tee /etc/openvpn/easy-rsa/vars >/dev/null
  827. set -e
  828.  
  829. # Edit the KEY_SIZE variable in the vars file to set user chosen key size
  830. cd /etc/openvpn/easy-rsa || exit
  831. $SUDO sed -i "s/\(KEY_SIZE\).*/\1 ${ENCRYPT}/" vars
  832.  
  833. # Remove any previous keys
  834. ${SUDOE} ./easyrsa --batch init-pki
  835.  
  836. # Build the certificate authority
  837. printf "::: Building CA...\n"
  838. ${SUDOE} ./easyrsa --batch build-ca nopass
  839. printf "\n::: CA Complete.\n"
  840.  
  841. if [[ ${useUpdateVars} == false ]]; then
  842. whiptail --msgbox --backtitle "Setup OpenVPN" --title "Server Information" "The server key, Diffie-Hellman key, and HMAC key will now be generated." ${r} ${c}
  843. fi
  844.  
  845. # Build the server
  846. ${SUDOE} ./easyrsa build-server-full ${SERVER_NAME} nopass
  847.  
  848. if [[ ${useUpdateVars} == false ]]; then
  849. 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})
  850. then
  851. DOWNLOAD_DH_PARAM=true
  852. else
  853. DOWNLOAD_DH_PARAM=false
  854. fi
  855. fi
  856.  
  857. if [ "$ENCRYPT" -ge "4096" ] && [[ ${DOWNLOAD_DH_PARAM} == true ]]
  858. then
  859. # Downloading parameters
  860. RANDOM_INDEX=$(( RANDOM % 128 ))
  861. ${SUDOE} curl "https://2ton.com.au/dhparam/${ENCRYPT}/${RANDOM_INDEX}" -o "/etc/openvpn/easy-rsa/pki/dh${ENCRYPT}.pem"
  862. else
  863. # Generate Diffie-Hellman key exchange
  864. ${SUDOE} ./easyrsa gen-dh
  865. ${SUDOE} mv pki/dh.pem pki/dh${ENCRYPT}.pem
  866. fi
  867.  
  868. # Generate static HMAC key to defend against DDoS
  869. ${SUDOE} openvpn --genkey --secret pki/ta.key
  870.  
  871. # Generate an empty Certificate Revocation List
  872. ${SUDOE} ./easyrsa gen-crl
  873. ${SUDOE} cp pki/crl.pem /etc/openvpn/crl.pem
  874. ${SUDOE} chown nobody:nogroup /etc/openvpn/crl.pem
  875.  
  876. # Write config file for server using the template .txt file
  877. $SUDO cp /etc/.pivpn/server_config.txt /etc/openvpn/server.conf
  878.  
  879. $SUDO sed -i "s/LOCALNET/${LOCALNET}/g" /etc/openvpn/server.conf
  880. $SUDO sed -i "s/LOCALMASK/${LOCALMASK}/g" /etc/openvpn/server.conf
  881.  
  882. # Set the user encryption key size
  883. $SUDO sed -i "s/\(dh \/etc\/openvpn\/easy-rsa\/pki\/dh\).*/\1${ENCRYPT}.pem/" /etc/openvpn/server.conf
  884.  
  885. # if they modified port put value in server.conf
  886. if [ $PORT != 1194 ]; then
  887. $SUDO sed -i "s/1194/${PORT}/g" /etc/openvpn/server.conf
  888. fi
  889.  
  890. # if they modified protocol put value in server.conf
  891. if [ "$PROTO" != "udp" ]; then
  892. $SUDO sed -i "s/proto udp/proto tcp/g" /etc/openvpn/server.conf
  893. fi
  894.  
  895. # write out server certs to conf file
  896. $SUDO sed -i "s/\(key \/etc\/openvpn\/easy-rsa\/pki\/private\/\).*/\1${SERVER_NAME}.key/" /etc/openvpn/server.conf
  897. $SUDO sed -i "s/\(cert \/etc\/openvpn\/easy-rsa\/pki\/issued\/\).*/\1${SERVER_NAME}.crt/" /etc/openvpn/server.conf
  898. }
  899.  
  900. confUnattendedUpgrades() {
  901. if [[ $UNATTUPG == "unattended-upgrades" ]]; then
  902. $SUDO apt-get --yes --quiet --no-install-recommends install "$UNATTUPG" > /dev/null & spinner $!
  903. if [[ $PLAT == "Ubuntu" ]]; then
  904. # Ubuntu 50unattended-upgrades should already just have security enabled
  905. # so we just need to configure the 10periodic file
  906. cat << EOT | $SUDO tee /etc/apt/apt.conf.d/10periodic >/dev/null
  907. APT::Periodic::Update-Package-Lists "1";
  908. APT::Periodic::Download-Upgradeable-Packages "1";
  909. APT::Periodic::AutocleanInterval "5";
  910. APT::Periodic::Unattended-Upgrade "1";
  911. EOT
  912. else
  913. $SUDO sed -i '/\(o=Raspbian,n=jessie\)/c\"o=Raspbian,n=jessie,l=Raspbian-Security";\' /etc/apt/apt.conf.d/50unattended-upgrades
  914. cat << EOT | $SUDO tee /etc/apt/apt.conf.d/02periodic >/dev/null
  915. APT::Periodic::Enable "1";
  916. APT::Periodic::Update-Package-Lists "1";
  917. APT::Periodic::Download-Upgradeable-Packages "1";
  918. APT::Periodic::Unattended-Upgrade "1";
  919. APT::Periodic::AutocleanInterval "7";
  920. APT::Periodic::Verbose "0";
  921. EOT
  922. fi
  923. fi
  924.  
  925. }
  926.  
  927. confNetwork() {
  928. # Enable forwarding of internet traffic
  929. $SUDO sed -i '/net.ipv4.ip_forward=1/s/^#//g' /etc/sysctl.conf
  930. $SUDO sysctl -p
  931.  
  932. # if ufw enabled, configure that
  933. if hash ufw 2>/dev/null; then
  934. if $SUDO ufw status | grep -q inactive
  935. then
  936. noUFW=1
  937. else
  938. echo "::: Detected UFW is enabled."
  939. echo "::: Adding UFW rules..."
  940. $SUDO cp /etc/.pivpn/ufw_add.txt /tmp/ufw_add.txt
  941. $SUDO sed -i 's/IPv4dev/'"$IPv4dev"'/' /tmp/ufw_add.txt
  942. $SUDO sed -i "s/\(DEFAULT_FORWARD_POLICY=\).*/\1\"ACCEPT\"/" /etc/default/ufw
  943. $SUDO sed -i -e '/delete these required/r /tmp/ufw_add.txt' -e//N /etc/ufw/before.rules
  944. $SUDO ufw allow "${PORT}/${PROTO}"
  945. $SUDO ufw allow from 10.8.0.0/24
  946. $SUDO ufw reload
  947. echo "::: UFW configuration completed."
  948. fi
  949. else
  950. noUFW=1
  951. fi
  952. # else configure iptables
  953. if [[ $noUFW -eq 1 ]]; then
  954. echo 1 > /tmp/noUFW
  955. $SUDO iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o "$IPv4dev" -j MASQUERADE
  956. case ${PLAT} in
  957. Ubuntu|Debian|Devuan)
  958. $SUDO iptables-save | $SUDO tee /etc/iptables/rules.v4 > /dev/null
  959. ;;
  960. *)
  961. $SUDO netfilter-persistent save
  962. ;;
  963. esac
  964. else
  965. echo 0 > /tmp/noUFW
  966. fi
  967.  
  968. $SUDO cp /tmp/noUFW /etc/pivpn/NO_UFW
  969. }
  970.  
  971. confOVPN() {
  972. if ! IPv4pub=$(dig +short myip.opendns.com @resolver1.opendns.com)
  973. then
  974. echo "dig failed, now trying to curl eth0.me"
  975. if ! IPv4pub=$(curl eth0.me)
  976. then
  977. echo "eth0.me failed, please check your internet connection/DNS"
  978. exit $?
  979. fi
  980. fi
  981. $SUDO cp /tmp/pivpnUSR /etc/pivpn/INSTALL_USER
  982. $SUDO cp /tmp/DET_PLATFORM /etc/pivpn/DET_PLATFORM
  983.  
  984. $SUDO cp /etc/.pivpn/Default.txt /etc/openvpn/easy-rsa/pki/Default.txt
  985.  
  986. if [[ ${useUpdateVars} == false ]]; then
  987. 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 \
  988. "$IPv4pub" "Use this public IP" "ON" \
  989. "DNS Entry" "Use a public DNS" "OFF" 3>&1 1>&2 2>&3)
  990.  
  991. exitstatus=$?
  992. if [ $exitstatus != 0 ]; then
  993. echo "::: Cancel selected. Exiting..."
  994. exit 1
  995. fi
  996.  
  997. if [ "$METH" == "$IPv4pub" ]; then
  998. $SUDO sed -i 's/IPv4pub/'"$IPv4pub"'/' /etc/openvpn/easy-rsa/pki/Default.txt
  999. else
  1000. until [[ $publicDNSCorrect = True ]]
  1001. do
  1002. PUBLICDNS=$(whiptail --title "PiVPN Setup" --inputbox "What is the public DNS name of this Server?" ${r} ${c} 3>&1 1>&2 2>&3)
  1003. exitstatus=$?
  1004. if [ $exitstatus != 0 ]; then
  1005. echo "::: Cancel selected. Exiting..."
  1006. exit 1
  1007. fi
  1008. if (whiptail --backtitle "Confirm DNS Name" --title "Confirm DNS Name" --yesno "Is this correct?\n\n Public DNS Name: $PUBLICDNS" ${r} ${c}) then
  1009. publicDNSCorrect=True
  1010. $SUDO sed -i 's/IPv4pub/'"$PUBLICDNS"'/' /etc/openvpn/easy-rsa/pki/Default.txt
  1011. else
  1012. publicDNSCorrect=False
  1013. fi
  1014. done
  1015. fi
  1016. else
  1017. $SUDO sed -i 's/IPv4pub/'"$PUBLICDNS"'/' /etc/openvpn/easy-rsa/pki/Default.txt
  1018. fi
  1019.  
  1020. # if they modified port put value in Default.txt for clients to use
  1021. if [ $PORT != 1194 ]; then
  1022. $SUDO sed -i -e "s/1194/${PORT}/g" /etc/openvpn/easy-rsa/pki/Default.txt
  1023. fi
  1024.  
  1025. # if they modified protocol put value in Default.txt for clients to use
  1026. if [ "$PROTO" != "udp" ]; then
  1027. $SUDO sed -i -e "s/proto udp/proto tcp/g" /etc/openvpn/easy-rsa/pki/Default.txt
  1028. fi
  1029.  
  1030. # verify server name to strengthen security
  1031. $SUDO sed -i "s/SRVRNAME/${SERVER_NAME}/" /etc/openvpn/easy-rsa/pki/Default.txt
  1032.  
  1033. if [ ! -d "/home/$pivpnUser/ovpns" ]; then
  1034. $SUDO mkdir "/home/$pivpnUser/ovpns"
  1035. fi
  1036. $SUDO chmod 0777 -R "/home/$pivpnUser/ovpns"
  1037. }
  1038.  
  1039. finalExports() {
  1040. # Update variables in setupVars.conf file
  1041. if [ -e "${setupVars}" ]; then
  1042. 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}"
  1043. fi
  1044. {
  1045. echo "pivpnUser=${pivpnUser}"
  1046. echo "UNATTUPG=${UNATTUPG}"
  1047. echo "pivpnInterface=${pivpnInterface}"
  1048. echo "IPv4dns=${IPv4dns}"
  1049. echo "IPv4addr=${IPv4addr}"
  1050. echo "IPv4gw=${IPv4gw}"
  1051. echo "pivpnProto=${pivpnProto}"
  1052. echo "PORT=${PORT}"
  1053. echo "ENCRYPT=${ENCRYPT}"
  1054. echo "DOWNLOAD_DH_PARAM=${DOWNLOAD_DH_PARAM}"
  1055. echo "PUBLICDNS=${PUBLICDNS}"
  1056. echo "OVPNDNS1=${OVPNDNS1}"
  1057. echo "OVPNDNS2=${OVPNDNS2}"
  1058. }>> "${setupVars}"
  1059. }
  1060.  
  1061.  
  1062. # I suggest replacing some of these names.
  1063.  
  1064. #accountForRefactor() {
  1065. # # At some point in the future this list can be pruned, for now we'll need it to ensure updates don't break.
  1066. #
  1067. # # Refactoring of install script has changed the name of a couple of variables. Sort them out here.
  1068. # sed -i 's/pivpnUser/PIVPN_USER/g' ${setupVars}
  1069. # #sed -i 's/UNATTUPG/UNATTUPG/g' ${setupVars}
  1070. # sed -i 's/pivpnInterface/PIVPN_INTERFACE/g' ${setupVars}
  1071. # sed -i 's/IPv4dns/IPV4_DNS/g' ${setupVars}
  1072. # sed -i 's/IPv4addr/IPV4_ADDRESS/g' ${setupVars}
  1073. # sed -i 's/IPv4gw/IPV4_GATEWAY/g' ${setupVars}
  1074. # sed -i 's/pivpnProto/TRANSPORT_LAYER/g' ${setupVars}
  1075. # #sed -i 's/PORT/PORT/g' ${setupVars}
  1076. # #sed -i 's/ENCRYPT/ENCRYPT/g' ${setupVars}
  1077. # #sed -i 's/DOWNLOAD_DH_PARAM/DOWNLOAD_DH_PARAM/g' ${setupVars}
  1078. # sed -i 's/PUBLICDNS/PUBLIC_DNS/g' ${setupVars}
  1079. # sed -i 's/OVPNDNS1/OVPN_DNS_1/g' ${setupVars}
  1080. # sed -i 's/OVPNDNS2/OVPN_DNS_2/g' ${setupVars}
  1081. #}
  1082.  
  1083. installPiVPN() {
  1084. stopServices
  1085. $SUDO mkdir -p /etc/pivpn/
  1086. confUnattendedUpgrades
  1087. installScripts
  1088. setCustomProto
  1089. setCustomPort
  1090. confOpenVPN
  1091. confNetwork
  1092. confOVPN
  1093. setClientDNS
  1094. finalExports
  1095. }
  1096.  
  1097. updatePiVPN() {
  1098. #accountForRefactor
  1099. stopServices
  1100. confUnattendedUpgrades
  1101. installScripts
  1102.  
  1103. # setCustomProto
  1104. # write out the PROTO
  1105. PROTO=$pivpnProto
  1106. $SUDO cp /tmp/pivpnPROTO /etc/pivpn/INSTALL_PROTO
  1107.  
  1108. #setCustomPort
  1109. # write out the port
  1110. $SUDO cp /tmp/INSTALL_PORT /etc/pivpn/INSTALL_PORT
  1111.  
  1112. confOpenVPN
  1113. confNetwork
  1114. confOVPN
  1115.  
  1116. # ?? Is this always OK? Also if you only select one DNS server ??
  1117. $SUDO sed -i '0,/\(dhcp-option DNS \)/ s/\(dhcp-option DNS \).*/\1'${OVPNDNS1}'\"/' /etc/openvpn/server.conf
  1118. $SUDO sed -i '0,/\(dhcp-option DNS \)/! s/\(dhcp-option DNS \).*/\1'${OVPNDNS2}'\"/' /etc/openvpn/server.conf
  1119.  
  1120. finalExports #re-export setupVars.conf to account for any new vars added in new versions
  1121. }
  1122.  
  1123.  
  1124. displayFinalMessage() {
  1125. # Final completion message to user
  1126. whiptail --msgbox --backtitle "Make it so." --title "Installation Complete!" "Now run 'pivpn add' to create the ovpn profiles.
  1127. Run 'pivpn help' to see what else you can do!
  1128. The install log is in /etc/pivpn." ${r} ${c}
  1129. if (whiptail --title "Reboot" --yesno --defaultno "It is strongly recommended you reboot after installation. Would you like to reboot now?" ${r} ${c}); then
  1130. whiptail --title "Rebooting" --msgbox "The system will now reboot." ${r} ${c}
  1131. printf "\nRebooting system...\n"
  1132. $SUDO sleep 3
  1133. $SUDO shutdown -r now
  1134. fi
  1135. }
  1136.  
  1137. update_dialogs() {
  1138. # reconfigure
  1139. if [ "${reconfigure}" = true ]; then
  1140. opt1a="Repair"
  1141. opt1b="This will retain existing settings"
  1142. strAdd="You will remain on the same version"
  1143. else
  1144. opt1a="Update"
  1145. opt1b="This will retain existing settings."
  1146. strAdd="You will be updated to the latest version."
  1147. fi
  1148. opt2a="Reconfigure"
  1149. opt2b="This will allow you to enter new settings"
  1150.  
  1151. 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 \
  1152. "${opt1a}" "${opt1b}" \
  1153. "${opt2a}" "${opt2b}" 3>&2 2>&1 1>&3) || \
  1154. { echo "::: Cancel selected. Exiting"; exit 1; }
  1155.  
  1156. case ${UpdateCmd} in
  1157. ${opt1a})
  1158. echo "::: ${opt1a} option selected."
  1159. useUpdateVars=true
  1160. ;;
  1161. ${opt2a})
  1162. echo "::: ${opt2a} option selected"
  1163. useUpdateVars=false
  1164. ;;
  1165. esac
  1166. }
  1167.  
  1168. clone_or_update_repos() {
  1169. if [[ "${reconfigure}" == true ]]; then
  1170. echo "::: --reconfigure passed to install script. Not downloading/updating local repos"
  1171. else
  1172. # Get Git files
  1173. getGitFiles ${pivpnFilesDir} ${pivpnGitUrl} || \
  1174. { echo "!!! Unable to clone ${pivpnGitUrl} into ${pivpnFilesDir}, unable to continue."; \
  1175. exit 1; \
  1176. }
  1177. fi
  1178. }
  1179.  
  1180. ######## SCRIPT ############
  1181.  
  1182. main() {
  1183.  
  1184. ######## FIRST CHECK ########
  1185. # Must be root to install
  1186. echo ":::"
  1187. if [[ $EUID -eq 0 ]];then
  1188. echo "::: You are root."
  1189. else
  1190. echo "::: sudo will be used for the install."
  1191. # Check if it is actually installed
  1192. # If it isn't, exit because the install cannot complete
  1193. if [[ $(dpkg-query -s sudo) ]];then
  1194. export SUDO="sudo"
  1195. export SUDOE="sudo -E"
  1196. else
  1197. echo "::: Please install sudo or run this as root."
  1198. exit 1
  1199. fi
  1200. fi
  1201.  
  1202. # Check for supported distribution
  1203. distro_check
  1204.  
  1205. # Check arguments for the undocumented flags
  1206. for var in "$@"; do
  1207. case "$var" in
  1208. "--reconfigure" ) reconfigure=true;;
  1209. "--i_do_not_follow_recommendations" ) skipSpaceCheck=false;;
  1210. "--unattended" ) runUnattended=true;;
  1211. esac
  1212. done
  1213.  
  1214. if [[ -f ${setupVars} ]]; then
  1215. if [[ "${runUnattended}" == true ]]; then
  1216. echo "::: --unattended passed to install script, no whiptail dialogs will be displayed"
  1217. useUpdateVars=true
  1218. else
  1219. update_dialogs
  1220. fi
  1221. fi
  1222.  
  1223. # Start the installer
  1224. # Verify there is enough disk space for the install
  1225. if [[ "${skipSpaceCheck}" == true ]]; then
  1226. echo "::: --i_do_not_follow_recommendations passed to script, skipping free disk space verification!"
  1227. else
  1228. verifyFreeDiskSpace
  1229. fi
  1230.  
  1231. # Install the packages (we do this first because we need whiptail)
  1232. #checkForDependencies
  1233. update_package_cache
  1234.  
  1235. # Notify user of package availability
  1236. notify_package_updates_available
  1237.  
  1238. # Install packages used by this installation script
  1239. install_dependent_packages PIVPN_DEPS[@]
  1240.  
  1241. if [[ ${useUpdateVars} == false ]]; then
  1242. # Display welcome dialogs
  1243. welcomeDialogs
  1244.  
  1245. # Find interfaces and let the user choose one
  1246. chooseInterface
  1247.  
  1248. # Only try to set static on Raspbian, otherwise let user do it
  1249. if [[ $PLAT != "Raspbian" ]]; then
  1250. avoidStaticIPv4Ubuntu
  1251. else
  1252. getStaticIPv4Settings
  1253.  
  1254. fi
  1255.  
  1256. # Set the Network IP and Mask correctly
  1257. setNetwork
  1258.  
  1259. # Choose the user for the ovpns
  1260. chooseUser
  1261.  
  1262. # Ask if unattended-upgrades will be enabled
  1263. unattendedUpgrades
  1264.  
  1265. # Clone/Update the repos
  1266. clone_or_update_repos
  1267.  
  1268. # Install and log everything to a file
  1269. installPiVPN | tee ${tmpLog}
  1270.  
  1271. echo "::: Install Complete..."
  1272. else
  1273. # Source ${setupVars} for use in the rest of the functions.
  1274. source ${setupVars}
  1275.  
  1276. echo "::: Using IP address: $IPv4addr"
  1277. echo "${IPv4addr%/*}" > /tmp/pivpnIP
  1278. echo "::: Using interface: $pivpnInterface"
  1279. echo "${pivpnInterface}" > /tmp/pivpnINT
  1280. echo "::: Using User: $pivpnUser"
  1281. echo "${pivpnUser}" > /tmp/pivpnUSR
  1282. echo "::: Using protocol: $pivpnProto"
  1283. echo "${pivpnProto}" > /tmp/pivpnPROTO
  1284. echo "::: Using port: $PORT"
  1285. echo ${PORT} > /tmp/INSTALL_PORT
  1286. echo ":::"
  1287.  
  1288. # Only try to set static on Raspbian
  1289. case ${PLAT} in
  1290. Rasp*)
  1291.  
  1292. ;;
  1293. *)
  1294. echo "::: IP Information"
  1295. echo "::: Since we think you are not using Raspbian, we will not configure a static IP for you."
  1296. echo "::: If you are in Amazon then you can not configure a static IP anyway."
  1297. echo "::: Just ensure before this installer started you had set an elastic IP on your instance."
  1298. ;;
  1299. esac
  1300.  
  1301. # Clone/Update the repos
  1302. clone_or_update_repos
  1303.  
  1304.  
  1305. updatePiVPN | tee ${tmpLog}
  1306. fi
  1307.  
  1308. #Move the install log into /etc/pivpn for storage
  1309. $SUDO mv ${tmpLog} ${instalLogLoc}
  1310.  
  1311. echo "::: Restarting services..."
  1312. # Start services
  1313. case ${PLAT} in
  1314. Ubuntu|Debian|*vuan)
  1315. $SUDO service openvpn start
  1316. ;;
  1317. *)
  1318. $SUDO systemctl enable openvpn.service
  1319. $SUDO systemctl start openvpn.service
  1320. ;;
  1321. esac
  1322.  
  1323. echo "::: done."
  1324.  
  1325. if [[ "${useUpdateVars}" == false ]]; then
  1326. displayFinalMessage
  1327. fi
  1328.  
  1329. echo ":::"
  1330. if [[ "${useUpdateVars}" == false ]]; then
  1331. echo "::: Installation Complete!"
  1332. echo "::: Now run 'pivpn add' to create an ovpn profile for each of your devices."
  1333. echo "::: Run 'pivpn help' to see what else you can do!"
  1334. echo "::: It is strongly recommended you reboot after installation."
  1335. else
  1336. echo "::: Update complete!"
  1337. fi
  1338.  
  1339. echo ":::"
  1340. echo "::: The install log is located at: ${instalLogLoc}"
  1341. }
  1342.  
  1343. if [[ "${PIVPN_TEST}" != true ]] ; then
  1344. main "$@"
  1345. fi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement