-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathpaqctl.sh
More file actions
7626 lines (6905 loc) · 321 KB
/
paqctl.sh
File metadata and controls
7626 lines (6905 loc) · 321 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
#
# ╔═══════════════════════════════════════════════════════════════════╗
# ║ PAQCTL - Paqet Manager v1.0.0 ║
# ║ ║
# ║ One-click setup for Paqet raw-socket proxy ║
# ║ ║
# ║ * Installs paqet binary + libpcap ║
# ║ * Auto-detects network config ║
# ║ * Configures server or client mode ║
# ║ * Manages iptables rules ║
# ║ * Auto-start on boot via systemd/OpenRC/SysVinit ║
# ║ * Easy management via CLI or interactive menu ║
# ║ ║
# ║ Paqet: https://github.com/SamNet-dev/paqctl ║
# ╚═══════════════════════════════════════════════════════════════════╝
#
# Usage:
# curl -sL https://raw.githubusercontent.com/SamNet-dev/paqctl/main/paqctl.sh | sudo bash
#
# Or: wget paqctl.sh && sudo bash paqctl.sh
#
set -eo pipefail
# Require bash
if [ -z "$BASH_VERSION" ]; then
echo "Error: This script requires bash. Please run with: bash $0"
exit 1
fi
VERSION="1.0.0"
# Pinned versions for stability (update these after testing new releases)
PAQET_VERSION_PINNED="v1.0.0-alpha.17"
XRAY_VERSION_PINNED="v26.2.4"
GFK_VERSION_PINNED="v1.0.0"
PAQET_REPO="hanselime/paqet"
PAQET_API_URL="https://api.github.com/repos/${PAQET_REPO}/releases/latest"
INSTALL_DIR="${INSTALL_DIR:-/opt/paqctl}"
BACKUP_DIR="$INSTALL_DIR/backups"
GFK_REPO="SamNet-dev/paqctl"
GFK_BRANCH="main"
GFK_RAW_URL="https://raw.githubusercontent.com/${GFK_REPO}/${GFK_BRANCH}/gfk"
GFK_DIR="$INSTALL_DIR/gfk"
MICROSOCKS_REPO="rofl0r/microsocks"
BACKEND="${BACKEND:-paqet}"
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
MAGENTA='\033[0;35m'
BOLD='\033[1m'
DIM='\033[2m'
NC='\033[0m'
#═══════════════════════════════════════════════════════════════════════
# Utility Functions
#═══════════════════════════════════════════════════════════════════════
print_header() {
echo -e "${CYAN}"
echo "╔════════════════════════════════════════════════════════════════╗"
echo "║ PAQCTL - Paqet Manager v${VERSION} ║"
echo "║ Raw-socket encrypted proxy - bypass firewalls ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo -e "${NC}"
}
log_info() {
echo -e "${BLUE}[INFO]${NC} $1"
}
log_success() {
echo -e "${GREEN}[✓]${NC} $1"
}
log_warn() {
echo -e "${YELLOW}[!]${NC} $1"
}
log_error() {
echo -e "${RED}[✗]${NC} $1"
}
check_root() {
if [ "$EUID" -ne 0 ]; then
log_error "This script must be run as root (use sudo)"
exit 1
fi
}
detect_os() {
OS="unknown"
OS_VERSION="unknown"
OS_FAMILY="unknown"
HAS_SYSTEMD=false
PKG_MANAGER="unknown"
if [ -f /etc/os-release ]; then
. /etc/os-release
OS="$ID"
OS_VERSION="${VERSION_ID:-unknown}"
elif [ -f /etc/redhat-release ]; then
OS="rhel"
elif [ -f /etc/debian_version ]; then
OS="debian"
elif [ -f /etc/alpine-release ]; then
OS="alpine"
elif [ -f /etc/arch-release ]; then
OS="arch"
elif [ -f /etc/SuSE-release ] || [ -f /etc/SUSE-brand ]; then
OS="opensuse"
else
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
fi
case "$OS" in
ubuntu|debian|linuxmint|pop|elementary|zorin|kali|raspbian)
OS_FAMILY="debian"
PKG_MANAGER="apt"
;;
rhel|centos|fedora|rocky|almalinux|oracle|amazon|amzn)
OS_FAMILY="rhel"
if command -v dnf &>/dev/null; then
PKG_MANAGER="dnf"
else
PKG_MANAGER="yum"
fi
;;
arch|manjaro|endeavouros|garuda)
OS_FAMILY="arch"
PKG_MANAGER="pacman"
;;
opensuse|opensuse-leap|opensuse-tumbleweed|sles)
OS_FAMILY="suse"
PKG_MANAGER="zypper"
;;
alpine)
OS_FAMILY="alpine"
PKG_MANAGER="apk"
;;
*)
OS_FAMILY="unknown"
PKG_MANAGER="unknown"
;;
esac
if command -v systemctl &>/dev/null && [ -d /run/systemd/system ]; then
HAS_SYSTEMD=true
fi
log_info "Detected: $OS ($OS_FAMILY family), Package manager: $PKG_MANAGER"
}
install_package() {
local package="$1"
log_info "Installing $package..."
case "$PKG_MANAGER" in
apt)
apt-get update -q 2>/dev/null || log_warn "apt-get update failed, attempting install anyway..."
if apt-get install -y -q "$package"; then
log_success "$package installed successfully"
else
log_error "Failed to install $package"
return 1
fi
;;
dnf)
if dnf install -y -q "$package"; then
log_success "$package installed successfully"
else
log_error "Failed to install $package"
return 1
fi
;;
yum)
if yum install -y -q "$package"; then
log_success "$package installed successfully"
else
log_error "Failed to install $package"
return 1
fi
;;
pacman)
if pacman -Sy --noconfirm "$package"; then
log_success "$package installed successfully"
else
log_error "Failed to install $package"
return 1
fi
;;
zypper)
if zypper install -y -n "$package"; then
log_success "$package installed successfully"
else
log_error "Failed to install $package"
return 1
fi
;;
apk)
if apk add --no-cache "$package"; then
log_success "$package installed successfully"
else
log_error "Failed to install $package"
return 1
fi
;;
*)
log_warn "Unknown package manager. Please install $package manually."
return 1
;;
esac
}
check_dependencies() {
if [ "$OS_FAMILY" = "alpine" ]; then
if ! command -v bash &>/dev/null; then
apk add --no-cache bash 2>/dev/null
fi
fi
if ! command -v curl &>/dev/null; then
install_package curl || log_warn "Could not install curl automatically"
fi
if ! command -v tar &>/dev/null; then
install_package tar || log_warn "Could not install tar automatically"
fi
if ! command -v ip &>/dev/null; then
case "$PKG_MANAGER" in
apt) install_package iproute2 || log_warn "Could not install iproute2" ;;
dnf|yum) install_package iproute || log_warn "Could not install iproute" ;;
pacman) install_package iproute2 || log_warn "Could not install iproute2" ;;
zypper) install_package iproute2 || log_warn "Could not install iproute2" ;;
apk) install_package iproute2 || log_warn "Could not install iproute2" ;;
esac
fi
if ! command -v tput &>/dev/null; then
case "$PKG_MANAGER" in
apt) install_package ncurses-bin || log_warn "Could not install ncurses-bin" ;;
apk) install_package ncurses || log_warn "Could not install ncurses" ;;
*) install_package ncurses || log_warn "Could not install ncurses" ;;
esac
fi
# Firewall rules: use firewalld if active, otherwise iptables
if _is_firewalld_active; then
log_info "firewalld detected — will use firewall-cmd for rules"
elif ! command -v iptables &>/dev/null; then
log_info "Installing iptables..."
case "$PKG_MANAGER" in
apt) install_package iptables || log_warn "Could not install iptables - firewall rules may not work" ;;
dnf|yum) install_package iptables || log_warn "Could not install iptables" ;;
pacman) install_package iptables || log_warn "Could not install iptables" ;;
zypper) install_package iptables || log_warn "Could not install iptables" ;;
apk) install_package iptables || log_warn "Could not install iptables" ;;
*) log_warn "Please install iptables manually for firewall rules to work" ;;
esac
fi
# openssl is required for GFK certificate generation
if ! command -v openssl &>/dev/null; then
install_package openssl || log_warn "Could not install openssl"
fi
# libpcap is required by paqet
install_libpcap
}
install_libpcap() {
log_info "Checking for libpcap..."
# Check if already available
if ldconfig -p 2>/dev/null | grep -q libpcap; then
log_success "libpcap already installed"
return 0
fi
case "$PKG_MANAGER" in
apt) install_package libpcap-dev ;;
dnf|yum) install_package libpcap-devel ;;
pacman) install_package libpcap ;;
zypper) install_package libpcap-devel ;;
apk) install_package libpcap-dev ;;
*) log_warn "Please install libpcap manually for your distribution"; return 1 ;;
esac
# Fedora/RHEL: ensure libpcap.so.1 symlink exists (package may only install versioned .so)
if [ "$PKG_MANAGER" = "dnf" ] || [ "$PKG_MANAGER" = "yum" ]; then
if ! ldconfig -p 2>/dev/null | grep -q 'libpcap\.so\.1 '; then
local _pcap_lib
_pcap_lib=$(find /usr/lib64 /usr/lib /lib64 /lib -name 'libpcap.so.*' -type f 2>/dev/null | head -1)
if [ -n "$_pcap_lib" ]; then
local _libdir
_libdir=$(dirname "$_pcap_lib")
if [ ! -e "${_libdir}/libpcap.so.1" ]; then
log_info "Creating libpcap.so.1 symlink for Fedora/RHEL compatibility"
ln -sf "$_pcap_lib" "${_libdir}/libpcap.so.1"
fi
ldconfig 2>/dev/null || true
fi
fi
fi
}
detect_arch() {
local arch
arch=$(uname -m)
case "$arch" in
x86_64|amd64) echo "amd64" ;;
aarch64|arm64) echo "arm64" ;;
armv7l|armv7|armhf) echo "arm32" ;;
mips64el|mips64le) echo "mips64le" ;;
mips64) echo "mips64" ;;
mipsel|mipsle) echo "mipsle" ;;
mips) echo "mips" ;;
*)
log_error "Unsupported architecture: $arch"
log_error "Paqet supports amd64, arm64, arm32, and MIPS variants"
exit 1
;;
esac
}
#═══════════════════════════════════════════════════════════════════════
# Input Validation Functions
#═══════════════════════════════════════════════════════════════════════
_validate_port() { [[ "$1" =~ ^[0-9]+$ ]] && [ "$1" -ge 1 ] && [ "$1" -le 65535 ]; }
_validate_ip() {
[[ "$1" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] || return 1
local IFS='.'; set -- $1
[ "$1" -le 255 ] && [ "$2" -le 255 ] && [ "$3" -le 255 ] && [ "$4" -le 255 ]
}
_validate_mac() { [[ "$1" =~ ^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$ ]]; }
_validate_iface() { [[ "$1" =~ ^[a-zA-Z0-9._-]+$ ]] && [ ${#1} -le 64 ]; }
_validate_version_tag() {
[[ "$1" =~ ^v?[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9._-]+)?$ ]]
}
#═══════════════════════════════════════════════════════════════════════
# Binary Download & Install
#═══════════════════════════════════════════════════════════════════════
# Retry helper with exponential backoff for API requests
_curl_with_retry() {
local url="$1"
local max_attempts="${2:-3}"
local attempt=1
local delay=2
local response=""
while [ $attempt -le $max_attempts ]; do
response=$(curl -s --max-time 15 "$url" 2>/dev/null)
if [ -n "$response" ]; then
# Check for rate limit response
if echo "$response" | grep -q '"message".*rate limit'; then
log_warn "GitHub API rate limited, waiting ${delay}s (attempt $attempt/$max_attempts)"
sleep $delay
delay=$((delay * 2))
attempt=$((attempt + 1))
continue
fi
echo "$response"
return 0
fi
[ $attempt -lt $max_attempts ] && sleep $delay
delay=$((delay * 2))
attempt=$((attempt + 1))
done
return 1
}
get_latest_version() {
local response
response=$(_curl_with_retry "$PAQET_API_URL" 3)
if [ -z "$response" ]; then
log_error "Failed to query GitHub API after retries"
return 1
fi
local tag
tag=$(echo "$response" | grep -o '"tag_name"[[:space:]]*:[[:space:]]*"[^"]*"' | head -1 | grep -o '"[^"]*"$' | tr -d '"')
if [ -z "$tag" ]; then
log_error "Could not determine latest paqet version"
return 1
fi
if ! _validate_version_tag "$tag"; then
log_error "Invalid version tag format: $tag"
return 1
fi
echo "$tag"
}
download_paqet() {
local version="$1"
local arch
arch=$(detect_arch)
local os_name="linux"
local ext="tar.gz"
local filename="paqet-${os_name}-${arch}-${version}.${ext}"
local url="https://github.com/${PAQET_REPO}/releases/download/${version}/${filename}"
log_info "Downloading paqet ${version} for ${os_name}/${arch}..."
if ! mkdir -p "$INSTALL_DIR/bin"; then
log_error "Failed to create directory $INSTALL_DIR/bin"
return 1
fi
local tmp_file
tmp_file=$(mktemp "/tmp/paqet-download-XXXXXXXX.${ext}") || { log_error "Failed to create temp file"; return 1; }
# Try curl first, fallback to wget
local download_ok=false
if curl -sL --max-time 180 --retry 3 --retry-delay 5 --fail -o "$tmp_file" "$url" 2>/dev/null; then
download_ok=true
elif command -v wget &>/dev/null; then
log_info "curl failed, trying wget..."
rm -f "$tmp_file"
if wget -q --timeout=180 --tries=3 -O "$tmp_file" "$url" 2>/dev/null; then
download_ok=true
fi
fi
if [ "$download_ok" != "true" ]; then
log_error "Failed to download: $url"
log_error "Try manual download: wget '$url' and place binary in $INSTALL_DIR/bin/"
rm -f "$tmp_file"
return 1
fi
# Validate download
local fsize
fsize=$(stat -c%s "$tmp_file" 2>/dev/null || stat -f%z "$tmp_file" 2>/dev/null || wc -c < "$tmp_file" 2>/dev/null || echo 0)
if [ "$fsize" -lt 1000 ]; then
log_error "Downloaded file is too small ($fsize bytes). Download may have failed."
rm -f "$tmp_file"
return 1
fi
# Extract
log_info "Extracting..."
local tmp_extract
tmp_extract=$(mktemp -d "/tmp/paqet-extract-XXXXXXXX") || { log_error "Failed to create temp file"; return 1; }
if ! tar -xzf "$tmp_file" -C "$tmp_extract" 2>/dev/null; then
log_error "Failed to extract archive"
rm -f "$tmp_file"
rm -rf "$tmp_extract"
return 1
fi
# Find the binary in extracted files
local binary_name="paqet_${os_name}_${arch}"
local found_binary=""
found_binary=$(find "$tmp_extract" -name "$binary_name" -type f 2>/dev/null | head -1)
if [ -z "$found_binary" ]; then
# Try alternate name patterns
found_binary=$(find "$tmp_extract" -name "paqet*" -type f -executable 2>/dev/null | head -1)
fi
if [ -z "$found_binary" ]; then
found_binary=$(find "$tmp_extract" -name "paqet*" -type f 2>/dev/null | head -1)
fi
if [ -z "$found_binary" ]; then
log_error "Could not find paqet binary in archive"
rm -f "$tmp_file"
rm -rf "$tmp_extract"
return 1
fi
# Stop paqet if running to avoid "Text file busy" error
if pgrep -f "$INSTALL_DIR/bin/paqet" &>/dev/null; then
log_info "Stopping paqet to update binary..."
pkill -f "$INSTALL_DIR/bin/paqet" 2>/dev/null || true
sleep 1
fi
if ! cp "$found_binary" "$INSTALL_DIR/bin/paqet"; then
log_error "Failed to copy paqet binary to $INSTALL_DIR/bin/"
rm -f "$tmp_file"
rm -rf "$tmp_extract"
return 1
fi
if ! chmod +x "$INSTALL_DIR/bin/paqet"; then
log_error "Failed to make paqet binary executable"
return 1
fi
# Copy example configs if they exist
find "$tmp_extract" -name "*.yaml.example" -exec cp {} "$INSTALL_DIR/" \; 2>/dev/null || true
rm -f "$tmp_file"
rm -rf "$tmp_extract"
# Verify binary runs
if "$INSTALL_DIR/bin/paqet" version &>/dev/null; then
log_success "paqet ${version} installed successfully"
else
log_warn "paqet binary installed but version check failed (may need libpcap)"
fi
}
#═══════════════════════════════════════════════════════════════════════
# Network Auto-Detection
#═══════════════════════════════════════════════════════════════════════
detect_network() {
log_info "Auto-detecting network configuration..."
# Default interface - handle both standard "via X dev Y" and OpenVZ "dev Y scope link" formats
# Standard: "default via 192.168.1.1 dev eth0" -> $5 = eth0
# OpenVZ: "default dev venet0 scope link" -> $3 = venet0
local _route_line
_route_line=$(ip route show default 2>/dev/null | head -1)
if [[ "$_route_line" == *" via "* ]]; then
# Standard format with gateway
DETECTED_IFACE=$(echo "$_route_line" | awk '{print $5}')
elif [[ "$_route_line" == *" dev "* ]]; then
# OpenVZ/direct format without gateway
DETECTED_IFACE=$(echo "$_route_line" | awk '{print $3}')
fi
# Validate detected interface exists
if [ -n "$DETECTED_IFACE" ] && ! ip link show "$DETECTED_IFACE" &>/dev/null; then
DETECTED_IFACE=""
fi
if [ -z "$DETECTED_IFACE" ]; then
# Skip loopback, docker, veth, bridge, and other virtual interfaces
# Note: grep -v returns exit 1 if no matches, so we add || true for pipefail
DETECTED_IFACE=$(ip -o link show 2>/dev/null | awk -F': ' '{gsub(/ /,"",$2); print $2}' | { grep -vE '^(lo|docker[0-9]|br-|veth|virbr|tun|tap|wg)' || true; } | head -1)
fi
# Local IP - wrap entire pipeline to prevent pipefail exit
if [ -n "$DETECTED_IFACE" ]; then
# Note: wrap in subshell with || true to handle cases where interface is invalid or has no IP
DETECTED_IP=$( (ip -4 addr show "$DETECTED_IFACE" 2>/dev/null | awk '/inet /{print $2}' | cut -d/ -f1 | { grep -o '[0-9.]*' || true; } | head -1) || true )
fi
if [ -z "$DETECTED_IP" ]; then
DETECTED_IP=$(hostname -I 2>/dev/null | awk '{print $1}')
[ -z "$DETECTED_IP" ] && DETECTED_IP=$(ip -4 addr show scope global 2>/dev/null | awk '/inet /{gsub(/\/.*/, "", $2); print $2; exit}')
fi
# Gateway IP - only present in standard "via X" format, not in OpenVZ
if [[ "$_route_line" == *" via "* ]]; then
DETECTED_GATEWAY=$(echo "$_route_line" | awk '{print $3}')
else
DETECTED_GATEWAY=""
fi
# Gateway MAC
DETECTED_GW_MAC=""
if [ -n "$DETECTED_GATEWAY" ]; then
# Try ip neigh first (most reliable on Linux)
DETECTED_GW_MAC=$(ip neigh show "$DETECTED_GATEWAY" 2>/dev/null | awk '/lladdr/{print $5; exit}')
if [ -z "$DETECTED_GW_MAC" ]; then
# Trigger ARP resolution
ping -c 1 -W 2 "$DETECTED_GATEWAY" &>/dev/null || true
sleep 1
DETECTED_GW_MAC=$(ip neigh show "$DETECTED_GATEWAY" 2>/dev/null | awk '/lladdr/{print $5; exit}')
fi
if [ -z "$DETECTED_GW_MAC" ] && command -v arp &>/dev/null; then
# Fallback: parse arp output looking for MAC pattern
# Note: grep returns exit 1 if no matches, so we add || true for pipefail
DETECTED_GW_MAC=$(arp -n "$DETECTED_GATEWAY" 2>/dev/null | { grep -oE '([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}' || true; } | head -1)
fi
fi
log_info "Interface: ${DETECTED_IFACE:-unknown}"
log_info "Local IP: ${DETECTED_IP:-unknown}"
log_info "Gateway: ${DETECTED_GATEWAY:-unknown}"
log_info "GW MAC: ${DETECTED_GW_MAC:-unknown}"
}
#═══════════════════════════════════════════════════════════════════════
# Configuration Wizard
#═══════════════════════════════════════════════════════════════════════
run_config_wizard() {
echo ""
echo -e "${CYAN}═══════════════════════════════════════════════════════════════${NC}"
echo -e "${BOLD} PAQCTL CONFIGURATION WIZARD${NC}"
echo -e "${CYAN}═══════════════════════════════════════════════════════════════${NC}"
echo ""
# Backend selection
echo -e "${BOLD}Select backend:${NC}"
echo " 1. paqet (Go/KCP, built-in SOCKS5, single binary)"
echo " 2. gfw-knocker (Python/QUIC, port forwarding + SOCKS5)"
echo ""
local backend_choice
read -p " Enter choice [1/2]: " backend_choice < /dev/tty || true
case "$backend_choice" in
2) BACKEND="gfw-knocker" ;;
*) BACKEND="paqet" ;;
esac
echo ""
log_info "Selected backend: $BACKEND"
echo ""
# Role selection
echo -e "${BOLD}Select role:${NC}"
echo " 1. Server (accept connections from clients)"
echo " 2. Client (connect to a server, provides SOCKS5 proxy)"
echo ""
local role_choice
read -p " Enter choice [1/2]: " role_choice < /dev/tty || true
case "$role_choice" in
1) ROLE="server" ;;
2) ROLE="client" ;;
*)
log_warn "Invalid choice. Defaulting to server."
ROLE="server"
;;
esac
echo ""
log_info "Selected role: $ROLE"
if [ "$BACKEND" = "paqet" ]; then
_wizard_paqet
else
_wizard_gfk
fi
# Save settings
save_settings
}
_wizard_paqet() {
# Auto-detect network
detect_network
echo ""
# Confirm/override interface
echo -e "${BOLD}Network interface${NC} [${DETECTED_IFACE:-eth0}]:"
read -p " Interface: " input < /dev/tty || true
IFACE="${input:-$DETECTED_IFACE}"
IFACE="${IFACE:-eth0}"
if ! _validate_iface "$IFACE"; then
log_warn "Invalid interface name. Using eth0."
IFACE="eth0"
fi
# Confirm/override local IP
echo -e "${BOLD}Local IP${NC} [${DETECTED_IP:-auto}]:"
read -p " IP: " input < /dev/tty || true
LOCAL_IP="${input:-$DETECTED_IP}"
if [ -n "$LOCAL_IP" ] && ! _validate_ip "$LOCAL_IP"; then
log_warn "Invalid IP format. Using detected IP."
LOCAL_IP="$DETECTED_IP"
fi
# Confirm/override gateway MAC
echo -e "${BOLD}Gateway MAC address${NC} [${DETECTED_GW_MAC:-auto}]:"
read -p " MAC: " input < /dev/tty || true
GW_MAC="${input:-$DETECTED_GW_MAC}"
if [ -z "$GW_MAC" ] || ! _validate_mac "$GW_MAC"; then
if [ -n "$GW_MAC" ]; then
log_warn "Invalid MAC format detected."
else
log_error "Could not detect gateway MAC address."
fi
log_error "Please enter it manually (format: aa:bb:cc:dd:ee:ff)"
read -p " Gateway MAC: " GW_MAC < /dev/tty || true
if [ -z "$GW_MAC" ] || ! _validate_mac "$GW_MAC"; then
log_error "Valid gateway MAC is required for paqet to function."
exit 1
fi
fi
if [ "$ROLE" = "server" ]; then
echo ""
echo -e "${BOLD}Listen port${NC} [8443]:"
read -p " Port: " input < /dev/tty || true
LISTEN_PORT="${input:-8443}"
if ! [[ "$LISTEN_PORT" =~ ^[0-9]+$ ]] || [ "$LISTEN_PORT" -lt 1 ] || [ "$LISTEN_PORT" -gt 65535 ]; then
log_warn "Invalid port. Using default 8443."
LISTEN_PORT=8443
fi
echo ""
log_info "Generating encryption key..."
ENCRYPTION_KEY=$("$INSTALL_DIR/bin/paqet" secret 2>/dev/null || true)
if [ -z "$ENCRYPTION_KEY" ]; then
log_warn "Could not auto-generate key. Using openssl fallback..."
ENCRYPTION_KEY=$(openssl rand -base64 32 2>/dev/null | tr -d '=+/' | head -c 32 || true)
fi
if [ -z "$ENCRYPTION_KEY" ] || [ "${#ENCRYPTION_KEY}" -lt 16 ]; then
log_error "Failed to generate a valid encryption key"
return 1
fi
echo ""
echo -e "${GREEN}${BOLD} Encryption Key: ${ENCRYPTION_KEY}${NC}"
echo ""
echo -e "${YELLOW} IMPORTANT: Save this key! Clients need it to connect.${NC}"
echo ""
SOCKS_PORT=""
else
echo ""
echo -e "${BOLD}Remote server address${NC} (IP:PORT):"
read -p " Server: " REMOTE_SERVER < /dev/tty || true
if [ -z "$REMOTE_SERVER" ]; then
log_error "Remote server address is required."
exit 1
fi
echo ""
echo -e "${BOLD}Encryption key${NC} (from server setup):"
read -p " Key: " ENCRYPTION_KEY < /dev/tty || true
if [ -z "$ENCRYPTION_KEY" ]; then
log_error "Encryption key is required."
exit 1
fi
echo ""
echo -e "${BOLD}SOCKS5 listen port${NC} [1080]:"
read -p " SOCKS port: " input < /dev/tty || true
SOCKS_PORT="${input:-1080}"
if ! [[ "$SOCKS_PORT" =~ ^[0-9]+$ ]] || [ "$SOCKS_PORT" -lt 1 ] || [ "$SOCKS_PORT" -gt 65535 ]; then
log_warn "Invalid port. Using default 1080."
SOCKS_PORT=1080
fi
LISTEN_PORT=""
fi
# Generate YAML config
generate_config
}
_wizard_gfk() {
if [ "$ROLE" = "server" ]; then
# Server IP (this machine's public IP)
detect_network
echo ""
echo -e "${BOLD}This server's public IP${NC} [${DETECTED_IP:-}]:"
read -p " IP: " input < /dev/tty || true
GFK_SERVER_IP="${input:-$DETECTED_IP}"
if [ -z "$GFK_SERVER_IP" ] || ! _validate_ip "$GFK_SERVER_IP"; then
log_error "Valid server IP is required."
exit 1
fi
# VIO TCP port (must be closed to OS, raw socket handles it)
echo ""
echo -e "${BOLD}VIO TCP port${NC} [45000] (raw socket port, must be blocked by firewall):"
read -p " Port: " input < /dev/tty || true
GFK_VIO_PORT="${input:-45000}"
if ! _validate_port "$GFK_VIO_PORT"; then
log_warn "Invalid port. Using default 45000."
GFK_VIO_PORT=45000
fi
# QUIC port
echo ""
echo -e "${BOLD}QUIC tunnel port${NC} [25000]:"
read -p " Port: " input < /dev/tty || true
GFK_QUIC_PORT="${input:-25000}"
if ! _validate_port "$GFK_QUIC_PORT"; then
log_warn "Invalid port. Using default 25000."
GFK_QUIC_PORT=25000
fi
# Auth code
echo ""
local auto_auth
auto_auth=$(openssl rand -base64 16 2>/dev/null | tr -d '=+/' | head -c 16)
echo -e "${BOLD}QUIC auth code${NC} [auto-generated]:"
read -p " Auth code: " input < /dev/tty || true
GFK_AUTH_CODE="${input:-$auto_auth}"
echo ""
echo -e "${GREEN}${BOLD} Auth Code: ${GFK_AUTH_CODE}${NC}"
echo ""
echo -e "${YELLOW} IMPORTANT: Save this auth code! Clients need it to connect.${NC}"
echo ""
# Port mappings
echo -e "${BOLD}TCP port mappings${NC} (local:remote, comma-separated) [14000:443]:"
echo -e " ${DIM}Example: 14000:443,15000:2096,16000:10809${NC}"
read -p " Mappings: " input < /dev/tty || true
GFK_PORT_MAPPINGS="${input:-14000:443}"
MICROSOCKS_PORT=""
else
# Client: server IP
echo ""
echo -e "${BOLD}Remote server IP${NC} (server's public IP):"
read -p " Server IP: " GFK_SERVER_IP < /dev/tty || true
if [ -z "$GFK_SERVER_IP" ] || ! _validate_ip "$GFK_SERVER_IP"; then
log_error "Valid server IP is required."
exit 1
fi
# Server's VIO TCP port (what port the server is listening on)
echo ""
echo -e "${BOLD}Server's VIO TCP port${NC} [45000] (must match server config):"
read -p " Port: " input < /dev/tty || true
GFK_VIO_PORT="${input:-45000}"
if ! _validate_port "$GFK_VIO_PORT"; then
log_warn "Invalid port. Using default 45000."
GFK_VIO_PORT=45000
fi
# Local VIO client port (client's local binding)
echo ""
echo -e "${BOLD}Local VIO client port${NC} [40000]:"
read -p " Port: " input < /dev/tty || true
GFK_VIO_CLIENT_PORT="${input:-40000}"
if ! _validate_port "$GFK_VIO_CLIENT_PORT"; then
log_warn "Invalid port. Using default 40000."
GFK_VIO_CLIENT_PORT=40000
fi
# Server's QUIC port
echo ""
echo -e "${BOLD}Server's QUIC port${NC} [25000] (must match server config):"
read -p " Port: " input < /dev/tty || true
GFK_QUIC_PORT="${input:-25000}"
if ! _validate_port "$GFK_QUIC_PORT"; then
log_warn "Invalid port. Using default 25000."
GFK_QUIC_PORT=25000
fi
# Local QUIC client port
echo ""
echo -e "${BOLD}Local QUIC client port${NC} [20000]:"
read -p " Port: " input < /dev/tty || true
GFK_QUIC_CLIENT_PORT="${input:-20000}"
if ! _validate_port "$GFK_QUIC_CLIENT_PORT"; then
log_warn "Invalid port. Using default 20000."
GFK_QUIC_CLIENT_PORT=20000
fi
# Auth code (from server)
echo ""
echo -e "${BOLD}QUIC auth code${NC} (from server setup):"
read -p " Auth code: " GFK_AUTH_CODE < /dev/tty || true
if [ -z "$GFK_AUTH_CODE" ]; then
log_error "Auth code is required."
exit 1
fi
# Port mappings (must match server)
echo ""
echo -e "${BOLD}TCP port mappings${NC} (must match server) [14000:443]:"
read -p " Mappings: " input < /dev/tty || true
GFK_PORT_MAPPINGS="${input:-14000:443}"
fi
# Generate GFK config
generate_gfk_config
}
generate_config() {
log_info "Generating paqet configuration..."
# Validate required fields
if [ -z "$IFACE" ] || [ -z "$LOCAL_IP" ] || [ -z "$GW_MAC" ] || [ -z "$ENCRYPTION_KEY" ]; then
log_error "Missing required configuration fields (interface, ip, gateway_mac, or secret)"
return 1
fi
if [ "$ROLE" = "server" ]; then
if [ -z "$LISTEN_PORT" ]; then log_error "Missing listen port"; return 1; fi
else
if [ -z "$REMOTE_SERVER" ] || [ -z "$SOCKS_PORT" ]; then
log_error "Missing server address or SOCKS port"
return 1
fi
local _rs_ip="${REMOTE_SERVER%:*}" _rs_port="${REMOTE_SERVER##*:}"
if ! _validate_ip "$_rs_ip" || ! _validate_port "$_rs_port"; then
log_error "Server address must be valid IP:PORT (e.g. 1.2.3.4:8443)"
return 1
fi
fi
# Escape YAML special characters to prevent injection
_escape_yaml() {
local s="$1"
# If value contains special chars, quote it
if [[ "$s" =~ [:\#\[\]{}\"\'\|\>\<\&\*\!\%\@\`] ]] || [[ "$s" =~ ^[[:space:]] ]] || [[ "$s" =~ [[:space:]]$ ]]; then
s="${s//\\/\\\\}" # Escape backslashes
s="${s//\"/\\\"}" # Escape double quotes
printf '"%s"' "$s"
else
printf '%s' "$s"
fi
}
# Ensure install directory exists
mkdir -p "$INSTALL_DIR" || { log_error "Failed to create $INSTALL_DIR"; return 1; }
local tmp_conf
tmp_conf=$(mktemp "$INSTALL_DIR/config.yaml.XXXXXXXX") || { log_error "Failed to create temp file"; return 1; }
# Set permissions on temp file before writing (fixes race condition)
chmod 600 "$tmp_conf" 2>/dev/null
(
umask 077
local _y_iface _y_ip _y_mac _y_key _y_server _y_port
_y_iface=$(_escape_yaml "$IFACE")
_y_ip=$(_escape_yaml "$LOCAL_IP")
_y_mac=$(_escape_yaml "$GW_MAC")
_y_key=$(_escape_yaml "$ENCRYPTION_KEY")
# Build TCP flags YAML array (default: ["PA"])
local _tcp_local_flags _tcp_remote_flags
_tcp_local_flags=$(echo "${PAQET_TCP_LOCAL_FLAG:-PA}" | sed 's/,/", "/g; s/.*/["&"]/')
_tcp_remote_flags=$(echo "${PAQET_TCP_REMOTE_FLAG:-PA}" | sed 's/,/", "/g; s/.*/["&"]/')
if [ "$ROLE" = "server" ]; then
cat > "$tmp_conf" << EOF
role: "server"
log:
level: "info"
listen:
addr: ":${LISTEN_PORT}"
network:
interface: "${_y_iface}"
ipv4:
addr: "${_y_ip}:${LISTEN_PORT}"
router_mac: "${_y_mac}"
tcp:
local_flag: ${_tcp_local_flags}
remote_flag: ${_tcp_remote_flags}
transport:
protocol: "kcp"
kcp:
mode: "fast"
key: "${_y_key}"
EOF
else
local _rs_ip="${REMOTE_SERVER%:*}" _rs_port="${REMOTE_SERVER##*:}"
_y_server=$(_escape_yaml "$REMOTE_SERVER")
cat > "$tmp_conf" << EOF
role: "client"
log:
level: "info"
socks5:
- listen: "127.0.0.1:${SOCKS_PORT}"
network:
interface: "${_y_iface}"
ipv4:
addr: "${_y_ip}:0"
router_mac: "${_y_mac}"
tcp:
local_flag: ${_tcp_local_flags}
remote_flag: ${_tcp_remote_flags}
server:
addr: "${_y_server}"
transport:
protocol: "kcp"
kcp:
mode: "fast"
key: "${_y_key}"
EOF
fi
)
if ! mv "$tmp_conf" "$INSTALL_DIR/config.yaml"; then
log_error "Failed to save configuration file"
rm -f "$tmp_conf"
return 1
fi
# Ensure final permissions (mv preserves source permissions on most systems)
chmod 600 "$INSTALL_DIR/config.yaml" 2>/dev/null
log_success "Configuration saved to $INSTALL_DIR/config.yaml"
}
save_settings() {
# Preserve existing Telegram settings if present
local _tg_token="" _tg_chat="" _tg_interval=6 _tg_enabled=false
local _tg_alerts=true _tg_daily=true _tg_weekly=true _tg_label="" _tg_start_hour=0
if [ -f "$INSTALL_DIR/settings.conf" ]; then
# Safe settings loading without eval
while IFS='=' read -r key value; do
[[ "$key" =~ ^[A-Z_][A-Z_0-9]*$ ]] || continue
# Remove surrounding quotes and sanitize value
value="${value#\"}"; value="${value%\"}"
# Validate value doesn't contain dangerous characters
if [[ "$value" =~ [\`\$\(] ]]; then
continue # Skip potentially dangerous values
fi
case "$key" in