-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtunnelforge.sh
More file actions
10353 lines (9221 loc) · 399 KB
/
tunnelforge.sh
File metadata and controls
10353 lines (9221 loc) · 399 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
#!/usr/bin/env bash
# ╔════════════════════════════════════════════════════════════════════╗
# ║ ▀▀█▀▀ █ █ █▄ █ █▄ █ █▀▀ █ █▀▀ █▀█ █▀█ █▀▀ █▀▀ ║
# ║ █ █ █ █ ▀█ █ ▀█ █▀▀ █ █▀ █ █ █▀█ █ █ █▀▀ ║
# ║ █ ▀▀ █ █ █ █ ▀▀▀ ▀▀▀ █ ▀▀▀ █ █ ▀▀▀ ▀▀▀ ║
# ╚════════════════════════════════════════════════════════════════════╝
#
# TunnelForge — SSH Tunnel Manager
# Copyright (C) 2026 SamNet Technologies, LLC
#
# Single-file bash tool with TUI menu, live dashboard,
# DNS leak protection, kill switch, server hardening, and Telegram bot.
#
# Version : 1.0.0
# Author : SamNet Technologies, LLC
# License : GNU General Public License v3.0
# GitHub : github.com/SamNet-dev/tunnelforge
# Usage : tunnelforge [command] [options]
# Run 'tunnelforge help' for full command reference.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# ============================================================================
# STRICT MODE & BASH VERSION CHECK
# ============================================================================
set -eo pipefail
MIN_BASH_VERSION="4.3"
check_bash_version() {
local major="${BASH_VERSINFO[0]}"
local minor="${BASH_VERSINFO[1]}"
local req_major="${MIN_BASH_VERSION%%.*}"
local req_minor="${MIN_BASH_VERSION##*.}"
if (( major < req_major )) || \
(( major == req_major && minor < req_minor )); then
echo "ERROR: TunnelForge requires bash ${MIN_BASH_VERSION}+" \
"(found ${BASH_VERSION})" >&2
exit 1
fi
}
check_bash_version
# ============================================================================
# VERSION & GLOBAL CONSTANTS
# ============================================================================
readonly VERSION="1.0.0"
readonly GITHUB_REPO="SamNet-dev/tunnelforge"
readonly APP_NAME="TunnelForge"
readonly APP_NAME_LOWER="tunnelforge"
# Installation directories
readonly INSTALL_DIR="/opt/tunnelforge"
readonly CONFIG_DIR="${INSTALL_DIR}/config"
readonly PROFILES_DIR="${INSTALL_DIR}/profiles"
readonly PID_DIR="${INSTALL_DIR}/pids"
readonly LOG_DIR="${INSTALL_DIR}/logs"
readonly BACKUP_DIR="${INSTALL_DIR}/backups"
readonly DATA_DIR="${INSTALL_DIR}/data"
readonly BIN_LINK="/usr/local/bin/tunnelforge"
# Config files
readonly MAIN_CONFIG="${CONFIG_DIR}/tunnelforge.conf"
# Temp / lock
TMP_DIR=""
# Background Telegram PIDs for cleanup
declare -a _TG_BG_PIDS=()
# SSH ControlMaster
readonly SSH_CONTROL_DIR="${INSTALL_DIR}/sockets"
# Bandwidth & reconnect history
readonly BW_HISTORY_DIR="${DATA_DIR}/bandwidth"
readonly RECONNECT_LOG_DIR="${DATA_DIR}/reconnects"
# ============================================================================
# TEMP FILE CLEANUP TRAP
# ============================================================================
cleanup() {
local exit_code=$?
tput cnorm 2>/dev/null || true
tput rmcup 2>/dev/null || true
# Reap background Telegram sends
local _tg_p
for _tg_p in "${_TG_BG_PIDS[@]}"; do
kill "$_tg_p" 2>/dev/null || true
wait "$_tg_p" 2>/dev/null || true
done
rm -rf "${TMP_DIR}" 2>/dev/null
rm -f "${PID_DIR}"/*.lock "${CONFIG_DIR}"/*.lock "${PROFILES_DIR}"/*.lock 2>/dev/null
# Clean stale SSH ControlMaster sockets
find "${SSH_CONTROL_DIR}" -type s -delete 2>/dev/null || true
# Clean up our own mkdir-based locks (stale after SIGKILL)
local _cleanup_lck _cleanup_pid
for _cleanup_lck in "${CONFIG_DIR}"/*.lck "${PROFILES_DIR}"/*.lck "${PID_DIR}"/*.lck "${BW_HISTORY_DIR}"/*.lck; do
if [[ -d "$_cleanup_lck" ]]; then
_cleanup_pid=$(cat "${_cleanup_lck}/pid" 2>/dev/null) || true
if [[ "${_cleanup_pid}" == "$$" ]] || [[ -z "$_cleanup_pid" ]]; then
rm -f "${_cleanup_lck}/pid" 2>/dev/null || true
rmdir "$_cleanup_lck" 2>/dev/null || true
fi
fi
done
exit "${exit_code}"
}
trap cleanup EXIT INT TERM HUP QUIT
TMP_DIR=$(mktemp -d "/tmp/tunnelforge.XXXXXX" 2>/dev/null) || {
echo "FATAL: Cannot create secure temporary directory" >&2
exit 1
}
chmod 700 "${TMP_DIR}" 2>/dev/null || true
readonly TMP_DIR
# ============================================================================
# CONFIGURATION DEFAULTS (declare -gA CONFIG)
# ============================================================================
declare -gA CONFIG=(
# SSH defaults
[SSH_DEFAULT_USER]="root"
[SSH_DEFAULT_PORT]="22"
[SSH_DEFAULT_KEY]=""
[SSH_CONNECT_TIMEOUT]="10"
[SSH_SERVER_ALIVE_INTERVAL]="30"
[SSH_SERVER_ALIVE_COUNT_MAX]="3"
[SSH_STRICT_HOST_KEY]="yes"
# AutoSSH
[AUTOSSH_ENABLED]="true"
[AUTOSSH_POLL]="30"
[AUTOSSH_FIRST_POLL]="30"
[AUTOSSH_GATETIME]="30"
[AUTOSSH_MONITOR_PORT]="0"
[AUTOSSH_LOG_LEVEL]="1"
# ControlMaster
[CONTROLMASTER_ENABLED]="false"
[CONTROLMASTER_PERSIST]="600"
# Security
[DNS_LEAK_PROTECTION]="false"
[DNS_SERVER_1]="1.1.1.1"
[DNS_SERVER_2]="1.0.0.1"
[KILL_SWITCH]="false"
# Telegram
[TELEGRAM_ENABLED]="false"
[TELEGRAM_BOT_TOKEN]=""
[TELEGRAM_CHAT_ID]=""
[TELEGRAM_ALERTS]="true"
[TELEGRAM_PERIODIC_STATUS]="false"
[TELEGRAM_STATUS_INTERVAL]="3600"
# Dashboard
[DASHBOARD_REFRESH]="5"
[DASHBOARD_THEME]="retro"
# Logging
[LOG_LEVEL]="info"
[LOG_JSON]="false"
[LOG_MAX_SIZE]="10485760"
[LOG_ROTATE_COUNT]="5"
# General
[AUTO_UPDATE_CHECK]="false"
)
config_get() {
local key="$1"
local default="${2:-}"
echo "${CONFIG[$key]:-$default}"
}
config_set() {
local key="$1"
local value="$2"
CONFIG["$key"]="$value"
}
# ============================================================================
# COLORS & TERMINAL DETECTION
# ============================================================================
if [[ -t 1 ]] && [[ -t 2 ]]; then
IS_TTY=true
else
IS_TTY=false
fi
if [[ "${IS_TTY}" == true ]] && [[ "${TERM:-dumb}" != "dumb" ]] && [[ -z "${NO_COLOR:-}" ]]; then
RED=$'\033[0;31m'
GREEN=$'\033[0;32m'
YELLOW=$'\033[0;33m'
BLUE=$'\033[0;34m'
MAGENTA=$'\033[0;35m'
CYAN=$'\033[0;36m'
WHITE=$'\033[0;37m'
BOLD=$'\033[1m'
BOLD_RED=$'\033[1;31m'
BOLD_GREEN=$'\033[1;32m'
BOLD_YELLOW=$'\033[1;33m'
BOLD_BLUE=$'\033[1;34m'
BOLD_MAGENTA=$'\033[1;35m'
BOLD_CYAN=$'\033[1;36m'
BOLD_WHITE=$'\033[1;37m'
BG_RED=$'\033[41m'
BG_GREEN=$'\033[42m'
BG_YELLOW=$'\033[43m'
BG_BLUE=$'\033[44m'
DIM=$'\033[2m'
UNDERLINE=$'\033[4m'
REVERSE=$'\033[7m'
RESET=$'\033[0m'
# Status indicators (Unicode + color)
readonly STATUS_OK="${GREEN}●${RESET}"
readonly STATUS_FAIL="${RED}✗${RESET}"
readonly STATUS_WARN="${YELLOW}▲${RESET}"
readonly STATUS_STOP="${DIM}■${RESET}"
readonly STATUS_SPIN="${CYAN}◆${RESET}"
else
RED='' GREEN='' YELLOW='' BLUE='' MAGENTA='' CYAN='' WHITE=''
BOLD='' BOLD_RED='' BOLD_GREEN='' BOLD_YELLOW='' BOLD_BLUE=''
BOLD_MAGENTA='' BOLD_CYAN='' BOLD_WHITE=''
BG_RED='' BG_GREEN='' BG_YELLOW='' BG_BLUE=''
DIM='' UNDERLINE='' REVERSE='' RESET=''
IS_TTY=false
# Status indicators (ASCII fallback for dumb/pipe/NO_COLOR)
readonly STATUS_OK="*"
readonly STATUS_FAIL="x"
readonly STATUS_WARN="!"
readonly STATUS_STOP="-"
readonly STATUS_SPIN="+"
fi
# ============================================================================
# LOGGING
# ============================================================================
declare -gA LOG_LEVELS=( [debug]=0 [info]=1 [success]=2 [warn]=3 [error]=4 )
_get_log_level_num() { echo "${LOG_LEVELS[${1:-info}]:-1}"; }
_should_log() {
local msg_level="$1"
local configured_level
configured_level=$(config_get "LOG_LEVEL" "info")
local msg_num configured_num
msg_num=$(_get_log_level_num "$msg_level")
configured_num=$(_get_log_level_num "$configured_level")
if (( msg_num >= configured_num )); then return 0; fi
return 1
}
log_json() {
local level="$1" message="$2"
local ts
ts=$(date -u '+%Y-%m-%dT%H:%M:%SZ')
# Escape JSON special characters: backslash first, then quotes, then control chars
message="${message//\\/\\\\}"
message="${message//\"/\\\"}"
message="${message//$'\n'/\\n}"
message="${message//$'\t'/\\t}"
message="${message//$'\r'/\\r}"
printf '{"timestamp":"%s","level":"%s","app":"%s","message":"%s"}\n' \
"$ts" "$level" "$APP_NAME_LOWER" "$message"
}
_log() {
local level="$1" color="$2" prefix="$3" message="$4"
_should_log "$level" || return 0
if [[ "$(config_get LOG_JSON false)" == "true" ]]; then
log_json "$level" "$message" \
>> "${LOG_DIR}/${APP_NAME_LOWER}.log" 2>/dev/null || true
fi
local ts
ts=$(date '+%H:%M:%S')
if [[ "${IS_TTY}" == true ]]; then
printf "${DIM}[%s]${RESET} ${color}${prefix}${RESET} %s\n" \
"$ts" "$message" >&2
else
printf "[%s] %s %s\n" "$ts" "$prefix" "$message" >&2
fi
}
log_debug() { _log "debug" "${DIM}" "[DEBUG]" "$1"; }
log_info() { _log "info" "${CYAN}" "[INFO] " "$1"; }
log_success() { _log "success" "${GREEN}" "[ OK ]" "$1"; }
log_warn() { _log "warn" "${YELLOW}" "[WARN] " "$1"; }
log_error() { _log "error" "${RED}" "[ERROR]" "$1"; }
log_file() {
local level="$1" message="$2"
if [[ "$(config_get LOG_JSON false)" == "true" ]]; then
log_json "$level" "$message" \
>> "${LOG_DIR}/${APP_NAME_LOWER}.log" 2>/dev/null || true
else
local ts
ts=$(date -u '+%Y-%m-%dT%H:%M:%SZ')
printf "[%s] [%s] %s\n" "$ts" "$level" "$message" \
>> "${LOG_DIR}/${APP_NAME_LOWER}.log" 2>/dev/null || true
fi
}
# ============================================================================
# UTILITY FUNCTIONS
# ============================================================================
# Drain trailing bytes from multi-byte escape sequences (arrow keys, etc.)
# Call after read -rsn1: if key is ESC, consume the rest and blank the var.
# Usage: _drain_esc varname
_drain_esc() {
local -n _de_ref="$1"
if [[ "${_de_ref}" == $'\033' ]]; then
local _de_trash
read -rsn2 -t 0.1 _de_trash </dev/tty 2>/dev/null || true
_de_ref=""
fi
}
validate_port() {
local port="$1"
if [[ "$port" =~ ^[0-9]+$ ]] && (( port >= 1 && port <= 65535 )); then
return 0
fi
return 1
}
# Check if a local port is already in use or assigned
# Returns 0 if free, 1 if busy. Prints suggestion on conflict.
_check_port_conflict() {
local _cp_port="$1" _cp_type="${2:-local}"
local _cp_busy=false _cp_who=""
# Check active listeners via ss
if command -v ss &>/dev/null; then
if ss -tln 2>/dev/null | tail -n +2 | grep -qE "[:.]${_cp_port}[[:space:]]"; then
_cp_busy=true
_cp_who="system process"
fi
fi
# Check other TunnelForge profiles
if [[ -d "$PROFILES_DIR" ]]; then
local _cp_f _cp_pname
for _cp_f in "$PROFILES_DIR"/*.conf; do
[[ -f "$_cp_f" ]] || continue
_cp_pname=$(basename "$_cp_f" .conf)
local _cp_pport=""
_cp_pport=$(grep -oE "^LOCAL_PORT='[0-9]+'" "$_cp_f" 2>/dev/null | cut -d"'" -f2) || true
if [[ "$_cp_pport" == "$_cp_port" ]]; then
_cp_busy=true
_cp_who="profile '${_cp_pname}'"
break
fi
done
fi
if [[ "$_cp_busy" == true ]]; then
printf " ${YELLOW}! Port %s is used by %s${RESET}\n" "$_cp_port" "$_cp_who" >/dev/tty
# Suggest next free port
local _cp_try=$(( _cp_port + 1 ))
local _cp_max=$(( _cp_port + 20 ))
while (( _cp_try <= _cp_max && _cp_try <= 65535 )); do
local _cp_free=true
if command -v ss &>/dev/null; then
if ss -tln 2>/dev/null | tail -n +2 | grep -qE "[:.]${_cp_try}[[:space:]]"; then
_cp_free=false
fi
fi
if [[ "$_cp_free" == true ]] && [[ -d "$PROFILES_DIR" ]]; then
for _cp_f in "$PROFILES_DIR"/*.conf; do
[[ -f "$_cp_f" ]] || continue
local _cp_pp=""
_cp_pp=$(grep -oE "^LOCAL_PORT='[0-9]+'" "$_cp_f" 2>/dev/null | cut -d"'" -f2) || true
if [[ "$_cp_pp" == "$_cp_try" ]]; then
_cp_free=false; break
fi
done
fi
if [[ "$_cp_free" == true ]]; then
printf " ${DIM}Suggested: %s${RESET}\n" "$_cp_try" >/dev/tty
return 1
fi
(( ++_cp_try ))
done
return 1
fi
return 0
}
validate_ip() {
local ip="$1"
if [[ "$ip" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then
local IFS='.'
read -ra octets <<< "$ip"
for octet in "${octets[@]}"; do
# Reject leading zeros (octal ambiguity with iptables/ssh)
if [[ "$octet" =~ ^0[0-9] ]]; then return 1; fi
if (( 10#$octet > 255 )); then return 1; fi
done
return 0
fi
return 1
}
validate_ip6() {
local ip="$1"
# Accept bracketed form [::1]
if [[ "$ip" =~ ^\[([0-9a-fA-F:]+)\]$ ]]; then
ip="${BASH_REMATCH[1]}"
fi
# Basic IPv6: must contain at least one colon, only hex digits and colons
if [[ "$ip" =~ ^[0-9a-fA-F]*:[0-9a-fA-F:]*$ ]]; then
# Reject more than one :: (invalid shorthand)
local _dc="${ip//[^:]/}"
if [[ "${ip}" == *"::"*"::"* ]]; then return 1; fi
return 0
fi
return 1
}
validate_hostname() {
local host="$1"
validate_ip "$host" && return 0
# Accept bracket-wrapped IPv6 (e.g., [::1], [2001:db8::1])
if [[ "$host" =~ ^\[[0-9a-fA-F:]+\]$ ]]; then return 0; fi
# Accept bare IPv6 (e.g., ::1, 2001:db8::1)
if [[ "$host" =~ ^[0-9a-fA-F]*:[0-9a-fA-F:]+$ ]]; then return 0; fi
[[ "$host" =~ ^[a-zA-Z0-9]([a-zA-Z0-9\-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]*[a-zA-Z0-9])?)*$ ]]
}
validate_profile_name() {
local name="$1"
[[ "$name" =~ ^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$ ]]
}
format_bytes() {
local bytes="${1:-0}"
[[ "$bytes" =~ ^[0-9]+$ ]] || bytes=0
if (( bytes < 1024 )); then
printf "%d B" "$bytes"
elif (( bytes < 1048576 )); then
printf "%d.%d KB" "$(( bytes / 1024 ))" "$(( (bytes % 1024) * 10 / 1024 ))"
elif (( bytes < 1073741824 )); then
printf "%d.%d MB" "$(( bytes / 1048576 ))" "$(( (bytes % 1048576) * 10 / 1048576 ))"
else
printf "%d.%02d GB" "$(( bytes / 1073741824 ))" "$(( (bytes % 1073741824) * 100 / 1073741824 ))"
fi
}
format_duration() {
local seconds="${1:-0}"
[[ "$seconds" =~ ^[0-9]+$ ]] || seconds=0
local d=$(( seconds / 86400 ))
local h=$(( (seconds % 86400) / 3600 ))
local m=$(( (seconds % 3600) / 60 ))
local s=$(( seconds % 60 ))
if (( d > 0 )); then
printf "%dd %dh %dm" "$d" "$h" "$m"
elif (( h > 0 )); then
printf "%dh %dm %ds" "$h" "$m" "$s"
elif (( m > 0 )); then
printf "%dm %ds" "$m" "$s"
else
printf "%ds" "$s"
fi
}
get_public_ip() {
local ip="" svc
local services=(
"https://api.ipify.org"
"https://ifconfig.me/ip"
"https://icanhazip.com"
"https://ipecho.net/plain"
)
for svc in "${services[@]}"; do
ip=$(curl -s --max-time 5 "$svc" 2>/dev/null | tr -d '[:space:]' || true)
if validate_ip "$ip" || validate_ip6 "$ip"; then
echo "$ip"; return 0
fi
done
echo "unknown"; return 1
}
check_root() {
local hint="${1:-}"
if [[ $EUID -ne 0 ]]; then
log_error "This operation requires root privileges"
log_info "Run with: sudo tunnelforge ${hint}"
return 1
fi
}
confirm_action() {
local message="${1:-Are you sure?}"
local default="${2:-n}"
local prompt
if [[ "$default" == "y" ]]; then
prompt="${message} [Y/n]: "
else
prompt="${message} [y/N]: "
fi
printf "${BOLD}%s${RESET}" "$prompt" >/dev/tty
local answer
read -r answer </dev/tty || true
answer="${answer:-$default}"
case "${answer,,}" in
y|yes) return 0 ;;
*) return 1 ;;
esac
}
print_line() {
local char="${1:-─}" width="${2:-$(get_term_width)}"
local i
local line=""
for (( i=0; i<width; i++ )); do
line+="$char"
done
printf '%s\n' "$line"
}
spinner() {
local pid="$1" message="${2:-Working...}"
local -a chars
if [[ "${IS_TTY}" == true ]] && [[ "${TERM:-dumb}" != "dumb" ]] && [[ -z "${NO_COLOR:-}" ]]; then
chars=('⠋' '⠙' '⠹' '⠸' '⠼' '⠴' '⠦' '⠧' '⠇' '⠏')
else
chars=('|' '/' '-' '\')
fi
local i=0
while kill -0 "$pid" 2>/dev/null; do
printf "\r${CYAN}%s${RESET} %s" "${chars[$i]}" "$message" >&2
i=$(( (i + 1) % ${#chars[@]} ))
sleep 0.1
done
printf "\r%*s\r" $(( ${#message} + 3 )) "" >&2
}
is_port_in_use() {
local port="$1" bind_addr="${2:-127.0.0.1}"
if command -v ss &>/dev/null; then
local _ss_pattern
if [[ "$bind_addr" == "0.0.0.0" ]] || [[ "$bind_addr" == "::" ]] || [[ "$bind_addr" == "[::]" ]]; then
_ss_pattern="\\*"
elif [[ "$bind_addr" =~ : ]]; then
# IPv6 — ss shows as [addr]:port; escape brackets for grep
local _stripped="${bind_addr#\[}"
_stripped="${_stripped%\]}"
_ss_pattern="\\[${_stripped}\\]"
else
_ss_pattern="${bind_addr//./\\.}"
fi
ss -tln sport = :"${port}" 2>/dev/null | tail -n +2 | grep -qE "(${_ss_pattern}|\\*):" 2>/dev/null
elif command -v netstat &>/dev/null; then
netstat -tln 2>/dev/null | grep -qE "(${bind_addr//./\\.}|0\\.0\\.0\\.0):${port}([[:space:]]|$)"
else
return 1
fi
}
get_term_width() {
tput cols 2>/dev/null || echo 80
}
# ============================================================================
# OS DETECTION & PACKAGE MANAGEMENT
# ============================================================================
declare -g OS_ID=""
declare -g OS_VERSION=""
declare -g OS_FAMILY=""
declare -g PKG_MANAGER=""
declare -g PKG_INSTALL=""
declare -g PKG_UPDATE=""
declare -g INIT_SYSTEM=""
detect_os() {
if [[ -f /etc/os-release ]]; then
# Parse directly — sourcing collides with our readonly VERSION
OS_ID=$(grep -m1 '^ID=' /etc/os-release 2>/dev/null | cut -d= -f2 | tr -d '"') || true
OS_VERSION=$(grep -m1 '^VERSION_ID=' /etc/os-release 2>/dev/null | cut -d= -f2 | tr -d '"') || true
: "${OS_ID:=unknown}" "${OS_VERSION:=unknown}"
elif [[ -f /etc/redhat-release ]]; then
OS_ID="rhel"
OS_VERSION=$(grep -oE '[0-9]+\.[0-9]+' /etc/redhat-release | head -1 || true)
else
OS_ID="unknown"
OS_VERSION="unknown"
fi
case "${OS_ID}" in
ubuntu|debian|raspbian|linuxmint|pop|kali|parrot)
OS_FAMILY="debian"
PKG_MANAGER="apt-get"
PKG_INSTALL="apt-get install -y"
PKG_UPDATE="apt-get update"
;;
fedora|centos|rhel|rocky|almalinux|ol)
OS_FAMILY="rhel"
if command -v dnf &>/dev/null; then
PKG_MANAGER="dnf"
PKG_INSTALL="dnf install -y"
PKG_UPDATE="dnf check-update"
else
PKG_MANAGER="yum"
PKG_INSTALL="yum install -y"
PKG_UPDATE="yum check-update"
fi
;;
arch|manjaro|endeavouros)
OS_FAMILY="arch"
PKG_MANAGER="pacman"
PKG_INSTALL="pacman -S --noconfirm"
PKG_UPDATE="pacman -Sy"
;;
alpine)
OS_FAMILY="alpine"
PKG_MANAGER="apk"
PKG_INSTALL="apk add"
PKG_UPDATE="apk update"
;;
opensuse*|sles)
OS_FAMILY="suse"
PKG_MANAGER="zypper"
PKG_INSTALL="zypper install -y"
PKG_UPDATE="zypper refresh"
;;
*)
OS_FAMILY="unknown"
log_warn "Unknown OS: ${OS_ID}. Some features may not work."
;;
esac
# Detect init system
if command -v systemctl &>/dev/null && [[ -d /run/systemd/system ]]; then
INIT_SYSTEM="systemd"
elif command -v rc-service &>/dev/null; then
INIT_SYSTEM="openrc"
elif [[ -d /etc/init.d ]]; then
INIT_SYSTEM="sysvinit"
else
INIT_SYSTEM="unknown"
fi
log_debug "Detected OS: ${OS_ID} ${OS_VERSION} (${OS_FAMILY}), init: ${INIT_SYSTEM}"
}
install_package() {
local pkg="$1"
local pkg_name="$pkg"
case "${OS_FAMILY}" in
debian)
case "$pkg" in
openssh-client) pkg_name="openssh-client" ;;
ncurses) pkg_name="ncurses-bin" ;;
esac ;;
rhel)
case "$pkg" in
openssh-client) pkg_name="openssh-clients" ;;
ncurses) pkg_name="ncurses" ;;
iproute2) pkg_name="iproute" ;;
esac ;;
arch)
case "$pkg" in
openssh-client) pkg_name="openssh" ;;
ncurses) pkg_name="ncurses" ;;
iproute2) pkg_name="iproute2" ;;
esac ;;
alpine)
case "$pkg" in
openssh-client) pkg_name="openssh-client" ;;
ncurses) pkg_name="ncurses" ;;
iproute2) pkg_name="iproute2" ;;
esac ;;
suse)
case "$pkg" in
openssh-client) pkg_name="openssh" ;;
ncurses) pkg_name="ncurses-utils" ;;
iproute2) pkg_name="iproute2" ;;
esac ;;
esac
if [[ -z "$PKG_INSTALL" ]]; then
log_error "No package manager configured for this OS"
return 1
fi
log_info "Installing ${pkg_name}..."
if ${PKG_INSTALL} "${pkg_name}" &>/dev/null; then
log_success "Installed ${pkg_name}"
return 0
else
log_error "Failed to install ${pkg_name}"
return 1
fi
}
check_dependencies() {
local missing=()
local -A deps=(
[ssh]="openssh-client"
[autossh]="autossh"
[sshpass]="sshpass"
[iptables]="iptables"
[curl]="curl"
[ip]="iproute2"
[tput]="ncurses"
[bc]="bc"
[jq]="jq"
)
log_info "Checking dependencies..."
for cmd in "${!deps[@]}"; do
if ! command -v "$cmd" &>/dev/null; then
missing+=("${deps[$cmd]}")
log_warn "Missing: ${cmd} (package: ${deps[$cmd]})"
else
log_debug "Found: ${cmd}"
fi
done
if [[ ${#missing[@]} -eq 0 ]]; then
log_success "All dependencies satisfied"
return 0
fi
log_info "Missing ${#missing[@]} package(s): ${missing[*]}"
if ! check_root; then
log_error "Root access needed to install missing packages"
return 1
fi
log_info "Updating package cache..."
${PKG_UPDATE} &>/dev/null || true
local failed=0
for pkg in "${missing[@]}"; do
install_package "$pkg" || ((++failed))
done
if (( failed > 0 )); then
log_error "${failed} package(s) failed to install"
return 1
fi
log_success "All dependencies installed"
return 0
}
# ============================================================================
# SETTINGS LOAD / SAVE (safe whitelist-validated parser)
# ============================================================================
readonly CONFIG_WHITELIST=(
SSH_DEFAULT_USER SSH_DEFAULT_PORT SSH_DEFAULT_KEY
SSH_CONNECT_TIMEOUT SSH_SERVER_ALIVE_INTERVAL SSH_SERVER_ALIVE_COUNT_MAX
SSH_STRICT_HOST_KEY
AUTOSSH_ENABLED AUTOSSH_POLL AUTOSSH_GATETIME AUTOSSH_MONITOR_PORT
AUTOSSH_FIRST_POLL AUTOSSH_LOG_LEVEL
CONTROLMASTER_ENABLED CONTROLMASTER_PERSIST
DNS_LEAK_PROTECTION DNS_SERVER_1 DNS_SERVER_2 KILL_SWITCH
TELEGRAM_ENABLED TELEGRAM_BOT_TOKEN TELEGRAM_CHAT_ID
TELEGRAM_ALERTS TELEGRAM_PERIODIC_STATUS TELEGRAM_STATUS_INTERVAL
DASHBOARD_REFRESH DASHBOARD_THEME
LOG_LEVEL LOG_JSON LOG_MAX_SIZE LOG_ROTATE_COUNT
AUTO_UPDATE_CHECK
)
_is_whitelisted() {
local key="$1" k
for k in "${CONFIG_WHITELIST[@]}"; do
if [[ "$k" == "$key" ]]; then return 0; fi
done
return 1
}
load_settings() {
local config_file="${1:-$MAIN_CONFIG}"
[[ -f "$config_file" ]] || return 0
log_debug "Loading settings from: ${config_file}"
while IFS= read -r line || [[ -n "$line" ]]; do
[[ "$line" =~ ^[[:space:]]*# ]] && continue
[[ "$line" =~ ^[[:space:]]*$ ]] && continue
if [[ "$line" =~ ^([A-Z_][A-Z0-9_]*)=(.*)$ ]]; then
local key="${BASH_REMATCH[1]}"
local value="${BASH_REMATCH[2]}"
# Strip matched outer quote pairs, then un-escape
if [[ "$value" == \'*\' ]]; then
value="${value#\'}"; value="${value%\'}"
value="${value//\'\\\'\'/\'}"
elif [[ "$value" == \"*\" ]]; then
value="${value#\"}"; value="${value%\"}"
fi
if _is_whitelisted "$key"; then
CONFIG["$key"]="$value"
if [[ "$key" == "TELEGRAM_BOT_TOKEN" ]] || [[ "$key" == "TELEGRAM_CHAT_ID" ]]; then
log_debug "Loaded: ${key}=****"
else
log_debug "Loaded: ${key}=${value}"
fi
else
log_warn "Ignoring unknown config key: ${key}"
fi
fi
done < "$config_file"
log_debug "Settings loaded"
}
save_settings() {
local config_file="${1:-$MAIN_CONFIG}"
# Acquire file-level lock to prevent concurrent writer races
local _ss_lock_fd="" _ss_lock_dir=""
_ss_unlock() {
if [[ -n "${_ss_lock_fd:-}" ]]; then exec {_ss_lock_fd}>&- 2>/dev/null || true; fi
if [[ -n "${_ss_lock_dir:-}" ]]; then
rm -f "${_ss_lock_dir}/pid" 2>/dev/null || true
rmdir "${_ss_lock_dir}" 2>/dev/null || true
_ss_lock_dir=""
fi
}
if command -v flock &>/dev/null; then
exec {_ss_lock_fd}>"${config_file}.lock"
flock -w 5 "$_ss_lock_fd" 2>/dev/null || { log_warn "Could not acquire settings lock"; _ss_unlock; return 1; }
else
_ss_lock_dir="${config_file}.lck"
local _ss_try=0
while ! mkdir "$_ss_lock_dir" 2>/dev/null; do
local _ss_stale_pid=""
_ss_stale_pid=$(cat "${_ss_lock_dir}/pid" 2>/dev/null) || true
if [[ -n "$_ss_stale_pid" ]] && ! kill -0 "$_ss_stale_pid" 2>/dev/null; then
rm -f "${_ss_lock_dir}/pid" 2>/dev/null || true
rmdir "$_ss_lock_dir" 2>/dev/null || true
continue
fi
if (( ++_ss_try >= 10 )); then log_warn "Could not acquire settings lock"; return 1; fi
sleep 0.5
done
printf '%s' "$$" > "${_ss_lock_dir}/pid" 2>/dev/null || true
fi
local tmp_file
tmp_file=$(mktemp "${TMP_DIR}/config.XXXXXX")
mkdir -p "$(dirname "$config_file")" 2>/dev/null || true
cat > "$tmp_file" <<'HEADER'
# ============================================================================
# TunnelForge Configuration
# Generated automatically — edit with care
# ============================================================================
HEADER
local key _sv
{
for key in "${CONFIG_WHITELIST[@]}"; do
if [[ -n "${CONFIG[$key]+x}" ]]; then
_sv="${CONFIG[$key]//$'\n'/}"
_sv="${_sv//\'/\'\\\'\'}"
printf "%s='%s'\n" "$key" "$_sv"
fi
done
} >> "$tmp_file"
# Set permissions before mv so there's no window of insecure perms
chmod 600 "$tmp_file" 2>/dev/null || true
# mv fails across filesystems (/tmp → /etc), fall back to cp to same-dir temp then mv
if mv "$tmp_file" "$config_file" 2>/dev/null || \
{ cp "$tmp_file" "${config_file}.tmp.$$" 2>/dev/null && \
mv "${config_file}.tmp.$$" "$config_file" 2>/dev/null && \
rm -f "$tmp_file" 2>/dev/null; }; then
log_debug "Settings saved to: ${config_file}"
_ss_unlock
return 0
fi
rm -f "${config_file}.tmp.$$" 2>/dev/null
rm -f "$tmp_file" 2>/dev/null
log_error "Failed to save settings to: ${config_file}"
_ss_unlock
return 1
}
# ============================================================================
# DIRECTORY INITIALIZATION
# ============================================================================
init_directories() {
local dirs=(
"$INSTALL_DIR" "$CONFIG_DIR" "$PROFILES_DIR"
"$PID_DIR" "$LOG_DIR" "$BACKUP_DIR"
"$DATA_DIR" "$SSH_CONTROL_DIR"
"$BW_HISTORY_DIR" "$RECONNECT_LOG_DIR"
)
for dir in "${dirs[@]}"; do
if [[ ! -d "$dir" ]]; then
mkdir -p "$dir" 2>/dev/null || {
log_error "Failed to create directory: ${dir}"
return 1
}
fi
done
chmod 700 "$CONFIG_DIR" 2>/dev/null || true
chmod 700 "$SSH_CONTROL_DIR" 2>/dev/null || true
chmod 700 "$LOG_DIR" 2>/dev/null || true
chmod 700 "$PROFILES_DIR" 2>/dev/null || true
chmod 700 "$PID_DIR" 2>/dev/null || true
chmod 700 "$BACKUP_DIR" 2>/dev/null || true
chmod 700 "$DATA_DIR" 2>/dev/null || true
chmod 700 "$BW_HISTORY_DIR" 2>/dev/null || true
chmod 700 "$RECONNECT_LOG_DIR" 2>/dev/null || true
chmod 755 "$INSTALL_DIR" 2>/dev/null || true
log_debug "Directories initialized"
}
# ============================================================================
# PROFILE MANAGEMENT
# ============================================================================
readonly PROFILE_FIELDS=(
PROFILE_NAME TUNNEL_TYPE
SSH_HOST SSH_PORT SSH_USER SSH_PASSWORD IDENTITY_KEY
LOCAL_BIND_ADDR LOCAL_PORT REMOTE_HOST REMOTE_PORT
JUMP_HOSTS SSH_OPTIONS
AUTOSSH_ENABLED AUTOSSH_MONITOR_PORT
DNS_LEAK_PROTECTION KILL_SWITCH AUTOSTART
OBFS_MODE OBFS_PORT OBFS_LOCAL_PORT OBFS_PSK
DESCRIPTION
)
_profile_path() { echo "${PROFILES_DIR}/${1}.conf"; }
create_profile() {
local name="$1"
if ! validate_profile_name "$name"; then
log_error "Invalid profile name: '${name}'"
log_info "Use letters, numbers, hyphens, underscores (max 64 chars)"
return 1
fi
local profile_file
profile_file=$(_profile_path "$name")
if [[ -f "$profile_file" ]]; then
log_error "Profile '${name}' already exists"
return 1
fi
local -A profile=(
[PROFILE_NAME]="$name"
[TUNNEL_TYPE]="socks5"
[SSH_HOST]=""
[SSH_PORT]="$(config_get SSH_DEFAULT_PORT 22)"
[SSH_USER]="$(config_get SSH_DEFAULT_USER root)"
[IDENTITY_KEY]="$(config_get SSH_DEFAULT_KEY)"
[LOCAL_BIND_ADDR]="127.0.0.1"
[LOCAL_PORT]="1080"
[REMOTE_HOST]=""
[REMOTE_PORT]=""
[JUMP_HOSTS]=""
[SSH_OPTIONS]=""
[AUTOSSH_ENABLED]="$(config_get AUTOSSH_ENABLED true)"
[AUTOSSH_MONITOR_PORT]="0"
[DNS_LEAK_PROTECTION]="false"
[KILL_SWITCH]="false"
[AUTOSTART]="false"