forked from pterodactyl/wings
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbetterconsolepatch.sh
More file actions
1088 lines (994 loc) · 31.6 KB
/
Copy pathbetterconsolepatch.sh
File metadata and controls
1088 lines (994 loc) · 31.6 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
set -euo pipefail
RAW_BASE="${TOMAXIKZ_RAW_BASE:-https://raw.githubusercontent.com/Tomaxikz/daemon/develop}"
BACKUP_ROOT="${TOMAXIKZ_BACKUP_ROOT:-.tomaxikz-betterconsole-backups}"
BACKUP_DIR="${BACKUP_ROOT}/$(date -u +%Y%m%dT%H%M%SZ)"
if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
BOLD="$(printf '\033[1m')"
DIM="$(printf '\033[2m')"
RESET="$(printf '\033[0m')"
RED="$(printf '\033[31m')"
GREEN="$(printf '\033[32m')"
YELLOW="$(printf '\033[33m')"
BLUE="$(printf '\033[34m')"
CYAN="$(printf '\033[36m')"
else
BOLD=""
DIM=""
RESET=""
RED=""
GREEN=""
YELLOW=""
BLUE=""
CYAN=""
fi
SPINNER_PID=""
log() {
printf '%s[betterconsole]%s %s\n' "$CYAN" "$RESET" "$*"
}
ok() {
printf '%s[OK]%s %s\n' "$GREEN" "$RESET" "$*"
}
warn() {
printf '%s[WARN]%s %s\n' "$YELLOW" "$RESET" "$*"
}
section() {
printf '\n%s==>%s %s%s%s\n' "$BLUE" "$RESET" "$BOLD" "$*" "$RESET"
}
fail() {
printf '%s[ERROR]%s %s\n' "$RED" "$RESET" "$*" >&2
exit 1
}
banner() {
printf '%s%s%s\n' "$BOLD" "Better Console Wings installer" "$RESET"
printf '%s%s%s\n' "$DIM" "Anchor-based installer for Tomaxikz daemon Better Console features" "$RESET"
}
start_spinner() {
local message="$1"
if [ ! -t 1 ] || [ -n "${NO_COLOR:-}" ]; then
log "$message"
return
fi
(
local frames='|/-\'
local i=0
while :; do
printf '\r%s[%s]%s %s' "$CYAN" "${frames:i++%${#frames}:1}" "$RESET" "$message"
sleep 0.1
done
) &
SPINNER_PID="$!"
}
stop_spinner() {
local status="$1"
local message="$2"
if [ -n "${SPINNER_PID:-}" ]; then
kill "$SPINNER_PID" >/dev/null 2>&1 || true
wait "$SPINNER_PID" 2>/dev/null || true
SPINNER_PID=""
printf '\r\033[K'
fi
case "$status" in
ok) ok "$message" ;;
warn) warn "$message" ;;
*) fail "$message" ;;
esac
}
run_with_spinner() {
local message="$1"
shift
start_spinner "$message"
if "$@"; then
stop_spinner ok "$message"
else
stop_spinner error "$message failed"
fi
}
cleanup_spinner() {
if [ -n "${SPINNER_PID:-}" ]; then
kill "$SPINNER_PID" >/dev/null 2>&1 || true
wait "$SPINNER_PID" 2>/dev/null || true
fi
}
trap cleanup_spinner EXIT
need_cmd() {
command -v "$1" >/dev/null 2>&1 || fail "missing required command: $1"
}
fetch_file() {
local remote_path="$1"
local local_path="$2"
local url="${RAW_BASE%/}/${remote_path}"
local tmp
mkdir -p "$(dirname "$local_path")"
case "$local_path" in
*.go) tmp="$(mktemp --suffix=.go)" ;;
*) tmp="$(mktemp)" ;;
esac
start_spinner "download ${remote_path}"
curl -fsSL --retry 5 --retry-delay 1 --retry-all-errors -o "$tmp" "$url" || {
rm -f "$tmp"
if [ -f "$local_path" ]; then
stop_spinner warn "could not download ${remote_path}; keeping existing ${local_path}"
return
fi
stop_spinner error "failed to download ${url}"
}
if [ "${local_path%.go}" != "$local_path" ]; then
gofmt -w "$tmp" || {
rm -f "$tmp"
stop_spinner error "downloaded Go file is not valid: ${url}"
}
fi
if [ -f "$local_path" ] && cmp -s "$tmp" "$local_path"; then
stop_spinner ok "unchanged ${local_path}"
rm -f "$tmp"
return
fi
if [ -f "$local_path" ]; then
mkdir -p "${BACKUP_DIR}/$(dirname "$local_path")"
cp -p "$local_path" "${BACKUP_DIR}/${local_path}"
warn "backed up ${local_path}"
fi
mv "$tmp" "$local_path"
stop_spinner ok "updated ${local_path}"
}
banner
[ -f go.mod ] || fail "run this from the Wings source root, where go.mod exists"
grep -q 'github.com/pterodactyl/wings' go.mod || fail "go.mod does not look like a Pterodactyl Wings module"
section "Checking requirements"
need_cmd curl
need_cmd python3
need_cmd go
need_cmd gofmt
ok "required commands are available"
section "Downloading Better Console files"
fetch_file "environment/docker/betterconsole_pull_progress.go" "environment/docker/betterconsole_pull_progress.go"
fetch_file "environment/docker/betterconsole_pull_progress_test.go" "environment/docker/betterconsole_pull_progress_test.go"
fetch_file "server/betterconsole_events.go" "server/betterconsole_events.go"
fetch_file "server/betterconsole_pull_progress.go" "server/betterconsole_pull_progress.go"
fetch_file "server/betterconsole_pull_progress_test.go" "server/betterconsole_pull_progress_test.go"
fetch_file "router/websocket/betterconsole_events.go" "router/websocket/betterconsole_events.go"
fetch_file "router/websocket/listeners_test.go" "router/websocket/listeners_test.go"
fetch_file "sftp/betterconsole_shell.go" "sftp/betterconsole_shell.go"
fetch_file "sftp/server_security_test.go" "sftp/server_security_test.go"
section "Applying anchor-based source edits"
export BCON_COLOR_RESET="$RESET"
export BCON_COLOR_GREEN="$GREEN"
export BCON_COLOR_YELLOW="$YELLOW"
export BCON_COLOR_RED="$RED"
python3 - "$BACKUP_DIR" <<'PY'
from pathlib import Path
import os
import shutil
import sys
backup_dir = Path(sys.argv[1])
RESET = os.environ.get("BCON_COLOR_RESET", "")
GREEN = os.environ.get("BCON_COLOR_GREEN", "")
YELLOW = os.environ.get("BCON_COLOR_YELLOW", "")
RED = os.environ.get("BCON_COLOR_RED", "")
def ok(message):
print(f"{GREEN}[OK]{RESET} {message}")
def fail(message):
print(f"{RED}[ERROR]{RESET} {message}", file=sys.stderr)
sys.exit(1)
def backup(path):
target = backup_dir / path
if target.exists():
return
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(path, target)
def read_text(path_name):
path = Path(path_name)
if not path.exists():
fail(f"required file is missing: {path_name}")
return path, path.read_text()
def write_text(path, original, updated, description):
if updated == original:
return False
backup(path)
path.write_text(updated)
ok(f"patched {path}: {description}")
return True
def replace_once(path_name, old, new, present, description):
path, text = read_text(path_name)
if present in text:
ok(f"already patched {path_name}: {description}")
return False
if old not in text:
fail(f"could not find expected source in {path_name} for {description}")
return write_text(path, text, text.replace(old, new, 1), description)
def insert_after(path_name, anchor, addition, present, description):
path, text = read_text(path_name)
if present in text:
ok(f"already patched {path_name}: {description}")
return False
if anchor not in text:
fail(f"could not find anchor in {path_name} for {description}")
return write_text(path, text, text.replace(anchor, anchor + addition, 1), description)
def insert_before(path_name, anchor, addition, present, description):
path, text = read_text(path_name)
if present in text:
ok(f"already patched {path_name}: {description}")
return False
if anchor not in text:
fail(f"could not find anchor in {path_name} for {description}")
return write_text(path, text, text.replace(anchor, addition + anchor, 1), description)
def remove_once(path_name, old, description):
path, text = read_text(path_name)
if old not in text:
ok(f"already clean {path_name}: {description}")
return False
return write_text(path, text, text.replace(old, "", 1), description)
sftp_shell_field = '''\
// Shell controls the optional interactive SSH shell exposed through the SFTP listener.
Shell SftpShellConfiguration `yaml:"shell"`
'''
sftp_shell_type = '''\
type SftpShellConfiguration struct {
// Enabled allows authenticated SFTP users to open the Better Console SSH CLI.
Enabled bool `default:"true" yaml:"enabled"`
}
'''
insert_after(
"config/config.go",
' ReadOnly bool `default:"false" yaml:"read_only"`\n',
sftp_shell_field,
"Shell SftpShellConfiguration",
"SFTP shell config field",
)
insert_after(
"config/config.go",
"type SftpConfiguration struct {\n",
"",
"type SftpShellConfiguration struct",
"SFTP shell config type check",
)
if "type SftpShellConfiguration struct" not in Path("config/config.go").read_text():
insert_before(
"config/config.go",
"// ApiConfiguration defines the configuration for the internal API that is\n",
sftp_shell_type,
"type SftpShellConfiguration struct",
"SFTP shell config type",
)
replace_once(
"config/config.go",
' Enabled bool `default:"false" yaml:"enabled"`\n',
' Enabled bool `default:"true" yaml:"enabled"`\n',
'Enabled bool `default:"true" yaml:"enabled"`',
"SFTP shell default enabled",
)
remove_once(
"environment/docker/container.go",
' "github.com/buger/jsonparser"\n',
"unused jsonparser import",
)
replace_once(
"environment/docker/container.go",
'''\
func (e *Environment) ensureImageExists(img string) error {
e.Events().Publish(environment.DockerImagePullStarted, "")
defer e.Events().Publish(environment.DockerImagePullCompleted, "")
''',
'''\
func (e *Environment) ensureImageExists(img string) error {
''',
"safeImage := betterConsoleDockerPullSafeImageRef(img)",
"move Docker pull events after successful pull",
)
insert_after(
"environment/docker/container.go",
" out, err := e.client.ImagePull(ctx, img, imagePullOptions)\n",
" safeImage := betterConsoleDockerPullSafeImageRef(img)\n",
"safeImage := betterConsoleDockerPullSafeImageRef(img)",
"safe image name for server image pulls",
)
replace_once(
"environment/docker/container.go",
' "image": img,\n',
' "image": safeImage,\n',
'"image": safeImage',
"sanitized fallback image log",
)
replace_once(
"environment/docker/container.go",
' return errors.Wrapf(err, "environment/docker: failed to pull \\"%s\\" image for server", img)\n',
' return errors.Wrapf(err, "environment/docker: failed to pull \\"%s\\" image for server", safeImage)\n',
"failed to pull \\\"%s\\\" image for server\", safeImage",
"sanitized pull error",
)
replace_once(
"environment/docker/container.go",
' log.WithField("image", img).Debug("pulling docker image... this could take a bit of time")\n',
'''\
e.Events().Publish(environment.DockerImagePullStarted, "")
defer e.Events().Publish(environment.DockerImagePullCompleted, "")
log.WithField("image", safeImage).Debug("pulling docker image... this could take a bit of time")
''',
'log.WithField("image", safeImage).Debug("pulling docker image... this could take a bit of time")',
"structured Docker pull start",
)
replace_once(
"environment/docker/container.go",
'''\
for scanner.Scan() {
b := scanner.Bytes()
status, _ := jsonparser.GetString(b, "status")
progress, _ := jsonparser.GetString(b, "progress")
e.Events().Publish(environment.DockerImagePullStatus, status+" "+progress)
}
''',
'''\
for scanner.Scan() {
if payload := betterConsoleDockerPullProgress(img, scanner.Bytes()); payload != "" {
e.Events().Publish(environment.DockerImagePullStatus, payload)
}
}
''',
"betterConsoleDockerPullProgress(img, scanner.Bytes())",
"structured Docker pull progress",
)
replace_once(
"environment/docker/container.go",
' log.WithField("image", img).Debug("completed docker image pull")\n',
' log.WithField("image", safeImage).Debug("completed docker image pull")\n',
'log.WithField("image", safeImage).Debug("completed docker image pull")',
"sanitized Docker pull completion log",
)
insert_after(
"server/install.go",
" r, err := ip.client.ImagePull(ip.Server.Context(), ip.Script.ContainerImage, imagePullOptions)\n",
" safeImage := betterConsoleDockerPullSafeImageRef(ip.Script.ContainerImage)\n",
"safeImage := betterConsoleDockerPullSafeImageRef(ip.Script.ContainerImage)",
"safe image name for installer image pulls",
)
replace_once(
"server/install.go",
' "image": ip.Script.ContainerImage,\n',
' "image": safeImage,\n',
'"image": safeImage',
"sanitized installer fallback image log",
)
replace_once(
"server/install.go",
' log.WithField("image", ip.Script.ContainerImage).Debug("pulling docker image... this could take a bit of time")\n',
'''\
log.WithField("image", safeImage).Debug("pulling docker image... this could take a bit of time")
ip.Server.Events().Publish(ImagePullStartedEvent, "")
defer ip.Server.Events().Publish(ImagePullCompletedEvent, "")
''',
'ip.Server.Events().Publish(ImagePullStartedEvent, "")',
"installer image pull start events",
)
replace_once(
"server/install.go",
'''\
for scanner.Scan() {
log.Debug(scanner.Text())
}
''',
'''\
for scanner.Scan() {
log.Debug(betterConsoleDockerPullSafeText(scanner.Text()))
payload := betterConsoleDockerPullProgress(ip.Script.ContainerImage, scanner.Bytes())
if payload != "" {
ip.Server.Events().Publish(ImagePullProgressEvent, payload)
}
if line := betterConsoleDockerPullInstallLine(scanner.Bytes()); line != "" {
ip.Server.Sink(system.InstallSink).Push([]byte(line))
}
}
''',
"betterConsoleDockerPullProgress(ip.Script.ContainerImage, scanner.Bytes())",
"installer image pull progress",
)
replace_once(
"server/install.go",
" err = system.ScanReader(reader, ip.Server.Sink(system.InstallSink).Push)\n",
" err = ip.streamRawInstallOutput(reader)\n",
"ip.streamRawInstallOutput(reader)",
"raw installer output streaming",
)
insert_before(
"server/install.go",
"// resourceLimits returns resource limits for the installation container. This\n",
'''\
func (ip *InstallationProcess) streamRawInstallOutput(reader io.Reader) error {
buf := make([]byte, 4096)
for {
n, err := reader.Read(buf)
if n > 0 {
chunk := make([]byte, n)
copy(chunk, buf[:n])
ip.Server.Sink(system.InstallSink).Push(chunk)
}
if err != nil {
if errors.Is(err, io.EOF) {
return nil
}
return err
}
}
}
''',
"func (ip *InstallationProcess) streamRawInstallOutput",
"raw installer output helper",
)
replace_once(
"server/listeners.go",
'''\
case environment.DockerImagePullStatus:
s.Events().Publish(InstallOutputEvent, e.Data)
case environment.DockerImagePullStarted:
s.PublishConsoleOutputFromDaemon("Pulling Docker container image, this could take a few minutes to complete...")
case environment.DockerImagePullCompleted:
s.PublishConsoleOutputFromDaemon("Finished pulling Docker container image")
''',
'''\
case environment.DockerImagePullStatus:
s.Events().Publish(ImagePullProgressEvent, e.Data)
if str, ok := e.Data.(string); ok {
if line := betterConsoleDockerPullInstallLine([]byte(str)); line != "" {
s.Sink(system.LogSink).Push([]byte(line))
}
}
case environment.DockerImagePullStarted:
s.Events().Publish(ImagePullStartedEvent, "")
s.PublishConsoleOutputFromDaemon("Pulling Docker container image, this could take a few minutes to complete...")
case environment.DockerImagePullCompleted:
s.Events().Publish(ImagePullCompletedEvent, "")
s.PublishConsoleOutputFromDaemon("Finished pulling Docker container image")
''',
"s.Events().Publish(ImagePullProgressEvent, e.Data)",
"server image pull events",
)
insert_after(
"router/websocket/listeners.go",
"import (\n\t\"context\"\n\t\"encoding/json\"\n",
"\t\"strings\"\n",
'"strings"',
"strings import for event guard",
)
path, text = read_text("router/websocket/listeners.go")
if "betterConsoleListenerEvents" in text:
ok("already patched router/websocket/listeners.go: Better Console event list")
elif "serverImporterListenerEvents" in text and "}, serverImporterListenerEvents...)" in text:
text2 = text.replace("}, serverImporterListenerEvents...)", "}, append(betterConsoleListenerEvents, serverImporterListenerEvents...)...)", 1)
write_text(path, text, text2, "Better Console event list with existing importer events")
elif "var e = []string{" in text:
text2 = text.replace("var e = []string{", "var e = append([]string{", 1)
text2 = text2.replace(' server.TransferStatusEvent,\n}\n', ' server.TransferStatusEvent,\n}, betterConsoleListenerEvents...)\n', 1)
if text2 == text:
fail("could not find event list end in router/websocket/listeners.go")
write_text(path, text, text2, "Better Console event list")
else:
fail("could not identify websocket event list shape in router/websocket/listeners.go")
insert_after(
"router/websocket/listeners.go",
"}, betterConsoleListenerEvents...)\n",
'''\
var allowedServerEvents = func() map[string]struct{} {
events := make(map[string]struct{}, len(e))
for _, event := range e {
events[event] = struct{}{}
}
return events
}()
''',
"var allowedServerEvents = func() map[string]struct{}",
"allowed websocket event guard map",
)
if "append(betterConsoleListenerEvents, serverImporterListenerEvents...)...)" in Path("router/websocket/listeners.go").read_text():
insert_after(
"router/websocket/listeners.go",
"}, append(betterConsoleListenerEvents, serverImporterListenerEvents...)...)\n",
'''\
var allowedServerEvents = func() map[string]struct{} {
events := make(map[string]struct{}, len(e))
for _, event := range e {
events[event] = struct{}{}
}
return events
}()
''',
"var allowedServerEvents = func() map[string]struct{}",
"allowed websocket event guard map",
)
insert_after(
"router/websocket/listeners.go",
'''\
eventChan := make(chan []byte)
logOutput := make(chan []byte, 8)
installOutput := make(chan []byte, 4)
''',
'''\
canReceiveInstall := false
if jwt := h.GetJwt(); jwt != nil {
canReceiveInstall = jwt.HasPermission(PermissionReceiveInstall)
}
''',
"canReceiveInstall := false",
"install event permission flag",
)
replace_once(
"router/websocket/listeners.go",
'''\
h.server.Events().On(eventChan) // TODO: make a sinky
h.server.Sink(system.LogSink).On(logOutput)
h.server.Sink(system.InstallSink).On(installOutput)
''',
'''\
h.server.Events().On(eventChan) // TODO: make a sinky
h.server.Sink(system.LogSink).On(logOutput)
if canReceiveInstall {
h.server.Sink(system.InstallSink).On(installOutput)
}
''',
"if canReceiveInstall {\n\t\th.server.Sink(system.InstallSink).On(installOutput)",
"permission-aware install sink registration",
)
insert_after(
"router/websocket/listeners.go",
'''\
if err := events.DecodeTo(b, &e); err != nil {
continue
}
''',
'''\
if _, ok := allowedServerEvents[e.Topic]; !ok && !strings.HasPrefix(e.Topic, server.BackupCompletedEvent+":") {
continue
}
''',
"allowedServerEvents[e.Topic]",
"unknown websocket event guard",
)
replace_once(
"router/websocket/listeners.go",
'''\
h.server.Events().Off(eventChan)
h.server.Sink(system.LogSink).Off(logOutput)
h.server.Sink(system.InstallSink).Off(installOutput)
''',
'''\
h.server.Events().Off(eventChan)
h.server.Sink(system.LogSink).Off(logOutput)
if canReceiveInstall {
h.server.Sink(system.InstallSink).Off(installOutput)
}
''',
"if canReceiveInstall {\n\t\th.server.Sink(system.InstallSink).Off(installOutput)",
"permission-aware install sink cleanup",
)
replace_once(
"router/websocket/websocket.go",
" if v.Event == server.InstallOutputEvent {\n",
" if isBetterConsoleInstallOutputEvent(v.Event) {\n",
"isBetterConsoleInstallOutputEvent(v.Event)",
"Better Console install-output permission check",
)
insert_after(
"sftp/server.go",
' "strings"\n',
' "sync/atomic"\n "time"\n "unicode"\n "unicode/utf8"\n',
'"sync/atomic"',
"SFTP security imports",
)
path, text = read_text("sftp/server.go")
security_constants = '''\
const (
sshHandshakeTimeout = 10 * time.Second
sftpCredentialValidationTimeout = 8 * time.Second
maxSftpUsernameBytes = 255
maxSSHSessionChannels = 8
)
type sshSessionLimiter struct {
active atomic.Int32
}
func (l *sshSessionLimiter) acquire() bool {
for {
active := l.active.Load()
if active >= maxSSHSessionChannels {
return false
}
if l.active.CompareAndSwap(active, active+1) {
return true
}
}
}
func (l *sshSessionLimiter) release() {
l.active.Add(-1)
}
'''
if "type sshSessionLimiter struct" in text:
ok("already patched sftp/server.go: SFTP security limits")
else:
old_constant = "const sshHandshakeTimeout = 10 * time.Second\n"
if old_constant in text:
text2 = text.replace(old_constant, security_constants, 1)
else:
anchor = "var validUsernameRegexp = regexp.MustCompile(`^(?i)(.+)\\.([a-z0-9]{8})$`)\n"
if anchor not in text:
fail("could not find username validator in sftp/server.go for SFTP security limits")
text2 = text.replace(anchor, anchor + "\n" + security_constants, 1)
write_text(path, text, text2, "SFTP security limits")
insert_after(
"sftp/server.go",
'''\
type SFTPServer struct {
manager *server.Manager
BasePath string
ReadOnly bool
Listen string
}
''',
'''\
type sshPtyRequest struct {
Term string
Cols uint32
Rows uint32
Width uint32
Height uint32
}
''',
"type sshPtyRequest struct",
"SFTP shell PTY request type",
)
replace_once(
"sftp/server.go",
'''\
KeyExchanges: []string{
"curve25519-sha256", "curve25519-sha256@libssh.org",
''',
'''\
KeyExchanges: []string{
ssh.KeyExchangeMLKEM768X25519,
"curve25519-sha256", "curve25519-sha256@libssh.org",
''',
"ssh.KeyExchangeMLKEM768X25519",
"post-quantum SFTP key exchange",
)
sftp_accept_old = '''\
func (c *SFTPServer) AcceptInbound(conn net.Conn, config *ssh.ServerConfig) error {
// Before beginning a handshake must be performed on the incoming net.Conn
sconn, chans, reqs, err := ssh.NewServerConn(conn, config)
if err != nil {
return errors.WithStack(err)
}
defer sconn.Close()
go ssh.DiscardRequests(reqs)
for ch := range chans {
// If its not a session channel we just move on because its not something we
// know how to handle at this point.
if ch.ChannelType() != "session" {
_ = ch.Reject(ssh.UnknownChannelType, "unknown channel type")
continue
}
channel, requests, err := ch.Accept()
if err != nil {
continue
}
go func(in <-chan *ssh.Request) {
for req := range in {
// Channels have a type that is dependent on the protocol. For SFTP
// this is "subsystem" with a payload that (should) be "sftp". Discard
// anything else we receive ("pty", "shell", etc)
ok := req.Type == "subsystem" && len(req.Payload) >= 4 && string(req.Payload[4:]) == "sftp"
_ = req.Reply(ok, nil)
}
}(requests)
if srv, ok := c.manager.Get(sconn.Permissions.Extensions["uuid"]); ok {
if err := c.Handle(sconn, srv, channel); err != nil {
return err
}
}
}
return nil
}
'''
sftp_accept_new = '''\
func (c *SFTPServer) AcceptInbound(conn net.Conn, config *ssh.ServerConfig) error {
// Before beginning a handshake must be performed on the incoming net.Conn
_ = conn.SetDeadline(time.Now().Add(sshHandshakeTimeout))
sconn, chans, reqs, err := ssh.NewServerConn(conn, config)
if err != nil {
return errors.WithStack(err)
}
_ = conn.SetDeadline(time.Time{})
defer sconn.Close()
go ssh.DiscardRequests(reqs)
var sessions sshSessionLimiter
for ch := range chans {
// If its not a session channel we just move on because its not something we
// know how to handle at this point.
if ch.ChannelType() != "session" {
_ = ch.Reject(ssh.UnknownChannelType, "unknown channel type")
continue
}
if !sessions.acquire() {
_ = ch.Reject(ssh.ResourceShortage, "too many active session channels")
continue
}
channel, requests, err := ch.Accept()
if err != nil {
sessions.release()
continue
}
if srv, ok := c.manager.Get(sconn.Permissions.Extensions["uuid"]); ok {
go func() {
defer sessions.release()
c.handleSession(sconn, srv, channel, requests)
}()
} else {
sessions.release()
_ = channel.Close()
}
}
return nil
}
func (c *SFTPServer) handleSession(conn *ssh.ServerConn, srv *server.Server, channel ssh.Channel, requests <-chan *ssh.Request) {
var requestedPty sshPtyRequest
for req := range requests {
switch req.Type {
case "subsystem":
ok := len(req.Payload) >= 4 && string(req.Payload[4:]) == "sftp"
_ = req.Reply(ok, nil)
if ok {
if err := c.Handle(conn, srv, channel); err != nil {
srv.Log().WithField("user", conn.User()).WithError(err).Warn("sftp: failed to handle session")
}
return
}
case "pty-req":
ok := config.Get().System.Sftp.Shell.Enabled
if ok {
handler, err := NewHandler(conn, srv)
ok = err == nil && handler.can("control.console")
if ok {
_ = ssh.Unmarshal(req.Payload, &requestedPty)
}
}
_ = req.Reply(ok, nil)
case "shell":
ok := config.Get().System.Sftp.Shell.Enabled
if ok {
handler, err := NewHandler(conn, srv)
if err != nil || !handler.can("control.console") {
_ = req.Reply(false, nil)
_ = channel.Close()
return
}
_ = req.Reply(true, nil)
if err := c.HandleShell(conn, srv, channel, requests, requestedPty, handler); err != nil {
srv.Log().WithField("user", conn.User()).WithError(err).Warn("sftp: failed to handle shell session")
}
return
}
_ = req.Reply(false, nil)
default:
_ = req.Reply(false, nil)
}
}
_ = channel.Close()
}
'''
replace_once(
"sftp/server.go",
sftp_accept_old,
sftp_accept_new,
"func (c *SFTPServer) handleSession",
"Better Console SFTP shell session routing",
)
insert_after(
"sftp/server.go",
"\tgo ssh.DiscardRequests(reqs)\n",
"\tvar sessions sshSessionLimiter\n",
"var sessions sshSessionLimiter",
"SFTP session limiter",
)
insert_after(
"sftp/server.go",
'''\
if ch.ChannelType() != "session" {
_ = ch.Reject(ssh.UnknownChannelType, "unknown channel type")
continue
}
''',
'''\
if !sessions.acquire() {
_ = ch.Reject(ssh.ResourceShortage, "too many active session channels")
continue
}
''',
"too many active session channels",
"SFTP session channel limit",
)
replace_once(
"sftp/server.go",
'''\
channel, requests, err := ch.Accept()
if err != nil {
continue
}
if srv, ok := c.manager.Get(sconn.Permissions.Extensions["uuid"]); ok {
go c.handleSession(sconn, srv, channel, requests)
} else {
_ = channel.Close()
}
''',
'''\
channel, requests, err := ch.Accept()
if err != nil {
sessions.release()
continue
}
if srv, ok := c.manager.Get(sconn.Permissions.Extensions["uuid"]); ok {
go func() {
defer sessions.release()
c.handleSession(sconn, srv, channel, requests)
}()
} else {
sessions.release()
_ = channel.Close()
}
''',
"defer sessions.release()",
"SFTP session limiter cleanup",
)
replace_once(
"sftp/server.go",
'''\
ctx := srv.Sftp().Context(handler.User())
rs := sftp.NewRequestServer(channel, handler.Handlers())
go func() {
select {
case <-ctx.Done():
srv.Log().WithField("user", conn.User()).Warn("sftp: terminating active session")
_ = rs.Close()
}
}()
''',
'''\
ctx := srv.Sftp().Context(handler.User())
rs := sftp.NewRequestServer(channel, handler.Handlers())
stopRevocation := closeSftpSessionOnRevocation(ctx, func() {
srv.Log().WithField("user", conn.User()).Warn("sftp: terminating active session")
_ = rs.Close()
})
defer stopRevocation()
''',
"stopRevocation := closeSftpSessionOnRevocation(ctx",
"leak-free SFTP session revocation",
)
insert_before(
"sftp/server.go",
"// Generates a new ED25519 private key that is used for host authentication when\n",
'''\
// HandleShell starts the optional Better Console SSH CLI for the authenticated user's server.
func (c *SFTPServer) HandleShell(conn *ssh.ServerConn, srv *server.Server, channel ssh.Channel, requests <-chan *ssh.Request, _ sshPtyRequest, handler *Handler) error {
defer channel.Close()
if !handler.can("control.console") {
_, _ = io.WriteString(channel, "Permission denied: control.console\\r\\n")
return nil
}
ctx := srv.Sftp().Context(handler.User())
stopRevocation := closeSftpSessionOnRevocation(ctx, func() {
srv.Log().WithField("user", conn.User()).Warn("sftp: terminating active shell session")
_ = channel.Close()
})
defer stopRevocation()
go func() {
for req := range requests {
if req.WantReply {
_ = req.Reply(false, nil)
}
}
}()
c.serveBetterConsoleCli(channel, srv, handler, conn.RemoteAddr().String())
return nil
}
func closeSftpSessionOnRevocation(ctx context.Context, closeSession func()) func() bool {
return context.AfterFunc(ctx, closeSession)
}
''',
"func (c *SFTPServer) HandleShell",
"Better Console SFTP shell handler",
)
insert_after(
"sftp/server.go",
'''\
if !handler.can("control.console") {
_, _ = io.WriteString(channel, "Permission denied: control.console\\r\\n")
return nil
}
''',
'''\
ctx := srv.Sftp().Context(handler.User())
stopRevocation := closeSftpSessionOnRevocation(ctx, func() {
srv.Log().WithField("user", conn.User()).Warn("sftp: terminating active shell session")
_ = channel.Close()
})
defer stopRevocation()