-
Notifications
You must be signed in to change notification settings - Fork 435
/
ss-tproxy
executable file
·1424 lines (1177 loc) · 38 KB
/
ss-tproxy
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
export PATH="$PATH:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin"
# 除了主脚本,其他文件都放这个目录,此值可被命令行参数覆盖
base_dir='/etc/ss-tproxy' # 同时也是工作目录
config_file='ss-tproxy.conf' # 可被命令行参数覆盖
# 已存在的函数和变量尽量别改名/删除,因为可能被 ss-tproxy.conf 引用(如钩子函数)
# 由于需要执行 iptables、策略路由、内核参数 等特权操作,脚本必须以 root 权限执行
# 有xtables锁时进行等待,而不是报错退出
iptables() {
command iptables -w "$@"
}
# 有xtables锁时进行等待,而不是报错退出
ip6tables() {
command ip6tables -w "$@"
}
font_bold() {
printf "\e[1m$*\e[0m"
}
color_red() {
printf "\e[35m$*\e[0m"
}
color_green() {
printf "\e[32m$*\e[0m"
}
color_yellow() {
printf "\e[31m$*\e[0m"
}
# 打印错误消息,并退出脚本
log_error() {
echo "$(font_bold $(color_yellow '[ERROR]')) $*" 1>&2
exit 1
}
is_func() {
[ "$(type -t $1)" = 'function' ]
}
# 如果函数存在,则调用
call_func() {
is_func "$1" && "$@"
}
# 使用数值0和1做布尔值最好,但由于历史原因,没法改了
is_true() {
[ "$1" = 'true' ]
}
is_false() {
! is_true "$1"
}
is_uint() {
[ "$1" ] && [ -z "${1//[0-9]/}" ]
}
# str substr
str_find() {
[[ "$1" == *"$2"* ]]
}
file_is_exists() {
[ -f "$1" ]
}
file_required() {
file_is_exists "$1" || log_error "file not found: $1"
}
list_ext_ipv4() {
grep '^-' "$1" | cut -c2-
}
list_ext_ipv6() {
grep '^~' "$1" | cut -c2-
}
list_ext_domain() {
grep '^@' "$1" | cut -c2-
}
command_path() {
type -P "$1"
}
command_is_exists() {
type -P "$1" &>/dev/null
}
command_required() {
command_is_exists "$1" || log_error "command not found: $1"
}
group_is_exists() {
if is_uint "$1"; then # gid
grep -q ":$1:" /etc/group
else # name
grep -q "^$1:" /etc/group
fi
}
create_group() {
if is_uint "$1"; then # gid
log_error "gid:'$1' not exists, please check proxy_procgroup/dns_procgroup"
elif command_is_exists groupadd; then
groupadd "$1" || log_error "failed to create group:'$1' via groupadd, exit-code: $?"
elif command_is_exists addgroup; then
addgroup "$1" || log_error "failed to create group:'$1' via addgroup, exit-code: $?"
else
log_error "group:'$1' not exists, and groupadd/addgroup are not found, please create it manually"
fi
}
# group command
set_command_group() {
command_required "$2"
local group="$1" path="$(command_path "$2")"
chgrp "$group" "$path" || log_error "chgrp failed: group=$group path=$path"
chmod g+xs "$path"
}
# command
set_proxy_group() {
set_command_group "$proxy_procgroup" "$1"
}
# command
set_dns_group() {
set_command_group "$dns_procgroup" "$1"
}
process_is_running() {
kill -0 "$1" &>/dev/null
}
# 优雅关闭进程
kill_by_pid() {
[ $# -eq 0 ] && return
# send SIGTERM
for pid in "$@"; do
process_is_running "$pid" && kill "$pid"
done
# wait up to 5s
local running_pids
for ((i = 0; i < 100; i++)); do
running_pids=()
for pid in "$@"; do
process_is_running "$pid" && running_pids+=("$pid")
done
[ "${#running_pids[@]}" -eq 0 ] && return
((i < 5)) && sleep 0.01 || sleep 0.05
((i % 20 == 0 && i >= 30)) && echo "[notice] kill process: ${running_pids[@]}"
done
# force kill
echo "[warning] force kill: ${running_pids[@]}"
kill -9 "${running_pids[@]}"
}
# 优雅关闭进程
kill_by_name() {
local pids=()
for name in "$@"; do
pids+=($(pidof "$name"))
done
kill_by_pid "${pids[@]}"
}
tcp_port_is_exists() {
$netstat -lnpt | grep -q ":$1[[:blank:]]"
}
udp_port_is_exists() {
$netstat -anpu | grep -q ":$1[[:blank:]]"
}
# 通过一些运行时特征(系统重启后不保留的状态),判断是否处于start状态
ss_tproxy_is_started() {
iptables -t mangle -S SSTP_OUTPUT &>/dev/null ||
iptables -t nat -S SSTP_OUTPUT &>/dev/null ||
ip6tables -t mangle -S SSTP_OUTPUT &>/dev/null ||
ip6tables -t nat -S SSTP_OUTPUT &>/dev/null ||
ip -4 rule 2>/dev/null | grep -q "lookup $ipts_rt_tab" ||
ip -6 rule 2>/dev/null | grep -q "lookup $ipts_rt_tab" ||
ip -4 route show table $ipts_rt_tab 2>/dev/null | grep -q '^' ||
ip -6 route show table $ipts_rt_tab 2>/dev/null | grep -q '^'
}
is_ipv4_ipts() {
[ "$1" = 'iptables' ]
}
is_ipv6_ipts() {
[ "$1" = 'ip6tables' ]
}
# $ipts table chain
chain_is_exists() {
local table="$2" chain="$3"
$1 -t $table -S $chain &>/dev/null
}
# 先判断chain是否存在
# $ipts table chain
chain_is_empty() {
local table="$2" chain="$3"
[ $($1 -t $table -S $chain | wc -l) -le 1 ]
}
is_global_mode() {
[ "$mode" = 'global' ]
}
is_gfwlist_mode() {
[ "$mode" = 'gfwlist' ]
}
is_chnroute_mode() {
[ "$mode" = 'chnroute' ]
}
# tcp也使用tproxy? (udp必须用tproxy)
is_tcp_tproxy() {
is_true "$tproxy"
}
is_built_in_dns() {
is_false "$dns_custom"
}
is_proxy_other() {
is_false "$selfonly"
}
is_drop_quic() {
case "$ipts_drop_quic" in
tcponly)
! is_enabled_udp;;
always)
true;;
*)
false;;
esac
}
is_enabled_ipv4() {
is_true "$ipv4"
}
is_enabled_ipv6() {
is_true "$ipv6"
}
is_enabled_udp() {
is_false "$tcponly"
}
is_need_iproute() {
is_tcp_tproxy || is_enabled_udp
}
# ip#port
get_ip_from_addr() {
local addr="$1"
echo "${addr%#*}"
}
# ip#port
get_port_from_addr() {
local addr="$1"
echo "${addr#*#}"
}
#===============================================================
# 加载上次start时的一些运行时状态,主要是pid
load_pidfile() {
if ss_tproxy_is_started; then
source .ss-tproxy.pid
else
# start状态下重启系统,pid文件会保留(未被清理),这里删一下
delete_pidfile
fi
}
# start之后调用,保存start时的一些运行时状态
save_pidfile() {
{
if is_built_in_dns; then
echo "sstp_pid_chinadns=$sstp_pid_chinadns"
else
call_func custom_dns_pid
fi
call_func extra_pid
} >.ss-tproxy.pid
}
# stop时移除,或者重启系统后有残留,也移除
delete_pidfile() {
rm -f .ss-tproxy.pid &>/dev/null
}
#===============================================================
load_config() {
file_required $config_file
source $config_file "${arg_list[@]}" ||
log_error "$config_file load failed, exit-code: $?"
# 覆盖同名配置,也可以用来定义新变量
for override in "${override_list[@]}"; do
eval "$override"
done
{ ! is_enabled_ipv4 && ! is_enabled_ipv6; } &&
log_error "both ipv4 and ipv6 are disabled, nothing to do"
if is_global_mode; then
# 白名单
file_required ignlist.ext
elif is_gfwlist_mode; then
# 黑名单
file_required gfwlist.txt
file_required gfwlist.ext
elif is_chnroute_mode; then
# 白名单 + 黑名单(优先)
file_required ignlist.ext
file_required chnlist.txt
file_required chnroute.txt
file_required chnroute6.txt
file_required gfwlist.txt
file_required gfwlist.ext
else
log_error "invalid config value for mode: '$mode'"
fi
[ "$proxy_procgroup" -a "$proxy_procgroup" != 0 -a "$proxy_procgroup" != root ] ||
log_error "invalid config value for proxy_procgroup: '$proxy_procgroup'"
[ "$dns_procgroup" -a "$dns_procgroup" != 0 -a "$dns_procgroup" != root ] ||
log_error "invalid config value for dns_procgroup: '$dns_procgroup'"
[ "$proxy_procgroup" != "$dns_procgroup" ] ||
log_error "proxy_procgroup and dns_procgroup must be different: '$proxy_procgroup'"
group_is_exists "$proxy_procgroup" || create_group "$proxy_procgroup"
group_is_exists "$dns_procgroup" || create_group "$dns_procgroup"
is_need_iproute && command_required 'ip'
command_required 'ipset'
is_enabled_ipv4 && command_required 'iptables'
is_enabled_ipv6 && command_required 'ip6tables'
if is_built_in_dns; then
set_dns_group 'chinadns-ng'
else
call_func custom_dns_init
fi
case "$opts_ss_netstat" in
auto)
if command_is_exists 'ss'; then
netstat='ss'
elif command_is_exists 'netstat'; then
netstat='netstat'
else
log_error "command not found: ss/netstat"
fi
;;
ss)
command_required 'ss'
netstat='ss'
;;
netstat)
command_required 'netstat'
netstat='netstat'
;;
*)
log_error "invalid config value for opts_ss_netstat: '$opts_ss_netstat'"
;;
esac
}
#===============================================================
# url filename
update_domain_list() {
command_required 'curl'
local url="$1" filename="$2"
local data # 声明和赋值必须分开,不然错误码会丢失
data="$(set -o pipefail; curl -4fsSkL "$url" | grep -v -e '^[[:space:]]*$' -e '^[[:space:]]*#')" ||
log_error "download failed: $url (exit-code: $?)"
if head -n1 <<<"$data" | grep -q /; then
# server=/域名后缀/dns_ip
echo "$data" | awk -F/ '{print $2}' | sort | uniq >$filename
else
# 纯域名后缀
echo "$data" | sort | uniq >$filename
fi
}
update_gfwlist() {
update_domain_list "$url_gfwlist" gfwlist.txt
}
update_chnlist() {
update_domain_list "$url_chnlist" chnlist.txt
}
update_chnroute() {
command_required 'curl'
local data # 声明和赋值必须分开,不然错误码会丢失
data="$(set -o pipefail; curl -4fsSkL "$url_chnroute" | grep CN)" ||
log_error "download failed: $url_chnroute (exit-code: $?)"
awk -F'|' '/ipv4/ {printf("%s/%d\n", $4, 32-log($5)/log(2))}' <<<"$data" >chnroute.txt
awk -F'|' '/ipv6/ {printf("%s/%d\n", $4, $5)}' <<<"$data" >chnroute6.txt
}
#===============================================================
# direct/remote "server1 server2 ..."
get_chinadns_upstream() {
local opt use_tcp_dns
if [ "$1" = direct ]; then
opt='-c'
use_tcp_dns=0
else
opt='-t'
case "$dns_remote_tcp" in
tcponly) ! is_enabled_udp && use_tcp_dns=1 || use_tcp_dns=0;;
always) use_tcp_dns=1;;
*) use_tcp_dns=0;;
esac
fi
for upstream in $2; do
if ((use_tcp_dns)) && ! str_find "$upstream" "://"; then
upstream="tcp://$upstream"
fi
echo " $opt $upstream"
done
}
start_chinadns() {
local args=""
if is_enabled_ipv6; then
args+=" -b ::"
else
args+=" -b 0.0.0.0"
fi
if [ "$chinadns_bind_port" ]; then
args+=" -l $chinadns_bind_port"
else
args+=" -l $dns_mainport"
fi
is_enabled_ipv4 && args+="$(get_chinadns_upstream direct "$dns_direct")"
is_enabled_ipv6 && args+="$(get_chinadns_upstream direct "$dns_direct6")"
is_enabled_ipv4 && args+="$(get_chinadns_upstream remote "$dns_remote")"
is_enabled_ipv6 && args+="$(get_chinadns_upstream remote "$dns_remote6")"
args+=" --cache $chinadns_cache_size"
args+=" --cache-stale $chinadns_cache_stale"
args+=" --cache-refresh $chinadns_cache_refresh"
args+=" --verdict-cache $chinadns_verdict_cache"
[ "$chinadns_cache_db" ] && args+=" --cache-db $chinadns_cache_db"
[ "$chinadns_verdict_db" ] && args+=" --verdict-cache-db $chinadns_verdict_db"
for config in $chinadns_config_files; do
args+=" -C $config"
done
[ "$chinadns_extra_options" ] && args+=" $chinadns_extra_options"
is_true "$chinadns_verbose" && args+=' -v'
if is_global_mode; then
sstp_pid_chinadns=$(
trap "" CHLD # 避免bash变为僵尸进程
chinadns-ng \
$args \
-m <(list_ext_domain ignlist.ext) \
-d gfw \
-a sstp_white,sstp_white6 \
</dev/null &>>$chinadns_logfile &
echo $!
)
elif is_gfwlist_mode; then
sstp_pid_chinadns=$(
trap "" CHLD # 避免bash变为僵尸进程
chinadns-ng \
$args \
-g gfwlist.txt,<(list_ext_domain gfwlist.ext) \
-d chn \
-A sstp_black,sstp_black6 \
</dev/null &>>$chinadns_logfile &
echo $!
)
else # chnroute
sstp_pid_chinadns=$(
trap "" CHLD # 避免bash变为僵尸进程
chinadns-ng \
$args \
-m chnlist.txt,<(list_ext_domain ignlist.ext) \
-g gfwlist.txt,<(list_ext_domain gfwlist.ext) \
$(is_true "$chinadns_chnlist_first" && echo '-M') \
-a sstp_white,sstp_white6 \
-A sstp_black,sstp_black6 \
-4 sstp_white -6 sstp_white6 \
</dev/null &>>$chinadns_logfile &
echo $!
)
fi
}
# dns: 删除dns-cache
# verdict: 删除verdict-cache
# 无参数: 删除dns-cache和verdict-cache
del_chinadns_cache() {
if [ -z "$1" ] || [ "$1" = dns ]; then
file_is_exists "$chinadns_cache_db" && rm "$chinadns_cache_db"
fi
if [ -z "$1" ] || [ "$1" = verdict ]; then
file_is_exists "$chinadns_verdict_db" && rm "$chinadns_verdict_db"
fi
}
#===============================================================
start_dnsserver() {
if is_built_in_dns; then
start_chinadns
else
call_func custom_dns_start
fi
}
stop_dnsserver() {
# 为防止修改配置导致进程残留,此处不做判断
kill_by_pid $sstp_pid_chinadns
call_func custom_dns_stop
}
restart_dnsserver() {
ss_tproxy_is_started || return 1
stop_dnsserver
start_dnsserver
save_pidfile
return 0
}
flush_dnscache() {
# ss_tproxy_is_started || return
if is_built_in_dns; then
if ss_tproxy_is_started; then
kill_by_pid $sstp_pid_chinadns
del_chinadns_cache "$1"
start_chinadns
save_pidfile
else
del_chinadns_cache "$1"
fi
else
call_func custom_dns_flush "$1"
fi
}
#===============================================================
# 4/6 key=val
sysctl_all_iface() {
for path in /proc/sys/net/ipv$1/conf/*; do
sysctl -wq ${path#/proc/sys/}/$2
done
}
set_kernel_param() {
# 允许ip转发,充当网关
is_enabled_ipv4 && sysctl -wq net.ipv4.ip_forward=1
is_enabled_ipv6 && sysctl_all_iface 6 forwarding=1
# 允许路由loopback地址,如果不开启,外部数据包将无法dnat至127.0.0.1
sysctl_all_iface 4 route_localnet=1
# 禁止发送icmp重定向包,防止内网机在ping的时候收到重定向消息("旁路由"拓扑)
sysctl_all_iface 4 send_redirects=0
}
#===============================================================
# 失败也不退出,避免逻辑执行不完整
start_proxyproc() {
eval "$proxy_startcmd"
}
stop_proxyproc() {
eval "$proxy_stopcmd"
}
restart_proxyproc() {
ss_tproxy_is_started || return 1
stop_proxyproc
start_proxyproc
return 0
}
#===============================================================
# setname <ip_list
init_ipset() {
ipset create $1 hash:net family $(str_find $1 6 && echo inet6 || echo inet)
sed "s/^/add $1 /" | ipset -! restore
}
# [proto://][host@]ip[#port][path]
get_upstream_ip() {
local upstream="$1"
upstream="${upstream##*://}"
upstream="${upstream##*@}"
upstream="${upstream%%/*}"
upstream="${upstream%%#*}"
echo "$upstream"
}
# prefix "true/false/ip..." "upstreams..."
get_ext_ip() {
case "$2" in
true) for u in $3; do echo "$1$(get_upstream_ip "$u")"; done;;
false) ;;
*) for ip in $2; do echo "$1$ip"; done;;
esac
}
get_ext_whiteip() {
if is_built_in_dns; then
get_ext_ip '-' "$dns_direct_white" "$dns_direct"
get_ext_ip '~' "$dns_direct6_white" "$dns_direct6"
else
call_func custom_dns_whiteip
fi
}
get_ext_blackip() {
if is_built_in_dns; then
get_ext_ip '-' "$dns_remote_black" "$dns_remote"
get_ext_ip '~' "$dns_remote6_black" "$dns_remote6"
else
call_func custom_dns_blackip
fi
}
# dns和iptables都需要ipset,为防止dns组件报错(A/AAAA),v4和v6集合将始终创建
start_ipset() {
if is_global_mode; then
{ list_ext_ipv4 ignlist.ext; get_ext_whiteip | list_ext_ipv4 -; } | init_ipset sstp_white
{ list_ext_ipv6 ignlist.ext; get_ext_whiteip | list_ext_ipv6 -; } | init_ipset sstp_white6
elif is_gfwlist_mode; then
{ list_ext_ipv4 gfwlist.ext; get_ext_blackip | list_ext_ipv4 -; } | init_ipset sstp_black
{ list_ext_ipv6 gfwlist.ext; get_ext_blackip | list_ext_ipv6 -; } | init_ipset sstp_black6
elif is_chnroute_mode; then
{ list_ext_ipv4 ignlist.ext; get_ext_whiteip | list_ext_ipv4 -; cat chnroute.txt; } | init_ipset sstp_white
{ list_ext_ipv6 ignlist.ext; get_ext_whiteip | list_ext_ipv6 -; cat chnroute6.txt; } | init_ipset sstp_white6
{ list_ext_ipv4 gfwlist.ext; get_ext_blackip | list_ext_ipv4 -; } | init_ipset sstp_black
{ list_ext_ipv6 gfwlist.ext; get_ext_blackip | list_ext_ipv6 -; } | init_ipset sstp_black6
fi
}
# stop就清空,如果只是换节点或重启代理,不要通过ss-tproxy进行,请直接操作代理进程
flush_ipset() {
for setname in $(ipset -n list | grep '^sstp_'); do
# https://github.com/zfl9/ss-tproxy/issues/234
while ! ipset destroy $setname &>/dev/null; do
sleep 0.02
done
done
}
#===============================================================
_start_iproute() {
local family="$1"
# 将数据包路由至本地
# 内网过来的包: prerouting -> routing -> input(lo)
# 本机发出的包: output -> routing -> postrouting(lo) -> prerouting(lo) -> routing -> input(lo)
ip $family route add local default dev $ipts_if_lo table $ipts_rt_tab
# https://github.com/zfl9/ss-tproxy/pull/186
# https://man7.org/linux/man-pages/man8/ip-rule.8.html
# https://man7.org/linux/man-pages/man7/rtnetlink.7.html
# https://stackoverflow.com/questions/10259266/what-does-proto-kernel-means-in-unix-routing-table
if ip rule help 2>&1 | grep -Fwq protocol; then
ip $family rule add fwmark $ipts_rt_mark table $ipts_rt_tab protocol static
else
ip $family rule add fwmark $ipts_rt_mark table $ipts_rt_tab
fi
}
start_iproute() {
! is_need_iproute && return
is_enabled_ipv4 && _start_iproute -4
is_enabled_ipv6 && _start_iproute -6
}
_flush_iproute() {
while ip $1 rule del table $ipts_rt_tab &>/dev/null; do true; done
ip $1 route flush table $ipts_rt_tab &>/dev/null
}
flush_iproute() {
# 不做判断,防止相关配置改动导致残留
_flush_iproute -4
_flush_iproute -6
}
#===============================================================
start_iptables_pre() {
$1 -t mangle -N SSTP_PREROUTING
$1 -t mangle -N SSTP_OUTPUT
$1 -t nat -N SSTP_PREROUTING
$1 -t nat -N SSTP_OUTPUT
$1 -t nat -N SSTP_POSTROUTING
}
start_iptables_post() {
$1 -t mangle -A PREROUTING -j SSTP_PREROUTING
$1 -t mangle -A OUTPUT -j SSTP_OUTPUT
$1 -t nat -A PREROUTING -j SSTP_PREROUTING
$1 -t nat -A OUTPUT -j SSTP_OUTPUT
$1 -t nat -A POSTROUTING -j SSTP_POSTROUTING
}
#===============================================================
# local loopback_addr loopback_addrx white_setname black_setname
init_iptables_param() {
if is_ipv4_ipts $1; then
loopback_addr="127.0.0.1"
loopback_addrx="127.0.0.1"
white_setname="sstp_white"
black_setname="sstp_black"
else
loopback_addr="::1"
loopback_addrx="[::1]"
white_setname="sstp_white6"
black_setname="sstp_black6"
fi
}
get_dst_port_match() {
[ "$ipts_proxy_dst_port" ] &&
echo "-m multiport --dports $ipts_proxy_dst_port"
}
#===============================================================
# $ipts tproxy/dnat
# tproxy: mangle表 (tcp,udp)
# dnat: nat表 (tcp)
# 进入SSTP_RULE的必须是"新连接的首包"
create_sstp_rule() {
local table action
if [ "$2" = 'tproxy' ]; then
table=mangle
action="-j CONNMARK --set-mark $ipts_rt_mark" # 用来保存ipset判定结果(每个"连接"只判定一次)
else
table=nat
action="-p tcp -j DNAT --to-destination $loopback_addrx:$proxy_tcpport" # nat的操作单位是"连接"
fi
$1 -t $table -N SSTP_RULE
if is_global_mode; then
$1 -t $table -A SSTP_RULE \
-m set ! --match-set $white_setname dst \
$action
elif is_gfwlist_mode; then
$1 -t $table -A SSTP_RULE \
-m set --match-set $black_setname dst \
$action
elif is_chnroute_mode; then
# 放行白名单ip (若该ip同时也位于黑名单,则不放行)
$1 -t $table -A SSTP_RULE \
-m set --match-set $white_setname dst \
-m set ! --match-set $black_setname dst \
-j RETURN
$1 -t $table -A SSTP_RULE \
$action
fi
}
# mangle表 OUTPUT/PREROUTING -p udp --dport 443
drop_quic() {
$1 -t mangle -N SSTP_QUIC
if is_global_mode; then
$1 -t mangle -A SSTP_QUIC \
-m set ! --match-set $white_setname dst \
-j DROP
elif is_gfwlist_mode; then
$1 -t mangle -A SSTP_QUIC \
-m set --match-set $black_setname dst \
-j DROP
elif is_chnroute_mode; then
# 放行白名单ip (若该ip同时也位于黑名单,则不放行)
$1 -t mangle -A SSTP_QUIC \
-m set --match-set $white_setname dst \
-m set ! --match-set $black_setname dst \
-j RETURN
$1 -t mangle -A SSTP_QUIC \
-j DROP
fi
$1 -t mangle -A SSTP_OUTPUT \
-p udp \
-m udp --dport 443 \
-m conntrack --ctdir ORIGINAL \
-m addrtype ! --dst-type LOCAL \
-m owner ! --gid-owner $proxy_procgroup \
-j SSTP_QUIC
is_proxy_other &&
$1 -t mangle -A SSTP_PREROUTING \
-p udp \
-m udp --dport 443 \
-m conntrack --ctdir ORIGINAL \
-m addrtype ! --dst-type LOCAL \
-j SSTP_QUIC
}
#===============================================================
# mangle表 OUTPUT/PREROUTING
do_proxy_tproxy() {
local tcp=$(is_tcp_tproxy && echo 1 || echo 0)
local udp=$(is_enabled_udp && echo 1 || echo 0)
create_sstp_rule $1 tproxy
# 放行发往本机的流量
$1 -t mangle -A SSTP_OUTPUT \
-m addrtype --dst-type LOCAL \
-j RETURN
# 放行reply流量,只处理original方向
$1 -t mangle -A SSTP_OUTPUT \
-m conntrack --ctdir REPLY \
-j RETURN
# 放行本机代理进程传出的流量
$1 -t mangle -A SSTP_OUTPUT \
-m owner --gid-owner $proxy_procgroup \
-j RETURN
# 放行本机发出的dns请求,留给nat去重定向
((tcp)) &&
$1 -t mangle -A SSTP_OUTPUT \
-p tcp \
-m tcp --dport 53 \
-m owner ! --gid-owner $dns_procgroup \
-j RETURN
((udp)) &&
$1 -t mangle -A SSTP_OUTPUT \
-p udp \
-m udp --dport 53 \
-m owner ! --gid-owner $dns_procgroup \
-j RETURN
# 本机传出流量 => SSTP_RULE
((tcp)) &&
$1 -t mangle -A SSTP_OUTPUT \
-p tcp \
-m tcp --syn \
$(get_dst_port_match) \
-j SSTP_RULE
((udp)) &&
$1 -t mangle -A SSTP_OUTPUT \
-p udp \
-m conntrack --ctstate NEW,RELATED \
$(get_dst_port_match) \
-j SSTP_RULE
# 打mark是为了将包路由到本地,进入prerouting
$1 -t mangle -A SSTP_OUTPUT \
-m connmark --mark $ipts_rt_mark \
-j MARK --set-mark $ipts_rt_mark
###################### prerouting ######################
# 放行发往本机的流量
$1 -t mangle -A SSTP_PREROUTING \
-m addrtype --dst-type LOCAL \
-j RETURN
# 放行reply流量,只处理original方向
$1 -t mangle -A SSTP_PREROUTING \
-m conntrack --ctdir REPLY \
-j RETURN
# 内网传出流量 => SSTP_RULE
if is_proxy_other; then
((tcp)) &&
$1 -t mangle -A SSTP_PREROUTING \
-p tcp \
-m tcp --syn ! --dport 53 \
-m addrtype ! --src-type LOCAL \
$(get_dst_port_match) \
-j SSTP_RULE
((udp)) &&
$1 -t mangle -A SSTP_PREROUTING \
-p udp \
-m udp ! --dport 53 \
-m conntrack --ctstate NEW,RELATED \
-m addrtype ! --src-type LOCAL \
$(get_dst_port_match) \
-j SSTP_RULE
fi
# 本机发出的/内网过来的skb => 代理进程
((tcp)) &&
$1 -t mangle -A SSTP_PREROUTING \
-p tcp \
-m connmark --mark $ipts_rt_mark \
-j TPROXY --on-ip $loopback_addr --on-port $proxy_tcpport --tproxy-mark $ipts_rt_mark
((udp)) &&
$1 -t mangle -A SSTP_PREROUTING \
-p udp \
-m connmark --mark $ipts_rt_mark \
-j TPROXY --on-ip $loopback_addr --on-port $proxy_udpport --tproxy-mark $ipts_rt_mark
}
# nat表 OUTPUT/PREROUTING -p tcp
do_proxy_dnat() {
create_sstp_rule $1 dnat
# 本机传出流量 => SSTP_RULE
$1 -t nat -A SSTP_OUTPUT \
-p tcp \
-m tcp --syn \
-m addrtype ! --dst-type LOCAL \
$(get_dst_port_match) \
-m owner ! --gid-owner $proxy_procgroup \
-j SSTP_RULE
# 内网传出流量 => SSTP_RULE
is_proxy_other &&
$1 -t nat -A SSTP_PREROUTING \
-p tcp \
-m tcp --syn \
-m addrtype ! --src-type LOCAL ! --dst-type LOCAL \
$(get_dst_port_match) \
-j SSTP_RULE
}
#===============================================================
# nat表 OUTPUT/PREROUTING -p tcp,udp
redir_dns_request() {
# 本机发出的dns请求 (dnat)
$1 -t nat -A SSTP_OUTPUT \
-p tcp \
-m tcp --dport 53 --syn \
-m owner ! --gid-owner $proxy_procgroup \
-m owner ! --gid-owner $dns_procgroup \
-j REDIRECT --to-ports $dns_mainport
$1 -t nat -A SSTP_OUTPUT \
-p udp \
-m udp --dport 53 \