-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathdnstm-setup.sh
More file actions
7092 lines (6403 loc) · 288 KB
/
dnstm-setup.sh
File metadata and controls
7092 lines (6403 loc) · 288 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
#
# dnstm-setup v1.3.1
# Interactive DNS Tunnel Setup
# Sets up Slipstream + DNSTT + NoizDNS tunnels for censorship-resistant internet access
#
# Made By SamNet Technologies - Saman
# GitHub: github.com/SamNet-dev/dnstm-setup
# License: MIT
set -euo pipefail
VERSION="1.3.1"
TOTAL_STEPS=12
# ─── Safety: ensure DNS is never left broken on exit ──────────────────────────
_dnstm_cleanup_dns() {
# If resolv.conf is empty, missing, points at a dead stub, or has no nameservers, fix it.
local _needs_dns_fix=false
if [[ ! -s /etc/resolv.conf ]]; then
_needs_dns_fix=true
elif grep -q '127\.0\.0\.53' /etc/resolv.conf 2>/dev/null && \
! ss -ulnp 2>/dev/null | grep -q '127\.0\.0\.53.*systemd-resolve'; then
_needs_dns_fix=true
elif ! grep -q '^nameserver' /etc/resolv.conf 2>/dev/null; then
_needs_dns_fix=true
fi
if [[ "$_needs_dns_fix" == true ]]; then
chattr -i /etc/resolv.conf 2>/dev/null || true
rm -f /etc/resolv.conf 2>/dev/null || true
cat > /etc/resolv.conf 2>/dev/null <<'DNSEOF' || true
nameserver 8.8.8.8
nameserver 1.1.1.1
DNSEOF
fi
}
trap '_dnstm_cleanup_dns' EXIT
# ─── Colors & Formatting ───────────────────────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
DIM='\033[2m'
NC='\033[0m' # No Color
CHECK="${GREEN}[✓]${NC}"
CROSS="${RED}[✗]${NC}"
WARN="${YELLOW}[!]${NC}"
INFO="${CYAN}[i]${NC}"
# ─── TUI Helper Functions ──────────────────────────────────────────────────────
print_header() {
local title="$1"
local width=60
local line
line=$(printf '─%.0s' $(seq 1 $width))
echo ""
echo -e "${BOLD}${CYAN}┌${line}┐${NC}"
printf "${BOLD}${CYAN}│${NC} %-$((width - 1))s${BOLD}${CYAN}│${NC}\n" "$title"
echo -e "${BOLD}${CYAN}└${line}┘${NC}"
echo ""
}
print_step() {
local step=$1
local title="$2"
echo ""
echo -e "${BOLD}${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e " ${BOLD}[${step}/${TOTAL_STEPS}]${NC} ${BOLD}${title}${NC}"
echo -e "${BOLD}${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
}
print_ok() {
echo -e " ${CHECK} $1"
}
print_fail() {
echo -e " ${CROSS} $1"
}
print_warn() {
echo -e " ${WARN} $1"
}
print_info() {
echo -e " ${INFO} $1"
}
print_box() {
local lines=("$@")
# Calculate width from longest line
local width=58
for l in "${lines[@]}"; do
local len=${#l}
if (( len + 2 > width )); then
width=$((len + 2))
fi
done
local line
line=$(printf '─%.0s' $(seq 1 $width))
echo -e " ${DIM}┌${line}┐${NC}"
for l in "${lines[@]}"; do
printf " ${DIM}│${NC} %-$((width - 1))s${DIM}│${NC}\n" "$l"
done
echo -e " ${DIM}└${line}┘${NC}"
}
# Check if a tunnel tag exists in dnstm tunnel list output.
# Handles both `tag=name` and bare `name` formats in the output.
# Usage: dnstm_tag_exists <tag>
dnstm_tag_exists() {
local t="$1"
local output
output=$(dnstm tunnel list 2>/dev/null || true)
[[ -z "$output" ]] && return 1
# Try tag=name format first
if echo "$output" | grep -qwF "tag=${t}"; then
return 0
fi
# Fallback: check if the tag appears as a standalone word anywhere
if echo "$output" | grep -qwF "$t"; then
return 0
fi
return 1
}
# Extract all tunnel tags from dnstm tunnel list output.
# Handles both `tag=name` and other formats.
# Usage: tags=$(dnstm_get_tags)
dnstm_get_tags() {
local output
output=$(dnstm tunnel list 2>/dev/null || true)
[[ -z "$output" ]] && return
# Try tag=name format first
local tags
tags=$(echo "$output" | grep -oE 'tag=[^ ]+' | sed 's/tag=//' || true)
if [[ -n "$tags" ]]; then
echo "$tags"
return
fi
# Fallback: extract known tag patterns (slip*, dnstt*, noiz*, xray*)
echo "$output" | grep -oE '\b(slip|dnstt|noiz|xray)[a-z0-9_-]*' | sort -u || true
}
# Check if any tunnels exist
dnstm_has_tunnels() {
local output
output=$(dnstm tunnel list 2>/dev/null || true)
[[ -n "$output" ]] && echo "$output" | grep -qiE 'tag=|slip|dnstt|noiz|xray'
}
prompt_yn() {
local question="$1"
local default="${2:-n}"
local yn_hint
if [[ "$default" == "y" ]]; then
yn_hint="[Y/n]"
else
yn_hint="[y/N]"
fi
while true; do
echo ""
echo -ne " ${BOLD}${question}${NC} ${yn_hint} ${DIM}[h=help]${NC} "
read -r answer </dev/tty 2>/dev/null || read -r answer
answer=${answer:-$default}
if [[ "$answer" =~ ^[Hh]$ ]]; then
show_help_menu
continue
fi
if [[ "$answer" =~ ^[Yy] ]]; then
return 0
else
return 1
fi
done
}
prompt_input() {
local question="$1"
local default="${2:-}"
local result
while true; do
if [[ -n "$default" ]]; then
echo -ne " ${BOLD}${question}${NC} [${default}] ${DIM}(h=help)${NC}: " >&2
else
echo -ne " ${BOLD}${question}${NC} ${DIM}(h=help)${NC}: " >&2
fi
read -r result </dev/tty 2>/dev/null || read -r result
result=${result:-$default}
if [[ "$result" =~ ^[Hh]$ ]]; then
show_help_menu >&2
continue
fi
echo "$result"
return
done
}
banner() {
local w=54
local border empty
border=$(printf '═%.0s' $(seq 1 $w))
empty=$(printf ' %.0s' $(seq 1 $w))
local ver_text="dnstm-setup v${VERSION}"
local sub_text="Interactive DNS Tunnel Setup"
local vl=$(( (w - ${#ver_text}) / 2 ))
local vr=$(( w - ${#ver_text} - vl ))
local sl=$(( (w - ${#sub_text}) / 2 ))
local sr=$(( w - ${#sub_text} - sl ))
echo ""
echo -e "${BOLD}${CYAN}"
printf " ╔%s╗\n" "$border"
printf " ║%s║\n" "$empty"
printf " ║%${vl}s%s%${vr}s║\n" "" "$ver_text" ""
printf " ║%${sl}s%s%${sr}s║\n" "" "$sub_text" ""
printf " ║%s║\n" "$empty"
printf " ╚%s╝\n" "$border"
echo -e "${NC}"
}
# ─── Help System ──────────────────────────────────────────────────────────────
help_topic_header() {
local title="$1"
local width=58
local line
line=$(printf '─%.0s' $(seq 1 $width))
# Compensate for multi-byte chars: pad width = visual width + (bytes - chars)
local byte_len=${#title}
local byte_count
byte_count=$(printf '%s' "$title" | wc -c)
local pad_width=$(( width - 1 + byte_count - byte_len ))
echo ""
echo -e " ${BOLD}${CYAN}┌${line}┐${NC}"
printf " ${BOLD}${CYAN}│${NC} ${BOLD}%-${pad_width}s${BOLD}${CYAN}│${NC}\n" "$title"
echo -e " ${BOLD}${CYAN}└${line}┘${NC}"
echo ""
}
help_press_enter() {
echo ""
echo -ne " ${DIM}Press Enter to go back...${NC}"
read -r </dev/tty 2>/dev/null || read -r || true
}
help_topic_domain() {
help_topic_header "1. Domains & DNS Basics"
echo -e " ${BOLD}What is a domain?${NC}"
echo " A domain (e.g. example.com) is a human-readable address"
echo " on the internet. DNS tunneling uses domains to encode"
echo " data inside DNS queries, making your traffic look like"
echo " normal DNS resolution."
echo ""
echo -e " ${BOLD}Why do you need one?${NC}"
echo " DNS tunnels work by making DNS queries for subdomains"
echo " of YOUR domain. The DNS system routes these queries to"
echo " your server, which decodes the hidden data. Without a"
echo " domain you own, you can't receive these queries."
echo ""
echo -e " ${BOLD}How DNS delegation works${NC}"
echo " When you create NS records pointing t.example.com to"
echo " ns.example.com (your server), you tell the global DNS"
echo " system: 'For any query about t.example.com, ask my"
echo " server directly.' This is how tunnel traffic finds you."
echo ""
echo -e " ${BOLD}Where to buy a domain${NC}"
echo " - Namecheap (namecheap.com) — cheap, privacy included"
echo " - Cloudflare Registrar — at-cost pricing"
echo " - Any registrar works, but you MUST use Cloudflare DNS"
echo " (free plan) to manage your records"
echo ""
echo -e " ${BOLD}Subdomains used by this script${NC}"
echo " If your domain is example.com:"
echo " t.example.com -> Slipstream + SOCKS tunnel"
echo " d.example.com -> DNSTT + SOCKS tunnel"
echo " s.example.com -> Slipstream + SSH tunnel"
echo " ds.example.com -> DNSTT + SSH tunnel"
help_press_enter
}
help_topic_dns_records() {
help_topic_header "2. DNS Records (Cloudflare Setup)"
echo -e " ${BOLD}What are DNS records?${NC}"
echo " DNS records are entries that tell the internet how to"
echo " find services for your domain."
echo ""
echo -e " ${BOLD}A Record (Address Record)${NC}"
echo " Maps a name to an IP address."
echo " We create: ns.yourdomain.com -> your server IP"
echo " This tells the internet where your DNS server lives."
echo ""
echo -e " ${BOLD}NS Record (Name Server Record)${NC}"
echo " Delegates a subdomain to another DNS server."
echo " We create: t.yourdomain.com NS -> ns.yourdomain.com"
echo " This tells the internet: 'For queries about t, ask"
echo " the server at ns.yourdomain.com (your VPS).'"
echo ""
echo -e " ${BOLD}Why 'DNS Only' (grey cloud)?${NC}"
echo " Cloudflare's proxy (orange cloud) intercepts traffic."
echo " DNS tunneling requires queries to reach YOUR server"
echo " directly. If the proxy is ON, queries go to Cloudflare"
echo " instead and tunneling breaks completely."
echo ""
echo -e " ${BOLD}Why 4 subdomains?${NC}"
echo " Each tunnel type needs its own subdomain so the DNS"
echo " Router can route them to the right tunnel:"
echo " t -> Slipstream + SOCKS (fastest, QUIC-based)"
echo " d -> DNSTT + SOCKS (classic, Noise protocol)"
echo " s -> Slipstream + SSH (SSH over DNS)"
echo " ds -> DNSTT + SSH (SSH over DNSTT)"
echo ""
echo -e " ${BOLD}Common mistakes${NC}"
echo " - Using 'tns' instead of 'ns' for the A record name"
echo " - Leaving Cloudflare proxy ON (must be grey cloud)"
echo " - Setting NS values to the IP instead of ns.domain"
echo " - Forgetting to click Save after adding records"
help_press_enter
}
help_topic_port53() {
help_topic_header "3. Port 53 & systemd-resolved"
echo -e " ${BOLD}What is port 53?${NC}"
echo " Port 53 is the standard port for all DNS traffic."
echo " Every DNS query in the world is sent to port 53."
echo " Censors almost never block it because it would break"
echo " DNS for everyone."
echo ""
echo -e " ${BOLD}Why do DNS tunnels need port 53?${NC}"
echo " When a DNS resolver (like 8.8.8.8) forwards a query"
echo " to your server, it always sends it to port 53. Your"
echo " tunnel server must listen on port 53 to receive these"
echo " queries. There is no way to use a different port."
echo ""
echo -e " ${BOLD}What is systemd-resolved?${NC}"
echo " systemd-resolved is Ubuntu's built-in DNS cache. It"
echo " listens on 127.0.0.53:53 to handle local DNS lookups."
echo " Since it occupies port 53, it must be stopped before"
echo " the DNS tunnel server can bind to that port."
echo ""
echo -e " ${BOLD}Is it safe to disable?${NC}"
echo " Yes! We replace it with 8.8.8.8 (Google DNS) in"
echo " /etc/resolv.conf. Your server still resolves domain"
echo " names normally — it just queries Google DNS directly"
echo " instead of using the local cache."
help_press_enter
}
help_topic_dnstm() {
help_topic_header "4. dnstm — DNS Tunnel Manager"
echo -e " ${BOLD}What is dnstm?${NC}"
echo " A command-line tool that installs, configures, and"
echo " manages DNS tunnel servers. Handles all the complex"
echo " setup automatically."
echo ""
echo -e " ${BOLD}What is 'multi mode'?${NC}"
echo " Multi mode lets multiple tunnels share port 53 through"
echo " a DNS Router. The router reads incoming DNS queries and"
echo " routes them to the correct tunnel based on subdomain."
echo ""
echo -e " ${BOLD}What gets installed${NC}"
echo " - slipstream-server QUIC-based tunnel binary"
echo " - dnstt-server Classic DNS tunnel binary"
echo " - microsocks SOCKS5 proxy (auto-assigned port)"
echo " - systemd services Auto-start tunnels on boot"
echo " - DNS Router Multiplexes port 53"
echo ""
echo -e " ${BOLD}How the DNS Router works${NC}"
echo " All DNS queries arrive at port 53. The router inspects"
echo " the domain name: if it's for t.example.com, it sends"
echo " the query to Slipstream. If it's for d.example.com,"
echo " it routes to DNSTT. Each tunnel decodes the data and"
echo " forwards it through microsocks to the internet."
help_press_enter
}
help_topic_ssh() {
help_topic_header "5. SSH Tunnel Users"
echo -e " ${BOLD}What is an SSH tunnel user?${NC}"
echo " A restricted account that can ONLY create SSH port-"
echo " forwarding tunnels. Cannot run commands, access a"
echo " shell, or browse the filesystem."
echo ""
echo -e " ${BOLD}How is it different from a regular user?${NC}"
echo " A regular user (like root) has full server access."
echo " An SSH tunnel user can ONLY forward ports. Even if"
echo " the password is leaked, no one can access your server."
echo ""
echo -e " ${BOLD}How Slipstream + SSH works${NC}"
echo " Client -> DNS query -> DNS resolver -> Your server"
echo " -> Slipstream (decodes DNS) -> SSH connection"
echo " -> SSH port forwarding (-D) -> Internet"
echo ""
echo -e " ${BOLD}SSH vs SOCKS backend${NC}"
echo " SOCKS (t/d tunnels):"
echo " - Faster, no authentication needed"
echo " - Anyone who knows the domain can connect"
echo " SSH (s/ds tunnels):"
echo " - Requires username + password to connect"
echo " - Only authorized users can use it"
echo " - Slightly slower (SSH encryption overhead)"
echo ""
echo -e " ${BOLD}Username & password${NC}"
echo " - The username/password are shared with ALL your users"
echo " - Keep the username simple (e.g. 'tunnel', 'vpn')"
echo " - Use a memorable password, NOT your root password"
echo " - Even if leaked, the account is port-forwarding only"
help_press_enter
}
help_topic_architecture() {
help_topic_header "6. Architecture & How It Works"
echo -e " ${BOLD}The Big Picture${NC}"
echo " DNS tunneling encodes your internet traffic inside DNS"
echo " queries. Since DNS is almost never blocked, it provides"
echo " a reliable channel even during internet shutdowns."
echo ""
echo -e " ${BOLD}Data Flow${NC}"
echo ""
echo " Phone (SlipNet app)"
echo " |"
echo " v"
echo " DNS Query (looks like normal DNS traffic)"
echo " |"
echo " v"
echo " Public DNS Resolver (8.8.8.8, 1.1.1.1, etc.)"
echo " |"
echo " v"
echo " Your Server, Port 53"
echo " |"
echo " v"
echo " DNS Router --+--> t --> Slipstream --+--> microsocks"
echo " +--> d --> DNSTT -------+ (SOCKS5)"
echo " +--> s --> Slip+SSH ----+ |"
echo " +--> ds --> DNSTT+SSH ---+ v"
echo " Internet"
echo ""
echo -e " ${BOLD}Protocols${NC}"
echo " Slipstream: QUIC-based, TLS encryption, ~63 KB/s"
echo " DNSTT: Noise protocol, Curve25519 keys, ~42 KB/s"
echo ""
echo -e " ${BOLD}Why DNS?${NC}"
echo " DNS is the internet's phone book. EVERY device needs"
echo " it to work, so censors almost never block it. By hiding"
echo " traffic inside DNS queries, you can bypass blocks that"
echo " shut down VPNs, Tor, and other tools."
help_press_enter
}
help_topic_about() {
help_topic_header "About dnstm-setup"
echo -e " ${BOLD}Made By SamNet Technologies - Saman${NC}"
echo ""
echo -e " ${BOLD}dnstm-setup${NC} v${VERSION}"
echo " Interactive DNS Tunnel Setup Wizard"
echo ""
echo " Automates the complete setup of DNS tunnel servers"
echo " for censorship-resistant internet access. Designed"
echo " to help people in restricted regions stay connected."
echo ""
echo -e " ${BOLD}Links${NC}"
echo " dnstm-setup github.com/SamNet-dev/dnstm-setup"
echo " dnstm github.com/net2share/dnstm"
echo " sshtun-user github.com/net2share/sshtun-user"
echo " SlipNet github.com/anonvector/SlipNet"
echo ""
echo -e " ${BOLD}Manual Guide (Farsi)${NC}"
echo " telegra.ph/Complete-Guide-to-Setting-Up-a-DNS-Tunnel-03-04"
echo ""
echo -e " ${BOLD}Donate${NC}"
echo " www.samnet.dev/donate"
echo ""
echo -e " ${BOLD}License${NC}"
echo " MIT License"
help_press_enter
}
show_help_menu() {
while true; do
help_topic_header "Help — Pick a Topic"
echo -e " ${BOLD}1${NC} Domains & DNS Basics"
echo -e " ${BOLD}2${NC} DNS Records (Cloudflare Setup)"
echo -e " ${BOLD}3${NC} Port 53 & systemd-resolved"
echo -e " ${BOLD}4${NC} dnstm — DNS Tunnel Manager"
echo -e " ${BOLD}5${NC} SSH Tunnel Users"
echo -e " ${BOLD}6${NC} Architecture & How It Works"
echo ""
echo -e " ${DIM}────────────────────────────────────────${NC}"
echo -e " ${BOLD}7${NC} About"
echo ""
echo -ne " ${DIM}Pick a topic (1-7) or Enter to go back: ${NC}"
read -r choice
case "${choice:-}" in
1) help_topic_domain ;;
2) help_topic_dns_records ;;
3) help_topic_port53 ;;
4) help_topic_dnstm ;;
5) help_topic_ssh ;;
6) help_topic_architecture ;;
7) help_topic_about ;;
*)
if [[ -n "${choice:-}" ]]; then
echo -e " ${WARN} Invalid choice. Please pick 1–7 or Enter to go back."
fi
echo ""
return
;;
esac
done
}
# ─── --help ─────────────────────────────────────────────────────────────────────
show_help() {
banner
echo -e "${BOLD}DESCRIPTION${NC}"
echo " dnstm-setup automates the complete setup of DNS tunnel servers for"
echo " censorship-resistant internet access. It installs and configures dnstm"
echo " (DNS Tunnel Manager) with Slipstream and DNSTT protocols, sets up SOCKS"
echo " and SSH tunnels, and verifies everything works end-to-end."
echo ""
echo -e "${BOLD}PREREQUISITES${NC}"
echo " - A VPS running Ubuntu/Debian with root access"
echo " - A domain managed on Cloudflare"
echo " - curl installed on the server"
echo ""
echo -e "${BOLD}USAGE${NC}"
echo " sudo bash dnstm-setup.sh Run interactive setup"
echo " sudo bash dnstm-setup.sh --manage Post-setup management menu"
echo " sudo bash dnstm-setup.sh --add-domain Add a backup domain to existing setup"
echo " sudo bash dnstm-setup.sh --mtu 1200 Set DNSTT MTU (default: 1232)"
echo " sudo bash dnstm-setup.sh --add-tunnel Add a single tunnel interactively"
echo " sudo bash dnstm-setup.sh --add-xray Connect existing Xray panel via DNS tunnel"
echo " sudo bash dnstm-setup.sh --remove-tunnel [tag] Remove a specific tunnel"
echo " sudo bash dnstm-setup.sh --harden Apply security hardening only"
echo " sudo bash dnstm-setup.sh --uninstall Remove everything"
echo " sudo bash dnstm-setup.sh --status Show all tunnels & share URLs"
echo " sudo bash dnstm-setup.sh --monitor Monitor tunnel usage & connections"
echo " sudo bash dnstm-setup.sh --diag Diagnose tunnel issues"
echo " bash dnstm-setup.sh --help Show this help"
echo " bash dnstm-setup.sh --about Show project info"
echo ""
echo -e "${BOLD}FLAGS${NC}"
echo " --help Show this help message"
echo " --about Show project information and credits"
echo " --manage Interactive management menu (all post-setup actions)"
echo " --status Show all tunnels, credentials, and share URLs"
echo " --monitor Show tunnel process stats, connections, and recent logs"
echo " --diag Run diagnostics: binaries, services, ports, DNS, config"
echo " --add-tunnel Add a single tunnel (interactive: choose transport, backend, domain)"
echo " --add-xray Connect existing 3x-ui panel to DNS tunnel (auto-detect + create inbound)"
echo " --remove-tunnel [tag] Remove a specific tunnel (interactive if no tag given)"
echo " --add-domain Add another domain to an existing server (backup/fallback)"
echo " --users Manage SSH tunnel users (add, list, update, delete)"
echo " --mtu <value> Set DNSTT MTU size (512-1400, default: 1232)"
echo " --harden Apply service and resolver hardening to an existing setup"
echo " --update Check for updates and install latest version"
echo " --uninstall Remove all installed components"
echo ""
echo -e "${BOLD}WHAT THIS SCRIPT SETS UP${NC}"
echo " 1. Slipstream + SOCKS tunnel (fastest, ~63 KB/s)"
echo " 2. DNSTT + SOCKS tunnel (classic, ~42 KB/s)"
echo " 3. Slipstream + SSH tunnel (SSH over DNS)"
echo " 4. DNSTT + SSH tunnel (SSH over DNSTT)"
echo " 5. microsocks SOCKS5 proxy (auto-installed by dnstm)"
echo " 6. SSH tunnel user (optional)"
echo ""
echo -e "${BOLD}CLIENT APP${NC}"
echo " SlipNet (Android): https://github.com/anonvector/SlipNet/releases"
echo ""
}
# ─── --about ────────────────────────────────────────────────────────────────────
show_about() {
banner
echo -e "${BOLD}ABOUT${NC}"
echo ""
echo " dnstm-setup is an interactive installer for DNS tunnel servers."
echo " It provides a guided, step-by-step setup process with colored"
echo " output, progress tracking, and automated verification."
echo ""
echo -e "${BOLD}HOW DNS TUNNELING WORKS${NC}"
echo ""
echo " DNS tunneling encodes data inside DNS queries and responses."
echo " Since DNS is almost never blocked (even during internet shutdowns),"
echo " it provides a reliable channel for internet access. Your traffic"
echo " flows through public DNS resolvers to your tunnel server, which"
echo " decodes it and forwards it to the internet."
echo ""
echo " Architecture:"
echo ""
echo " Client (SlipNet)"
echo " --> DNS Query"
echo " --> Public Resolver (8.8.8.8)"
echo " --> Your Server (Port 53)"
echo " --> DNS Router"
echo " --> Tunnel --> Internet"
echo ""
echo -e "${BOLD}SUPPORTED PROTOCOLS${NC}"
echo ""
echo " Slipstream QUIC-based DNS tunnel with TLS encryption"
echo " Uses self-signed certificates (cert.pem/key.pem)"
echo " Speed: ~63 KB/s"
echo ""
echo " DNSTT Classic DNS tunnel using Noise protocol"
echo " Uses Curve25519 key pairs (server.key/server.pub)"
echo " Speed: ~42 KB/s"
echo ""
echo -e "${BOLD}RELATED PROJECTS${NC}"
echo ""
echo " dnstm https://github.com/net2share/dnstm"
echo " sshtun-user https://github.com/net2share/sshtun-user"
echo " SlipNet https://github.com/anonvector/SlipNet/releases"
echo ""
echo -e "${BOLD}LICENSE${NC}"
echo ""
echo " MIT License"
echo ""
echo -e "${BOLD}AUTHOR${NC}"
echo ""
echo " Made By SamNet Technologies - Saman"
echo " https://github.com/SamNet-dev"
echo ""
}
# ─── SOCKS Auth Detection Helper ──────────────────────────────────────────────
# Detect SOCKS5 auth state from dnstm backend status.
# Sets globals: SOCKS_AUTH (true/false), SOCKS_USER, SOCKS_PASS
# Returns 0 if auth is enabled, 1 otherwise.
detect_socks_auth() {
local status_output
status_output=$(timeout --kill-after=3 10 dnstm backend status -t socks 2>/dev/null || true)
local detected_user detected_pass
detected_user=$(echo "$status_output" | sed -n 's/^[[:space:]]*User:[[:space:]]*//p' | sed 's/[[:space:]]*$//' || true)
detected_pass=$(echo "$status_output" | sed -n 's/^[[:space:]]*Password:[[:space:]]*//p' | sed 's/[[:space:]]*$//' || true)
if [[ -n "$detected_user" && -n "$detected_pass" ]]; then
# Reject credentials with pipe chars (would corrupt slipnet URL format)
if [[ "$detected_user" == *"|"* || "$detected_pass" == *"|"* ]]; then
SOCKS_AUTH=false
SOCKS_USER=""
SOCKS_PASS=""
return 1
fi
SOCKS_AUTH=true
SOCKS_USER="$detected_user"
SOCKS_PASS="$detected_pass"
return 0
fi
SOCKS_AUTH=false
SOCKS_USER=""
SOCKS_PASS=""
return 1
}
# ─── Configure SOCKS Auth (manage menu) ──────────────────────────────────────
do_configure_socks_auth() {
banner
print_header "Configure SOCKS5 Authentication"
if [[ $EUID -ne 0 ]]; then
print_fail "Not running as root."
exit 1
fi
if ! command -v dnstm &>/dev/null; then
print_fail "dnstm is not installed."
exit 1
fi
# Show current state
echo ""
detect_socks_auth || true
if [[ "$SOCKS_AUTH" == true ]]; then
echo -e " ${BOLD}Current status:${NC} ${GREEN}Enabled${NC}"
echo -e " ${DIM}Username: ${SOCKS_USER}${NC}"
echo ""
echo -e " ${BOLD}1)${NC} Change credentials"
echo -e " ${BOLD}2)${NC} Disable authentication"
echo -e " ${BOLD}0)${NC} Cancel"
echo ""
local choice=""
read -rp " Select [0-2]: " choice || exit 0
case "$choice" in
1)
echo ""
;;
2)
echo ""
print_info "Disabling SOCKS5 authentication..."
if dnstm backend auth -t socks --disable; then
print_ok "SOCKS5 authentication disabled"
sleep 2
if pgrep -x microsocks &>/dev/null || systemctl is-active --quiet microsocks 2>/dev/null; then
print_ok "microsocks restarted without authentication"
else
print_warn "microsocks may not have restarted — check: systemctl status microsocks"
fi
else
print_fail "Failed to disable authentication"
fi
exit 0
;;
*)
exit 0
;;
esac
else
echo -e " ${BOLD}Current status:${NC} ${RED}Disabled (open proxy)${NC}"
echo ""
if ! prompt_yn "Enable SOCKS5 authentication?" "y"; then
print_info "Cancelled."
exit 0
fi
echo ""
fi
# Collect credentials
local new_user new_pass
new_user=$(prompt_input "Enter SOCKS proxy username" "proxy")
new_user=$(echo "$new_user" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
if [[ -z "$new_user" ]]; then
print_fail "Username cannot be empty"
exit 1
fi
if [[ "$new_user" == *"|"* || "$new_user" == *":"* ]]; then
print_fail "Username cannot contain | or : characters"
exit 1
fi
new_pass=$(prompt_input "Enter SOCKS proxy password")
new_pass=$(echo "$new_pass" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
if [[ -z "$new_pass" ]]; then
print_fail "Password cannot be empty"
exit 1
fi
if [[ "$new_pass" == *"|"* ]]; then
print_fail "Password cannot contain the | character"
exit 1
fi
echo ""
print_info "Applying SOCKS5 authentication..."
if dnstm backend auth -t socks -u "$new_user" -p "$new_pass"; then
print_ok "SOCKS5 authentication enabled (user: ${new_user})"
sleep 2
if pgrep -x microsocks &>/dev/null || systemctl is-active --quiet microsocks 2>/dev/null; then
print_ok "microsocks restarted with authentication"
else
print_warn "microsocks may not have restarted — check: systemctl status microsocks"
fi
# Verify auth enforcement
local socks_port=""
socks_port=$(ss -tlnp 2>/dev/null | grep microsocks | awk '{for(i=1;i<=NF;i++) if($i ~ /:[0-9]+$/) {split($i,a,":"); print a[length(a)]; exit}}' || true)
if [[ -z "$socks_port" ]]; then
socks_port="19801"
fi
local noauth_test
noauth_test=$(curl -s --max-time 5 --socks5 "127.0.0.1:${socks_port}" https://api.ipify.org 2>/dev/null || true)
if [[ -z "$noauth_test" ]]; then
print_ok "Auth enforced: unauthenticated connections are rejected"
else
print_warn "Auth NOT enforced: proxy still works without credentials!"
print_info "Try restarting: systemctl restart microsocks"
fi
else
print_fail "Failed to configure SOCKS5 authentication"
print_info "Try manually: dnstm backend auth -t socks -u ${new_user} -p <password>"
fi
}
# ─── --status ───────────────────────────────────────────────────────────────────
do_status() {
banner
# Warn if not root (ss -p and file reads may not work)
if [[ $EUID -ne 0 ]]; then
print_warn "Running without root — some info may be unavailable"
echo ""
fi
# Check dnstm is installed
if ! command -v dnstm &>/dev/null; then
print_fail "dnstm is not installed. Run the full setup first: sudo bash $0"
exit 1
fi
# Save/restore global DOMAIN so generate_slipnet_url() can read it
local _saved_domain="$DOMAIN"
# Detect server IP
local server_ip
server_ip=$(curl -4 -s --max-time 10 https://api.ipify.org 2>/dev/null || true)
if [[ -n "$server_ip" ]]; then
echo -e " ${BOLD}Server IP:${NC} ${GREEN}${server_ip}${NC}"
fi
echo ""
# ─── Cache tunnel list output (reused throughout) ───
local tunnel_list_output
tunnel_list_output=$(timeout --kill-after=3 10 dnstm tunnel list 2>/dev/null || true)
echo -e " ${BOLD}Tunnel Status${NC}"
echo -e " ${DIM}────────────────────────────────────────${NC}"
if [[ -n "$tunnel_list_output" ]]; then
echo "$tunnel_list_output"
else
print_warn "Could not get tunnel list"
fi
echo ""
# ─── Detect SOCKS auth via dnstm ───
detect_socks_auth || true
local socks_user="$SOCKS_USER" socks_pass="$SOCKS_PASS" socks_auth="$SOCKS_AUTH"
echo -e " ${BOLD}SOCKS Proxy Authentication${NC}"
echo -e " ${DIM}────────────────────────────────────────${NC}"
if [[ "$socks_auth" == true ]]; then
echo -e " Username: ${GREEN}${socks_user}${NC}"
echo -e " Password: ${GREEN}${socks_pass}${NC}"
else
echo -e " ${YELLOW}No authentication (open proxy)${NC}"
fi
echo ""
# ─── Detect microsocks port ───
local socks_port=""
socks_port=$(ss -tlnp 2>/dev/null | grep microsocks | awk '{for(i=1;i<=NF;i++) if($i ~ /:[0-9]+$/) {split($i,a,":"); print a[length(a)]; exit}}' || true)
if [[ -z "$socks_port" ]]; then
socks_port=$(sed -n 's/.*-p[[:space:]]*\([0-9]*\).*/\1/p' /etc/systemd/system/microsocks.service 2>/dev/null | head -1 || true)
fi
if [[ -n "$socks_port" ]]; then
echo -e " ${BOLD}microsocks Port:${NC} ${GREEN}${socks_port}${NC}"
echo ""
fi
# ─── Collect all tunnel tags and their domains ───
local tags
tags=$(echo "$tunnel_list_output" | grep -oE 'tag=[^ ]+' | sed 's/tag=//' || true)
# Fallback: extract known tag patterns if tag= format not found
if [[ -z "$tags" ]] && [[ -n "$tunnel_list_output" ]]; then
tags=$(echo "$tunnel_list_output" | grep -oE '\b(slip|dnstt|noiz|xray)[a-z0-9_-]*' | sort -u || true)
fi
if [[ -z "$tags" ]]; then
print_warn "No tunnels found"
return
fi
# ─── Detect SSH users (check if sshtun-user is available) ───
local ssh_user="" ssh_pass=""
local has_ssh_users=false
if command -v sshtun-user &>/dev/null; then
local user_list
user_list=$(timeout --kill-after=3 10 sshtun-user list </dev/null 2>/dev/null || true)
# Fallback: sshtun-user list may require TTY
if [[ -z "$user_list" ]]; then
user_list=$(awk -F: '/SSH tunnel only/{print $1}' /etc/passwd 2>/dev/null || true)
fi
if [[ -n "$user_list" ]]; then
has_ssh_users=true
echo -e " ${BOLD}SSH Tunnel Users${NC}"
echo -e " ${DIM}────────────────────────────────────────${NC}"
echo "$user_list" | while IFS= read -r line; do
echo -e " ${GREEN}${line}${NC}"
done
echo ""
fi
fi
# Check and auto-fix sshd reachability (needed for SSH tunnels)
if [[ "$has_ssh_users" == true ]]; then
if ! timeout 3 bash -c 'echo | nc -w2 127.0.0.1 22' &>/dev/null; then
echo -e " ${YELLOW}[!] sshd not reachable on 127.0.0.1:22 — fixing...${NC}"
systemctl restart sshd 2>/dev/null || systemctl restart ssh 2>/dev/null || true
if command -v iptables &>/dev/null; then
iptables -I INPUT -i lo -p tcp --dport 22 -j ACCEPT 2>/dev/null || true
fi
if command -v ufw &>/dev/null && ufw status 2>/dev/null | grep -q "active"; then
ufw allow from 127.0.0.1 to any port 22 2>/dev/null || true
fi
sleep 1
if timeout 3 bash -c 'echo | nc -w2 127.0.0.1 22' &>/dev/null; then
echo -e " ${GREEN}[+] sshd fixed — now reachable on 127.0.0.1:22${NC}"
else
echo -e " ${RED}[x] sshd still not reachable — SSH tunnels will NOT work${NC}"
echo -e " ${DIM}Check: sudo iptables -L -n | grep 22${NC}"
fi
echo ""
fi
fi
# Read stored SSH credentials for URL generation
if [[ -f /etc/dnstm/ssh-credentials ]]; then
ssh_user=$(cut -d: -f1 /etc/dnstm/ssh-credentials 2>/dev/null || true)
ssh_pass=$(cut -d: -f2- /etc/dnstm/ssh-credentials 2>/dev/null || true)
fi
# ─── Share URLs — dnst:// ───
echo -e " ${BOLD}Share URLs — dnst:// (for dnstc CLI)${NC}"
echo -e " ${DIM}────────────────────────────────────────${NC}"
local share_url
for tag in $tags; do
# SOCKS tunnels — no SSH credentials needed
if echo "$tag" | grep -qE '^(slip[0-9]+|dnstt[0-9]+|noiz[0-9]+)$'; then
share_url=$(timeout --kill-after=3 10 dnstm tunnel share -t "$tag" 2>/dev/null || true)
if [[ -n "$share_url" ]]; then
echo -e " ${GREEN}${tag}:${NC}"
echo " ${share_url}"
echo ""
fi
fi
done
# SSH tunnels — need credentials
local ssh_tags
ssh_tags=$(echo "$tags" | grep -E 'ssh' || true)
if [[ -n "$ssh_tags" ]]; then
if [[ "$has_ssh_users" == true ]]; then
echo -e " ${DIM}SSH tunnel share URLs require credentials:${NC}"
for tag in $ssh_tags; do
echo -e " ${DIM} dnstm tunnel share -t ${tag} --user <username> --password <pass>${NC}"
done
else
echo -e " ${YELLOW}SSH tunnels: no users configured — create one with: sshtun-user create <user> --insecure-password <pass>${NC}"
fi
echo ""
fi
# ─── Share URLs — slipnet:// ───
# We need the domain for each tunnel to generate slipnet:// URLs
echo -e " ${BOLD}Share URLs — slipnet:// (for SlipNet app)${NC}"
echo -e " ${DIM}────────────────────────────────────────${NC}"
local s_user="" s_pass=""
if [[ "$socks_auth" == true ]]; then
s_user="$socks_user"
s_pass="$socks_pass"
fi
# Pre-load domain map from dnstm config.json (most reliable source)
local _dnstm_config="/etc/dnstm/config.json"
local _domain_map=""
if [[ -f "$_dnstm_config" ]]; then
if command -v jq &>/dev/null; then
_domain_map=$(jq -r '.tunnels[]? | "\(.tag)=\(.domain)"' "$_dnstm_config" 2>/dev/null || true)
elif command -v python3 &>/dev/null; then
_domain_map=$(python3 -c '
import sys, json
try:
cfg = json.load(sys.stdin)
for t in cfg.get("tunnels", []):
tag, domain = t.get("tag",""), t.get("domain","")
if tag and domain: print(f"{tag}={domain}")
except: pass
' < "$_dnstm_config" 2>/dev/null || true)
fi
fi
for tag in $tags; do
# Extract domain for this tunnel from dnstm
local tag_domain
tag_domain=$(echo "$tunnel_list_output" | grep -wF "$tag" | grep -oE 'domain=[^ ]+' | head -1 | sed 's/domain=//' || true)
# Fallback: parse table format (TAG TRANSPORT BACKEND PORT DOMAIN STATUS)
if [[ -z "$tag_domain" ]]; then
tag_domain=$(echo "$tunnel_list_output" | awk -v t="$tag" '$1 == t {for(i=2;i<=NF;i++) if($i ~ /\./) {print $i; exit}}' || true)
fi
# Fallback: read domain from dnstm config.json
if [[ -z "$tag_domain" && -n "$_domain_map" ]]; then
tag_domain=$(echo "$_domain_map" | grep "^${tag}=" | head -1 | sed 's/^[^=]*=//' || true)
fi
if [[ -z "$tag_domain" ]]; then
continue
fi
# Extract base domain (strip subdomain prefix)
DOMAIN=$(echo "$tag_domain" | sed 's/^[^.]*\.//')
local subdomain
subdomain=$(echo "$tag_domain" | sed 's/\..*//')
# Get DNSTT pubkey — required by SlipNet for ALL tunnel types
local pubkey=""
if [[ -f "/etc/dnstm/tunnels/${tag}/server.pub" ]]; then
pubkey=$(cat "/etc/dnstm/tunnels/${tag}/server.pub" 2>/dev/null || true)
fi
# Slipstream tunnels don't have server.pub — grab any available dnstt pubkey
if [[ -z "$pubkey" ]]; then
pubkey=$(cat /etc/dnstm/tunnels/*/server.pub 2>/dev/null | head -1 || true)
fi
local url=""
case "$tag" in
slip[0-9]*)
url=$(generate_slipnet_url "ss" "$subdomain" "$pubkey" "" "" "$s_user" "$s_pass")
;;