/
install.sh
executable file
·2267 lines (1939 loc) · 78.5 KB
/
install.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# PiVPN: Trivial OpenVPN or WireGuard setup and configuration
# Easiest setup and mangement of OpenVPN or WireGuard on Raspberry Pi
# https://pivpn.io
# Heavily adapted from the pi-hole.net project and...
# https://github.com/StarshipEngineer/OpenVPN-Setup/
#
# Install with this command (from your Pi):
#
# curl -L https://install.pivpn.io | bash
# Make sure you have `curl` installed
######## VARIABLES #########
pivpnGitUrl="https://github.com/pivpn/pivpn.git"
setupVars="/etc/pivpn/setupVars.conf"
pivpnFilesDir="/etc/.pivpn"
piholeSetupVars="/etc/pihole/setupVars.conf"
dnsmasqConfig="/etc/dnsmasq.d/02-pivpn.conf"
dhcpcdFile="/etc/dhcpcd.conf"
subnetClass="24"
debianOvpnUserGroup="openvpn:openvpn"
# OpenVPN GPG fingerprint, you can look it up at https://keyserver.ubuntu.com (prepend '0x' before it)
OPENVPN_KEY_ID="30EBF4E73CCE63EEE124DD278E6DA8B4E158C569"
######## PKG Vars ########
PKG_MANAGER="apt-get"
PKG_CACHE="/var/lib/apt/lists/"
### FIXME: quoting UPDATE_PKG_CACHE and PKG_INSTALL hangs the script, shellcheck SC2086
UPDATE_PKG_CACHE="${PKG_MANAGER} update"
PKG_INSTALL="${PKG_MANAGER} --yes --no-install-recommends install"
PKG_COUNT="${PKG_MANAGER} -s -o Debug::NoLocking=true upgrade | grep -c ^Inst || true"
# Dependencies that are required by the script, regardless of the VPN protocol chosen
BASE_DEPS=(git tar wget curl grep dnsutils whiptail net-tools bsdmainutils)
# Dependencies that where actually installed by the script. For example if the script requires
# grep and dnsutils but dnsutils is already installed, we save grep here. This way when uninstalling
# PiVPN we won't prompt to remove packages that may have been installed by the user for other reasons
INSTALLED_PACKAGES=()
######## URLs ########
easyrsaVer="3.0.6"
easyrsaRel="https://github.com/OpenVPN/easy-rsa/releases/download/v${easyrsaVer}/EasyRSA-unix-v${easyrsaVer}.tgz"
# Raspbian's unattended-upgrades package downloads Debian's config, so this is the link for the proper config
UNATTUPG_RELEASE="1.16"
UNATTUPG_CONFIG="https://github.com/mvo5/unattended-upgrades/archive/${UNATTUPG_RELEASE}.tar.gz"
# Fallback url for the OpenVPN key
OPENVPN_KEY_URL="https://swupdate.openvpn.net/repos/repo-public.gpg"
######## Undocumented Flags. Shhh ########
runUnattended=false
skipSpaceCheck=false
reconfigure=false
######## SCRIPT ########
# Find the rows and columns. Will default to 80x24 if it can not be detected.
screen_size=$(stty size 2>/dev/null || echo 24 80)
rows=$(echo "$screen_size" | awk '{print $1}')
columns=$(echo "$screen_size" | awk '{print $2}')
# Divide by two so the dialogs take up half of the screen, which looks nice.
r=$(( rows / 2 ))
c=$(( columns / 2 ))
# Unless the screen is tiny
r=$(( r < 20 ? 20 : r ))
c=$(( c < 70 ? 70 : c ))
# Override localization settings so the output is in English language.
export LC_ALL=C
main(){
######## FIRST CHECK ########
# Must be root to install
echo ":::"
if [[ $EUID -eq 0 ]];then
echo "::: You are root."
else
echo "::: sudo will be used for the install."
# Check if it is actually installed
# If it isn't, exit because the install cannot complete
if [[ $(dpkg-query -s sudo) ]];then
export SUDO="sudo"
export SUDOE="sudo -E"
else
echo "::: Please install sudo or run this as root."
exit 1
fi
fi
# Check arguments for the undocumented flags
for var in "$@"; do
case "$var" in
"--i_do_not_follow_recommendations" ) skipSpaceCheck=false;;
"--unattended" ) runUnattended=true;;
"--reconfigure" ) reconfigure=true;;
esac
done
if [[ "${runUnattended}" == true ]]; then
echo "::: --unattended passed to install script, no whiptail dialogs will be displayed"
if [ -z "$2" ]; then
echo "::: No configuration file passed, using default settings..."
else
if [ -r "$2" ]; then
# shellcheck disable=SC1090
source "$2"
else
echo "::: Can't open $2"
exit 1
fi
fi
fi
if [ -r "$setupVars" ]; then
if [[ "${reconfigure}" == true ]]; then
echo "::: --reconfigure passed to install script, will reinstall PiVPN overwriting existing settings"
UpdateCmd="Reconfigure"
elif [[ "${runUnattended}" == true ]]; then
### What should the script do when passing --unattended to an existing installation?
UpdateCmd="Reconfigure"
else
askAboutExistingInstall
fi
fi
if [ -z "$UpdateCmd" ] || [ "$UpdateCmd" = "Reconfigure" ]; then
:
elif [ "$UpdateCmd" = "Update" ]; then
$SUDO /opt/pivpn/update.sh "$@"
exit 0
elif [ "$UpdateCmd" = "Repair" ]; then
# shellcheck disable=SC1090
source "$setupVars"
runUnattended=true
fi
# Check for supported distribution
distroCheck
# Checks for hostname Length
checkHostname
# Start the installer
# Verify there is enough disk space for the install
if [[ "${skipSpaceCheck}" == true ]]; then
echo "::: --i_do_not_follow_recommendations passed to script, skipping free disk space verification!"
else
verifyFreeDiskSpace
fi
updatePackageCache
# Notify user of package availability
notifyPackageUpdatesAvailable
# Install packages used by this installation script
preconfigurePackages
installDependentPackages BASE_DEPS[@]
# Display welcome dialogs
welcomeDialogs
# Find interfaces and let the user choose one
chooseInterface
if [ "$PLAT" != "Raspbian" ]; then
avoidStaticIPv4Ubuntu
else
getStaticIPv4Settings
if [ -z "$dhcpReserv" ] || [ "$dhcpReserv" -ne 1 ]; then
setStaticIPv4
fi
fi
# Choose the user for the ovpns
chooseUser
# Clone/Update the repos
cloneOrUpdateRepos
# Install
if installPiVPN; then
echo "::: Install Complete..."
else
exit 1
fi
# Start services
restartServices
# Ask if unattended-upgrades will be enabled
askUnattendedUpgrades
if [ "$UNATTUPG" -eq 1 ]; then
confUnattendedUpgrades
fi
# Save installation setting to the final location
echo "INSTALLED_PACKAGES=(${INSTALLED_PACKAGES[*]})" >> /tmp/setupVars.conf
$SUDO cp /tmp/setupVars.conf "$setupVars"
installScripts
# Ensure that cached writes reach persistent storage
echo "::: Flushing writes to disk..."
sync
echo "::: done."
displayFinalMessage
echo ":::"
}
####### FUNCTIONS ##########
askAboutExistingInstall(){
opt1a="Update"
opt1b="Get the latest PiVPN scripts"
opt2a="Repair"
opt2b="Reinstall PiVPN using existing settings"
opt3a="Reconfigure"
opt3b="Reinstall PiVPN with new settings"
UpdateCmd=$(whiptail --title "Existing Install Detected!" --menu "\nWe have detected an existing install.\n\nPlease choose from the following options:" ${r} ${c} 3 \
"${opt1a}" "${opt1b}" \
"${opt2a}" "${opt2b}" \
"${opt3a}" "${opt3b}" 3>&2 2>&1 1>&3) || \
{ echo "::: Cancel selected. Exiting"; exit 1; }
echo "::: ${UpdateCmd} option selected."
}
# Compatibility, functions to check for supported OS
# distroCheck, maybeOSSupport, noOSSupport
distroCheck(){
# if lsb_release command is on their system
if command -v lsb_release > /dev/null; then
PLAT=$(lsb_release -si)
OSCN=$(lsb_release -sc)
else # else get info from os-release
# shellcheck disable=SC1091
source /etc/os-release
PLAT=$(awk '{print $1}' <<< "$NAME")
VER="$VERSION_ID"
declare -A VER_MAP=(["9"]="stretch" ["10"]="buster" ["16.04"]="xenial" ["18.04"]="bionic")
OSCN=${VER_MAP["${VER}"]}
fi
if [ "$PLAT" = "Debian" ] || [ "$PLAT" = "Ubuntu" ]; then
DPKG_ARCH="$(dpkg --print-architecture)"
if [ "$DPKG_ARCH" = "amd64" ] || [ "$DPKG_ARCH" = "i386" ]; then
X86_SYSTEM=1
else
X86_SYSTEM=0
fi
fi
case ${PLAT} in
Debian|Raspbian|Ubuntu)
case ${OSCN} in
buster|xenial|bionic|stretch)
:
;;
*)
maybeOSSupport
;;
esac
;;
*)
noOSSupport
;;
esac
if [ "$PLAT" = "Raspbian" ]; then
BASE_DEPS+=(dhcpcd5)
fi
echo "PLAT=${PLAT}" > /tmp/setupVars.conf
echo "OSCN=${OSCN}" >> /tmp/setupVars.conf
}
noOSSupport(){
if [ "${runUnattended}" = 'true' ]; then
echo "::: Invalid OS detected"
echo "::: We have not been able to detect a supported OS."
echo "::: Currently this installer supports Raspbian, Debian and Ubuntu."
exit 1
fi
whiptail --msgbox --backtitle "INVALID OS DETECTED" --title "Invalid OS" "We have not been able to detect a supported OS.
Currently this installer supports Raspbian, Debian and Ubuntu.
For more details, check our documentation at https://github.com/pivpn/pivpn/wiki " ${r} ${c}
exit 1
}
maybeOSSupport(){
if [ "${runUnattended}" = 'true' ]; then
echo "::: OS Not Supported"
echo "::: You are on an OS that we have not tested but MAY work, continuing anyway..."
return
fi
if (whiptail --backtitle "Untested OS" --title "Untested OS" --yesno "You are on an OS that we have not tested but MAY work.
Currently this installer supports Raspbian, Debian and Ubuntu.
For more details about supported OS please check our documentation at https://github.com/pivpn/pivpn/wiki
Would you like to continue anyway?" ${r} ${c}) then
echo "::: Did not detect perfectly supported OS but,"
echo "::: Continuing installation at user's own risk..."
else
echo "::: Exiting due to untested OS"
exit 1
fi
}
checkHostname(){
###Checks for hostname size
host_name=$(hostname -s)
if [[ ! ${#host_name} -le 28 ]]; then
if [ "${runUnattended}" = 'true' ]; then
echo "::: Your hostname is too long."
echo "::: Use 'hostnamectl set-hostname YOURHOSTNAME' to set a new hostname"
echo "::: It must be less then 28 characters long and it must not use special characters"
exit 1
fi
until [[ ${#host_name} -le 28 && $host_name =~ ^[a-zA-Z0-9][a-zA-Z0-9-]{1,28}$ ]]; do
host_name=$(whiptail --inputbox "Your hostname is too long.\\nEnter new hostname with less then 28 characters\\nNo special characters allowed." \
--title "Hostname too long" ${r} ${c} 3>&1 1>&2 2>&3)
$SUDO hostnamectl set-hostname "${host_name}"
if [[ ${#host_name} -le 28 && $host_name =~ ^[a-zA-Z0-9][a-zA-Z0-9-]{1,28}$ ]]; then
echo "::: Hostname valid and length OK, proceeding..."
fi
done
else
echo "::: Hostname length OK"
fi
}
spinner(){
local pid=$1
local delay=0.50
local spinstr='/-\|'
while ps a | awk '{print $1}' | grep -q "$pid"; do
local temp=${spinstr#?}
printf " [%c] " "${spinstr}"
local spinstr=${temp}${spinstr%"$temp"}
sleep ${delay}
printf "\\b\\b\\b\\b\\b\\b"
done
printf " \\b\\b\\b\\b"
}
verifyFreeDiskSpace(){
# If user installs unattended-upgrades we'd need about 60MB so will check for 75MB free
echo "::: Verifying free disk space..."
local required_free_kilobytes=76800
local existing_free_kilobytes
existing_free_kilobytes=$(df -Pk | grep -m1 '\/$' | awk '{print $4}')
# - Unknown free disk space , not a integer
if ! [[ "${existing_free_kilobytes}" =~ ^([0-9])+$ ]]; then
echo "::: Unknown free disk space!"
echo "::: We were unable to determine available free disk space on this system."
if [ "${runUnattended}" = 'true' ]; then
exit 1
fi
echo "::: You may continue with the installation, however, it is not recommended."
read -r -p "::: If you are sure you want to continue, type YES and press enter :: " response
case $response in
[Y][E][S])
;;
*)
echo "::: Confirmation not received, exiting..."
exit 1
;;
esac
# - Insufficient free disk space
elif [[ ${existing_free_kilobytes} -lt ${required_free_kilobytes} ]]; then
echo "::: Insufficient Disk Space!"
echo "::: Your system appears to be low on disk space. PiVPN recommends a minimum of $required_free_kilobytes KiloBytes."
echo "::: You only have ${existing_free_kilobytes} KiloBytes free."
echo "::: If this is a new install on a Raspberry Pi you may need to expand your disk."
echo "::: Try running 'sudo raspi-config', and choose the 'expand file system option'"
echo "::: After rebooting, run this installation again. (curl -L https://install.pivpn.io | bash)"
echo "Insufficient free space, exiting..."
exit 1
fi
}
updatePackageCache(){
#Running apt-get update/upgrade with minimal output can cause some issues with
#requiring user input
#Check to see if apt-get update has already been run today
#it needs to have been run at least once on new installs!
timestamp=$(stat -c %Y ${PKG_CACHE})
timestampAsDate=$(date -d @"${timestamp}" "+%b %e")
today=$(date "+%b %e")
if [ ! "${today}" == "${timestampAsDate}" ]; then
#update package lists
echo ":::"
echo -ne "::: ${PKG_MANAGER} update has not been run today. Running now...\\n"
# shellcheck disable=SC2086
$SUDO ${UPDATE_PKG_CACHE} &> /dev/null & spinner $!
echo " done!"
fi
}
notifyPackageUpdatesAvailable(){
# Let user know if they have outdated packages on their system and
# advise them to run a package update at soonest possible.
echo ":::"
echo -n "::: Checking ${PKG_MANAGER} for upgraded packages...."
updatesToInstall=$(eval "${PKG_COUNT}")
echo " done!"
echo ":::"
if [[ ${updatesToInstall} -eq "0" ]]; then
echo "::: Your system is up to date! Continuing with PiVPN installation..."
else
echo "::: There are ${updatesToInstall} updates available for your system!"
echo "::: We recommend you update your OS after installing PiVPN! "
echo ":::"
fi
}
preconfigurePackages(){
# Add support for https repositories that will be used later on
if [[ -f /etc/apt/sources.list ]]; then
# buster and bionic have apt >= 1.5 which has https support built in
if [[ ${OSCN} != "buster" ]] && [[ ${OSCN} != "bionic" ]]; then
BASE_DEPS+=("apt-transport-https")
fi
fi
if [[ ${OSCN} == "buster" ]]; then
$SUDO update-alternatives --set iptables /usr/sbin/iptables-legacy
$SUDO update-alternatives --set ip6tables /usr/sbin/ip6tables-legacy
fi
# if ufw is enabled, configure that.
# running as root because sometimes the executable is not in the user's $PATH
if $SUDO bash -c 'command -v ufw' > /dev/null; then
if $SUDO ufw status | grep -q inactive; then
USING_UFW=0
else
USING_UFW=1
fi
else
USING_UFW=0
fi
if [ "$USING_UFW" -eq 0 ]; then
BASE_DEPS+=(iptables-persistent)
echo iptables-persistent iptables-persistent/autosave_v4 boolean true | $SUDO debconf-set-selections
echo iptables-persistent iptables-persistent/autosave_v6 boolean false | $SUDO debconf-set-selections
fi
echo "USING_UFW=${USING_UFW}" >> /tmp/setupVars.conf
}
installDependentPackages(){
declare -a TO_INSTALL=()
# Install packages passed in via argument array
# No spinner - conflicts with set -e
declare -a argArray1=("${!1}")
for i in "${argArray1[@]}"; do
echo -n "::: Checking for $i..."
if dpkg-query -W -f='${Status}' "${i}" 2>/dev/null | grep -q "ok installed"; then
echo " already installed!"
else
echo " not installed!"
# Add this package to the list of packages in the argument array that need to be installed
TO_INSTALL+=("${i}")
fi
done
if command -v debconf-apt-progress > /dev/null; then
# shellcheck disable=SC2086
$SUDO debconf-apt-progress -- ${PKG_INSTALL} "${TO_INSTALL[@]}"
else
# shellcheck disable=SC2086
$SUDO ${PKG_INSTALL} "${TO_INSTALL[@]}"
fi
local FAILED=0
for i in "${TO_INSTALL[@]}"; do
if dpkg-query -W -f='${Status}' "${i}" 2>/dev/null | grep -q "ok installed"; then
echo "::: Package $i successfully installed!"
# Add this package to the total list of packages that were actually installed by the script
INSTALLED_PACKAGES+=("${i}")
else
echo "::: Failed to install $i!"
((FAILED++))
fi
done
if [ "$FAILED" -gt 0 ]; then
exit 1
fi
}
welcomeDialogs(){
if [ "${runUnattended}" = 'true' ]; then
echo "::: PiVPN Automated Installer"
echo "::: This installer will transform your ${PLAT} host into an OpenVPN or WireGuard server!"
echo "::: Initiating network interface"
return
fi
# Display the welcome dialog
whiptail --msgbox --backtitle "Welcome" --title "PiVPN Automated Installer" "This installer will transform your Raspberry Pi into an OpenVPN or WireGuard server!" ${r} ${c}
# Explain the need for a static address
whiptail --msgbox --backtitle "Initiating network interface" --title "Static IP Needed" "The PiVPN is a SERVER so it needs a STATIC IP ADDRESS to function properly.
In the next section, you can choose to use your current network settings (DHCP) or to manually edit them." ${r} ${c}
}
chooseInterface(){
# Turn the available interfaces into an array so it can be used with a whiptail dialog
local interfacesArray=()
# Number of available interfaces
local interfaceCount
# Whiptail variable storage
local chooseInterfaceCmd
# Temporary Whiptail options storage
local chooseInterfaceOptions
# Loop sentinel variable
local firstloop=1
# Find network interfaces whose state is UP, so as to skip virtual interfaces and the loopback interface
availableInterfaces=$(ip -o link | awk '/state UP/ {print $2}' | cut -d':' -f1 | cut -d'@' -f1)
if [ -z "$availableInterfaces" ]; then
echo "::: Could not find any active network interface, exiting"
exit 1
else
while read -r line; do
mode="OFF"
if [[ ${firstloop} -eq 1 ]]; then
firstloop=0
mode="ON"
fi
interfacesArray+=("${line}" "available" "${mode}")
((interfaceCount++))
done <<< "${availableInterfaces}"
fi
if [ "${runUnattended}" = 'true' ]; then
if [ -z "$IPv4dev" ]; then
if [ $interfaceCount -eq 1 ]; then
IPv4dev="${availableInterfaces}"
echo "::: No interface specified, but only ${IPv4dev} is available, using it"
else
echo "::: No interface specified and failed to determine one"
exit 1
fi
else
if ip -o link | grep -qw "${IPv4dev}"; then
echo "::: Using interface: ${IPv4dev}"
else
echo "::: Interface ${IPv4dev} does not exist"
exit 1
fi
fi
echo "IPv4dev=${IPv4dev}" >> /tmp/setupVars.conf
return
else
if [ "$interfaceCount" -eq 1 ]; then
IPv4dev="${availableInterfaces}"
echo "IPv4dev=${IPv4dev}" >> /tmp/setupVars.conf
return
fi
fi
chooseInterfaceCmd=(whiptail --separate-output --radiolist "Choose An interface (press space to select):" "${r}" "${c}" "${interfaceCount}")
if chooseInterfaceOptions=$("${chooseInterfaceCmd[@]}" "${interfacesArray[@]}" 2>&1 >/dev/tty) ; then
for desiredInterface in ${chooseInterfaceOptions}; do
IPv4dev=${desiredInterface}
echo "::: Using interface: $IPv4dev"
echo "IPv4dev=${IPv4dev}" >> /tmp/setupVars.conf
done
else
echo "::: Cancel selected, exiting...."
exit 1
fi
}
avoidStaticIPv4Ubuntu() {
if [ "${runUnattended}" = 'true' ]; then
echo "::: Since we think you are not using Raspbian, we will not configure a static IP for you."
return
fi
# If we are in Ubuntu then they need to have previously set their network, so just use what you have.
whiptail --msgbox --backtitle "IP Information" --title "IP Information" "Since we think you are not using Raspbian, we will not configure a static IP for you.
If you are in Amazon then you can not configure a static IP anyway. Just ensure before this installer started you had set an elastic IP on your instance." ${r} ${c}
}
validIP(){
local ip=$1
local stat=1
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS='.'
read -r -a ip <<< "$ip"
IFS=$OIFS
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
stat=$?
fi
return $stat
}
validIPAndNetmask(){
local ip=$1
local stat=1
ip="${ip/\//.}"
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,2}$ ]]; then
OIFS=$IFS
IFS='.'
read -r -a ip <<< "$ip"
IFS=$OIFS
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 \
&& ${ip[4]} -le 32 ]]
stat=$?
fi
return $stat
}
getStaticIPv4Settings() {
# Find the gateway IP used to route to outside world
CurrentIPv4gw="$(ip -o route get 192.0.2.1 | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | awk 'NR==2')"
# Find the IP address (and netmask) of the desidered interface
CurrentIPv4addr="$(ip -o -f inet address show dev "${IPv4dev}" | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\/[0-9]{1,2}')"
# Grab their current DNS servers
IPv4dns=$(grep -v "^#" /etc/resolv.conf | grep -w nameserver | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | xargs)
if [ "${runUnattended}" = 'true' ]; then
if [ -z "$dhcpReserv" ] || [ "$dhcpReserv" -ne 1 ]; then
local MISSING_STATIC_IPV4_SETTINGS=0
if [ -z "$IPv4addr" ]; then
echo "::: Missing static IP address"
((MISSING_STATIC_IPV4_SETTINGS++))
fi
if [ -z "$IPv4gw" ]; then
echo "::: Missing static IP gateway"
((MISSING_STATIC_IPV4_SETTINGS++))
fi
if [ "$MISSING_STATIC_IPV4_SETTINGS" -eq 0 ]; then
# If both settings are not empty, check if they are valid and proceed
if validIPAndNetmask "${IPv4addr}"; then
echo "::: Your static IPv4 address: ${IPv4addr}"
else
echo "::: ${IPv4addr} is not a valid IP address"
exit 1
fi
if validIP "${IPv4gw}"; then
echo "::: Your static IPv4 gateway: ${IPv4gw}"
else
echo "::: ${IPv4gw} is not a valid IP address"
exit 1
fi
elif [ "$MISSING_STATIC_IPV4_SETTINGS" -eq 1 ]; then
# If either of the settings is missing, consider the input inconsistent
echo "::: Incomplete static IP settings"
exit 1
elif [ "$MISSING_STATIC_IPV4_SETTINGS" -eq 2 ]; then
# If both of the settings are missing, assume the user wants to use current settings
IPv4addr="${CurrentIPv4addr}"
IPv4gw="${CurrentIPv4gw}"
echo "::: No static IP settings, using current settings"
echo "::: Your static IPv4 address: ${IPv4addr}"
echo "::: Your static IPv4 gateway: ${IPv4gw}"
fi
else
echo "::: Skipping setting static IP address"
fi
echo "dhcpReserv=${dhcpReserv}" >> /tmp/setupVars.conf
echo "IPv4addr=${IPv4addr}" >> /tmp/setupVars.conf
echo "IPv4gw=${IPv4gw}" >> /tmp/setupVars.conf
return
fi
local ipSettingsCorrect
local IPv4AddrValid
local IPv4gwValid
# Some users reserve IP addresses on another DHCP Server or on their routers,
# Lets ask them if they want to make any changes to their interfaces.
if (whiptail --backtitle "Calibrating network interface" --title "DHCP Reservation" --yesno --defaultno \
"Are you Using DHCP Reservation on your Router/DHCP Server?
These are your current Network Settings:
IP address: ${CurrentIPv4addr}
Gateway: ${CurrentIPv4gw}
Yes: Keep using DHCP reservation
No: Setup static IP address
Don't know what DHCP Reservation is? Answer No." ${r} ${c}); then
dhcpReserv=1
# shellcheck disable=SC2129
echo "dhcpReserv=${dhcpReserv}" >> /tmp/setupVars.conf
# We don't really need to save them as we won't set a static IP but they might be useful for debugging
echo "IPv4addr=${CurrentIPv4addr}" >> /tmp/setupVars.conf
echo "IPv4gw=${CurrentIPv4gw}" >> /tmp/setupVars.conf
else
# Ask if the user wants to use DHCP settings as their static IP
if (whiptail --backtitle "Calibrating network interface" --title "Static IP Address" --yesno "Do you want to use your current network settings as a static address?
IP address: ${CurrentIPv4addr}
Gateway: ${CurrentIPv4gw}" ${r} ${c}); then
IPv4addr=${CurrentIPv4addr}
IPv4gw=${CurrentIPv4gw}
echo "IPv4addr=${IPv4addr}" >> /tmp/setupVars.conf
echo "IPv4gw=${IPv4gw}" >> /tmp/setupVars.conf
# If they choose yes, let the user know that the IP address will not be available via DHCP and may cause a conflict.
whiptail --msgbox --backtitle "IP information" --title "FYI: IP Conflict" "It is possible your router could still try to assign this IP to a device, which would cause a conflict. But in most cases the router is smart enough to not do that.
If you are worried, either manually set the address, or modify the DHCP reservation pool so it does not include the IP you want.
It is also possible to use a DHCP reservation, but if you are going to do that, you might as well set a static address." ${r} ${c}
# Nothing else to do since the variables are already set above
else
# Otherwise, we need to ask the user to input their desired settings.
# Start by getting the IPv4 address (pre-filling it with info gathered from DHCP)
# Start a loop to let the user enter their information with the chance to go back and edit it if necessary
until [[ ${ipSettingsCorrect} = True ]]; do
until [[ ${IPv4AddrValid} = True ]]; do
# Ask for the IPv4 address
if IPv4addr=$(whiptail --backtitle "Calibrating network interface" --title "IPv4 address" --inputbox "Enter your desired IPv4 address" ${r} ${c} "${CurrentIPv4addr}" 3>&1 1>&2 2>&3) ; then
if validIPAndNetmask "${IPv4addr}"; then
echo "::: Your static IPv4 address: ${IPv4addr}"
IPv4AddrValid=True
else
whiptail --msgbox --backtitle "Calibrating network interface" --title "IPv4 address" "You've entered an invalid IP address: ${IPv4addr}\\n\\nPlease enter an IP address in the CIDR notation, example: 192.168.23.211/24\\n\\nIf you are not sure, please just keep the default." ${r} ${c}
echo "::: Invalid IPv4 address: ${IPv4addr}"
IPv4AddrValid=False
fi
else
# Cancelling IPv4 settings window
echo "::: Cancel selected. Exiting..."
exit 1
fi
done
until [[ ${IPv4gwValid} = True ]]; do
# Ask for the gateway
if IPv4gw=$(whiptail --backtitle "Calibrating network interface" --title "IPv4 gateway (router)" --inputbox "Enter your desired IPv4 default gateway" ${r} ${c} "${CurrentIPv4gw}" 3>&1 1>&2 2>&3) ; then
if validIP "${IPv4gw}"; then
echo "::: Your static IPv4 gateway: ${IPv4gw}"
IPv4gwValid=True
else
whiptail --msgbox --backtitle "Calibrating network interface" --title "IPv4 gateway (router)" "You've entered an invalid gateway IP: ${IPv4gw}\\n\\nPlease enter the IP address of your gateway (router), example: 192.168.23.1\\n\\nIf you are not sure, please just keep the default." ${r} ${c}
echo "::: Invalid IPv4 gateway: ${IPv4gw}"
IPv4gwValid=False
fi
else
# Cancelling gateway settings window
echo "::: Cancel selected. Exiting..."
exit 1
fi
done
# Give the user a chance to review their settings before moving on
if (whiptail --backtitle "Calibrating network interface" --title "Static IP Address" --yesno "Are these settings correct?
IP address: ${IPv4addr}
Gateway: ${IPv4gw}" ${r} ${c}); then
# If the settings are correct, then we need to set the pivpnIP
echo "IPv4addr=${IPv4addr}" >> /tmp/setupVars.conf
echo "IPv4gw=${IPv4gw}" >> /tmp/setupVars.conf
# After that's done, the loop ends and we move on
ipSettingsCorrect=True
else
# If the settings are wrong, the loop continues
ipSettingsCorrect=False
IPv4AddrValid=False
IPv4gwValid=False
fi
done
# End the if statement for DHCP vs. static
fi
# End of If Statement for DCHCP Reservation
fi
}
setDHCPCD(){
# Append these lines to dhcpcd.conf to enable a static IP
echo "interface ${IPv4dev}
static ip_address=${IPv4addr}
static routers=${IPv4gw}
static domain_name_servers=${IPv4dns}" | $SUDO tee -a ${dhcpcdFile} >/dev/null
}
setStaticIPv4(){
# Tries to set the IPv4 address
if [[ -f /etc/dhcpcd.conf ]]; then
if grep -q "${IPv4addr}" ${dhcpcdFile}; then
echo "::: Static IP already configured."
else
setDHCPCD
$SUDO ip addr replace dev "${IPv4dev}" "${IPv4addr}"
echo ":::"
echo "::: Setting IP to ${IPv4addr}. You may need to restart after the install is complete."
echo ":::"
fi
else
echo "::: Critical: Unable to locate configuration file to set static IPv4 address!"
exit 1
fi
}
chooseUser(){
if [ "${runUnattended}" = 'true' ]; then
if [ -z "$install_user" ]; then
if [ "$(awk -F':' 'BEGIN {count=0} $3>=1000 && $3<=60000 { count++ } END{ print count }' /etc/passwd)" -eq 1 ]; then
install_user="$(awk -F':' '$3>=1000 && $3<=60000 {print $1}' /etc/passwd)"
echo "::: No user specified, but only ${install_user} is available, using it"
else
echo "::: No user specified"
exit 1
fi
else
if awk -F':' '$3>=1000 && $3<=60000 {print $1}' /etc/passwd | grep -qw "${install_user}"; then
echo "::: ${install_user} will hold your ovpn configurations."
else
echo "::: User ${install_user} does not exist, creating..."
$SUDO useradd -m -s /bin/bash "${install_user}"
echo "::: User created without a password, please do sudo passwd $install_user to create one"
fi
fi
install_home=$(grep -m1 "^${install_user}:" /etc/passwd | cut -d: -f6)
install_home=${install_home%/}
echo "install_user=${install_user}" >> /tmp/setupVars.conf
echo "install_home=${install_home}" >> /tmp/setupVars.conf
return
fi
# Explain the local user
whiptail --msgbox --backtitle "Parsing User List" --title "Local Users" "Choose a local user that will hold your ovpn configurations." ${r} ${c}
# First, let's check if there is a user available.
numUsers=$(awk -F':' 'BEGIN {count=0} $3>=1000 && $3<=60000 { count++ } END{ print count }' /etc/passwd)
if [ "$numUsers" -eq 0 ]
then
# We don't have a user, let's ask to add one.
if userToAdd=$(whiptail --title "Choose A User" --inputbox "No non-root user account was found. Please type a new username." ${r} ${c} 3>&1 1>&2 2>&3)
then
# See https://askubuntu.com/a/667842/459815
PASSWORD=$(whiptail --title "password dialog" --passwordbox "Please enter the new user password" ${r} ${c} 3>&1 1>&2 2>&3)
CRYPT=$(perl -e 'printf("%s\n", crypt($ARGV[0], "password"))' "${PASSWORD}")
if $SUDO useradd -m -p "${CRYPT}" -s /bin/bash "${userToAdd}" ; then
echo "Succeeded"
((numUsers+=1))
else
exit 1
fi
else
exit 1
fi
fi
availableUsers=$(awk -F':' '$3>=1000 && $3<=60000 {print $1}' /etc/passwd)
local userArray=()
local firstloop=1
while read -r line
do
mode="OFF"
if [[ $firstloop -eq 1 ]]; then
firstloop=0
mode="ON"
fi
userArray+=("${line}" "" "${mode}")
done <<< "${availableUsers}"
chooseUserCmd=(whiptail --title "Choose A User" --separate-output --radiolist
"Choose (press space to select):" "${r}" "${c}" "${numUsers}")
if chooseUserOptions=$("${chooseUserCmd[@]}" "${userArray[@]}" 2>&1 >/dev/tty) ; then
for desiredUser in ${chooseUserOptions}; do
install_user=${desiredUser}
echo "::: Using User: $install_user"
install_home=$(grep -m1 "^${install_user}:" /etc/passwd | cut -d: -f6)
install_home=${install_home%/} # remove possible trailing slash
echo "install_user=${install_user}" >> /tmp/setupVars.conf
echo "install_home=${install_home}" >> /tmp/setupVars.conf
done
else
echo "::: Cancel selected, exiting...."
exit 1
fi
}
isRepo(){
# If the directory does not have a .git folder it is not a repo
echo -n "::: Checking $1 is a repo..."
cd "${1}" &> /dev/null || return 1
$SUDO git status &> /dev/null && echo " OK!"; return 0 || echo " not found!"; return 1
}
updateRepo(){
if [ "${UpdateCmd}" = "Repair" ]; then
echo "::: Repairing an existing installation, not downloading/updating local repos"
else
# Pull the latest commits
echo -n "::: Updating repo in $1..."
### FIXME: Never call rm -rf with a plain variable. Never again as SU!
#$SUDO rm -rf "${1}"
if test -n "$1"; then
$SUDO rm -rf "$(dirname "$1")/.pivpn"
fi
# Go back to /etc otherwise git will complain when the current working
# directory has just been deleted (/etc/.pivpn).
cd /etc && \
$SUDO git clone -q --depth 1 --no-single-branch "${2}" "${1}" > /dev/null & spinner $!
cd "${1}" || exit 1
if [ -z "${TESTING+x}" ]; then
:
else
${SUDOE} git checkout test
fi
echo " done!"
fi
}
makeRepo(){
# Remove the non-repos interface and clone the interface
echo -n "::: Cloning $2 into $1..."
### FIXME: Never call rm -rf with a plain variable. Never again as SU!
#$SUDO rm -rf "${1}"
if test -n "$1"; then
$SUDO rm -rf "$(dirname "$1")/.pivpn"
fi
# Go back to /etc otherwhise git will complain when the current working
# directory has just been deleted (/etc/.pivpn).
cd /etc && \
$SUDO git clone -q --depth 1 --no-single-branch "${2}" "${1}" > /dev/null & spinner $!
cd "${1}" || exit 1
if [ -z "${TESTING+x}" ]; then
:
else
${SUDOE} git checkout test
fi
echo " done!"
}
getGitFiles(){
# Setup git repos for base files
echo ":::"
echo "::: Checking for existing base files..."
if isRepo "${1}"; then
updateRepo "${1}" "${2}"
else
makeRepo "${1}" "${2}"
fi
}
cloneOrUpdateRepos(){
# Get Git files
getGitFiles ${pivpnFilesDir} ${pivpnGitUrl} || \
{ echo "!!! Unable to clone ${pivpnGitUrl} into ${pivpnFilesDir}, unable to continue."; \
exit 1; \
}
}
installPiVPN(){
$SUDO mkdir -p /etc/pivpn/