forked from hwdsl2/setup-ipsec-vpn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ikev2setup.sh
executable file
·1750 lines (1612 loc) · 49.7 KB
/
ikev2setup.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
#!/bin/bash
#
# Script to set up and manage IKEv2 on Ubuntu, Debian, CentOS/RHEL, Rocky Linux,
# AlmaLinux, Oracle Linux, Amazon Linux 2 and Alpine Linux
#
# DO NOT RUN THIS SCRIPT ON YOUR PC OR MAC!
#
# The latest version of this script is available at:
# https://github.com/hwdsl2/setup-ipsec-vpn
#
# Copyright (C) 2020-2024 Lin Song <[email protected]>
#
# This work is licensed under the Creative Commons Attribution-ShareAlike 3.0
# Unported License: http://creativecommons.org/licenses/by-sa/3.0/
#
# Attribution required: please include my name in any derivative and let me
# know how you have improved it!
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
exiterr() { echo "Error: $1" >&2; exit 1; }
bigecho() { echo "## $1"; }
bigecho2() { printf '\e[2K\r%s' "## $1"; }
check_ip() {
IP_REGEX='^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'
printf '%s' "$1" | tr -d '\n' | grep -Eq "$IP_REGEX"
}
check_dns_name() {
FQDN_REGEX='^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$'
printf '%s' "$1" | tr -d '\n' | grep -Eq "$FQDN_REGEX"
}
check_root() {
if [ "$(id -u)" != 0 ]; then
exiterr "Script must be run as root. Try 'sudo bash $0'"
fi
}
check_container() {
in_container=0
if grep -qs "hwdsl2" /opt/src/run.sh; then
in_container=1
fi
}
check_os() {
rh_file="/etc/redhat-release"
if [ -f "$rh_file" ]; then
os_type=centos
if grep -q "Red Hat" "$rh_file"; then
os_type=rhel
fi
[ -f /etc/oracle-release ] && os_type=ol
grep -qi rocky "$rh_file" && os_type=rocky
grep -qi alma "$rh_file" && os_type=alma
if grep -q "release 7" "$rh_file"; then
os_ver=7
elif grep -q "release 8" "$rh_file"; then
os_ver=8
grep -qi stream "$rh_file" && os_ver=8s
elif grep -q "release 9" "$rh_file"; then
os_ver=9
grep -qi stream "$rh_file" && os_ver=9s
else
exiterr "This script only supports CentOS/RHEL 7-9."
fi
if [ "$os_type" = "centos" ] \
&& { [ "$os_ver" = 7 ] || [ "$os_ver" = 8 ] || [ "$os_ver" = 8s ]; }; then
exiterr "CentOS Linux $os_ver is EOL and not supported."
fi
elif grep -qs "Amazon Linux release 2 " /etc/system-release; then
os_type=amzn
os_ver=2
else
os_type=$(lsb_release -si 2>/dev/null)
[ -z "$os_type" ] && [ -f /etc/os-release ] && os_type=$(. /etc/os-release && printf '%s' "$ID")
case $os_type in
[Uu]buntu)
os_type=ubuntu
;;
[Dd]ebian|[Kk]ali)
os_type=debian
;;
[Rr]aspbian)
os_type=raspbian
;;
[Aa]lpine)
os_type=alpine
;;
*)
cat 1>&2 <<'EOF'
Error: This script only supports one of the following OS:
Ubuntu, Debian, CentOS/RHEL, Rocky Linux, AlmaLinux,
Oracle Linux, Amazon Linux 2 or Alpine Linux
EOF
exit 1
;;
esac
if [ "$os_type" = "alpine" ]; then
os_ver=$(. /etc/os-release && printf '%s' "$VERSION_ID" | cut -d '.' -f 1,2)
if [ "$os_ver" != "3.19" ] && [ "$os_ver" != "3.20" ]; then
exiterr "This script only supports Alpine Linux 3.19/3.20."
fi
else
os_ver=$(sed 's/\..*//' /etc/debian_version | tr -dc 'A-Za-z0-9')
if [ "$os_ver" = 8 ] || [ "$os_ver" = 9 ] || [ "$os_ver" = "jessiesid" ] \
|| [ "$os_ver" = "bustersid" ]; then
cat 1>&2 <<EOF
Error: This script requires Debian >= 10 or Ubuntu >= 20.04.
This version of Ubuntu/Debian is too old and not supported.
EOF
exit 1
fi
fi
fi
}
check_libreswan() {
ipsec_ver=$(ipsec --version 2>/dev/null)
if ( ! grep -qs "hwdsl2 VPN script" /etc/sysctl.conf && ! grep -qs "hwdsl2" /opt/src/run.sh ) \
|| ! printf '%s' "$ipsec_ver" | grep -qi 'libreswan'; then
cat 1>&2 <<'EOF'
Error: Your must first set up the IPsec VPN server before setting up IKEv2.
See: https://github.com/hwdsl2/setup-ipsec-vpn
EOF
exit 1
fi
}
check_swan_ver() {
swan_ver=$(printf '%s' "$ipsec_ver" | sed -e 's/.*Libreswan U\?//' -e 's/\( (\|\/K\).*//')
if ! printf '%s\n%s' "3.23" "$swan_ver" | sort -C -V; then
cat 1>&2 <<EOF
Error: Libreswan version '$swan_ver' is not supported.
This script requires Libreswan 3.23 or newer.
To update Libreswan, run:
wget https://get.vpnsetup.net/upg -O vpnup.sh && sudo sh vpnup.sh
EOF
exit 1
fi
}
check_utils_exist() {
command -v certutil >/dev/null 2>&1 || exiterr "'certutil' not found. Abort."
command -v crlutil >/dev/null 2>&1 || exiterr "'crlutil' not found. Abort."
command -v pk12util >/dev/null 2>&1 || exiterr "'pk12util' not found. Abort."
}
abort_and_exit() {
echo "Abort. No changes were made." >&2
exit 1
}
confirm_or_abort() {
printf '%s' "$1"
read -r response
case $response in
[yY][eE][sS]|[yY])
echo
;;
*)
abort_and_exit
;;
esac
}
show_header() {
cat <<'EOF'
IKEv2 Script Copyright (c) 2020-2024 Lin Song 28 Jul 2024
EOF
}
show_usage() {
if [ -n "$1" ]; then
echo "Error: $1" >&2
fi
show_header
cat 1>&2 <<EOF
Usage: bash $0 [options]
Options:
--auto run IKEv2 setup in auto mode using default options (for initial setup only)
--addclient [client name] add a new client using default options
--exportclient [client name] export configuration for an existing client
--listclients list the names of existing clients
--revokeclient [client name] revoke an existing client
--deleteclient [client name] delete an existing client
--removeikev2 remove IKEv2 and delete all certificates and keys from the IPsec database
-y, --yes assume "yes" as answer to prompts when revoking/deleting a client or removing IKEv2
-h, --help show this help message and exit
To customize IKEv2 or client options, run this script without arguments.
For documentation, see: https://vpnsetup.net/ikev2
EOF
exit 1
}
check_ikev2_exists() {
grep -qs "conn ikev2-cp" "$IPSEC_CONF" || [ -f "$IKEV2_CONF" ]
}
check_client_name() {
! { [ "${#1}" -gt "64" ] || printf '%s' "$1" | LC_ALL=C grep -q '[^A-Za-z0-9_-]\+' \
|| case $1 in -*) true ;; *) false ;; esac; }
}
check_cert_exists() {
certutil -L -d "$CERT_DB" -n "$1" >/dev/null 2>&1
}
check_cert_exists_and_exit() {
if certutil -L -d "$CERT_DB" -n "$1" >/dev/null 2>&1; then
echo "Error: Certificate '$1' already exists." >&2
abort_and_exit
fi
}
check_cert_status() {
cert_status=$(certutil -V -u C -d "$CERT_DB" -n "$1")
}
check_arguments() {
if [ "$use_defaults" = 1 ] && check_ikev2_exists; then
echo "Error: Invalid parameter '--auto'. IKEv2 is already set up on this server." >&2
echo " To manage VPN clients, re-run this script without '--auto'." >&2
echo " To change IKEv2 server address, see https://vpnsetup.net/ikev2" >&2
exit 1
fi
if [ "$((add_client + export_client + list_clients + revoke_client + delete_client))" -gt 1 ]; then
show_usage "Invalid parameters. Specify only one of '--addclient', '--exportclient', '--listclients', '--revokeclient' or '--deleteclient'."
fi
if [ "$remove_ikev2" = 1 ]; then
if [ "$((add_client + export_client + list_clients + revoke_client + delete_client + use_defaults))" -gt 0 ]; then
show_usage "Invalid parameters. '--removeikev2' cannot be specified with other parameters."
fi
fi
if ! check_ikev2_exists; then
[ "$add_client" = 1 ] && exiterr "You must first set up IKEv2 before adding a client."
[ "$export_client" = 1 ] && exiterr "You must first set up IKEv2 before exporting a client."
[ "$list_clients" = 1 ] && exiterr "You must first set up IKEv2 before listing clients."
[ "$revoke_client" = 1 ] && exiterr "You must first set up IKEv2 before revoking a client."
[ "$delete_client" = 1 ] && exiterr "You must first set up IKEv2 before deleting a client."
[ "$remove_ikev2" = 1 ] && exiterr "Cannot remove IKEv2 because it has not been set up on this server."
fi
if [ "$add_client" = 1 ]; then
if [ -z "$client_name" ] || ! check_client_name "$client_name"; then
exiterr "Invalid client name. Use one word only, no special characters except '-' and '_'."
elif check_cert_exists "$client_name"; then
exiterr "Invalid client name. Client '$client_name' already exists."
fi
fi
if [ "$export_client" = 1 ] || [ "$revoke_client" = 1 ] || [ "$delete_client" = 1 ]; then
get_server_address
if [ -z "$client_name" ] || ! check_client_name "$client_name" \
|| [ "$client_name" = "$CA_NAME" ] || [ "$client_name" = "$server_addr" ] \
|| ! check_cert_exists "$client_name"; then
exiterr "Invalid client name, or client does not exist."
fi
if [ "$delete_client" = 0 ] && ! check_cert_status "$client_name"; then
printf '%s' "Error: Certificate '$client_name' " >&2
if printf '%s' "$cert_status" | grep -q "revoked"; then
if [ "$revoke_client" = 1 ]; then
echo "has already been revoked." >&2
else
echo "has been revoked." >&2
fi
elif printf '%s' "$cert_status" | grep -q "expired"; then
echo "has expired." >&2
else
echo "is invalid." >&2
fi
exit 1
fi
fi
}
check_server_dns_name() {
if [ -n "$VPN_DNS_NAME" ]; then
check_dns_name "$VPN_DNS_NAME" || exiterr "Invalid DNS name. 'VPN_DNS_NAME' must be a fully qualified domain name (FQDN)."
fi
}
check_custom_dns() {
if { [ -n "$VPN_DNS_SRV1" ] && ! check_ip "$VPN_DNS_SRV1"; } \
|| { [ -n "$VPN_DNS_SRV2" ] && ! check_ip "$VPN_DNS_SRV2"; }; then
exiterr "Invalid DNS server(s)."
fi
}
check_client_validity() {
! { printf '%s' "$1" | LC_ALL=C grep -q '[^0-9]\+' || [ "$1" -lt "1" ] \
|| [ "$1" -gt "120" ] || [ "$1" != "$((10#$1))" ]; }
}
check_and_set_client_name() {
if [ -n "$VPN_CLIENT_NAME" ]; then
client_name="$VPN_CLIENT_NAME"
check_client_name "$client_name" \
|| exiterr "Invalid client name. Use one word only, no special characters except '-' and '_'."
else
client_name=vpnclient
fi
check_cert_exists "$client_name" && exiterr "Client '$client_name' already exists."
}
check_and_set_client_validity() {
if [ -n "$VPN_CLIENT_VALIDITY" ]; then
client_validity="$VPN_CLIENT_VALIDITY"
if ! check_client_validity "$client_validity"; then
cat <<EOF
WARNING: Invalid client cert validity period. Must be an integer between 1 and 120.
Falling back to default validity (120 months).
EOF
VPN_CLIENT_VALIDITY=""
client_validity=120
fi
else
client_validity=120
fi
}
set_server_address() {
if [ -n "$VPN_DNS_NAME" ]; then
use_dns_name=1
server_addr="$VPN_DNS_NAME"
else
use_dns_name=0
get_server_ip
check_ip "$public_ip" || exiterr "Cannot detect this server's public IP."
server_addr="$public_ip"
fi
check_cert_exists_and_exit "$server_addr"
}
set_dns_servers() {
if [ -n "$VPN_DNS_SRV1" ] && [ -n "$VPN_DNS_SRV2" ]; then
dns_server_1="$VPN_DNS_SRV1"
dns_server_2="$VPN_DNS_SRV2"
dns_servers="$VPN_DNS_SRV1 $VPN_DNS_SRV2"
elif [ -n "$VPN_DNS_SRV1" ]; then
dns_server_1="$VPN_DNS_SRV1"
dns_server_2=""
dns_servers="$VPN_DNS_SRV1"
else
dns_server_1=8.8.8.8
dns_server_2=8.8.4.4
dns_servers="8.8.8.8 8.8.4.4"
fi
}
show_welcome() {
cat <<'EOF'
Welcome! Use this script to set up IKEv2 on your VPN server.
I need to ask you a few questions before starting setup.
You can use the default options and just press enter if you are OK with them.
EOF
}
show_start_setup() {
op_text=default
if [ -n "$VPN_DNS_NAME" ] || [ -n "$VPN_CLIENT_NAME" ] \
|| [ -n "$VPN_DNS_SRV1" ] || [ -n "$VPN_PROTECT_CONFIG" ] \
|| [ -n "$VPN_CLIENT_VALIDITY" ]; then
op_text=custom
fi
bigecho "Starting IKEv2 setup in auto mode, using $op_text options."
}
show_add_client() {
op_text=default
if [ -n "$VPN_CLIENT_VALIDITY" ]; then
op_text=custom
fi
bigecho "Adding a new IKEv2 client '$client_name', using $op_text options."
}
show_export_client() {
bigecho "Exporting IKEv2 client '$client_name'."
}
get_export_dir() {
export_to_home_dir=0
if grep -qs "hwdsl2" /opt/src/run.sh; then
export_dir="/etc/ipsec.d/"
else
export_dir=~/
if [ -n "$SUDO_USER" ] && getent group "$SUDO_USER" >/dev/null 2>&1; then
user_home_dir=$(getent passwd "$SUDO_USER" 2>/dev/null | cut -d: -f6)
if [ -d "$user_home_dir" ] && [ "$user_home_dir" != "/" ]; then
export_dir="$user_home_dir/"
export_to_home_dir=1
fi
fi
fi
}
get_default_ip() {
def_ip=$(ip -4 route get 1 | sed 's/ uid .*//' | awk '{print $NF;exit}' 2>/dev/null)
if check_ip "$def_ip" \
&& ! printf '%s' "$def_ip" | grep -Eq '^(10|127|172\.(1[6-9]|2[0-9]|3[0-1])|192\.168|169\.254)\.'; then
public_ip="$def_ip"
fi
}
get_server_ip() {
use_default_ip=0
public_ip=${VPN_PUBLIC_IP:-''}
check_ip "$public_ip" || get_default_ip
check_ip "$public_ip" && { use_default_ip=1; return 0; }
bigecho2 "Trying to auto discover IP of this server..."
check_ip "$public_ip" || public_ip=$(dig @resolver1.opendns.com -t A -4 myip.opendns.com +short)
check_ip "$public_ip" || public_ip=$(wget -t 2 -T 10 -qO- http://ipv4.icanhazip.com)
check_ip "$public_ip" || public_ip=$(wget -t 2 -T 10 -qO- http://ip1.dynupdate.no-ip.com)
}
get_server_address() {
server_addr=$(grep -s "leftcert=" "$IKEV2_CONF" | cut -f2 -d=)
[ -z "$server_addr" ] && server_addr=$(grep -s "leftcert=" "$IPSEC_CONF" | cut -f2 -d=)
check_ip "$server_addr" || check_dns_name "$server_addr" || exiterr "Could not get VPN server address."
}
list_existing_clients() {
echo "Checking for existing IKEv2 client(s)..."
echo
client_names=$(certutil -L -d "$CERT_DB" | grep -v -e '^$' -e "$CA_NAME" -e '\.' | tail -n +3 | cut -f1 -d ' ')
max_len=$(printf '%s\n' "$client_names" | wc -L 2>/dev/null)
[[ $max_len =~ ^[0-9]+$ ]] || max_len=64
[ "$max_len" -gt "64" ] && max_len=64
[ "$max_len" -lt "16" ] && max_len=16
printf "%-${max_len}s %s\n" 'Client Name' 'Certificate Status'
printf "%-${max_len}s %s\n" '------------' '-------------------'
if [ -n "$client_names" ]; then
client_list=$(printf '%s\n' "$client_names" | LC_ALL=C sort)
while IFS= read -r line; do
printf "%-${max_len}s " "$line"
client_status=$(certutil -V -u C -d "$CERT_DB" -n "$line" | grep -o -e ' valid' -e expired -e revoked | sed -e 's/^ //')
[ -z "$client_status" ] && client_status=unknown
printf '%s\n' "$client_status"
done <<< "$client_list"
fi
client_count=$(printf '%s\n' "$client_names" | wc -l 2>/dev/null)
[ -z "$client_names" ] && client_count=0
if [ "$client_count" = 1 ]; then
printf '\n%s\n' "Total: 1 client"
elif [ -n "$client_count" ]; then
printf '\n%s\n' "Total: $client_count clients"
fi
}
enter_server_address() {
echo "Do you want IKEv2 clients to connect to this server using a DNS name,"
printf "e.g. vpn.example.com, instead of its IP address? [y/N] "
read -r response
case $response in
[yY][eE][sS]|[yY])
use_dns_name=1
echo
;;
*)
use_dns_name=0
echo
;;
esac
if [ "$use_dns_name" = 1 ]; then
read -rp "Enter the DNS name of this VPN server: " server_addr
until check_dns_name "$server_addr"; do
echo "Invalid DNS name. You must enter a fully qualified domain name (FQDN)."
read -rp "Enter the DNS name of this VPN server: " server_addr
done
else
get_server_ip
[ "$use_default_ip" = 0 ] && { echo; echo; }
read -rp "Enter the IPv4 address of this VPN server: [$public_ip] " server_addr
[ -z "$server_addr" ] && server_addr="$public_ip"
until check_ip "$server_addr"; do
echo "Invalid IP address."
read -rp "Enter the IPv4 address of this VPN server: [$public_ip] " server_addr
[ -z "$server_addr" ] && server_addr="$public_ip"
done
fi
}
enter_client_name() {
echo
echo "Provide a name for the IKEv2 client."
echo "Use one word only, no special characters except '-' and '_'."
if [ "$1" = "with_defaults" ]; then
read -rp "Client name: [vpnclient] " client_name
[ -z "$client_name" ] && client_name=vpnclient
else
read -rp "Client name: " client_name
[ -z "$client_name" ] && abort_and_exit
fi
while ! check_client_name "$client_name" || check_cert_exists "$client_name"; do
if ! check_client_name "$client_name"; then
echo "Invalid client name."
else
echo "Invalid client name. Client '$client_name' already exists."
fi
if [ "$1" = "with_defaults" ]; then
read -rp "Client name: [vpnclient] " client_name
[ -z "$client_name" ] && client_name=vpnclient
else
read -rp "Client name: " client_name
[ -z "$client_name" ] && abort_and_exit
fi
done
}
enter_client_name_for() {
echo
list_existing_clients
if [ "$client_count" = 0 ]; then
echo
echo "No IKEv2 clients in the IPsec database. Nothing to $1." >&2
exit 1
fi
get_server_address
echo
read -rp "Enter the name of the IKEv2 client to $1: " client_name
[ -z "$client_name" ] && abort_and_exit
while ! check_client_name "$client_name" || [ "$client_name" = "$CA_NAME" ] \
|| [ "$client_name" = "$server_addr" ] || ! check_cert_exists "$client_name" \
|| ! check_cert_status "$client_name"; do
if ! check_client_name "$client_name" || [ "$client_name" = "$CA_NAME" ] \
|| [ "$client_name" = "$server_addr" ] || ! check_cert_exists "$client_name"; then
echo "Invalid client name, or client does not exist."
else
[ "$1" = "delete" ] && break
printf '%s' "Error: Certificate '$client_name' "
if printf '%s' "$cert_status" | grep -q "revoked"; then
if [ "$1" = "revoke" ]; then
echo "has already been revoked."
else
echo "has been revoked."
fi
elif printf '%s' "$cert_status" | grep -q "expired"; then
echo "has expired."
else
echo "is invalid."
fi
fi
read -rp "Enter the name of the IKEv2 client to $1: " client_name
[ -z "$client_name" ] && abort_and_exit
done
}
enter_client_validity() {
echo
echo "Specify the validity period (in months) for this client certificate."
read -rp "Enter an integer between 1 and 120: [120] " client_validity
[ -z "$client_validity" ] && client_validity=120
while ! check_client_validity "$client_validity"; do
echo "Invalid validity period."
read -rp "Enter an integer between 1 and 120: [120] " client_validity
[ -z "$client_validity" ] && client_validity=120
done
}
enter_custom_dns() {
echo
echo "By default, clients are set to use Google Public DNS when the VPN is active."
printf "Do you want to specify custom DNS servers for IKEv2? [y/N] "
read -r response
case $response in
[yY][eE][sS]|[yY])
use_custom_dns=1
;;
*)
use_custom_dns=0
dns_server_1=8.8.8.8
dns_server_2=8.8.4.4
dns_servers="8.8.8.8 8.8.4.4"
;;
esac
if [ "$use_custom_dns" = 1 ]; then
read -rp "Enter primary DNS server: " dns_server_1
until check_ip "$dns_server_1"; do
echo "Invalid DNS server."
read -rp "Enter primary DNS server: " dns_server_1
done
read -rp "Enter secondary DNS server (Enter to skip): " dns_server_2
until [ -z "$dns_server_2" ] || check_ip "$dns_server_2"; do
echo "Invalid DNS server."
read -rp "Enter secondary DNS server (Enter to skip): " dns_server_2
done
if [ -n "$dns_server_2" ]; then
dns_servers="$dns_server_1 $dns_server_2"
else
dns_servers="$dns_server_1"
fi
else
echo "Using Google Public DNS (8.8.8.8, 8.8.4.4)."
fi
echo
}
check_mobike_support() {
mobike_support=1
if uname -m | grep -qi -e '^arm' -e '^aarch64'; then
modprobe -q configs
if [ -f /proc/config.gz ]; then
if ! zcat /proc/config.gz | grep -q "CONFIG_XFRM_MIGRATE=y"; then
mobike_support=0
fi
else
mobike_support=0
fi
fi
kernel_conf="/boot/config-$(uname -r)"
if [ -f "$kernel_conf" ]; then
if ! grep -qs "CONFIG_XFRM_MIGRATE=y" "$kernel_conf"; then
mobike_support=0
fi
fi
# Linux kernels on Ubuntu do not support MOBIKE
if [ "$in_container" = 0 ]; then
if [ "$os_type" = "ubuntu" ] || uname -v | grep -qi ubuntu; then
mobike_support=0
fi
else
if uname -v | grep -qi ubuntu; then
mobike_support=0
fi
fi
if uname -a | grep -qi qnap; then
mobike_support=0
fi
if uname -a | grep -qi synology; then
mobike_support=0
fi
if [ "$mobike_support" = 1 ]; then
bigecho2 "Checking for MOBIKE support... available"
else
bigecho2 "Checking for MOBIKE support... not available"
fi
}
select_mobike() {
echo
mobike_enable=0
if [ "$mobike_support" = 1 ]; then
cat <<'EOF'
The MOBIKE IKEv2 extension allows VPN clients to change network attachment points,
e.g. switch between mobile data and Wi-Fi and keep the IPsec tunnel up on the new IP.
EOF
printf "Enable MOBIKE support? [Y/n] "
read -r response
case $response in
[yY][eE][sS]|[yY]|'')
mobike_enable=1
;;
*)
mobike_enable=0
;;
esac
fi
}
check_config_password() {
use_config_password=0
case $VPN_PROTECT_CONFIG in
[yY][eE][sS])
use_config_password=1
;;
*)
if grep -qs '^IKEV2_CONFIG_PASSWORD=.\+' "$CONF_FILE"; then
use_config_password=1
fi
;;
esac
}
select_config_password() {
if [ "$use_config_password" = 0 ]; then
cat <<'EOF'
IKEv2 client config files contain the client certificate, private key and CA certificate.
This script can optionally generate a random password to protect these files.
EOF
printf "Protect client config files using a password? [y/N] "
read -r response
case $response in
[yY][eE][sS]|[yY])
use_config_password=1
;;
*)
use_config_password=0
;;
esac
fi
}
select_menu_option() {
cat <<'EOF'
IKEv2 is already set up on this server.
Select an option:
1) Add a new client
2) Export config for an existing client
3) List existing clients
4) Revoke an existing client
5) Delete an existing client
6) Remove IKEv2
7) Exit
EOF
read -rp "Option: " selected_option
until [[ "$selected_option" =~ ^[1-7]$ ]]; do
printf '%s\n' "$selected_option: invalid selection."
read -rp "Option: " selected_option
done
}
print_server_info() {
cat <<EOF
VPN server address: $server_addr
EOF
}
confirm_setup_options() {
cat <<EOF
We are ready to set up IKEv2 now. Below are the setup options you selected.
======================================
Server address: $server_addr
Client name: $client_name
EOF
if [ "$client_validity" = 1 ]; then
echo "Client cert valid for: 1 month"
else
echo "Client cert valid for: $client_validity months"
fi
if [ "$mobike_support" = 1 ]; then
if [ "$mobike_enable" = 1 ]; then
echo "MOBIKE support: Enable"
else
echo "MOBIKE support: Disable"
fi
else
echo "MOBIKE support: Not available"
fi
if [ "$use_config_password" = 1 ]; then
echo "Protect client config: Yes"
else
echo "Protect client config: No"
fi
cat <<EOF
DNS server(s): $dns_servers
======================================
EOF
printf "Do you want to continue? [Y/n] "
read -r response
case $response in
[yY][eE][sS]|[yY]|'')
echo
;;
*)
abort_and_exit
;;
esac
}
create_client_cert() {
bigecho2 "Generating client certificate..."
sleep 1
certutil -z <(head -c 1024 /dev/urandom) \
-S -c "$CA_NAME" -n "$client_name" \
-s "O=IKEv2 VPN,CN=$client_name" \
-k rsa -g 3072 -v "$client_validity" \
-d "$CERT_DB" -t ",," \
--keyUsage digitalSignature,keyEncipherment \
--extKeyUsage serverAuth,clientAuth -8 "$client_name" >/dev/null 2>&1 || exiterr "Failed to create client certificate."
}
create_p12_password() {
p12_password=$(LC_CTYPE=C tr -dc 'A-HJ-NPR-Za-km-z2-9' </dev/urandom 2>/dev/null | head -c 18)
[ -z "$p12_password" ] && exiterr "Could not generate a random password for .p12 file."
}
get_p12_password() {
if [ "$use_config_password" = 0 ]; then
create_p12_password
else
p12_password=$(grep -s '^IKEV2_CONFIG_PASSWORD=.\+' "$CONF_FILE" | tail -n 1 | cut -f2- -d= | sed -e "s/^'//" -e "s/'$//")
if [ -z "$p12_password" ]; then
create_p12_password
if [ -n "$CONF_FILE" ] && [ -n "$CONF_DIR" ]; then
mkdir -p "$CONF_DIR"
printf '%s\n' "IKEV2_CONFIG_PASSWORD='$p12_password'" >> "$CONF_FILE"
chmod 600 "$CONF_FILE"
fi
fi
fi
}
export_p12_file() {
bigecho2 "Creating client configuration..."
get_p12_password
p12_file="$export_dir$client_name.p12"
p12_file_enc="$export_dir$client_name.enc.p12"
pk12util -W "$p12_password" -d "$CERT_DB" -n "$client_name" -o "$p12_file_enc" >/dev/null || exit 1
if [ "$os_ver" = "bookwormsid" ] || openssl version 2>/dev/null | grep -q "^OpenSSL 3"; then
ca_crt="$export_dir$client_name.ca.crt"
client_crt="$export_dir$client_name.client.crt"
client_key="$export_dir$client_name.client.key"
pem_file="$export_dir$client_name.temp.pem"
openssl pkcs12 -in "$p12_file_enc" -passin "pass:$p12_password" -cacerts -nokeys -out "$ca_crt" || exit 1
openssl pkcs12 -in "$p12_file_enc" -passin "pass:$p12_password" -clcerts -nokeys -out "$client_crt" || exit 1
openssl pkcs12 -in "$p12_file_enc" -passin "pass:$p12_password" -passout "pass:$p12_password" \
-nocerts -out "$client_key" || exit 1
cat "$client_key" "$client_crt" "$ca_crt" > "$pem_file"
/bin/rm -f "$client_key" "$client_crt" "$ca_crt"
openssl pkcs12 -keypbe PBE-SHA1-3DES -certpbe PBE-SHA1-3DES -export -in "$pem_file" -out "$p12_file_enc" \
-legacy -name "$client_name" -passin "pass:$p12_password" -passout "pass:$p12_password" || exit 1
if [ "$use_config_password" = 0 ]; then
openssl pkcs12 -keypbe PBE-SHA1-3DES -certpbe PBE-SHA1-3DES -export -in "$pem_file" -out "$p12_file" \
-legacy -name "$client_name" -passin "pass:$p12_password" -passout pass: || exit 1
fi
/bin/rm -f "$pem_file"
elif [ "$os_type" = "alpine" ] || [ "$os_ver" = "kalirolling" ] || [ "$os_ver" = "bullseyesid" ]; then
pem_file="$export_dir$client_name.temp.pem"
openssl pkcs12 -in "$p12_file_enc" -out "$pem_file" -passin "pass:$p12_password" -passout "pass:$p12_password" || exit 1
openssl pkcs12 -keypbe PBE-SHA1-3DES -certpbe PBE-SHA1-3DES -export -in "$pem_file" -out "$p12_file_enc" \
-name "$client_name" -passin "pass:$p12_password" -passout "pass:$p12_password" || exit 1
if [ "$use_config_password" = 0 ]; then
openssl pkcs12 -keypbe PBE-SHA1-3DES -certpbe PBE-SHA1-3DES -export -in "$pem_file" -out "$p12_file" \
-name "$client_name" -passin "pass:$p12_password" -passout pass: || exit 1
fi
/bin/rm -f "$pem_file"
elif [ "$use_config_password" = 0 ]; then
pk12util -W "" -d "$CERT_DB" -n "$client_name" -o "$p12_file" >/dev/null || exit 1
fi
if [ "$use_config_password" = 1 ]; then
/bin/cp -f "$p12_file_enc" "$p12_file"
fi
if [ "$export_to_home_dir" = 1 ]; then
chown "$SUDO_USER:$SUDO_USER" "$p12_file"
fi
chmod 600 "$p12_file"
}
install_base64_uuidgen() {
if ! command -v base64 >/dev/null 2>&1 || ! command -v uuidgen >/dev/null 2>&1; then
bigecho2 "Installing required packages..."
if [ "$os_type" = "ubuntu" ] || [ "$os_type" = "debian" ] || [ "$os_type" = "raspbian" ]; then
export DEBIAN_FRONTEND=noninteractive
apt-get -yqq update || apt-get -yqq update || exiterr "'apt-get update' failed."
fi
fi
if ! command -v base64 >/dev/null 2>&1; then
if [ "$os_type" = "ubuntu" ] || [ "$os_type" = "debian" ] || [ "$os_type" = "raspbian" ]; then
apt-get -yqq install coreutils >/dev/null || exiterr "'apt-get install' failed."
else
yum -y -q install coreutils >/dev/null || exiterr "'yum install' failed."
fi
fi
if ! command -v uuidgen >/dev/null 2>&1; then
if [ "$os_type" = "ubuntu" ] || [ "$os_type" = "debian" ] || [ "$os_type" = "raspbian" ]; then
apt-get -yqq install uuid-runtime >/dev/null || exiterr "'apt-get install' failed."
else
yum -y -q install util-linux >/dev/null || exiterr "'yum install' failed."
fi
fi
}
install_uuidgen() {
if ! command -v uuidgen >/dev/null 2>&1; then
bigecho2 "Installing required packages..."
apk add -U -q uuidgen || exiterr "'apk add' failed."
fi
}
update_ikev2_conf() {
if grep -qs 'ike=aes256-sha2,aes128-sha2,aes256-sha1,aes128-sha1$' "$IKEV2_CONF"; then
bigecho2 "Updating IKEv2 configuration..."
sed -i \
"/ike=aes256-sha2,aes128-sha2,aes256-sha1,aes128-sha1$/s/ike=/ike=aes_gcm_c_256-hmac_sha2_256-ecp_256,/" \
"$IKEV2_CONF"
if [ "$os_type" = "alpine" ]; then
ipsec auto --add ikev2-cp >/dev/null
else
restart_ipsec_service >/dev/null
fi
fi
}
create_mobileconfig() {
[ -z "$server_addr" ] && get_server_address
p12_file_enc="$export_dir$client_name.enc.p12"
p12_base64=$(base64 -w 52 "$p12_file_enc")
/bin/rm -f "$p12_file_enc"
[ -z "$p12_base64" ] && exiterr "Could not encode .p12 file."
ca_base64=$(certutil -L -d "$CERT_DB" -n "$CA_NAME" -a | grep -v CERTIFICATE)
[ -z "$ca_base64" ] && exiterr "Could not encode $CA_NAME certificate."
uuid1=$(uuidgen)
[ -z "$uuid1" ] && exiterr "Could not generate UUID value."
mc_file="$export_dir$client_name.mobileconfig"
cat > "$mc_file" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>PayloadContent</key>
<array>
<dict>
<key>IKEv2</key>
<dict>
<key>AuthenticationMethod</key>
<string>Certificate</string>
<key>ChildSecurityAssociationParameters</key>
<dict>
<key>DiffieHellmanGroup</key>
<integer>19</integer>
<key>EncryptionAlgorithm</key>
<string>AES-256-GCM</string>
<key>LifeTimeInMinutes</key>
<integer>1410</integer>
</dict>
<key>DeadPeerDetectionRate</key>
<string>Medium</string>
<key>DisableRedirect</key>
<true/>
<key>EnableCertificateRevocationCheck</key>
<integer>0</integer>
<key>EnablePFS</key>
<integer>0</integer>
<key>IKESecurityAssociationParameters</key>
<dict>
<key>DiffieHellmanGroup</key>
<integer>19</integer>
<key>EncryptionAlgorithm</key>
<string>AES-256-GCM</string>
<key>IntegrityAlgorithm</key>
<string>SHA2-256</string>
<key>LifeTimeInMinutes</key>
<integer>1410</integer>
</dict>
<key>LocalIdentifier</key>
<string>$client_name</string>
<key>PayloadCertificateUUID</key>
<string>$uuid1</string>
<key>OnDemandEnabled</key>
<integer>0</integer>
<key>OnDemandRules</key>
<array>
<dict>
<key>InterfaceTypeMatch</key>
<string>WiFi</string>
<key>URLStringProbe</key>
<string>http://captive.apple.com/hotspot-detect.html</string>
<key>Action</key>
<string>Connect</string>
</dict>
<dict>
<key>InterfaceTypeMatch</key>
<string>Cellular</string>
<key>Action</key>
<string>Disconnect</string>
</dict>
<dict>
<key>Action</key>
<string>Ignore</string>
</dict>
</array>
<key>RemoteAddress</key>
<string>$server_addr</string>
<key>RemoteIdentifier</key>
<string>$server_addr</string>
<key>UseConfigurationAttributeInternalIPSubnet</key>
<integer>0</integer>
</dict>
<key>IPv4</key>
<dict>
<key>OverridePrimary</key>
<integer>1</integer>
</dict>
<key>PayloadDescription</key>
<string>Configures VPN settings</string>
<key>PayloadDisplayName</key>
<string>VPN</string>
<key>PayloadOrganization</key>
<string>IKEv2 VPN</string>
<key>PayloadIdentifier</key>
<string>com.apple.vpn.managed.$(uuidgen)</string>
<key>PayloadType</key>