-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsusops.sh
More file actions
executable file
·1542 lines (1340 loc) · 56.5 KB
/
susops.sh
File metadata and controls
executable file
·1542 lines (1340 loc) · 56.5 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
susops() {
# Disable job control PID output
set +m
# Defaults
local -r workspace="${SUSOPS_WORKSPACE:-$HOME/.susops}"
# local -r workspace="."
# Define file paths for storing ports and config
local -r pacfile="$workspace/susops.pac"
local -r cfgfile="$workspace/config.yaml"
# Define process names for easier identification
local -r SUSOPS_PROCESS_NAME_BASE="susops"
local -r SUSOPS_SSH_PROCESS_NAME="$SUSOPS_PROCESS_NAME_BASE-ssh"
local -r SUSOPS_PAC_UNIFIED_PROCESS_NAME="$SUSOPS_PROCESS_NAME_BASE-pac"
local -r SUSOPS_PAC_LOOP_PROCESS_NAME="$SUSOPS_PAC_UNIFIED_PROCESS_NAME-loop"
local -r SUSOPS_PAC_NC_PROCESS_NAME="$SUSOPS_PAC_UNIFIED_PROCESS_NAME-nc"
local -r SUSOPS_SHARE_PROCESS_NAME="$SUSOPS_PROCESS_NAME_BASE-share"
mkdir -p "$workspace"
# Bootstrap config if missing
if [[ ! -f "$cfgfile" ]]; then
cat >"$cfgfile" <<EOF
pac_server_port: 0
connections: []
EOF
fi
# Parse global flags: --conn TAG, --verbose
local verbose=false conn_tag="" conn_specified=false
local args=()
while [[ $# -gt 0 ]]; do
case "$1" in
-v|--v|--verbose) verbose=true; shift ;;
-c|--c|--connection) conn_tag=$2; conn_specified=true; shift 2 ;;
*) args+=("$1"); shift ;;
esac
done
set -- "${args[@]}"
# Ensure at least one sub-command is provided
[[ $1 ]] || { susops help; return 1; }
local cmd=$1; shift
# Run yq in-place
read_config() {
yq e "$1" "$cfgfile"
}
update_config() {
yq e -i "$1" "$cfgfile";
}
# Default to first connection if none specified
if [[ -z $conn_tag ]]; then
conn_tag=$(read_config '.connections[0].tag')
if [[ $conn_tag == "null" && $cmd != "add-connection" ]]; then
echo "No connection specified and no default connection found."
echo "Please add a connection using:
susops add-connection <tag> <ssh_host> [<socks_proxy_port>]
"
cmd="invalid-command" # shows help and returns 1
fi
fi
# Initialize ports
pac_port=$(read_config ".pac_server_port")
ssh_host=$(read_config ".connections[] | select(.tag==\"$conn_tag\").ssh_host")
# Get connection tags from the config file
# If a specific connection is specified, return only that tag
get_connection_tags() {
# $1: force all
local always_all=${1:-false}
if $conn_specified && [[ $always_all == false ]]; then
# If a specific connection is specified, return only that tag
read_config ".connections[] | select(.tag==\"$conn_tag\").tag"
else
# Otherwise, return all connection tags
read_config '.connections[].tag'
fi
}
###############################################################################
# load_port <key> [conn_tag]
#
# • key – Key to read from the config file (e.g. "socks_proxy_port")
# • conn_tag – Connection tag (optional, defaults to the current connection)
#
# Returns – Port number (or generates a random one if not set)
#
# Generates a random port number if the key is not already set in the config file.
##############################################################################
load_port() {
local key=$1 filter
local conn_tag=${2:-$conn_tag}
if [[ $key == "pac_server_port" ]]; then
filter=".pac_server_port"
else
filter=".connections[] | select(.tag==\"$conn_tag\").$key"
fi
local cur=$(read_config "$filter" | head -1)
if [[ $cur =~ ^[0-9]+$ ]] && [[ $cur -gt 0 ]]; then
echo $cur
else
local port
port=$(get_random_free_port)
if [[ $key == pac_server_port ]]; then
update_config ".pac_server_port = $port"
else
update_config ".connections[] |= (select(.tag==\"$conn_tag\") .${key} = $port)"
fi
echo $port
fi
}
##############################################################################
# prune_and_add_entry <new_entry>
# For a wildcard or CIDR, delete narrower entries already covered.
##############################################################################
prune_and_add_entry() {
local entry="$1"
# 1) Wildcard pruning (if any)
if [[ $entry == *"*"* ]]; then
# prune out any existing host with wildcard
# get matching pac_hosts comma se-separated
existing_hosts=$(read_config '.connections[].pac_hosts | map(select(. == "'"$entry"'")) | join(", ")' | tr -d '\n')
if [[ -n $existing_hosts ]]; then
update_config "del(.connections[].pac_hosts[] | select(.==\"$entry\"))"
echo "Removed more narrow domains $existing_hosts"
fi
# 2) CIDR pruning (if any)
elif [[ $entry =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]+$ ]]; then
local net=${entry%/*} bits=${entry#*/}
# remove narrower CIDRs under the same connection
read_config ".connections[] | select(.tag==\"$conn_tag\") .pac_hosts[]" \
| while IFS= read -r line; do
if [[ $line =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]+$ ]] && [[ $line == */* ]]; then
local lnet=${line%/*} lbits=${line#*/}
if (( bits < lbits )) && [[ $net == "$lnet" ]]; then
update_config "del(.connections[].pac_hosts[] | select(.==\"$line\"))"
echo "Removed more narrow CIDR $line"
fi
fi
done
fi
# 3) Append the new entry
update_config ".connections[] |= (select(.tag==\"$conn_tag\") .pac_hosts += [\"$entry\"])"
}
######################################################################
# pac_entry_overlaps <candidate>
# Returns 0 (true) if candidate is already covered by an existing rule
######################################################################
pac_entry_overlaps() {
local candidate="$1"
local line suffix
# 1) Check for exact duplicate
if read_config '.connections[].pac_hosts[]' | grep -Fxq "$candidate"; then
return 0
fi
# 2) Existing wildcard covers the new literal/CIDR?
# (skip this check if the candidate itself is a wildcard)
if [[ $candidate != *"*"* ]]; then
while read -r line; do
[[ $line == *"*"* ]] || continue
suffix=${line#\*}
if [[ $candidate == *"$suffix" ]]; then
return 0
fi
done < <(read_config '.connections[].pac_hosts[]')
fi
# 3) CIDR containment: only reject if an EXISTING broader-or-equal CIDR covers the new one
if [[ $candidate == */* ]]; then
local net1 bits1 net2 bits2
net1=${candidate%/*}; bits1=${candidate#*/}
while read -r line; do
[[ $line =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]+$ ]] || continue
net2=${line%/*}; bits2=${line#*/}
# if existing mask is <= candidate mask AND same prefix, existing covers candidate
if (( bits2 <= bits1 )) && [[ ${net1%%.*} == "${net2%%.*}" ]]; then
return 0
fi
done < <(read_config '.connections[].pac_hosts[]')
fi
# 4) Otherwise: no overlap
return 1
}
##############################################################################
# cidr_to_netmask <bits>
# Converts /8 /16 /24 (and any 0-32) into dotted-decimal netmask.
##############################################################################
cidr_to_netmask() {
local bits=$1 mask="" i
for i in {0..3}; do
local n=$(( bits > 7 ? 8 : bits ))
mask+=$(( 256 - 2**(8-n) ))
bits=$(( bits-8 > 0 ? bits-8 : 0 ))
[[ $i -lt 3 ]] && mask+=.
done
echo "$mask"
}
# (Re)generate unified PAC file with rules for all connections
write_pac_file() {
{
echo 'function FindProxyForURL(url, host) {'
while IFS= read -r tag; do
local socks_proxy_port
socks_proxy_port=$(read_config ".connections[] | select(.tag==\"$tag\").socks_proxy_port")
read_config ".connections[] | select(.tag==\"$tag\") | .pac_hosts[]" |
while read -r entry; do
if [[ $entry == *"*"* ]]; then
# wildcard – use shExpMatch
echo " if (shExpMatch(host, '$entry')) return 'SOCKS5 127.0.0.1:$socks_proxy_port';"
elif [[ $entry =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]+$ ]]; then
# CIDR – split net/mask
net=${entry%/*}; bits=${entry#*/}
mask=$(cidr_to_netmask "$bits")
echo " if (isInNet(host, '$net', '$mask')) return 'SOCKS5 127.0.0.1:$socks_proxy_port';"
else
# plain host or exact IP
echo " if (host == '$entry' || dnsDomainIs(host, '.$entry')) return 'SOCKS5 127.0.0.1:$socks_proxy_port';"
fi
done
done < <(get_connection_tags true)
echo ' return "DIRECT";'
echo '}'
} > "$pacfile"
}
##############################################################################
# build_args <key> <flag> [conn_tag]
#
# • key – "local" ⇒ -L style (bind on client)
# "remote" ⇒ -R style (bind on server)
# • flag – The SSH flag to emit ("-L" or "-R")
# • conn_tag – Connection tag (optional; defaults to $conn_tag)
#
# Returns – Array of arguments ready to splice into an ssh command
##############################################################################
build_args() {
local key=$1 flag=$2 conn_tag=${3:-$conn_tag}
local args=()
# jq prints either 4 fields (new schema) or 2 fields (old schema); we normalise to 4.
while IFS=' ' read -r src_addr src_port dst_addr dst_port; do
# Trailing fields may be empty (old schema) – convert on-the-fly.
if [[ -z $dst_addr || -z $dst_port ]]; then
# Legacy "src dst" line: assume loopback for both addresses
src_port=$src_addr
src_addr="localhost"
dst_port=$dst_addr
dst_addr="localhost"
fi
[[ -z $src_port || -z $dst_port ]] && continue # still malformed? skip.
args+=("$flag" "${src_addr}:${src_port}:${dst_addr}:${dst_port}")
done < <(
read_config '
.connections[]
| select(.tag == "'"$conn_tag"'")
| (.forwards.'"$key"' // [])[]
| [
(.src_addr // "localhost"),
(.src_port // .src | tostring),
(.dst_addr // "localhost"),
(.dst_port // .dst | tostring)
] | join(" ")
' "$cfgfile"
)
echo "${args[@]}"
}
# Align printf output for better readability
align_printf() {
local format=$1; shift
local args=("$@")
printf "%-25s $format\n" "${args[@]}"
}
##############################################################################
# is_running <proc-pattern> [description] [print?] [port] [extra] [exact?]
#
# • proc-pattern – String passed to pgrep -f.
# If exact? is “true” (6th arg) we anchor it with ^…$ so
# only a *full-command* match is returned.
# • description – Label printed in the first column (defaults to “Service”).
# • print? – “true” → always print a status line (✅/⚠️).
# – “false” → stay silent; caller checks exit status only.
# • port / extra – Optional bits appended to the status line.
# • exact? – “true” or “false” (default); see above.
#
# Return value – 0 if *any* matching PIDs found, 1 otherwise.
##############################################################################
is_running() {
local pattern=$1
local exact=${2:-true}
local do_print=${3:-false}
local desc=${4:-Service}
local port=$5
local extra=$6
local pids
if [[ $exact == true ]]; then
# pgrep -x matches comm (kernel name), not argv[0] on Linux.
# Use pgrep -f with an anchored regex to match argv[0] set by exec -a.
pids=$(pgrep -f "^${pattern}( |$)" 2>/dev/null || :)
else
pids=$(pgrep -f "${pattern}" 2>/dev/null || :)
fi
if [[ -n $pids ]]; then
if [[ $do_print == true ]]; then
# Build “PID 123 456” or “PIDs 123 456”
local list
list=$(printf '%s\n' "$pids" | awk '{print $1}' | xargs)
local how_many
how_many=$(wc -w <<< "$list")
local label="PID"
[[ $how_many -gt 1 ]] && label="PIDs"
if [[ -n $extra ]]; then
align_printf "✅ running (%s %s%s%s)" "$desc:" "$label" "$list" "${port:+, port $port}" ", $extra"
else
align_printf "✅ running (%s %s%s)" "$desc:" "$label" "$list" "${port:+, port $port}"
fi
fi
return 0
fi
# --- Not running ---------------------------------------------------------
[[ $do_print == true ]] && align_printf "⚠️ not running" "$desc:"
return 1
}
##############################################################################
# stop_by_name <proc-pattern> <label> [keep_ports] [tag] [exact?]
#
# • proc-pattern – Pattern for pgrep to match processes.
# • label – Human-readable label (optional).
# • keep_ports – If "true", do not reset socks_proxy_port (default: false).
# • tag – Connection tag for port reset (optional).
# • exact? – "true" for exact match, "false" for pattern match (default: false).
#
# Kills all matching PIDs (SIGTERM), prints status, and resets port unless keep_ports is true.
#
# Behaviour
# – Finds every matching PID, kills them (SIGTERM).
# – Prints 🛑 stopped / ⚠️ not running lines in the same aligned style
# as is_running / align_printf.
# – No port-file cleanup here (ports now live in config.yaml and are
# cleared by the caller, e.g. in `susops stop`).
##############################################################################
stop_by_name() {
local pattern=$1
local label=$2
local keep_ports=${3:-false}
local tag=${4:-false}
local exact=${5:-false}
local pids
if [[ $exact == true ]]; then
pids=$(pgrep -f "^${pattern}( |$)" 2>/dev/null || :)
else
pids=$(pgrep -f "$pattern" 2>/dev/null || :)
fi
if [[ -n $pids ]]; then
# Terminate every PID that is still alive
for pid in $(printf '%s\n' "$pids" | awk '{print $1}'); do
kill "$pid" 2>/dev/null
done
# zero out the socks_proxy_port unless user asked to keep
if [[ $keep_ports == false && -n "$tag" ]]; then
update_config "(.connections[] | select(.tag==\"$tag\")).socks_proxy_port = 0"
fi
align_printf "🛑 stopped" "${label:-Service}:"
return 0
fi
align_printf "⚠️ not running" "${label:-Service}:"
return 1
}
############################################################################
# test_entry <target> [conn_tag]
#
# • target – Host or port to test (e.g. localhost:8080 or example.com)
# • conn_tag – Connection tag (optional, defaults to the current connection)
#
# Test connectivity to a target through the SOCKS proxy.
# If the target is a port, it will be tested as a local or remote forward.
# If the target is a hostname, it will be tested through the SOCKS proxy.
############################################################################
test_entry() {
local target=$1
local conn_tag=${2:-$conn_tag}
local label=${3:-""}
local ssh_host socks_port
ssh_host=$(read_config ".connections[] | select(.tag==\"$conn_tag\").ssh_host")
socks_port=$(read_config ".connections[] | select(.tag==\"$conn_tag\").socks_proxy_port")
if [[ $target =~ ^[0-9]+$ ]]; then
# Target looks like a port → could be local or remote
if read_config ".connections[] | select(.tag==\"$conn_tag\").forwards.local[]?
| select((.src // .src_port) == $target)" | grep -q . >/dev/null; then
# Local forward exists: test localhost:src
$verbose && echo "Testing local forward $target on localhost"
if curl -s --max-time 5 "http://localhost:$target" >/dev/null 2>&1; then
align_printf "✅ local:%s (localhost:%s → %s:%s)" "$label" \
"$target" "$target" "$ssh_host" \
"$(read_config '.forwards.local[] | select((.src // .src_port)=='"$target"') | (.dst // .dst_port)' \
<<<"$(read_config '.connections[] | select(.tag=="'"$conn_tag"'")')")"
return 0
else
align_printf "❌ localhost:%s unreachable" "$label" "$target"
return 1
fi
elif read_config ".connections[] | select(.tag==\"$conn_tag\").forwards.remote[]?
| select((.src // .src_port) == $target)" | grep -q . >/dev/null; then
# Remote forward exists: test via ssh on remote side
$verbose && echo "Testing remote forward $target on $ssh_host:$target"
if ssh "$ssh_host" curl -s --max-time 5 "http://localhost:$target" >/dev/null 2>&1; then
align_printf "✅ remote:%s (%s:%s → localhost:%s)" "$label" \
"$target" "$ssh_host" "$target" \
"$(read_config '.forwards.remote[] | select((.src // .src_port)=='"$target"') | (.dst // .dst_port)' \
<<<"$(read_config '.connections[] | select(.tag=="'"$conn_tag"'")')")"
return 0
else
align_printf "❌ $ssh_host:%s unreachable" "$label" "$target"
return 1
fi
else
align_printf "❌ Port %s not found in forwards" "$label" "$target"
return 1
fi
else
if [[ $target == *"*"* ]] || [[ $target =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]+$ ]]; then
align_printf "⚠️%s skipped" "$label" "$target"
elif curl -s -k --max-time 5 \
--proxy "socks5h://127.0.0.1:$socks_port" \
"https://$target" >/dev/null 2>&1; then
align_printf "✅ %s via SOCKS" "$label" "$target"
return 0
else
align_printf "❌ %s via SOCKS" "$label" "$target"
return 1
fi
fi
}
# Validate if a port is in the range 1-65535
validate_port_in_range() {
# $1: port
[[ $1 =~ ^[0-9]+$ && $1 -ge 1 && $1 -le 65535 ]]
}
# Check if exact local/remote forward rule exists
check_exact_rule() {
# $1: src, $2: dst, $3: type (local|remote)
read_config ".connections[].forwards.$3[] | select((.src // .src_port)==\"$1\" and (.dst // .dst_port)==\"$2\")" | grep -q . && return 0
return 1
}
# Check if a src port is configured for given type
check_port_source() {
# $1: port, $2: type (local|remote)
read_config ".connections[].forwards.$2[] | select((.src // .src_port)==\"$1\")" | grep -q . && return 0
return 1
}
# Check if a dst port is configured for given type
check_port_target() {
# $1: port, $2: type (local|remote)
read_config ".connections[].forwards.$2[] | select((.dst // .dst_port)==\"$1\")" | grep -q . && return 0
return 1
}
get_random_free_port() {
local port raw
while true; do
raw=$(head -c2 /dev/random | od -An -tu2 | tr -d ' ')
port=$(( raw % 16384 + 49152 ))
if ! check_port_in_use "$port"; then
echo "$port"
return
fi
done
}
# Check if a port is in use on localhost or remote host
check_port_in_use() {
# $1: port, $2: host (optional, defaults to localhost)
local port=$1 host=${2:-localhost}
if [[ "$host" == localhost ]]; then
lsof -iTCP:"$port" -sTCP:LISTEN -t >/dev/null 2>&1
else
ssh "$host" lsof -iTCP:"$port" -sTCP:LISTEN -t >/dev/null 2>&1
fi
}
# Replace spaces with hyphens, remove leading/trailing whitespace
normalize_process_name() {
# $1: process name
echo "$1" | xargs | tr ' ' '-'
}
start_susops() {
# Usage: start [SSH_HOST] [SOCKS_PORT] [PAC_PORT]
#
# • SSH_HOST – SSH host to connect to (overrides config.yaml)
# • SOCKS_PORT – Port for the SOCKS proxy (overrides config.yaml)
# • PAC_PORT – Port for the PAC server (overrides config.yaml)
[[ -n $1 ]] && ssh_host=$1 && update_config "(.connections[] | select(.tag==\"$conn_tag\")).ssh_host = \"$ssh_host\""
[[ -n $2 ]] && socks_port=$2 && update_config "(.connections[] | select(.tag==\"$conn_tag\")).socks_proxy_port = $socks_port"
[[ -n $1 ]] || [[ -n $2 ]] && stop_by_name "$(normalize_process_name "$SUSOPS_SSH_PROCESS_NAME-$conn_tag")" "SOCKS5 proxy [$conn_tag]" true
[[ -n $3 ]] && pac_port=$3 && update_config ".pac_server_port = $pac_port" && stop_by_name "$SUSOPS_PAC_UNIFIED_PROCESS_NAME" "PAC server" true
while IFS= read -r tag; do
ssh_host=$(read_config ".connections[] | select(.tag==\"$tag\").ssh_host")
# Ensure ephemeral port is set
socks_port=$(load_port "socks_proxy_port" "$tag")
# Start SOCKS proxy for chosen connection
local process_name
process_name=$(normalize_process_name "$SUSOPS_SSH_PROCESS_NAME-$tag")
if is_running "$process_name" >/dev/null; then
is_running "$process_name" true true "SOCKS5 proxy [$tag]" "$socks_port" "SSH host $ssh_host"
else
local_args=$(build_args "local" "-L" "$tag")
remote_args=$(build_args "remote" "-R" "$tag")
common_flags=(
-N # no remote shell
-T # disable pty
-D "$socks_port" # start with SOCKS
-o ExitOnForwardFailure=yes # exit if port forwarding fails
-o ServerAliveInterval=30 # send keepalive every 30 seconds
-o ServerAliveCountMax=3 # exit after 3 failed keepalives
"${local_args[@]}"
"${remote_args[@]}"
"$ssh_host"
)
if command -v autossh &>/dev/null; then
ssh_binary=(autossh -M 0)
else
$verbose && echo "autossh not found, falling back to ssh"
ssh_binary=(ssh)
fi
inner_cmd=( exec -a "$process_name" "${ssh_binary[@]}" "${common_flags[@]}" )
nohup bash -c "${inner_cmd[*]}" </dev/null >/dev/null 2>&1 &
process_pid=$!
if $verbose; then
quoted_inner=$(IFS=' '; echo "${inner_cmd[*]}" | tr -s ' ')
full_cmd="nohup bash -c '$quoted_inner' </dev/null >/dev/null 2>&1 &"
echo "Full SSH command: $full_cmd"
fi
align_printf "🚀 started (PID %s, port %s, SSH host %s)" "SOCKS5 proxy [$tag]:" "$process_pid" "$socks_port" "$ssh_host"
fi
done < <(get_connection_tags)
# persist changes for ephemeral ports and given arguments
write_pac_file
# Only start PAC server if not already running. Ensure ephemeral port is set
local pac_port
pac_port=$(load_port "pac_server_port")
if is_running "$SUSOPS_PAC_UNIFIED_PROCESS_NAME" false >/dev/null; then
is_running "$SUSOPS_PAC_UNIFIED_PROCESS_NAME" false true "PAC server" "$pac_port" "URL http://localhost:$pac_port/susops.pac"
else
length=$(wc -c <"$pacfile")
nohup bash -c "exec -a $SUSOPS_PAC_LOOP_PROCESS_NAME bash -c \"while true; do
{
printf 'HTTP/1.1 200 OK\r\n'
printf 'Content-Type: application/x-ns-proxy-autoconfig\r\n'
printf 'Content-Length: %s\r\n' $length
printf 'Connection: close\r\n'
printf '\r\n'
cat \\\"$pacfile\\\"
} | exec -a $SUSOPS_PAC_NC_PROCESS_NAME nc -l $pac_port
done\"" </dev/null >/dev/null 2>&1 &
local pac_pid=$!
# ensure
local max_wait=5
local interval=0.1
steps=$(printf "%.0f" "$(echo "$max_wait / $interval" | bc -l)") # workaround, $i has to be an integer value
for ((i=0; i<steps; i++)); do
if nc_pid=$(pgrep -f "$SUSOPS_PAC_NC_PROCESS_NAME"); then
align_printf "🚀 started (PIDs %s & %s, port %s, URL %s)" "PAC server:" "$pac_pid" "$nc_pid" "$pac_port" "http://localhost:$pac_port/susops.pac"
break
fi
$verbose && printf "Waiting for PAC server to start... (%d/%d)\n" $((i + 1)) "$steps"
sleep "$interval"
done
if [[ $i -ge $steps ]]; then
align_printf "⚠️ partially started (PID %s, port %s, URL %s)" "PAC server:" "$pac_pid" "$pac_port" "http://localhost:$pac_port/susops.pac"
return 1
fi
fi
}
stop_susops() {
# Usage: susops stop [--keep-ports] [--force]
#
# • --keep-ports keeps the ports in config.yaml unchanged; otherwise the
# stopped connection’s socks_proxy_port is reset to 0.
# • --force stops all connections and the PAC server no matter what's currently in the config
local keep_ports=false
local force=false
while [[ $# -gt 0 ]]; do
case "$1" in
--keep-ports) keep_ports=true; shift ;;
--force) force=true; shift ;;
*) shift ;;
esac
done
if $force; then
# Stop all connections and the PAC server
pkill -f "$SUSOPS_SSH_PROCESS_NAME"
pkill -f "$SUSOPS_PAC_UNIFIED_PROCESS_NAME"
return 0
fi
while IFS= read -r tag; do
local process_name
process_name=$(normalize_process_name "$SUSOPS_SSH_PROCESS_NAME-$tag")
stop_by_name "$process_name" "SOCKS5 proxy [$tag]" "$keep_ports" "$tag" true
done < <(get_connection_tags)
# Stop the PAC server if no other connections are running
if ! pgrep -f $SUSOPS_SSH_PROCESS_NAME >/dev/null; then
stop_by_name "$SUSOPS_PAC_UNIFIED_PROCESS_NAME" "PAC server" true # keep port the same no matter if $keep_ports is set
fi
return 0
}
restart_susops() {
# Usage: susops restart
#
# Restart the SOCKS proxy and PAC server without changing the ports.
stop_susops --keep-ports --force
start_susops
}
add_entry() {
local process_name
process_name=$(normalize_process_name "$SUSOPS_SSH_PROCESS_NAME-$conn_tag")
case "$1" in
-l)
local lport=$2 # LOCAL_PORT (field-2 of -L)
local rport=$3 # REMOTE_PORT (field-4 of -L)
local tag=${4:-""} # human label
local local_bind=${5:-"localhost"} # field-1 of -L (bind addr on *your* host)
local remote_bind=${6:-"localhost"} # field-3 of -L (target addr on SSH server)
# --------------------------------------------------------------------------- #
[[ $lport && $rport ]] || {
echo "Usage: susops add -l LOCAL_PORT REMOTE_PORT [TAG] [LOCAL_BIND] [REMOTE_BIND]"
echo "Map a port from \${LOCAL_BIND:-localhost} to a remote server address"
return 1
}
[[ -z $tag || $tag =~ ^[[:space:]]+$ ]] && tag="$lport"
tag=$(echo "$tag" | xargs)
# ── sanity checks ─────────────────────────────────────────────────────────── #
if ! validate_port_in_range "$lport"; then
echo "LOCAL_PORT must be between 1 and 65535"
return 1
elif ! validate_port_in_range "$rport"; then
echo "REMOTE_PORT must be between 1 and 65535"
return 1
elif check_exact_rule "$lport" "$rport" "local"; then
echo "Local forward ${local_bind}:${lport} → $ssh_host:${rport} already exists"
return 1
elif check_port_source "$lport" "local"; then
echo "Local port ${lport} is already the source of a local forward"
return 1
elif check_port_target "$lport" "local"; then
echo "Local port ${lport} is already the target of a remote forward"
return 1
elif check_port_source "$rport" "remote"; then
echo "Remote port ${rport} is already the source of a remote forward"
return 1
elif check_port_in_use "$lport"; then
echo "Local port ${lport} is already in use"
return 1
fi
update_config ".connections[]
|= (select(.tag==\"$conn_tag\")
.forwards.local += [{
\"tag\": \"$tag\",
\"src_addr\": \"$local_bind\",
\"src_port\": $lport,
\"dst_addr\": \"$remote_bind\",
\"dst_port\": $rport
}])"
align_printf \
"✅ Added local forward [${tag}] ${local_bind}:${lport} → ${ssh_host}:${remote_bind}:${rport}" \
"Connection [$conn_tag]:"
is_running "$process_name" && echo "Restart proxy to apply"
return 0
;;
-r)
local rport=$2 # REMOTE_PORT (bind port on server)
local lport=$3 # LOCAL_PORT (target port on client)
local tag=${4:-""} # human label
local remote_bind=${5:-"localhost"} # field-1 of -R (bind addr on server)
local local_bind=${6:-"localhost"} # field-3 of -R (target addr on client)
[[ $rport && $lport ]] || {
echo "Usage: susops add -r REMOTE_PORT LOCAL_PORT [TAG] [REMOTE_BIND] [LOCAL_BIND]"
echo "Map a port from \${REMOTE_BIND:-localhost} on the server to \${LOCAL_BIND:-localhost} on your machine"
return 1
}
[[ -z $tag || $tag =~ ^[[:space:]]+$ ]] && tag="$rport"
tag=$(echo "$tag" | xargs) # trim
# ── sanity checks ─────────────────────────────────────────────────────────── #
if ! validate_port_in_range "$rport"; then
echo "REMOTE_PORT must be between 1 and 65535"
return 1
elif ! validate_port_in_range "$lport"; then
echo "LOCAL_PORT must be between 1 and 65535"
return 1
elif check_exact_rule "$rport" "$lport" "remote"; then
echo "Remote forward ${ssh_host}:${rport} → ${local_bind}:${lport} already exists"
return 1
elif check_port_source "$rport" "remote"; then
echo "Remote port ${rport} is already the source of a remote forward"
return 1
elif check_port_target "$rport" "remote"; then
echo "Remote port ${rport} is already the target of a local forward"
return 1
elif check_port_source "$lport" "local"; then
echo "Local port ${lport} is already the source of a local forward"
return 1
elif check_port_in_use "$rport" "$ssh_host"; then
echo "Remote port ${rport} is already in use on ${ssh_host} (${remote_bind})"
return 1
fi
update_config ".connections[]
|= (select(.tag==\"$conn_tag\")
.forwards.remote += [{
\"tag\": \"$tag\",
\"src_addr\": \"$remote_bind\",
\"src_port\": $rport,
\"dst_addr\": \"$local_bind\",
\"dst_port\": $lport
}])"
align_printf \
"✅ Added remote forward [${tag}] ${ssh_host}:${remote_bind}:${rport} → ${local_bind}:${lport}" \
"Connection [$conn_tag]:"
is_running "$process_name" && echo "Restart proxy to apply"
return 0
;;
*)
local entry=$1
[[ $entry ]] || { echo "Usage: susops add [HOST|WILDCARD|CIDR]"; return 1; }
# On URL, strip scheme + path, otherwise leave CIDRs intact
if [[ $entry == *"://"* ]]; then
# remove scheme:// and any trailing path
entry=${entry#*://}
entry=${entry%%/*}
fi
# Validate pattern
if ! [[ $entry == *"*"* \
|| $entry =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]+$ \
|| $entry =~ ^[A-Za-z0-9.-]+$ ]]; then
echo "Error: unsupported host pattern '$entry'"
return 1
fi
# Abort if truly duplicate; otherwise clean narrower ones
if pac_entry_overlaps "$entry"; then
echo "Error: PAC entry '$entry' already exists or is covered"
return 1
fi
# prune and add (handles both wildcard & CIDR)
prune_and_add_entry "$entry"
write_pac_file
align_printf "✅ Added $entry" "Connection [$conn_tag]:"
# Connectivity test only for literal host / IP
if [[ $entry != *"*"* && $entry != */* ]]; then
is_running "$process_name" && test_entry "$entry" "$conn_tag" "Connectivity check:"
fi
echo "Please reload your browser proxy settings."
return 0
esac
}
remove_entry() {
local process_name
process_name=$(normalize_process_name "$SUSOPS_SSH_PROCESS_NAME-$conn_tag")
case "$1" in
-l)
local lport=$2
[[ $lport ]] || { echo "Usage: susops rm -l LOCAL_PORT"; return 1; }
if check_port_source "$lport" "local"; then
update_config "del(.connections[].forwards.local[] | select((.src // .src_port)==$lport))"
echo "Removed local forward $lport"
is_running "$process_name" && echo "Restart proxy to apply"
return 0
else
echo "No local forward for $lport"
return 1
fi
;;
-r)
local rport=$2
[[ $rport ]] || { echo "Usage: susops rm -r REMOTE_PORT"; return 1; }
if check_port_source "$rport" "remote"; then
update_config "del(.connections[].forwards.remote[] | select((.src // .src_port)==$rport))"
echo "Removed remote forward $ssh_host:$rport"
is_running "$process_name" && echo "Restart proxy to apply"
return 0
else
echo "No remote forward for $ssh_host:$rport"
return 1
fi
;;
*)
local host=$1 existing_hosts
[[ $host ]] || { echo "Usage: rm [HOST] [-l LOCAL_PORT] [-r REMOTE_PORT]"; return 1; }
existing_hosts=$(read_config '.connections[].pac_hosts | map(select(. == "'"$host"'")) | join(", ")' | tr -d '\n')
if [[ -n $existing_hosts ]]; then
update_config "del(.connections[].pac_hosts[] | select(.==\"$host\"))"
write_pac_file
echo "Removed $existing_hosts"
is_running "$process_name" && echo "Please reload your browser proxy settings."
return 0
else
echo "$host not found"
if [[ $host =~ ^[0-9]+$ ]]; then echo "Use \"susops -l LOCAL_PORT\" OR \"susops -r REMOTE_PORT\" to remove a forwarded port"; fi
return 1
fi
;;
esac
}
encrypt_value_base64() {
local string=$1 pass=$2
echo "$string" | openssl enc -aes-256-ctr -salt -pbkdf2 -pass pass:"$pass" -base64 -A
}
decrypt_value_base64() {
local encrypted_string=$1 pass=$2
echo "$encrypted_string" | openssl enc -d -aes-256-ctr -salt -pbkdf2 -pass pass:"$pass" -base64 -A
}
compress_and_encrypt_file() {
local file=$1 pass=$2
gzip -c "$file" | openssl enc -aes-256-ctr -salt -pbkdf2 -pass pass:"$pass"
}
decrypt_and_decompress_file() {
local encrypted_file=$1 pass=$2
openssl enc -d -aes-256-ctr -salt -pbkdf2 -pass pass:"$pass" < "$encrypted_file" | gunzip
}
# Starts nc listening on $1, populating READ_FD and WRITE_FD
listen() {
local port=$1 in_fifo out_fifo
in_fifo=$(mktemp -u)
out_fifo=$(mktemp -u)
mkfifo "$in_fifo" "$out_fifo"
# launch netcat with FIFO redirection
exec -a "$SUSOPS_SHARE_PROCESS_NAME-$port" nc -l "$port" <"$out_fifo" >"$in_fifo" &
NC_PID=$!
# assign them to numbered FDs
exec 3<>"$in_fifo"
exec 4<>"$out_fifo"
FIFOS=("$in_fifo" "$out_fifo")
}
cleanup_conn() {
# close our FDs
exec 3>&-
exec 4>&-
# wait for netcat to exit
wait "$NC_PID"
# remove fifos if we created them
if [[ -n "${FIFOS[*]}" ]]; then
for fifo in "${FIFOS[@]}"; do
unlink "$fifo"
done
fi
}
handle_connection() {
# launch nc as numbered file descriptors to allow read & write to the same socket
if ! listen "$port"; then
echo "Error: Failed to start share on port $port"
running=false
return
fi
# 1) read headers until blank line, capture Basic auth
local auth header
while IFS=$'\r\n' read -r header <&3; do
[[ -z $header ]] && break
if [[ $header =~ ^Authorization:\ Basic\ (.+)$ ]]; then
auth=${BASH_REMATCH[1]}
fi
done
# break early to prevent "ambiguous redirect" file errors as NC_SHARE has been closed
if ! $running; then
echo "Exiting share server..."
return
fi
# 2) validate creds
local decoded
decoded=$(printf '%s' "$auth" | base64 -d 2>/dev/null)
if [[ ":$pass" == "$decoded" ]]; then
align_printf "✅ authorized access" "$(date +'%Y-%m-%d %H:%M:%S'):"
# 200 OK + headers
{
printf 'HTTP/1.1 200 OK\r\n'
printf 'Content-Type: application/octet-stream\r\n'
# printf 'Content-Length: %s\r\n' "$length"
printf 'Content-Disposition: attachment; filename="%s"\r\n' "$encrypted_filename"
printf 'Connection: close\r\n'
printf '\r\n'
cat "$contentfile"
} >&4
else
align_printf "🚫 unauthorized access" "$(date +'%Y-%m-%d %H:%M:%S'):"
# 401 challenge
{
printf 'HTTP/1.1 401 Unauthorized\r\n'
printf 'WWW-Authenticate: Basic realm="susops share"\r\n'
# printf 'Content-Length: 0\r\n'
printf '\r\n'
} >&4
fi
# clean up this coprocess
cleanup_conn
}
##############################################################################
# susops share <file> [password] [port]
#
# • <file> File to share (must be readable)
# • [password] Password to protect the share (optional, generated if not provided)
# • [port] Port to serve the file on (optional, random if not provided)
##############################################################################