forked from MartineauUK/wireguard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wg_manager.sh
8412 lines (7104 loc) · 432 KB
/
wg_manager.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/sh
# shellcheck disable=SC2039,SC2155,SC2124,SC2046,SC2027
VERSION="v4.18"
#============================================================================================ © 2021-2022 Martineau v4.18
#
# wgm [ help | -h ]
# wgm [ { start | stop | restart } [wg_interface]... ]
# wgm [ list | show | ? | diag | import {xxxxx[.conf]} | uninstall ]
# wgm [ menu { hide | show } ] [ colo[u]r { off | on } ]
#
# wgm
# Enter/use the interactive menu-driven wireguard_manager© (wgm) command line interface
# wgm start
# Initialises ALL 'client'/'server' Peers that have AUTO=Y or AUTO=P or AUTO=S
# wgm stop
# Terminates ALL ACTIVE 'client'/'server' Peers
# wgm start wg11
# Initialises 'client' Peer wg11
# wgm start wg14 wg21
# Initialises 'server' Peer wg21 and 'client' Peer wg14
# wgm restart wg12
# ReInitialises 'client' Peer wg12 (i.e. issues stop wg12;start wg12)
# wgm list
# Displays ACTIVE Peers
# wgm ?
# Displays current wireguard_manager© settings such as WireGuard® Kernel Module version number, clickable URLs e.g. Change Log/Hints and Tips etc.
# wgm diag
# Displays Diagnostic dump of SQL defined Database Peers, firewall/RPDB/routing rules etc.
# wgm import Mullvad_NewYork.conf
# Import Vendor generated WireGuard® profile '/opt/etc/wireguard.d/Mullvad_NewYork.conf' into SQL database as next available wg1X 'client' Peer interface
# wgm menu hide color off
# Useful when using wireguard_manager© on say a mobile where ANSI escape sequences are not honoured/executed e.g. iPhone Siri App
#
# Maintainer: Martineau
# Last Updated Date: 20-Sep-2022
#
# Description:
#
# Acknowledgement:
#
# Contributors: odkrys,Torson,ZebMcKayhan,jobhax,elorimer,Sh0cker54,here1310,defung,The Chief,abir1909,JGrana,heysoundude,archiel,Cam,endiz,Meshkoff,johndoe85,Juched
GIT_REPO="wireguard"
GITHUB_MARTINEAU="https://raw.githubusercontent.com/MartineauUK/$GIT_REPO/main"
GITHUB_MARTINEAU_DEV="https://raw.githubusercontent.com/MartineauUK/$GIT_REPO/dev"
GITHUB_ZEBMCKAYHAN="https://raw.githubusercontent.com/ZebMcKayhan/WireguardManager/main" # v4.15
GITHUB_ZEBMCKAYHAN_DEV="https://raw.githubusercontent.com/ZebMcKayhan/WireguardManager/dev" # v4.15
GITHUB_DIR=$GITHUB_MARTINEAU # default for script
CONFIG_DIR="/opt/etc/wireguard.d/" # Conform to "standards" # v2.03 @elorimer
IMPORT_DIR=$CONFIG_DIR # Allow custom Peer .config import directory v4.01
INSTALL_DIR="/jffs/addons/wireguard/"
CHECK_GITHUB="Y" # Check versions on Github
SILENT="s" # Default is no progress messages for file downloads
DEBUGMODE=
READLINE="ReadLine" # Emulate 'readline' for 'read' # v2.03
CMDLINE= # Command line INPUT # v2.03
CMD1=;CMD2=;CMD3=;CMD4=;CMD5= # Command recall push stack # v2.03
SQL_DATABASE="/opt/etc/wireguard.d/WireGuard.db" # SQL # v3.05
INSTALL_MIGRATE="N" # Migration from v3.0 to v4.0 # v4.01
IMPORTED_PEER_NAME= # Global tacky! # v4.15
readonly SCRIPT_WEBPAGE_DIR="$(readlink /www/user)"
readonly SCRIPT_WEB_DIR="$SCRIPT_WEBPAGE_DIR/wireguard" # v4.17
readonly SCRIPT_DIR="/jffs/addons/wireguard"
installedMD5File="${INSTALL_DIR}www-installed.md5" # Save md5 of last installed www ASP file so you can find it again later (in case of www ASP update)
WEBUI_COLOUR_REINSTATE= # WebUI Service Events temporarily suppresses ANSI color Escape sequences # v4.17
WEBUI_AUTOREPLY= # WebUI Service Events must not prompt for reply by a Human!
Say() {
# shellcheck disable=SC2068
echo -e $$ $@ | logger -st "($(basename $0))"
}
SayT() {
# shellcheck disable=SC2068
echo -e $$ $@ | logger -t "($(basename $0))"
}
# shellcheck disable=SC2034
ANSIColours() {
local ACTION=$1
cRESET=
aBOLD=;aDIM=;aUNDER=;aBLINK=;aREVERSE=
aBOLDr=;aDIMr=;aUNDERr=;aBLINKr=;aREVERSEr=
cBLA=;cRED=;cGRE=;cYEL=;cBLU=;cMAG=;cCYA=;cGRA=;cFGRESET=
cBGRA=;cBRED=;cBGRE=;cBYEL=;cBBLU=;cBMAG=;cBCYA=;cBWHT=
cWRED=;cWGRE=;cWYEL=;cWBLU=;cWMAG=;cWCYA=;cWGRA=
cYBLU=
cRED_=;cGRE_=
if [ "$ACTION" != "disable" ];then
cRESET="\e[0m";
aBOLD="\e[1m";aDIM="\e[2m";aUNDER="\e[4m";aBLINK="\e[5m";aREVERSE="\e[7m"
aBOLDr="\e[21m";aDIMr="\e[22m";aUNDERr="\e[24m";aBLINKr="\e[25m";aREVERSEr="\e[27m"
cBLA="\e[30m";cRED="\e[31m";cGRE="\e[32m";cYEL="\e[33m";cBLU="\e[34m";cMAG="\e[35m";cCYA="\e[36m";cGRA="\e[37m";cFGRESET="\e[39m"
cBGRA="\e[90m";cBRED="\e[91m";cBGRE="\e[92m";cBYEL="\e[93m";cBBLU="\e[94m";cBMAG="\e[95m";cBCYA="\e[96m";cBWHT="\e[97m"
aBOLD="\e[1m";aDIM="\e[2m";aUNDER="\e[4m";aBLINK="\e[5m";aREVERSE="\e[7m"
cWRED="\e[41m";cWGRE="\e[42m";cWYEL="\e[43m";cWBLU="\e[44m";cWMAG="\e[45m";cWCYA="\e[46m";cWGRA="\e[47m"
cYBLU="\e[93;48;5;21m"
cRED_="\e[41m";cGRE_="\e[42m"
fi
xHOME="\e[H";xERASE="\e[2J";xERASEDOWN="\e[J";xERASEUP="\e[1J";xCSRPOS="\e[s";xPOSCSR="\e[u";xERASEEOL="\e[K";xQUERYCSRPOS="\e[6n"
xGoto="\e[Line;Columnf"
}
ShowHelp() {
# Print between line beginning with'#==' to first blank line inclusive
echo -en $cBWHT >&2
awk '/^#==/{f=1} f{print; if (!NF) exit}' $0
echo -en $cRESET >&2
}
Parse() {
#
# Parse "Word1,Word2|Word3" ",|" VAR1 VAR2 REST
# (Effectivley executes VAR1="Word1";VAR2="Word2";REST="Word3")
local TEXT IFS
TEXT="$1"
IFS="$2"
shift 2
read -r -- "$@" <<EOF
$TEXT
EOF
}
Is_HND() {
# Use the following at the command line otherwise 'return X' makes the SSH session terminate!
#[ -n "$(/bin/uname -m | grep "aarch64")" ] && echo Y || echo N
[ -n "$(/bin/uname -m | grep "aarch64")" ] && { echo Y; return 0; } || { echo N; return 1; } # v4.14
}
Is_AX() {
# Kernel is '4.1.52+' (i.e. isn't '2.6.36*') and it isn't HND
# Use the following at the command line otherwise 'return X' makes the SSH session terminate!
# [ -n "$(/bin/uname -r | grep "^4")" ] && [ -z "$(/bin/uname -m | grep "aarch64")" ] && echo Y || echo N
[ -n "$(/bin/uname -r | grep "^4")" ] && [ -z "$(/bin/uname -m | grep "aarch64")" ] && { echo Y; return 0; } || { echo N; return 1; } # v4.14
}
Get_Router_Model() {
# Contribution by @thelonelycoder as odmpid is blank for non SKU hardware,
local HARDWARE_MODEL
[ -z "$(nvram get odmpid)" ] && HARDWARE_MODEL=$(nvram get productid) || HARDWARE_MODEL=$(nvram get odmpid)
echo $HARDWARE_MODEL
return 0
}
Chain_exists() {
# Args: {chain_name} [table_name]
local CHAIN="$1"
shift
[ $# -eq 1 ] && local TABLE="-t $1"
iptables $TABLE -n -L $CHAIN >/dev/null 2>&1
local RC=$?
if [ $RC -ne 0 ];then
echo "N"
return 1
else
echo "Y"
return 0
fi
}
Get_WAN_IF_Name() {
# echo $([ -n "$(nvram get wan0_pppoe_ifname)" ] && echo $(nvram get wan0_pppoe_ifname) || echo $(nvram get wan0_ifname))
# nvram get wan0_gw_ifname
# nvram get wan0_proto
local IF_NAME=$(ip route | awk '/^default/{print $NF}') # Should ALWAYS be 100% reliable ?
local IF_NAME=$(nvram get wan0_ifname) # ...but use the NVRAM e.g. DHCP/Static ?
# Usually this is probably valid for both eth0/ppp0e ?
if [ "$(nvram get wan0_gw_ifname)" != "$IF_NAME" ];then
local IF_NAME=$(nvram get wan0_gw_ifname)
fi
if [ ! -z "$(nvram get wan0_pppoe_ifname)" ];then
local IF_NAME="$(nvram get wan0_pppoe_ifname)" # PPPoE
fi
echo $IF_NAME
}
Repeat() {
# Print 25 '=' use HDRLINE=$(Repeat 25 "=")
printf "%${1}s\n" | tr " " "$2"
}
Is_IPv4() {
grep -oE '^([0-9]{1,3}\.){3}[0-9]{1,3}$' # IPv4 format
}
Is_IPv4_CIDR() {
grep -oE '^([0-9]{1,3}\.){3}[0-9]{1,3}/(3[012]|[12]?[0-9])$' # IPv4 CIDR range notation
}
Is_Private_IPv4() {
# 127. 0.0.0 – 127.255.255.255 127.0.0.0 /8
# 10. 0.0.0 – 10.255.255.255 10.0.0.0 /8
# 172. 16.0.0 – 172. 31.255.255 172.16.0.0 /12
# 192.168.0.0 – 192.168.255.255 192.168.0.0 /16
#grep -oE "(^192\.168\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)|(^172\.([1][6-9]|[2][0-9]|[3][0-1])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)|(^10\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)"
grep -oE "(^127\.)|(^(0)?10\.)|(^172\.(0)?1[6-9]\.)|(^172\.(0)?2[0-9]\.)|(^172\.(0)?3[0-1]\.)|(^169\.254\.)|(^192\.168\.)"
}
Is_IPv6() {
# Note this matches compression anywhere in the address, though it won't match the loopback address ::1
grep -oE '([A-Fa-f0-9]{1,4}::?){1,7}[A-Fa-f0-9]{1,4}' # IPv6 format -very crude
}
Is_Private_IPv6() {
grep -oE "(::1$)|([fF][cCdD])"
}
Generate_IPv6_ULA() {
local USE_ULA=$1 # 'fcxx' or fdxx' prefix
# From time+EUI-64 as per RFC 4193 https://www.rfc-editor.org/rfc/rfc4193#section-3.2.2
# Pre-reqs Entware date (coreutils-date)
[ ! -f /opt/bin/date ] && { SayT "***ERROR Requires Entware 'date' module....ABORTing\n"; echo "***ERROR Requires Entware module" 2>&1; return 1 ;}
local NANO_SECS=$(/opt/bin/date +%s%N)
# wl1_hwaddr=24:4B:FE:AC:54:DC
# wan0_gw_mac=AC:9E:17:7E:E4:A0
local HEX1=$(nvram get wan0_gw_mac)
local HEX2=$(nvram get wl1_hwaddr)
local HEX=${NANO_SECS}${HEX1//:/}${HEX2//:/}
echo -e "$HEX" >/tmp/wgm_ula
local HASH=$(openssl dgst -sha1 /tmp/wgm_ula | awk '{print $2}' | cut -c 31- )
# Flip the 7th Bit
local WORD=${HASH:0:2}
local WORD_BIT7FLIPPED=$(printf '%0X\n' "$(( 0x$WORD ^ 0x02 ))" | tr 'A-F' 'a-f') # Bitwise XOR
#local IPV6="fd"${HASH:0:2}:${HASH:2:4}:${HASH:6:4}"::1/64"
local IPV6="fd"${WORD_BIT7FLIPPED}:${HASH:2:4}:${HASH:6:4}"::1/64"
# https://blogs.infoblox.com/ipv6-coe/ula-is-broken-in-dual-stack-networks/ # @heysoundude
SayT "Here is your IPv6 ULA based on this hardware's MACs IPV6="$IPV6" (Use 'aa"${HASH:0:2}:${HASH:2:4}:${HASH:6:4}"::1/64' for Dual-stack IPv4+IPv6)"
[ -z "$USE_ULA" ] && local IPV6="$(echo "$IPV6" | sed 's/^fd/aa/')" # v4.16 Override standard ULA 'fcxx/fdxx' prefix
rm /tmp/wgm_ula 2>/dev/null
echo "$IPV6" 2>&1
}
Hex2Dec(){
# Convert Hex to Dec (portable version) (see https://github.com/chmduquesne/wg-ip/blob/master/wg-ip)
for I in $(echo "$@"); do
printf "%d\n" "$(( 0x$I ))"
done
}
Expand_IPv6() {
# Returns an expanded IPv6 128-bit address under the form recommended by RFC5952 (see https://github.com/chmduquesne/wg-ip/blob/master/wg-ip)
# Martineau see https://iplocation.io/ipv6-expand
local ip=$1
# Prepend 0 if we start with :
echo $ip | grep -qs "^:" && local ip="0${ip}"
# Expand ::
if echo $ip | grep -qs "::"; then
local colons=$(echo $ip | sed 's/[^:]//g')
local missing=$(echo ":::::::::" | sed "s/$colons//")
local expanded=$(echo $missing | sed 's/:/:0/g')
local ip=$(echo $ip | sed "s/::/$expanded/")
fi
local blocks=$(echo $ip | grep -o "[0-9a-f]\+")
set $blocks
# shellcheck disable=SC2068,SC2183
printf "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x\n" $(Hex2Dec $@)
}
Compress_IPv6() {
# Returns a compressed IPv6 128-bit address under the form recommended by RFC5952 (see https://github.com/chmduquesne/wg-IP/blob/master/wg-IP)
# Martineau see https://iplocation.io/ipv6-compress
local ip=$1
local blocks=$(echo $ip | grep -o "[0-9a-f]\+")
set $blocks
# Compress leading zeros
#local ip=$(printf "%x:%x:%x:%x:%x:%x:%x:%x\n" $(Hex2Dec $@)) # Martineau HACK!
# shellcheck disable=SC2068,SC2183
[ $# -eq 8 ] && local ip=$(printf "%x:%x:%x:%x:%x:%x:%x:%x\n" $(Hex2Dec $@)) || local ip=$(printf "%x:%x:%x:%x:%x:%x:%x\n" $(Hex2Dec $@))
# Prepend : for easier matching
local ip=:$ip
# :: must compress the longest chain
# Martineau Hacked
for pattern in :0:0:0:0:0:0:0:0 \
:0:0:0:0:0:0:0 \
:0:0:0:0:0:0 \
:0:0:0:0:0 \
:0:0:0:0 \
:0:0:0 \
:0:0; do
if echo $ip | grep -qs $pattern; then
local ip=$(echo $ip | sed "s/$pattern/::/")
# if the substitution occured before the end, we have :::
local ip=$(echo $ip | sed 's/:::/::/')
break # only one substitution
fi
done
# Remove prepending : if necessary
echo $ip | grep -qs "^:[^:]" && local ip=$(echo $ip | sed 's/://')
echo $ip
}
IPv6_RFC() {
local IPV6=$1 # v4.15
local IPV6_IP=${IPV6%/*}
if [ -n "$(echo "$IPV6" | grep -F "/")" ];then
local IPV6_IP_MASK=${IPV6##*/}
fi
local IPV6_SUBNET=${IPV6_IP%:*}
local IPV6_IP_EXPANDED=$(Expand_IPv6 "$IPV6_IP")
local IPV6_IP_COMPRESSED=$(Compress_IPv6 "$IPV6_IP_EXPANDED")
[ -n "$IPV6_IP_MASK" ] && local IPV6=${IPV6_IP_COMPRESSED}"/"$IPV6_IP_MASK || local IPV6=${IPV6_IP_COMPRESSED}
echo $IPV6
}
Convert_1024KMG() {
local NUM=$1
local UNIT=$(echo "$2" | tr '[a-z]' '[A-Z]')
case "$UNIT" in
M|MB|MIB)
NUM=$(echo $NUM | awk '{printf "%.0f", $1*1024*1024}') # v4.02 Hotfix
;;
G|GB|GIB)
NUM=$(echo $NUM | awk '{printf "%.0f", $1*1024*1024*1024}') # v4.02 Hotfix
;;
K|KB|KIB)
NUM=$(echo $NUM | awk '{printf "%.0f", $1*1024}') # v4.02 Hotfix
;;
B)
;;
esac
echo $NUM
}
Convert_SECS_to_HHMMSS() {
local SECS=$1
local DAYS_TXT=
if [ $SECS -ge 86400 ] && [ -n "$2" ];then # More than 24:00 i.e. 1 day?
local DAYS=$((${SECS}/86400))
SECS=$((SECS-DAYS*86400))
local DAYS_TXT=$DAYS" days"
fi
local HH=$((${SECS}/3600))
local MM=$((${SECS}%3600/60))
local SS=$((${SECS}%60))
if [ -z "$2" ];then
echo $(printf "%02d:%02d:%02d" $HH $MM $SS) # Return 'hh:mm:ss" format
else
if [ -n "$2" ] && [ -z "$DAYS_TXT" ];then
DAYS_TXT="0 Days, "
fi
echo $(printf "%s %02d:%02d:%02d" "$DAYS_TXT" $HH $MM $SS) # Return in "x days hh:mm:ss" format
fi
}
EpochTime(){
#e.g. Convert a time into Epoch seconds...
# date -d "2018-11-13 20:56" +%s
# 1542142560
# and to convert it back
#
# date -d @1542142560 "+%F %T"
# 2018-11-13 20:56:00
# or
# date -d @1542142560 "+%c"
# Tue 13 Nov 2018 08:56:00 PM GMT
if [ -z "$1" ];then
RESULT=$(date +%s) # Convert current timestamp into Epoch seconds
else
if [ -z "$2" ];then
RESULT=$(date -d @"$1" +%s) # Convert specified YYYY-MM-DD HH:MM:SS into Epoch seconds
else
if [ "$2" == "Human" ];then
RESULT=$(date -d @"$1" "+%F %T") # Convert specified Epoch seconds into YYYY-MM-DD HH:MM:SS
else
RESULT=$(date -d @"$1" "+%c") # Convert specified Epoch seconds into ddd mmm dd HH:MM:SS YYYY
fi
fi
fi
echo $RESULT
}
Size_Human() {
local SIZE=$1
if [ -z "$SIZE" ];then
echo "N/A"
return 1
fi
#echo $(echo $SIZE | awk '{ suffix=" KMGT"; for(i=1; $1>1024 && i < length(suffix); i++) $1/=1024; print int($1) substr(suffix, i, 1), $3; }')
# if [ $SIZE -gt $((1024*1024*1024*1024)) ];then # 1,099,511,627,776
# printf "%2.2f TB\n" $(echo $SIZE | awk '{$1=$1/(1024^4); print $1;}')
# else
if [ $SIZE -gt $((1024*1024*1024)) ];then # 1,073,741,824
printf "%2.2f GiB\n" $(echo $SIZE | awk '{$1=$1/(1024^3); print $1;}')
else
if [ $SIZE -gt $((1024*1024)) ];then # 1,048,576
printf "%2.2f MiB\n" $(echo $SIZE | awk '{$1=$1/(1024^2); print $1;}')
else
if [ $SIZE -gt $((1024)) ];then
printf "%2.2f KiB\n" $(echo $SIZE | awk '{$1=$1/(1024); print $1;}')
else
printf "%d Bytes\n" $SIZE
fi
fi
fi
# fi
return 0
}
Check_Lock() {
if [ -f "/tmp/wg.lock" ] && [ -d "/proc/$(sed -n '2p' /tmp/wg.lock)" ] && [ "$(sed -n '2p' /tmp/wg.lock)" != "$$" ]; then
if [ "$(($(date +%s)-$(sed -n '3p' /tmp/wg.lock)))" -gt "1800" ]; then
Kill_Lock
else
logger -st wg "[*] Lock File Detected ($(sed -n '1p' /tmp/wg.lock)) (pid=$(sed -n '2p' /tmp/wg.lock)) - Exiting (cpid=$$)"
echo; exit 1
fi
fi
if [ -n "$1" ]; then
echo "$1" > /tmp/wg.lock
else
echo "menu" > /tmp/wg.lock
fi
echo "$$" >> /tmp/wg.lock
date +%s >> /tmp/wg.lock
}
Kill_Lock() {
if [ -f "/tmp/wg.lock" ] && [ -d "/proc/$(sed -n '2p' /tmp/wg.lock)" ]; then
logger -st wg "[*] Killing Locked Processes ($(sed -n '1p' /tmp/wg.lock)) (pid=$(sed -n '2p' /tmp/wg.lock))"
logger -st wg "[*] $(ps | awk -v pid="$(sed -n '2p' /tmp/wg.lock)" '$1 == pid')"
kill "$(sed -n '2p' /tmp/wg.lock)"
rm -rf /tmp/wg.lock
echo
fi
}
Manage_Addon() {
# https://raw.githubusercontent.com/ZebMcKayhan/WireguardManager/main/wgmExpo.sh
FN="$1"
local BRANCH=$2
if [ "$2" != "remove" ] && [ "$2" != "del" ];then
[ -z "$BRANCH" ] && local BRANCH="main"
download_file ${INSTALL_DIR} $FN zebmckayhan $BRANCH dos2unix 777
chmod +x ${INSTALL_DIR}$FN
ln -s /jffs/addons/wireguard/$FN /opt/bin/${FN%.*} 2>/dev/null
md5sum ${INSTALL_DIR}$FN > ${INSTALL_DIR}${FN%.*}.md5
else
rm ${INSTALL_DIR}$FN 2>/dev/null
rm /opt/bin/$FN 2>/dev/null
fi
}
download_file() {
local DIR="$1"
local FILE="$2"
local GITHUB="$3"
local GITHUB_BRANCH="$4"
local DOSUNIX="$5"
local CHMOD="$6"
case $GITHUB in
martineau)
[ "$GITHUB_BRANCH" != "dev" ] && GITHUB_DIR=$GITHUB_MARTINEAU || GITHUB_DIR=$GITHUB_MARTINEAU_DEV
;;
zebmckayhan)
[ "$GITHUB_BRANCH" != "dev" ] && GITHUB_DIR=$GITHUB_ZEBMCKAYHAN || GITHUB_DIR=$GITHUB_ZEBMCKAYHAN_DEV
;;
esac
[ "$GITHUB_BRANCH" == "dev" ] && local DEVTXT=${cRESET}$cWRED"Github 'dev/development' branch"$cRESET || local DEVTXT=
STATUS="$(curl --retry 3 -L${SILENT} -w '%{http_code}' "$GITHUB_DIR/$FILE" -o "$DIR/$FILE")"
if [ "$STATUS" -eq "200" ]; then
if [ -n "$(echo "$@" | grep -F "dos2unix")" ];then
[ "$(which dos2unix)" == "/usr/bin/dos2unix" ] && dos2unix $DIR/$FILE || dos2unix -q $DIR/$FILE # v4.12
fi
printf '\t%b%s%b downloaded successfully %b\n' "$cBGRE" "$FILE" "$cRESET" "$DEVTXT"
[ -n "$CHMOD" ] && chmod $CHMOD "$DIR/$FILE"
else
printf '\n%b%s%b download FAILED with curl error %s\n\n' "\n\t\a$cRESET" "'${GITHUB_DIR}/${FILE}'" "$cBRED" "$STATUS"
echo -e $cRESET"\a\n"
return 1
fi
}
_Get_File() {
local WEBFILE=$1
local REPOSITORY_OWNER=$2
local FROM_REPOSITORY="main"
[ "$3" == "dev" ] && { local FROM_REPOSITORY=$3; local FROM_RESPOSITORY_TXT="${cRESET}${cWRED}Github '$FROM_REPOSITORY' branch$cRESET"; } # v4.12
REPOSITORY="https://github.com/odkrys/entware-makefile-for-merlin/raw/main/" # v4.11
[ "$REPOSITORY_OWNER" != "odkrys" ] && local REPOSITORY="https://github.com/ZebMcKayhan/Wireguard/raw/${FROM_REPOSITORY}/" # v4.12 v4.11
[ -z "$(echo "$@" | grep "NOMSG")" ] && echo -e $cBCYA"\n\tDownloading WireGuard® Kernel module ${cBWHT}'$WEBFILE'$cBCYA for $ROUTER (v$BUILDNO) @$REPOSITORY_OWNER $FROM_RESPOSITORY_TXT"$cRESET # v4.12
echo -en $cBGRE
curl -# -s -fL --retry 3 ${REPOSITORY}${WEBFILE} -o ${INSTALL_DIR}${WEBFILE} # v4.11
local RC=$?
[ $RC -ne 0 ] && { echo -e $cBRED; curl -# -fL --retry 3 ${REPOSITORY}${WEBFILE} -o ${INSTALL_DIR}${WEBFILE}; echo "URL: '${REPOSITORY}${WEBFILE}'"; } || echo -e "Success!" # v4.12
return $?
}
Download_Modules() {
local ROUTER=$1
local FROM_REPOSITORY=$2 # v4.12
[ -z "$FROM_REPOSITORY" ] && local FROM_REPOSITORY="main" # v4.12
local REPOSITORY_OWNER="odkrys" # v4.11
local USE_ENTWARE_KERNEL_MODULE="N" # v4.12
if [ -f ${INSTALL_DIR}WireguardVPN.conf ] && [ -n "$(grep -oE "^USE_ENTWARE_KERNEL_MODULE" ${INSTALL_DIR}WireguardVPN.conf)" ];then # v4.12
local USE_ENTWARE_KERNEL_MODULE="Y"
fi
if [ "$USE_ENTWARE_KERNEL_MODULE" == "Y" ];then
rm ${INSTALL_DIR}*.ipk 2>/dev/null # v4.12
[ -n "$(opkg list-installed | grep "wireguard-kernel")" ] && opkg remove wireguard-kernel 1>/dev/null
[ -n "$(opkg list-installed | grep "wireguard-tools")" ] && opkg remove wireguard-tools 1>/dev/null
rm ${INSTALL_DIR}*.ipk 2>/dev/null
fi
#local WEBFILE_NAMES=$(curl -${SILENT}fL https://www.snbforums.com/threads/experimental-wireguard-for-hnd-platform-4-1-x-kernels.46164/ | grep "<a href=.*odkrys.*wireguard" | grep -oE "wireguard.*" | sed 's/\"//g' | tr '\n' ' ')
local WEBFILE_NAMES=$(curl -${SILENT}fL https://api.github.com/repos/odkrys/entware-makefile-for-merlin/git/trees/main | grep "\"path\": \"wireguard-.*\.ipk\"," | cut -d'"' -f 4) # v4.11 @defung pull request https://github.com/MartineauUK/wireguard/pull/3
# Allow use of Entware/3rd Party Kernel modules even if included in firmware
if [ ! -f /usr/sbin/wg ] || [ "$USE_ENTWARE_KERNEL_MODULE" == "Y" ];then
case "$ROUTER" in
RT-AC86U|GT-AC2900) # RT-AC86U, GT-AC2900 - 4.1.27 e.g. wireguard-kernel_1.0.20210606-k27_1_aarch64-3.10.ipk
local WEBFILE_NAMES=$(curl -${SILENT}fL https://api.github.com/repos/ZebMcKayhan/Wireguard/git/trees/$FROM_REPOSITORY | grep "\"path\": \"wireguard-.*\.ipk\"," | cut -d'"' -f 4) # v4.12 v4.11
local REPOSITORY_OWNER="ZebMcKayhan"
local MODULE="$(echo "$WEBFILE_NAMES" | awk "/$ROUTER/ {print}")" # v4.13
[ -z "$MODULE" ] && local MODULE=$(echo "$WEBFILE_NAMES" | awk "/k27/ {print}") # v4.13
_Get_File "$MODULE" "$REPOSITORY_OWNER" "$FROM_REPOSITORY"
;;
RT-AX88U|GT-AX11000) # RT-AX88U, GT-AX11000 - 4.1.51 e.g. wireguard-kernel_1.0.20210219-k51_1_aarch64-3.10.ipk
local WEBFILE_NAMES=$(curl -${SILENT}fL https://api.github.com/repos/ZebMcKayhan/Wireguard/git/trees/$FROM_REPOSITORY | grep "\"path\": \"wireguard-.*\.ipk\"," | cut -d'"' -f 4) # v4.12
local REPOSITORY_OWNER="ZebMcKayhan"
local MODULE="$(echo "$WEBFILE_NAMES" | awk "/$ROUTER/ {print}")" # v4.13
[ -z "$MODULE" ] && local MODULE=$(echo "$WEBFILE_NAMES" | awk "/k51/ {print}") # v4.13
_Get_File "$MODULE" "$REPOSITORY_OWNER" "$FROM_REPOSITORY"
;;
RT-AX68U) # RT-AX68U - 4.1.52 e.g. wireguard-kernel_1.0.20210219-k52_1_aarch64-3.10.ipk
_Get_File "$(echo "$WEBFILE_NAMES" | awk '/k52/ {print}')" "$REPOSITORY_OWNER" "$FROM_REPOSITORY" # k52_1
;;
RT-AX86U|GT-AC5700) # v4.12 These models have wireguard in the firmware
# RT-AX68U, RT-AX86U - 4.1.52 e.g. wireguard-kernel_1.0.20210219-k52_1_aarch64-3.10.ipk
_Get_File "$(echo "$WEBFILE_NAMES" | awk '/k52/ {print}')" "$REPOSITORY_OWNER" "$FROM_REPOSITORY" # k52_1
;;
*)
echo -e $cBRED"\a\n\t***ERROR: Unable to find 3rd-Party WireGuard® Kernel module for $ROUTER (v$BUILDNO)\n"$cRESET
# Deliberately Download an incompatible file simply so that an error message is produced by 'opkg install*.ipk'
#
# Unknown package 'wireguard-kernel'.
# Collected errors:
# * pkg_hash_fetch_best_installation_candidate: Packages for wireguard-kernel found, but incompatible with the architectures configured
# * opkg_install_cmd: Cannot install package wireguard-kernel.
#
#
#_Get_File "$(echo "$WEBFILE_NAMES" | awk '{print $1}')" "$REPOSITORY_OWNER" "$FROM_REPOSITORY"
ROUTER_COMPATIBLE="N"
;;
esac
else
local FPATH=$(modprobe --show-depends wireguard | awk '{print $2}')
local FVERSION=$(strings $FPATH | grep "^version" | cut -d'=' -f2) # v4.12 @ZebMcKayhan
echo -e $cBGRE"\n\t[✔]$cBWHT WireGuard® Kernel module/User Space Tools included in Firmware $ROUTER (v$BUILDNO)"$cRED" ($FVERSION)\n"$cRESET # v4.12
echo -e $cBYEL"\a\t\tWireGuard® exists in firmware - use ${cRESET}'vx'${cBYEL} command to override with 3rd-Party/Entware (if available)"$cRESET
fi
# User Space Tools - Allow use of Entware/3rd Party modules even if Modules included in firmware
if [ ! -f /usr/sbin/wg ] || [ "$USE_ENTWARE_KERNEL_MODULE" == "Y" ];then # v4.12 Is the User Space Tools included in the firmware?
if [ "$ROUTER_COMPATIBLE" != "N" ];then # v4.13 HOTFIX
WEBFILE=$(echo "$WEBFILE_NAMES" | awk '/wireguard-tools/ {print}')
echo -e $cBCYA"\n\tDownloading WireGuard® User space Tool$cBWHT '$WEBFILE'$cBCYA for $ROUTER (v$BUILDNO) @$REPOSITORY_OWNER $FROM_RESPOSITORY_TXT"$cRESET # v4.11
_Get_File "$WEBFILE" "$REPOSITORY_OWNER" "$FROM_REPOSITORY" "NOMSG" # v4.12 v4.11
fi
else
echo -e $cBYEL"\a\t\tUser Space tool exists in firmware - use ${cRESET}'vx'${cBYEL} command to override with 3rd-Party/Entware (if available)\n"$cRESET
fi
}
Load_UserspaceTool() {
local USE_ENTWARE_KERNEL_MODULE="N" # v4.12
if [ -f ${INSTALL_DIR}WireguardVPN.conf ] && [ -n "$(grep -oE "^USE_ENTWARE_KERNEL_MODULE" ${INSTALL_DIR}WireguardVPN.conf)" ];then # v4.12
local USE_ENTWARE_KERNEL_MODULE="Y"
fi
if [ ! -d "${INSTALL_DIR}" ];then
echo -e $cRED"\a\n\tNo modules found - '/${INSTALL_DIR} doesn't exist'\n"
echo -e "\tPress$cBRED y$cRESET to$cBRED DOWNLOAD WireGuard® Kernel and Userspace Tool modules ${cRESET} or press$cBGRE [Enter] to SKIP."
[ -z "$WEBUI_AUTOREPLY" ] && read -r "ANS" || echo -e "$WEBUI_AUTOREPLY" >&2
if [ -n "$WEBUI_AUTOREPLY" ] || [ "$ANS" == "y" ];then
Download_Modules $HARDWARE_MODEL
fi
fi
local ACTIVE_WG_INTERFACES=$(echo "$(wg show interfaces)" | tr " " "\n" | sort -r | tr "\n" " ") # v4.13
local STATUS=0
if [ ! -f /usr/sbin/wg ] || [ "$USE_ENTWARE_KERNEL_MODULE" == "Y" ];then # v4.12 Is the User Space Tools included in the firmware?
echo -e $cBCYA"\n\tLoading WireGuard® Kernel module and Userspace Tool for $HARDWARE_MODEL (v$BUILDNO)"$cRESET
if [ -n "$(ls /jffs/addons/wireguard/*.ipk 2>/dev/null)" ];then
[ -n "$ACTIVE_WG_INTERFACES" ] && Manage_Wireguard_Sessions "stop" "$ACTIVE_WG_INTERFACES" # v4.14
# shellcheck disable=SC2045
for MODULE in $(ls /jffs/addons/wireguard/*.ipk)
do
local MODULE_NAME=$(echo "$(basename $MODULE)" | sed 's/_.*$//')
SayT "Initialising WireGuard® module '$MODULE_NAME'"
echo -e $cBCYA"\tInitialising WireGuard® module $cRESET'$MODULE_NAME'"
opkg install $MODULE
if [ $? -eq 0 ];then
md5sum $MODULE > ${INSTALL_DIR}$MODULE_NAME".md5"
sed -i 's~/jffs/addons/wireguard/~~' ${INSTALL_DIR}$MODULE_NAME".md5"
else
local STATUS=1
fi
done
fi
if [ "$STATUS" -eq 0 ];then
insmod /opt/lib/modules/wireguard 2>/dev/null
echo -e $cBGRA"\t"$(dmesg | grep -a "WireGuard" | tail -n 1)
echo -e $cBGRA"\t"$(dmesg | grep -a "wireguard: Copyright" | tail -n 1)"\n"$cRESET
local STATUS=0
else
echo -e $cBRED"\a\n\t***ERROR: Unable to LOAD Entware/3rd-party WireGuard® Kernel and Userspace Tool modules\n"
local STATUS=1
fi
else
local KERNEL_MODULE=$(find /lib/modules -name "wireguard.ko" | tr '\n' ' ' | awk '{print $1}') # v4.14 v4.12
if [ -n "$KERNEL_MODULE" ];then
local FPATH=$(modprobe --show-depends wireguard | awk '{print $2}')
local FVERSION=$(strings $FPATH | grep "^version" | cut -d'=' -f2) # v4.12 @ZebMcKayhan
echo -e $cBGRE"\n\t[✔]$cBWHT WireGuard® Kernel module/User Space Tools included in Firmware"$cRED" ($FVERSION)\n"$cRESET
[ -n "$ACTIVE_WG_INTERFACES" ] && Manage_Wireguard_Sessions "stop" "$ACTIVE_WG_INTERFACES" # v4.14
SayT "Initialising WireGuard® Kernel module '$KERNEL_MODULE'"
echo -e $cBCYA"\tInitialising WireGuard® Kernel module $cRESET'$KERNEL_MODULE'"
rmmod $KERNEL_MODULE 2>/dev/null # v4.12
insmod $KERNEL_MODULE 2>/dev/null # v4.12
echo -e $cBGRA"\t"$(dmesg | grep -a "WireGuard" | tail -n 1)
echo -e $cBGRA"\t"$(dmesg | grep -a "wireguard: Copyright" | tail -n 1)"\n"$cRESET
rm ${INSTALL_DIR}*.ipk 2>/dev/null # v4.12
[ -n "$(opkg list-installed | grep "wireguard-kernel")" ] && opkg remove wireguard-kernel 1>/dev/null
[ -n "$(opkg list-installed | grep "wireguard-tools")" ] && opkg remove wireguard-tools 1>/dev/null
else
logger -t "wireguard-server${VPN_ID:3:1}" "***ERROR Failure to Initialise WireGuard® Kernel module!"
local STATUS=1
fi
fi
[ -n "$ACTIVE_WG_INTERFACES" ] && Manage_Wireguard_Sessions "start" "$ACTIVE_WG_INTERFACES" # v4.13
return $STATUS # v4.14
}
Show_MD5() {
local TYPE=$1
if [ "$TYPE" == "script" ];then
echo -e $cBCYA"\tMD5="$(awk '{print $0}' ${INSTALL_DIR}wg_manager.md5)
else
if [ ! -f /usr/sbin/wg ] || [ "$(which wg)" == "/opt/bin/wg" ];then # v4.12
echo -e $cBCYA"\tMD5="$(awk '{print $0}' ${INSTALL_DIR}wireguard-kernel.md5)
echo -e $cBCYA"\tMD5="$(awk '{print $0}' ${INSTALL_DIR}wireguard-tools.md5)
else
#echo -e $cBYEL"\a\n\t***ERROR: MD5= ???? - WireGuard® exists in firmware for $ROUTER (v$BUILDNO)\n"$cRESET
:
fi
fi
}
Check_Module_Versions() {
local ACTION=$1
local UPDATES="N"
echo -e $cBGRA"\t"$(dmesg | grep -a "WireGuard" | tail -n 1) # v4.12
echo -e $cBGRA"\t"$(dmesg | grep -a "wireguard: Copyright" | tail -n 1)"\n"$cRESET # v4.12
if [ -n "$(lsmod | grep -i wireguard)" ];then
if [ -n "$(opkg status wireguard-kernel | awk '/^Installed/ {print $2}')" ];then
local LOADTIME=$(date -d @$(opkg status wireguard-kernel | awk '/^Installed/ {print $2}'))
else
local LOADTIME=
fi
echo -e $cBGRE"\t[✔] WireGuard® Module LOADED $LOADTIME\n"$cRESET
else
echo -e $cBRED"\t[✖] WireGuard® Module is NOT LOADED\n"$cRESET
fi
# Without a BOOT or 'loadmodule' command was issued, there may be a mismatch
local BOOTLOADED=$(dmesg | grep -a WireGuard | tail -n 1 | awk '{print $3}')
local WGKERNEL=$(opkg list-installed | grep "wireguard-kernel" | awk '{print $3}' | sed 's/\-.*$//')
local WGTOOLS=$(opkg list-installed | grep "wireguard-tools" | awk '{print $3}' | sed 's/\-.*$//')
local USE_ENTWARE_KERNEL_MODULE="N" # v4.12
if [ -f ${INSTALL_DIR}WireguardVPN.conf ] && [ -n "$(grep -oE "^USE_ENTWARE_KERNEL_MODULE" ${INSTALL_DIR}WireguardVPN.conf)" ];then
local USE_ENTWARE_KERNEL_MODULE="Y"
fi
if [ -f /usr/sbin/wg ] && [ "$USE_ENTWARE_KERNEL_MODULE" == "N" ];then
local FPATH=$(modprobe --show-depends wireguard | awk '{print $2}')
local WGKERNEL=$(strings $FPATH | grep "^version" | cut -d'=' -f2) # v4.12 @ZebMcKayhan
fi
#[ "$WGKERNEL" != "$BOOTLOADED" ] && echo -e $cRED"\a\n\tWarning: Reboot or 'loadmodule command' required for (dmesg) WireGuard® $WGKERNEL $BOOTLOADED\n"
Show_MD5
if [ "$ACTION" != "report" ];then
# Check if Kernel and User Tools Update available
echo -e $cBWHT"\tChecking for WireGuard® Kernel and Userspace Tool updates..."
if [ "$HARDWARE_MODEL" != "RT-AC86U" ] && [ "$HARDWARE_MODEL" != "GT-AC2900" ];then # v4.12
local REPOSITORY_OWNER="odkrys" # v4.12
local REPOSITORY_TITLE="entware-makefile-for-merlin" # v4.12
else
local REPOSITORY_OWNER="ZebMcKayhan" # v4.12
local REPOSITORY_TITLE="Wireguard" # v4.12
fi
local FILES=$(curl -${SILENT}fL https://api.github.com/repos/$REPOSITORY_OWNER/$REPOSITORY_TITLE/git/trees/main | grep "\"path\": \"wireguard-.*\.ipk\"," | cut -d'"' -f 4 | tr '\r\n' ' ') # v4.12 v4.11 @defung pull request https://github.com/MartineauUK/wireguard/pull/3
if [ "$ACTION" == "force" ];then # v4.12
local UPDATES="Y" # v4.12
else
[ -z "$(echo "$FILES" | grep -F "$WGKERNEL")" ] && { echo -e $cBYEL"\t\tKernel UPDATE available" $FILE; local UPDATES="Y"; }
[ -z "$(echo "$FILES" | grep -F "$WGTOOLS")" ] && { echo -e $cBYEL"\t\tUserspace Tool UPDATE available" $FILE; local UPDATES="Y"; }
fi
if [ "$UPDATES" == "Y" ];then
if [ "$ACTION" != "force" ];then # v4.12
echo -e $cRESET"\n\tPress$cBRED y$cRESET to$cBRED Update WireGuard® Kernel and Userspace Tool${cRESET} or press$cBGRE [Enter] to SKIP."
[ -z "$WEBUI_AUTOREPLY" ] && read -r "ANS" || echo -e "$WEBUI_AUTOREPLY" >&2
else
local ANS="y" # v4.12
fi
if [ -n "$WEBUI_AUTOREPLY" ] || [ "$ANS" == "y" ];then
Download_Modules $HARDWARE_MODEL
#Load_UserspaceTool
else
echo -e $cBWHT"\n\tUpdate skipped\n"$cRESET
fi
else
echo -e $cBGRE"\n\tWireGuard® Kernel and Userspace Tool up to date.\n"$cRESET
fi
fi
}
Create_Peer() {
# Default subnet IPv4 only, but IPv4,IPv6 if applicable/specified or just IPv6
# peer new # IPv4 only
# peer new ipv6[=[private_ipv6 subnet]] # Multi IPv4 and IPv6
# peer new ipv6 noipv4 # no IPv4
local ACTION=$1;shift
local USE_IPV4="Y" # v4.15
local USE_IPV6="N"
local VPN_POOL6= # v4.15
local IPV6_TXT= # v4.16 @archiel
while [ $# -gt 0 ]; do # v3.02
case "$1" in
auto*)
local AUTO="$(echo "$@" | sed -n "s/^.*auto=//p" | awk '{print $1}')"
;;
port*)
local LISTEN_PORT="$(echo "$@" | sed -n "s/^.*port=//p" | awk '{print $1}')"
local LISTEN_PORT_USER="Y"
;;
ipv6|ipv6=*)
local USE_IPV6="Y"
local IPV6_TXT="(IPv6) "
local SERVER_PEER=
local VPN_POOL6="$(echo "$@" | sed -n "s/^.*ipv6=//p" | awk '{print $1}')"
if [ "${1:0:5}" == "ipv6=" ] && [ -n "$VPN_POOL6" ];then
# Ensure IPv6 address is in standard compressed format
VPN_POOL6="$(IPv6_RFC "$VPN_POOL6")" # v4.15
local VPN_POOL_USER="Y"
local USE_ULA=
fi
;;
ula4|ula)
[ "$1" == "ula" ] && local USE_ULA="Y"
[ "$1" == "ula4" ] && local USE_ULA="4" # v4.16
;;
ip=*)
local VPN_POOL4="$(echo "$@" | sed -n "s/^.*ip=//p" | awk '{print $1}')"
local VPN_POOL_USER="Y"
;;
noipv4|noIPv4)
local USE_IPV4="N" # v4.15
local IPV6_TXT="(IPv6 Only) " # v4.15
;;
*)
local SERVER_PEER=$1
case $SERVER_PEER in
new)
local SERVER_PEER=
;;
esac
;;
esac
shift
done
local INDEX=
[ -z "$LISTEN_PORT" ] && local LISTEN_PORT=11500
[ -z "$AUTO" ] && local AUTO="N" || AUTO=$(echo "$AUTO" | tr 'a-z' 'A-Z')
if [ -z "$SERVER_PEER" ];then
# Use the last IPv4 server as the VPN POOL
local SERVER_PEER=$(sqlite3 $SQL_DATABASE "SELECT peer FROM servers WHERE subnet LIKE '%.%';" | sort | tail -n 1)
local AUTO_VPN_POOL="10.50.0.1/24"
local INDEX=$(sqlite3 $SQL_DATABASE "SELECT COUNT(peer) FROM servers;")
local INDEX=$((INDEX+1))
local SERVER_PEER="wg2"$INDEX
else
if [ "${SERVER_PEER:0:3}" == "wg2" ];then
INDEX=${SERVER_PEER:3:1}
local AUTO_VPN_POOL="10.50.$((INDEX-1)).1/24" # v4.15
else
echo -e $cBRED"\a\n\t***ERROR Invalid WireGuard® 'server' Peer prefix (wg2*) '$SERVER_PEER'\n"$cRESET
return 1
fi
fi
# User specified VPN Tunnel subnet?
if [ "$VPN_POOL_USER" != "Y" ];then # v4.17 @Meshkoff
[ -z "$AUTO_VPN_POOL" ] && local AUTO_VPN_POOL="10.50.1.1/24"
local ONE_OCTET=$(echo "$AUTO_VPN_POOL" | cut -d'.' -f1)
local TWO_OCTET=$(echo "$AUTO_VPN_POOL" | cut -d'.' -f2)
local THIRD_OCTET=$(echo "$AUTO_VPN_POOL" | cut -d'.' -f3)
local REST=$(echo "$AUTO_VPN_POOL" | cut -d'.' -f4-)
local NEW_THIRD_OCTET=$((THIRD_OCTET+1))
local SERVER_CNT=$(sqlite3 $SQL_DATABASE "SELECT COUNT(peer) FROM servers;")
[ $SERVER_CNT -ge $NEW_THIRD_OCTET ] && local NEW_THIRD_OCTET=$((SERVER_CNT+1))
[ "$USE_IPV4" == "Y" ] && local VPN_POOL4=$(echo -e "$ONE_OCTET.$TWO_OCTET.$NEW_THIRD_OCTET.$REST")
if [ "$USE_IPV6" == "Y" ] && [ -z "$VPN_POOL6" ];then
[ -z "$TWO_OCTET" ] && local TWO_OCTET="50"
[ -z "$NEW_THIRD_OCTET" ] && local NEW_THIRD_OCTET="1"
case $USE_ULA in
4)
local VPN_POOL6="fd00:${TWO_OCTET}:${NEW_THIRD_OCTET}::1/64"
;;
*)
local VPN_POOL6=$(Generate_IPv6_ULA "$USE_ULA") # v4.16
[ "$VPN_POOL6" == "***ERROR Requires Entware module" ] && local VPN_POOL6="fd00:${TWO_OCTET}:${NEW_THIRD_OCTET}::1/64"
;;
esac
fi
fi
[ -n "$VPN_POOL4" ] && local VPN_POOL=$VPN_POOL4 # v4.15
if [ -n "$VPN_POOL4" ] && [ -n "$VPN_POOL6" ];then # v4.15
local VPN_POOL=$VPN_POOL4","$VPN_POOL6
local IPV6_TXT="(IPv4/IPv6) " # v4.15
fi
if [ "$USE_IPV4" == "N" ];then # v4.15
if [ -n "$VPN_POOL6" ];then # v4.15
local VPN_POOL=$VPN_POOL6 # v4.15
local IPV6_TXT="(IPv6) " # v4.15
else
echo -e $cBRED"\a\n\t***ERROR Create new WireGuard® ${IPV6_TXT}'server' Peer has missing ${cRESET}IPv6 Private subnet${cBRED} - use $cRESET'ipv6[=]'$cBRED arg\n"$cRESET
return 1
fi
fi
# User specified Listen Port?
[ -z "$LISTEN_PORT_USER" ] && LISTEN_PORT=$((LISTEN_PORT+INDEX))
for THIS in $(echo "$VPN_POOL" | tr ',' ' ') # v4.15
do
if [ -z "$(echo "$THIS" | grep -F ":")" ];then
[ -z "$(echo "$THIS" | Is_IPv4_CIDR)" ] && { echo -e $cBRED"\a\n\t***ERROR: '$THIS' must be IPv4 CIDR"$cRESET; return 1; } # v4.15
else
# ANY IPv6 but don't allow Link-Local IPv6 (i.e. fe80::/10 but in practice, only fe80::/64 is commonly used) # v4.16
[ "${THIS:0:4}" == "fe80" ] && { echo -e $cBRED"\a\n\t***ERROR: IPv6 Link-Local address '$THIS' NOT allowed!"$cRESET; return 1; } # v4.16
fi
done
if [ -f ${CONFIG_DIR}${SERVER_PEER}.conf ] || [ -n "$(grep -E "^$SERVER_PEER" ${INSTALL_DIR}WireguardVPN.conf)" ];then
echo -e $cBRED"\a\n\t***ERROR Invalid WireGuard® 'server' Peer '$SERVER_PEER' already exists\n"$cRESET
return 1
fi
local WANIPADDR=$(nvram get wan0_ipaddr)
[ -n "$(echo "$WANIPADDR" | Is_Private_IPv4)" ] && echo -e ${cRESET}${cBRED}${aBOLD}"\a\n\t*** Ensure Upstream router Port Foward entry for port:${cBMAG}${LISTEN_PORT}${cRESET}${cBRED}${aBOLD} ***"$cRESET
echo -e $cBWHT"\n\tPress$cBGRE y$cRESET to$cBGRE Create ${cBCYA}${IPV6_TXT}${cBGRE}'server' Peer (${cBMAG}${SERVER_PEER}${cBGRE}) ${cBCYA}${VPN_POOL}:${LISTEN_PORT}${cRESET} or press$cBGRE [Enter] to SKIP." # v4.15
[ -z "$WEBUI_AUTOREPLY" ] && read -r "ANS" || echo -e "$WEBUI_AUTOREPLY" >&2
if [ -z "$WEBUI_AUTOREPLY" ] && [ "$ANS" != "y" ];then
return 1
fi
echo -e $cBCYA"\tCreating WireGuard® Private/Public key-pair for ${IPV6_TXT}'server' Peer ${cBMAG}${SERVER_PEER}${cBCYA} on $HARDWARE_MODEL (v$BUILDNO)"$cRESET
if [ -n "$(which wg)" ];then
wg genkey | tee ${CONFIG_DIR}${SERVER_PEER}_private.key | wg pubkey > ${CONFIG_DIR}${SERVER_PEER}_public.key
local PRI_KEY=$(cat ${CONFIG_DIR}${SERVER_PEER}_private.key)
local PRI_KEY=$(Convert_Key "$PRI_KEY")
local PUB_KEY=$(cat ${CONFIG_DIR}${SERVER_PEER}_public.key)
local PUB_KEY=$(Convert_Key "$PUB_KEY") # v4.14
#sed -i "/^PrivateKey/ s~[^ ]*[^ ]~$PRI_KEY~3" ${CONFIG_DIR}${SERVER_PEER}.conf
local ANNOTATE="# $HARDWARE_MODEL ${IPV6_TXT}Server $INDEX"
# Create Server template
cat > ${CONFIG_DIR}${SERVER_PEER}.conf << EOF
$ANNOTATE
[Interface]
PrivateKey = $PRI_KEY
Address = $VPN_POOL
ListenPort = $LISTEN_PORT
EOF
# e.g. Accept a WireGuard connection from say YOUR mobile device to the router
# see '${CONFIG_DIR}mobilephone_private.key'
# Peer Example
#[Peer]
#PublicKey = Replace_with_the_Public_Key_of_YOUR_mobile_device
#AllowedIPs = PEER.ip.xxx.xxx/32
#PresharedKey = Replace_with_the_Pre-shared_Key_of_YOUR_mobile_device
# Peer Example End
chmod 600 ${CONFIG_DIR}${SERVER_PEER}.conf # v4.15 Prevent wg-quick "Warning: '/opt/etc/wireguard.d/wg22.conf' is world accessible"
sqlite3 $SQL_DATABASE "INSERT INTO servers values('$SERVER_PEER','$AUTO','${VPN_POOL}','$LISTEN_PORT','$PUB_KEY','$PRI_KEY','$ANNOTATE');"
fi
# shellcheck disable=SC1087
echo -e $cBWHT"\tPress$cBGRE y$cRESET to$cBGRE Start ${cBCYA}${IPV6_TXT}${cBGRE}'server' Peer (${cBMAG}${SERVER_PEER}$cBGRE)$cRESET or press $cBGRE[Enter] to SKIP."
[ -z "$WEBUI_AUTOREPLY" ] && read -r "ANS" || echo -e "$WEBUI_AUTOREPLY" >&2
if [ -n "$WEBUI_AUTOREPLY" ] || [ "$ANS" == "y" ];then
Manage_Wireguard_Sessions "start" "$SERVER_PEER"
fi
Show_Peer_Status "show" # v3.03
# Firewall rule to listen on multiple ports?
# e.g. iptables -t nat -I PREROUTING -i $WAN_IF -d <yourIP/32> -p udp -m multiport --dports 53,80,4444 -j REDIRECT --to-ports $LISTEN_PORT
}
Delete_Peer() {