-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathopenvpn-install.sh
More file actions
executable file
·4572 lines (4067 loc) · 145 KB
/
openvpn-install.sh
File metadata and controls
executable file
·4572 lines (4067 loc) · 145 KB
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
# shellcheck disable=SC1091,SC2034
# SC1091: Not following /etc/os-release (sourced dynamically)
# SC2034: Variables used indirectly or exported for subprocesses
# Secure OpenVPN server installer for Debian, Ubuntu, CentOS, Amazon Linux 2023, Fedora, Oracle Linux, Arch Linux, Rocky Linux and AlmaLinux.
# https://github.com/angristan/openvpn-install
# Configuration constants
readonly DEFAULT_CERT_VALIDITY_DURATION_DAYS=3650 # 10 years
readonly DEFAULT_CRL_VALIDITY_DURATION_DAYS=5475 # 15 years
readonly EASYRSA_VERSION="3.2.6"
readonly EASYRSA_SHA256="c2572990ce91112eef8d1b8e4a3b58790da95b68501785c621f69121dfbd22d7"
# =============================================================================
# Logging Configuration
# =============================================================================
# Set VERBOSE=1 to see command output, VERBOSE=0 (default) for quiet mode
# Set LOG_FILE to customize log location (default: openvpn-install.log in current dir)
# Set LOG_FILE="" to disable file logging
VERBOSE=${VERBOSE:-0}
LOG_FILE=${LOG_FILE:-openvpn-install.log}
OUTPUT_FORMAT=${OUTPUT_FORMAT:-table} # table or json - json suppresses log output
# Color definitions (disabled if not a terminal, unless FORCE_COLOR=1)
if [[ -t 1 ]] || [[ $FORCE_COLOR == "1" ]]; then
readonly COLOR_RESET='\033[0m'
readonly COLOR_RED='\033[0;31m'
readonly COLOR_GREEN='\033[0;32m'
readonly COLOR_YELLOW='\033[0;33m'
readonly COLOR_BLUE='\033[0;34m'
readonly COLOR_CYAN='\033[0;36m'
readonly COLOR_DIM='\033[0;90m'
readonly COLOR_BOLD='\033[1m'
else
readonly COLOR_RESET=''
readonly COLOR_RED=''
readonly COLOR_GREEN=''
readonly COLOR_YELLOW=''
readonly COLOR_BLUE=''
readonly COLOR_CYAN=''
readonly COLOR_DIM=''
readonly COLOR_BOLD=''
fi
# Write to log file (no colors, with timestamp)
_log_to_file() {
if [[ -n "$LOG_FILE" ]]; then
echo "$(date '+%Y-%m-%d %H:%M:%S') $*" >>"$LOG_FILE"
fi
}
# Logging functions
log_info() {
[[ $OUTPUT_FORMAT == "json" ]] && return
echo -e "${COLOR_BLUE}[INFO]${COLOR_RESET} $*"
_log_to_file "[INFO] $*"
}
log_warn() {
[[ $OUTPUT_FORMAT == "json" ]] && return
echo -e "${COLOR_YELLOW}[WARN]${COLOR_RESET} $*"
_log_to_file "[WARN] $*"
}
log_error() {
echo -e "${COLOR_RED}[ERROR]${COLOR_RESET} $*" >&2
_log_to_file "[ERROR] $*"
if [[ -n "$LOG_FILE" ]]; then
echo -e "${COLOR_YELLOW} Check the log file for details: ${LOG_FILE}${COLOR_RESET}" >&2
fi
}
log_fatal() {
echo -e "${COLOR_RED}[ERROR]${COLOR_RESET} $*" >&2
_log_to_file "[FATAL] $*"
if [[ -n "$LOG_FILE" ]]; then
echo -e "${COLOR_YELLOW} Check the log file for details: ${LOG_FILE}${COLOR_RESET}" >&2
_log_to_file "Script exited with error"
fi
exit 1
}
log_success() {
[[ $OUTPUT_FORMAT == "json" ]] && return
echo -e "${COLOR_GREEN}[OK]${COLOR_RESET} $*"
_log_to_file "[OK] $*"
}
log_debug() {
if [[ $VERBOSE -eq 1 && $OUTPUT_FORMAT != "json" ]]; then
echo -e "${COLOR_DIM}[DEBUG]${COLOR_RESET} $*"
fi
_log_to_file "[DEBUG] $*"
}
log_prompt() {
# For user-facing prompts/questions (no prefix, just cyan)
# Skip display in non-interactive mode
if [[ $NON_INTERACTIVE_INSTALL != "y" ]]; then
echo -e "${COLOR_CYAN}$*${COLOR_RESET}"
fi
_log_to_file "[PROMPT] $*"
}
log_header() {
# For section headers
# Skip display in non-interactive mode
if [[ $NON_INTERACTIVE_INSTALL != "y" ]]; then
echo ""
echo -e "${COLOR_BOLD}${COLOR_BLUE}=== $* ===${COLOR_RESET}"
echo ""
fi
_log_to_file "=== $* ==="
}
log_menu() {
# For menu options - only show in interactive mode
if [[ $NON_INTERACTIVE_INSTALL != "y" ]]; then
echo "$@"
fi
}
# Run a command with optional output suppression
# Usage: run_cmd "description" command [args...]
run_cmd() {
local desc="$1"
shift
# Display the command being run
echo -e "${COLOR_DIM}> $*${COLOR_RESET}"
_log_to_file "[CMD] $*"
if [[ $VERBOSE -eq 1 ]]; then
if [[ -n "$LOG_FILE" ]]; then
"$@" 2>&1 | tee -a "$LOG_FILE"
else
"$@"
fi
else
if [[ -n "$LOG_FILE" ]]; then
"$@" >>"$LOG_FILE" 2>&1
else
"$@" >/dev/null 2>&1
fi
fi
local ret=$?
if [[ $ret -eq 0 ]]; then
log_debug "$desc completed successfully"
else
log_error "$desc failed with exit code $ret"
fi
return $ret
}
# Run a command that must succeed, exit on failure
# Usage: run_cmd_fatal "description" command [args...]
run_cmd_fatal() {
local desc="$1"
shift
if ! run_cmd "$desc" "$@"; then
log_fatal "$desc failed"
fi
}
# =============================================================================
# CLI Configuration
# =============================================================================
readonly SCRIPT_NAME="openvpn-install"
# =============================================================================
# Help Text Functions
# =============================================================================
show_help() {
cat <<-EOF
OpenVPN installer and manager
Usage: $SCRIPT_NAME <command> [options]
Commands:
install Install and configure OpenVPN server
uninstall Remove OpenVPN server
client Manage client certificates
server Server management
interactive Launch interactive menu
Global Options:
--verbose Show detailed output
--log <path> Log file path (default: openvpn-install.log)
--no-log Disable file logging
--no-color Disable colored output
-h, --help Show help
Run '$SCRIPT_NAME <command> --help' for command-specific help.
EOF
}
show_install_help() {
cat <<-EOF
Install and configure OpenVPN server
Usage: $SCRIPT_NAME install [options]
Options:
-i, --interactive Run interactive install wizard
Network Options:
--endpoint <host> Public IP or hostname for clients (auto-detected)
--endpoint-type <4|6> Endpoint IP version: 4 or 6 (default: 4)
--ip <addr> Server listening IP (auto-detected)
--client-ipv4 Enable IPv4 for VPN clients (default: enabled)
--no-client-ipv4 Disable IPv4 for VPN clients
--client-ipv6 Enable IPv6 for VPN clients
--no-client-ipv6 Disable IPv6 for VPN clients (default)
--subnet-ipv4 <x.x.x.0> IPv4 VPN subnet (default: 10.8.0.0)
--subnet-ipv6 <prefix> IPv6 VPN subnet (default: fd42:42:42:42::)
--port <num> OpenVPN port (default: 1194)
--port-random Use random port (49152-65535)
--protocol <proto> Protocol: udp or tcp (default: udp)
--mtu <size> Tunnel MTU (default: 1500)
DNS Options:
--dns <provider> DNS provider (default: cloudflare)
Providers: system, unbound, cloudflare, quad9, quad9-uncensored,
fdn, dnswatch, opendns, google, yandex, adguard, nextdns, custom
--dns-primary <ip> Custom primary DNS (requires --dns custom)
--dns-secondary <ip> Custom secondary DNS (optional)
Security Options:
--cipher <cipher> Data channel cipher (default: AES-128-GCM)
Ciphers: AES-128-GCM, AES-192-GCM, AES-256-GCM, AES-128-CBC,
AES-192-CBC, AES-256-CBC, CHACHA20-POLY1305
--cert-type <type> Certificate type: ecdsa or rsa (default: ecdsa)
--cert-curve <curve> ECDSA curve (default: prime256v1)
Curves: prime256v1, secp384r1, secp521r1
--rsa-bits <size> RSA key size: 2048, 3072, 4096 (default: 2048)
--cc-cipher <cipher> Control channel cipher (auto-selected)
--tls-version-min <ver> Minimum TLS version: 1.2 or 1.3 (default: 1.2)
--tls-ciphersuites <list> TLS 1.3 cipher suites, colon-separated
--tls-groups <list> Key exchange groups, colon-separated
(default: X25519:prime256v1:secp384r1:secp521r1)
--hmac <alg> HMAC algorithm: SHA256, SHA384, SHA512 (default: SHA256)
--tls-sig <mode> TLS mode: crypt-v2, crypt, auth (default: crypt-v2)
--auth-mode <mode> Auth mode: pki, fingerprint (default: pki)
fingerprint requires OpenVPN 2.6+
--server-cert-days <n> Server cert validity in days (default: 3650)
Other Options:
--multi-client Allow same cert on multiple devices
Initial Client Options:
--client <name> Initial client name (default: client)
--client-password [p] Password-protect client (prompts if no value given)
--client-cert-days <n> Client cert validity in days (default: 3650)
--no-client Skip initial client creation
Examples:
$SCRIPT_NAME install
$SCRIPT_NAME install --port 443 --protocol tcp
$SCRIPT_NAME install --dns quad9 --cipher AES-256-GCM
$SCRIPT_NAME install -i
EOF
}
show_uninstall_help() {
cat <<-EOF
Remove OpenVPN server
Usage: $SCRIPT_NAME uninstall [options]
Options:
-f, --force Skip confirmation prompt
Examples:
$SCRIPT_NAME uninstall
$SCRIPT_NAME uninstall --force
EOF
}
show_client_help() {
cat <<-EOF
Manage client certificates
Usage: $SCRIPT_NAME client <subcommand> [options]
Subcommands:
add <name> Add a new client
list List all clients
revoke <name> Revoke a client certificate
renew <name> Renew a client certificate
Run '$SCRIPT_NAME client <subcommand> --help' for more info.
EOF
}
show_client_add_help() {
cat <<-EOF
Add a new VPN client
Usage: $SCRIPT_NAME client add <name> [options]
Options:
--password [pass] Password-protect client (prompts if no value given)
--cert-days <n> Certificate validity in days (default: 3650)
--output <path> Output path for .ovpn file (default: ~/<name>.ovpn)
Examples:
$SCRIPT_NAME client add alice
$SCRIPT_NAME client add bob --password
$SCRIPT_NAME client add charlie --cert-days 365 --output /tmp/charlie.ovpn
EOF
}
show_client_list_help() {
cat <<-EOF
List all client certificates
Usage: $SCRIPT_NAME client list [options]
Options:
--format <fmt> Output format: table or json (default: table)
Examples:
$SCRIPT_NAME client list
$SCRIPT_NAME client list --format json
EOF
}
show_client_revoke_help() {
cat <<-EOF
Revoke a client certificate
Usage: $SCRIPT_NAME client revoke <name> [options]
Options:
-f, --force Skip confirmation prompt
Examples:
$SCRIPT_NAME client revoke alice
$SCRIPT_NAME client revoke bob --force
EOF
}
show_client_renew_help() {
cat <<-EOF
Renew a client certificate
Usage: $SCRIPT_NAME client renew <name> [options]
Options:
--cert-days <n> New certificate validity in days (default: 3650)
Examples:
$SCRIPT_NAME client renew alice
$SCRIPT_NAME client renew bob --cert-days 365
EOF
}
show_server_help() {
cat <<-EOF
Server management
Usage: $SCRIPT_NAME server <subcommand> [options]
Subcommands:
status List currently connected clients
renew Renew server certificate
Run '$SCRIPT_NAME server <subcommand> --help' for more info.
EOF
}
show_server_status_help() {
cat <<-EOF
List currently connected clients
Note: Client data is updated every 60 seconds by OpenVPN.
Usage: $SCRIPT_NAME server status [options]
Options:
--format <fmt> Output format: table or json (default: table)
Examples:
$SCRIPT_NAME server status
$SCRIPT_NAME server status --format json
EOF
}
show_server_renew_help() {
cat <<-EOF
Renew server certificate
Usage: $SCRIPT_NAME server renew [options]
Options:
--cert-days <n> New certificate validity in days (default: 3650)
-f, --force Skip confirmation/warning
Examples:
$SCRIPT_NAME server renew
$SCRIPT_NAME server renew --cert-days 1825
EOF
}
# =============================================================================
# CLI Command Handlers
# =============================================================================
# Check if OpenVPN is installed
isOpenVPNInstalled() {
[[ -e /etc/openvpn/server/server.conf ]]
}
# Require OpenVPN to be installed
requireOpenVPN() {
if ! isOpenVPNInstalled; then
log_fatal "OpenVPN is not installed. Run '$SCRIPT_NAME install' first."
fi
}
# Require OpenVPN to NOT be installed
requireNoOpenVPN() {
if isOpenVPNInstalled; then
log_fatal "OpenVPN is already installed. Use '$SCRIPT_NAME client' to manage clients or '$SCRIPT_NAME uninstall' to remove."
fi
}
# Parse DNS provider string to DNS number
parse_dns_provider() {
case "$1" in
system | unbound | cloudflare | quad9 | quad9-uncensored | fdn | dnswatch | opendns | google | yandex | adguard | nextdns | custom)
DNS="$1"
;;
*) log_fatal "Invalid DNS provider: $1. See '$SCRIPT_NAME install --help' for valid providers." ;;
esac
}
# Parse cipher string
parse_cipher() {
case "$1" in
AES-128-GCM | AES-192-GCM | AES-256-GCM | AES-128-CBC | AES-192-CBC | AES-256-CBC | CHACHA20-POLY1305)
CIPHER="$1"
;;
*) log_fatal "Invalid cipher: $1. See '$SCRIPT_NAME install --help' for valid ciphers." ;;
esac
}
# Parse curve string
parse_curve() {
case "$1" in
prime256v1 | secp384r1 | secp521r1) echo "$1" ;;
*) log_fatal "Invalid curve: $1. Valid curves: prime256v1, secp384r1, secp521r1" ;;
esac
}
# =============================================================================
# Configuration Constants
# =============================================================================
# Protocol options
readonly PROTOCOLS=("udp" "tcp")
# DNS providers (use string names)
readonly DNS_PROVIDERS=("system" "unbound" "cloudflare" "quad9" "quad9-uncensored" "fdn" "dnswatch" "opendns" "google" "yandex" "adguard" "nextdns" "custom")
# Cipher options
readonly CIPHERS=("AES-128-GCM" "AES-192-GCM" "AES-256-GCM" "AES-128-CBC" "AES-192-CBC" "AES-256-CBC" "CHACHA20-POLY1305")
# Certificate types (use strings)
readonly CERT_TYPES=("ecdsa" "rsa")
# ECDSA curves
readonly CERT_CURVES=("prime256v1" "secp384r1" "secp521r1")
# RSA key sizes
readonly RSA_KEY_SIZES=("2048" "3072" "4096")
# TLS versions
readonly TLS_VERSIONS=("1.2" "1.3")
# TLS signature modes (use strings)
readonly TLS_SIG_MODES=("crypt-v2" "crypt" "auth")
# Authentication modes: pki (CA-based) or fingerprint (peer-fingerprint, OpenVPN 2.6+)
readonly AUTH_MODES=("pki" "fingerprint")
# HMAC algorithms
readonly HMAC_ALGS=("SHA256" "SHA384" "SHA512")
# TLS 1.3 cipher suite options
readonly TLS13_OPTIONS=("all" "aes-256-only" "aes-128-only" "chacha20-only")
# TLS groups options
readonly TLS_GROUPS_OPTIONS=("all" "x25519-only" "nist-only")
# =============================================================================
# Set Installation Defaults
# =============================================================================
# Centralized function to set all defaults - called before configuration
set_installation_defaults() {
# Network
ENDPOINT_TYPE="${ENDPOINT_TYPE:-4}"
CLIENT_IPV4="${CLIENT_IPV4:-y}"
CLIENT_IPV6="${CLIENT_IPV6:-n}"
VPN_SUBNET_IPV4="${VPN_SUBNET_IPV4:-10.8.0.0}"
VPN_SUBNET_IPV6="${VPN_SUBNET_IPV6:-fd42:42:42:42::}"
PORT="${PORT:-1194}"
PROTOCOL="${PROTOCOL:-udp}"
# DNS (use string name)
DNS="${DNS:-cloudflare}"
# Multi-client
MULTI_CLIENT="${MULTI_CLIENT:-n}"
# Encryption
CIPHER="${CIPHER:-AES-128-GCM}"
CERT_TYPE="${CERT_TYPE:-ecdsa}"
CERT_CURVE="${CERT_CURVE:-prime256v1}"
RSA_KEY_SIZE="${RSA_KEY_SIZE:-2048}"
TLS_VERSION_MIN="${TLS_VERSION_MIN:-1.2}"
TLS13_CIPHERSUITES="${TLS13_CIPHERSUITES:-TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256}"
TLS_GROUPS="${TLS_GROUPS:-X25519:prime256v1:secp384r1:secp521r1}"
HMAC_ALG="${HMAC_ALG:-SHA256}"
TLS_SIG="${TLS_SIG:-crypt-v2}"
AUTH_MODE="${AUTH_MODE:-pki}"
# Derive CC_CIPHER from CERT_TYPE if not set
if [[ -z $CC_CIPHER ]]; then
if [[ $CERT_TYPE == "ecdsa" ]]; then
CC_CIPHER="TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256"
else
CC_CIPHER="TLS-ECDHE-RSA-WITH-AES-128-GCM-SHA256"
fi
fi
# Client
CLIENT="${CLIENT:-client}"
PASS="${PASS:-1}"
CLIENT_CERT_DURATION_DAYS="${CLIENT_CERT_DURATION_DAYS:-$DEFAULT_CERT_VALIDITY_DURATION_DAYS}"
SERVER_CERT_DURATION_DAYS="${SERVER_CERT_DURATION_DAYS:-$DEFAULT_CERT_VALIDITY_DURATION_DAYS}"
# Note: Gateway values (VPN_GATEWAY_IPV4, VPN_GATEWAY_IPV6) and IPV6_SUPPORT
# are computed in prepare_network_config() which is called after validation
}
# Version comparison: returns 0 if version1 >= version2
version_ge() {
local ver1="$1" ver2="$2"
# Use sort -V for version comparison
[[ "$(printf '%s\n%s' "$ver1" "$ver2" | sort -V | head -n1)" == "$ver2" ]]
}
# Get installed OpenVPN version (e.g., "2.6.12")
get_openvpn_version() {
openvpn --version 2>/dev/null | head -1 | awk '{print $2}'
}
# Validation functions
validate_port() {
local port="$1"
if ! [[ "$port" =~ ^[0-9]+$ ]] || [[ "$port" -lt 1 ]] || [[ "$port" -gt 65535 ]]; then
log_fatal "Invalid port: $port. Must be a number between 1 and 65535."
fi
}
validate_subnet_ipv4() {
local subnet="$1"
# Check format: x.x.x.0 where x is 0-255
if ! [[ "$subnet" =~ ^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.0$ ]]; then
log_fatal "Invalid IPv4 subnet: $subnet. Must be in format x.x.x.0 (e.g., 10.8.0.0)"
fi
local octet1="${BASH_REMATCH[1]}"
local octet2="${BASH_REMATCH[2]}"
local octet3="${BASH_REMATCH[3]}"
# Validate each octet is 0-255
if [[ "$octet1" -gt 255 ]] || [[ "$octet2" -gt 255 ]] || [[ "$octet3" -gt 255 ]]; then
log_fatal "Invalid IPv4 subnet: $subnet. Octets must be 0-255."
fi
# Check for RFC1918 private address ranges
if ! { [[ "$octet1" -eq 10 ]] ||
[[ "$octet1" -eq 172 && "$octet2" -ge 16 && "$octet2" -le 31 ]] ||
[[ "$octet1" -eq 192 && "$octet2" -eq 168 ]]; }; then
log_fatal "Invalid IPv4 subnet: $subnet. Must be a private network (10.x.x.0, 172.16-31.x.0, or 192.168.x.0)."
fi
}
validate_subnet_ipv6() {
local subnet="$1"
# Accept format: IPv6 address ending with :: (prefix only, no CIDR notation here)
# We expect formats like: fd42:42:42:42:: or fdxx:xxxx:xxxx:xxxx::
# The script will append /112 for the server directive
# IPv6 ULA validation (fd00::/8 range with at least /48 prefix)
# ULA format: fdxx:xxxx:xxxx:: or fdxx:xxxx:xxxx:xxxx:: where x is hex
if ! [[ "$subnet" =~ ^fd[0-9a-fA-F]{2}(:[0-9a-fA-F]{1,4}){2,5}::$ ]]; then
log_fatal "Invalid IPv6 subnet: $subnet. Must be a ULA address with at least a /48 prefix, ending with :: (e.g., fd42:42:42::)"
fi
}
validate_positive_int() {
local value="$1"
local name="$2"
if ! [[ "$value" =~ ^[0-9]+$ ]] || [[ "$value" -lt 1 ]]; then
log_fatal "Invalid $name: $value. Must be a positive integer."
fi
}
validate_mtu() {
local mtu="$1"
if ! [[ "$mtu" =~ ^[0-9]+$ ]] || [[ "$mtu" -lt 576 ]] || [[ "$mtu" -gt 65535 ]]; then
log_fatal "Invalid MTU: $mtu. Must be between 576 and 65535."
fi
}
# Maximum length for client names (OpenSSL CN limit)
readonly MAX_CLIENT_NAME_LENGTH=64
# Check if client name is valid (non-fatal, returns true/false)
is_valid_client_name() {
local name="$1"
[[ "$name" =~ ^[a-zA-Z0-9_-]+$ ]] && [[ ${#name} -le $MAX_CLIENT_NAME_LENGTH ]]
}
# Validate client name and exit with error if invalid
validate_client_name() {
local name="$1"
if [[ -z "$name" ]]; then
log_fatal "Client name cannot be empty."
fi
if ! [[ "$name" =~ ^[a-zA-Z0-9_-]+$ ]]; then
log_fatal "Invalid client name: $name. Only alphanumeric characters, underscores, and hyphens are allowed."
fi
if [[ ${#name} -gt $MAX_CLIENT_NAME_LENGTH ]]; then
log_fatal "Client name too long: ${#name} characters. Maximum is $MAX_CLIENT_NAME_LENGTH characters (OpenSSL CN limit)."
fi
}
# Validate all configuration values (catches invalid env vars in non-interactive mode)
validate_configuration() {
# Validate PROTOCOL
case "$PROTOCOL" in
udp | tcp) ;;
*) log_fatal "Invalid protocol: $PROTOCOL. Must be 'udp' or 'tcp'." ;;
esac
# Validate DNS
case "$DNS" in
system | unbound | cloudflare | quad9 | quad9-uncensored | fdn | dnswatch | opendns | google | yandex | adguard | nextdns | custom) ;;
*) log_fatal "Invalid DNS provider: $DNS. Valid providers: system, unbound, cloudflare, quad9, quad9-uncensored, fdn, dnswatch, opendns, google, yandex, adguard, nextdns, custom" ;;
esac
# Validate CERT_TYPE
case "$CERT_TYPE" in
ecdsa | rsa) ;;
*) log_fatal "Invalid cert type: $CERT_TYPE. Must be 'ecdsa' or 'rsa'." ;;
esac
# Validate TLS_SIG
case "$TLS_SIG" in
crypt-v2 | crypt | auth) ;;
*) log_fatal "Invalid TLS signature mode: $TLS_SIG. Must be 'crypt-v2', 'crypt', or 'auth'." ;;
esac
# Validate AUTH_MODE
case "$AUTH_MODE" in
pki | fingerprint) ;;
*) log_fatal "Invalid auth mode: $AUTH_MODE. Must be 'pki' or 'fingerprint'." ;;
esac
# Fingerprint mode requires OpenVPN 2.6+
if [[ $AUTH_MODE == "fingerprint" ]]; then
local openvpn_ver
openvpn_ver=$(get_openvpn_version)
if [[ -n "$openvpn_ver" ]] && ! version_ge "$openvpn_ver" "2.6.0"; then
log_fatal "Fingerprint mode requires OpenVPN 2.6.0 or later. Installed version: $openvpn_ver"
fi
fi
# Validate PORT
if ! [[ "$PORT" =~ ^[0-9]+$ ]] || [[ "$PORT" -lt 1 ]] || [[ "$PORT" -gt 65535 ]]; then
log_fatal "Invalid port: $PORT. Must be a number between 1 and 65535."
fi
# Validate CLIENT_IPV4/CLIENT_IPV6
if [[ $CLIENT_IPV4 != "y" ]] && [[ $CLIENT_IPV6 != "y" ]]; then
log_fatal "At least one of CLIENT_IPV4 or CLIENT_IPV6 must be 'y'"
fi
# Validate ENDPOINT_TYPE
case "$ENDPOINT_TYPE" in
4 | 6) ;;
*) log_fatal "Invalid endpoint type: $ENDPOINT_TYPE. Must be '4' or '6'." ;;
esac
# Validate CIPHER
case "$CIPHER" in
AES-128-GCM | AES-192-GCM | AES-256-GCM | AES-128-CBC | AES-192-CBC | AES-256-CBC | CHACHA20-POLY1305) ;;
*) log_fatal "Invalid cipher: $CIPHER. Valid ciphers: AES-128-GCM, AES-192-GCM, AES-256-GCM, AES-128-CBC, AES-192-CBC, AES-256-CBC, CHACHA20-POLY1305" ;;
esac
# Validate CERT_CURVE (only if ECDSA)
if [[ $CERT_TYPE == "ecdsa" ]]; then
case "$CERT_CURVE" in
prime256v1 | secp384r1 | secp521r1) ;;
*) log_fatal "Invalid cert curve: $CERT_CURVE. Must be 'prime256v1', 'secp384r1', or 'secp521r1'." ;;
esac
fi
# Validate RSA_KEY_SIZE (only if RSA)
if [[ $CERT_TYPE == "rsa" ]]; then
case "$RSA_KEY_SIZE" in
2048 | 3072 | 4096) ;;
*) log_fatal "Invalid RSA key size: $RSA_KEY_SIZE. Must be 2048, 3072, or 4096." ;;
esac
fi
# Validate TLS_VERSION_MIN
case "$TLS_VERSION_MIN" in
1.2 | 1.3) ;;
*) log_fatal "Invalid TLS version: $TLS_VERSION_MIN. Must be '1.2' or '1.3'." ;;
esac
# Validate HMAC_ALG
case "$HMAC_ALG" in
SHA256 | SHA384 | SHA512) ;;
*) log_fatal "Invalid HMAC algorithm: $HMAC_ALG. Must be SHA256, SHA384, or SHA512." ;;
esac
# Validate MTU if set
if [[ -n $MTU ]]; then
if ! [[ "$MTU" =~ ^[0-9]+$ ]] || [[ "$MTU" -lt 576 ]] || [[ "$MTU" -gt 65535 ]]; then
log_fatal "Invalid MTU: $MTU. Must be a number between 576 and 65535."
fi
fi
# Validate custom DNS if selected
if [[ $DNS == "custom" ]] && [[ -z $DNS1 ]]; then
log_fatal "Custom DNS selected but DNS1 (primary DNS) is not set. Use --dns-primary to specify."
fi
# Validate VPN subnets using the dedicated validation functions
# These check format, octet ranges, and RFC1918/ULA compliance
if [[ -n $VPN_SUBNET_IPV4 ]]; then
validate_subnet_ipv4 "$VPN_SUBNET_IPV4"
fi
if [[ $CLIENT_IPV6 == "y" ]] && [[ -n $VPN_SUBNET_IPV6 ]]; then
validate_subnet_ipv6 "$VPN_SUBNET_IPV6"
fi
}
# =============================================================================
# Interactive Helper Functions
# =============================================================================
# Generic select-from-menu function for arrays
# Usage: select_from_array "prompt" array_name "default_value" result_var
# Note: Uses namerefs (-n) for arrays
select_from_array() {
local prompt="$1"
local -n _options_ref="$2"
local default="$3"
local -n _result_ref="$4"
# If already set (non-interactive mode), just return
if [[ -n $_result_ref ]]; then
return
fi
# Find default index (1-based for display)
local default_idx=1
for i in "${!_options_ref[@]}"; do
if [[ "${_options_ref[$i]}" == "$default" ]]; then
default_idx=$((i + 1))
break
fi
done
# Display menu
local count=${#_options_ref[@]}
for i in "${!_options_ref[@]}"; do
log_menu " $((i + 1))) ${_options_ref[$i]}"
done
# Read selection
local choice
until [[ $choice =~ ^[0-9]+$ ]] && ((choice >= 1 && choice <= count)); do
read -rp "$prompt [1-$count]: " -e -i "$default_idx" choice
done
_result_ref="${_options_ref[$((choice - 1))]}"
}
# Select with custom labels (for menu items that need different display text)
# Usage: select_with_labels "prompt" labels_array values_array "default_value" result_var
select_with_labels() {
local prompt="$1"
local -n _labels_ref="$2"
local -n _values_ref="$3"
local default="$4"
local -n _result_ref="$5"
# If already set (non-interactive mode), just return
if [[ -n $_result_ref ]]; then
return
fi
# Find default index
local default_idx=1
for i in "${!_values_ref[@]}"; do
if [[ "${_values_ref[$i]}" == "$default" ]]; then
default_idx=$((i + 1))
break
fi
done
# Display menu
local count=${#_labels_ref[@]}
for i in "${!_labels_ref[@]}"; do
log_menu " $((i + 1))) ${_labels_ref[$i]}"
done
# Read selection
local choice
until [[ $choice =~ ^[0-9]+$ ]] && ((choice >= 1 && choice <= count)); do
read -rp "$prompt [1-$count]: " -e -i "$default_idx" choice
done
_result_ref="${_values_ref[$((choice - 1))]}"
}
# Prompt for yes/no with default
# Usage: prompt_yes_no "prompt" "default" result_var
prompt_yes_no() {
local prompt="$1"
local default="$2"
local -n _result_ref="$3"
# If already set, just return
if [[ $_result_ref =~ ^[yn]$ ]]; then
return
fi
until [[ $_result_ref =~ ^[yn]$ ]]; do
read -rp "$prompt [y/n]: " -e -i "$default" _result_ref
done
}
# Prompt for a value with validation function
# Usage: prompt_validated "prompt" "validator_func" "default" result_var
# The validator should return 0 for valid, non-0 for invalid
prompt_validated() {
local prompt="$1"
local validator="$2"
local default="$3"
local -n _result_ref="$4"
# If already set and valid, return
if [[ -n $_result_ref ]] && $validator "$_result_ref" 2>/dev/null; then
return
fi
_result_ref=""
until [[ -n $_result_ref ]] && $validator "$_result_ref" 2>/dev/null; do
read -rp "$prompt: " -e -i "$default" _result_ref
done
}
# Non-fatal port validator (returns 0/1)
is_valid_port() {
local port="$1"
[[ "$port" =~ ^[0-9]+$ ]] && ((port >= 1 && port <= 65535))
}
# Non-fatal MTU validator (returns 0/1)
is_valid_mtu() {
local mtu="$1"
[[ "$mtu" =~ ^[0-9]+$ ]] && ((mtu >= 576 && mtu <= 65535))
}
# Handle install command
cmd_install() {
local interactive=false
local no_client=false
local client_password_flag=false
local client_password_value=""
while [[ $# -gt 0 ]]; do
case "$1" in
-i | --interactive)
interactive=true
shift
;;
--endpoint)
[[ -z "${2:-}" ]] && log_fatal "--endpoint requires an argument"
ENDPOINT="$2"
shift 2
;;
--ip)
[[ -z "${2:-}" ]] && log_fatal "--ip requires an argument"
IP="$2"
APPROVE_IP=y
shift 2
;;
--endpoint-type)
[[ -z "${2:-}" ]] && log_fatal "--endpoint-type requires an argument"
case "$2" in
4) ENDPOINT_TYPE="4" ;;
6) ENDPOINT_TYPE="6" ;;
*) log_fatal "Invalid endpoint type: $2. Use '4' or '6'." ;;
esac
shift 2
;;
--client-ipv4)
CLIENT_IPV4=y
shift
;;
--no-client-ipv4)
CLIENT_IPV4=n
shift
;;
--client-ipv6)
CLIENT_IPV6=y
shift
;;
--no-client-ipv6)
CLIENT_IPV6=n
shift
;;
--ipv6)
# Legacy flag: enable IPv6 for clients (backward compatibility)
CLIENT_IPV6=y
shift
;;
--subnet-ipv4)
[[ -z "${2:-}" ]] && log_fatal "--subnet-ipv4 requires an argument"
validate_subnet_ipv4 "$2"
VPN_SUBNET_IPV4="$2"
shift 2
;;
--subnet-ipv6)
[[ -z "${2:-}" ]] && log_fatal "--subnet-ipv6 requires an argument"
validate_subnet_ipv6 "$2"
VPN_SUBNET_IPV6="$2"
shift 2
;;
--subnet)
# Legacy flag: --subnet now maps to --subnet-ipv4
[[ -z "${2:-}" ]] && log_fatal "--subnet requires an argument"
validate_subnet_ipv4 "$2"
VPN_SUBNET_IPV4="$2"
shift 2
;;
--port)
[[ -z "${2:-}" ]] && log_fatal "--port requires an argument"
validate_port "$2"
PORT="$2"
shift 2
;;
--port-random)
PORT="random"
shift
;;
--protocol)
[[ -z "${2:-}" ]] && log_fatal "--protocol requires an argument"
case "$2" in
udp | tcp)
PROTOCOL="$2"
;;
*) log_fatal "Invalid protocol: $2. Use 'udp' or 'tcp'." ;;
esac
shift 2
;;
--mtu)
[[ -z "${2:-}" ]] && log_fatal "--mtu requires an argument"
validate_mtu "$2"
MTU="$2"
shift 2
;;
--dns)
[[ -z "${2:-}" ]] && log_fatal "--dns requires an argument"
parse_dns_provider "$2"
shift 2
;;
--dns-primary)
[[ -z "${2:-}" ]] && log_fatal "--dns-primary requires an argument"
DNS1="$2"
shift 2
;;
--dns-secondary)
[[ -z "${2:-}" ]] && log_fatal "--dns-secondary requires an argument"
DNS2="$2"
shift 2
;;
--multi-client)
MULTI_CLIENT=y
shift
;;
--cipher)
[[ -z "${2:-}" ]] && log_fatal "--cipher requires an argument"
parse_cipher "$2"
CUSTOMIZE_ENC=y