forked from gliderlabs/ssh
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstreamlocal_test.go
More file actions
799 lines (724 loc) · 22.6 KB
/
streamlocal_test.go
File metadata and controls
799 lines (724 loc) · 22.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
//go:build !plan9 && !js && !wasip1
package ssh
import (
"bytes"
"errors"
"fmt"
"io"
"net"
"os"
"path/filepath"
"runtime"
"strings"
"sync/atomic"
"testing"
gossh "golang.org/x/crypto/ssh"
)
// tempDirUnixSocket returns a temporary directory that can safely hold unix
// sockets.
//
// On all platforms other than darwin this just returns t.TempDir(). On darwin
// we manually make a temporary directory in /tmp because t.TempDir() returns a
// very long directory name, and the path length limit for Unix sockets on
// darwin is 104 characters.
func tempDirUnixSocket(t *testing.T) string {
t.Helper()
if runtime.GOOS == "darwin" {
testName := strings.ReplaceAll(t.Name(), "/", "_")
dir, err := os.MkdirTemp("/tmp", fmt.Sprintf("gliderlabs-ssh-test-%s-", testName))
if err != nil {
t.Fatalf("create temp dir for test: %v", err)
}
t.Cleanup(func() {
err := os.RemoveAll(dir)
if err != nil {
t.Errorf("remove temp dir %s: %v", dir, err)
}
})
return dir
}
return t.TempDir()
}
func newLocalUnixListener(t *testing.T) net.Listener {
path := filepath.Join(tempDirUnixSocket(t), "socket.sock")
l, err := net.Listen("unix", path)
if err != nil {
t.Fatalf("failed to listen on a unix socket %q: %v", path, err)
}
return l
}
func sampleUnixSocketServer(t *testing.T) net.Listener {
l := newLocalUnixListener(t)
go func() {
conn, err := l.Accept()
if err != nil {
return
}
_, _ = conn.Write(sampleServerResponse)
_ = conn.Close()
}()
return l
}
func newTestSessionWithUnixForwarding(t *testing.T, forwardingEnabled bool) (net.Listener, *gossh.Client, func()) {
l := sampleUnixSocketServer(t)
allowAllCb := NewLocalUnixForwardingCallback(UnixForwardingOptions{AllowAll: true})
_, client, cleanup := newTestSession(t, &Server{
Handler: func(s Session) {},
LocalUnixForwardingCallback: func(ctx Context, socketPath string) (net.Conn, error) {
if socketPath != l.Addr().String() {
panic("unexpected socket path: " + socketPath)
}
if !forwardingEnabled {
return nil, ErrRejected
}
return allowAllCb(ctx, socketPath)
},
}, nil)
return l, client, func() {
cleanup()
_ = l.Close()
}
}
func TestLocalUnixForwardingWorks(t *testing.T) {
t.Parallel()
l, client, cleanup := newTestSessionWithUnixForwarding(t, true)
defer cleanup()
conn, err := client.Dial("unix", l.Addr().String())
if err != nil {
t.Fatalf("Error connecting to %v: %v", l.Addr().String(), err)
}
result, err := io.ReadAll(conn)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(result, sampleServerResponse) {
t.Fatalf("result = %#v; want %#v", result, sampleServerResponse)
}
}
func TestLocalUnixForwardingRespectsCallback(t *testing.T) {
t.Parallel()
l, client, cleanup := newTestSessionWithUnixForwarding(t, false)
defer cleanup()
_, err := client.Dial("unix", l.Addr().String())
if err == nil {
t.Fatalf("Expected error connecting to %v but it succeeded", l.Addr().String())
}
if !strings.Contains(err.Error(), "unix forwarding is disabled") {
t.Fatalf("Expected permission error but got %#v", err)
}
}
func TestReverseUnixForwardingWorks(t *testing.T) {
t.Parallel()
remoteSocketPath := filepath.Join(tempDirUnixSocket(t), "remote.sock")
allowAllCb := NewReverseUnixForwardingCallback(UnixForwardingOptions{
AllowAll: true,
BindUnlink: true,
})
_, client, cleanup := newTestSession(t, &Server{
Handler: func(s Session) {},
ReverseUnixForwardingCallback: func(ctx Context, socketPath string) (net.Listener, error) {
if socketPath != remoteSocketPath {
panic("unexpected socket path: " + socketPath)
}
return allowAllCb(ctx, socketPath)
},
}, nil)
defer cleanup()
l, err := client.ListenUnix(remoteSocketPath)
if err != nil {
t.Fatalf("failed to listen on a unix socket over SSH %q: %v", remoteSocketPath, err)
}
defer l.Close() //nolint:errcheck
go func() {
conn, err := l.Accept()
if err != nil {
return
}
_, _ = conn.Write(sampleServerResponse)
_ = conn.Close()
}()
// Dial the listener that should've been created by the server.
conn, err := net.Dial("unix", remoteSocketPath)
if err != nil {
t.Fatalf("Error connecting to %v: %v", remoteSocketPath, err)
}
result, err := io.ReadAll(conn)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(result, sampleServerResponse) {
t.Fatalf("result = %#v; want %#v", result, sampleServerResponse)
}
// Close the listener and make sure that the Unix socket is gone.
err = l.Close()
if err != nil {
t.Fatalf("failed to close remote listener: %v", err)
}
_, err = os.Stat(remoteSocketPath)
if err == nil {
t.Fatal("expected remote socket to be removed after close")
}
}
func TestValidateSocketPath(t *testing.T) {
t.Parallel()
tests := []struct {
name string
path string
opts UnixForwardingOptions
wantErr bool
wantClean string // expected cleaned path on success
errSubstr string // substring expected in error message
wantType error // expected error type (ErrRejected)
}{
// Basic validation (applies to all modes).
{
name: "absolute path accepted with AllowAll",
path: "/tmp/test.sock",
opts: UnixForwardingOptions{AllowAll: true},
wantClean: "/tmp/test.sock",
},
{
name: "relative path rejected",
path: "relative/path.sock",
opts: UnixForwardingOptions{AllowAll: true},
wantErr: true,
errSubstr: "must be absolute",
wantType: ErrRejected,
},
{
name: "dot-relative path rejected",
path: "./local.sock",
opts: UnixForwardingOptions{AllowAll: true},
wantErr: true,
errSubstr: "must be absolute",
wantType: ErrRejected,
},
{
name: "empty path rejected",
path: "",
opts: UnixForwardingOptions{AllowAll: true},
wantErr: true,
errSubstr: "must be absolute",
wantType: ErrRejected,
},
{
name: "path with dot-dot cleaned and accepted",
path: "/tmp/foo/../bar/test.sock",
opts: UnixForwardingOptions{AllowAll: true},
wantClean: "/tmp/bar/test.sock",
},
{
name: "path with double slashes cleaned",
path: "/tmp//foo//test.sock",
opts: UnixForwardingOptions{AllowAll: true},
wantClean: "/tmp/foo/test.sock",
},
{
name: "path with trailing slash cleaned",
path: "/tmp/test.sock/",
opts: UnixForwardingOptions{AllowAll: true},
wantClean: "/tmp/test.sock",
},
{
name: "path at sun_path limit rejected",
path: "/" + strings.Repeat("a", maxSunPathLen-1),
opts: UnixForwardingOptions{AllowAll: true},
wantErr: true,
errSubstr: "too long",
wantType: ErrRejected,
},
{
name: "path just under sun_path limit accepted",
path: "/" + strings.Repeat("a", maxSunPathLen-3),
opts: UnixForwardingOptions{AllowAll: true},
wantClean: "/" + strings.Repeat("a", maxSunPathLen-3),
},
// AllowedDirectories tests.
{
name: "path in allowed directory accepted",
path: "/tmp/ssh/agent.sock",
opts: UnixForwardingOptions{AllowedDirectories: []string{"/tmp"}},
wantClean: "/tmp/ssh/agent.sock",
},
{
name: "path in second allowed directory accepted",
path: "/home/user/.ssh/agent.sock",
opts: UnixForwardingOptions{AllowedDirectories: []string{"/tmp", "/home/user"}},
wantClean: "/home/user/.ssh/agent.sock",
},
{
name: "path outside allowed directories rejected",
path: "/var/run/docker.sock",
opts: UnixForwardingOptions{AllowedDirectories: []string{"/tmp", "/home/user"}},
wantErr: true,
errSubstr: "not in an allowed directory",
wantType: ErrRejected,
},
{
name: "empty allowed directories rejects all",
path: "/tmp/test.sock",
opts: UnixForwardingOptions{AllowedDirectories: []string{}},
wantErr: true,
errSubstr: "not in an allowed directory",
wantType: ErrRejected,
},
{
name: "nil allowed directories rejects all",
path: "/tmp/test.sock",
opts: UnixForwardingOptions{},
wantErr: true,
errSubstr: "not in an allowed directory",
wantType: ErrRejected,
},
{
name: "allowed directory itself is not a valid socket path",
path: "/tmp",
opts: UnixForwardingOptions{AllowedDirectories: []string{"/tmp"}},
wantErr: true,
errSubstr: "not in an allowed directory",
wantType: ErrRejected,
},
{
name: "allowed directory with trailing slash works",
path: "/tmp/test.sock",
opts: UnixForwardingOptions{AllowedDirectories: []string{"/tmp/"}},
wantClean: "/tmp/test.sock",
},
{
name: "dot-dot traversal out of allowed directory rejected",
path: "/tmp/../var/run/docker.sock",
opts: UnixForwardingOptions{AllowedDirectories: []string{"/tmp"}},
wantErr: true,
errSubstr: "not in an allowed directory",
wantType: ErrRejected,
},
{
name: "dot-dot traversal staying in allowed directory accepted",
path: "/tmp/foo/../bar/test.sock",
opts: UnixForwardingOptions{AllowedDirectories: []string{"/tmp"}},
wantClean: "/tmp/bar/test.sock",
},
{
name: "allowed directory prefix attack rejected",
path: "/tmpevil/test.sock",
opts: UnixForwardingOptions{AllowedDirectories: []string{"/tmp"}},
wantErr: true,
errSubstr: "not in an allowed directory",
wantType: ErrRejected,
},
// DeniedPrefixes tests.
{
name: "path in denied prefix rejected",
path: "/run/user/1000/systemd/private.sock",
opts: UnixForwardingOptions{AllowedDirectories: []string{"/run/user/1000"}, DeniedPrefixes: []string{"/run/user/1000/systemd"}},
wantErr: true,
errSubstr: "is denied",
wantType: ErrRejected,
},
{
name: "exact denied path rejected",
path: "/var/run/docker.sock",
opts: UnixForwardingOptions{AllowedDirectories: []string{"/var/run"}, DeniedPrefixes: []string{"/var/run/docker.sock"}},
wantErr: true,
errSubstr: "is denied",
wantType: ErrRejected,
},
{
name: "path not matching denied prefix accepted",
path: "/run/user/1000/podman/podman.sock",
opts: UnixForwardingOptions{AllowedDirectories: []string{"/run/user/1000"}, DeniedPrefixes: []string{"/run/user/1000/systemd"}},
wantClean: "/run/user/1000/podman/podman.sock",
},
{
name: "denied prefix does not match partial directory names",
path: "/run/user/1000/systemd-resolved/test.sock",
opts: UnixForwardingOptions{AllowedDirectories: []string{"/run/user/1000"}, DeniedPrefixes: []string{"/run/user/1000/systemd"}},
wantClean: "/run/user/1000/systemd-resolved/test.sock",
},
// AllowAll overrides AllowedDirectories/DeniedPrefixes.
{
name: "AllowAll ignores AllowedDirectories",
path: "/var/run/docker.sock",
opts: UnixForwardingOptions{AllowAll: true, AllowedDirectories: []string{"/tmp"}},
wantClean: "/var/run/docker.sock",
},
{
name: "AllowAll ignores DeniedPrefixes",
path: "/run/user/1000/systemd/private.sock",
opts: UnixForwardingOptions{AllowAll: true, DeniedPrefixes: []string{"/run/user/1000/systemd"}},
wantClean: "/run/user/1000/systemd/private.sock",
},
// Real-world socket paths.
{
name: "podman socket path",
path: "/run/user/1000/podman/podman.sock",
opts: UnixForwardingOptions{AllowedDirectories: []string{"/run/user/1000"}},
wantClean: "/run/user/1000/podman/podman.sock",
},
{
name: "gpg agent socket",
path: "/home/user/.gnupg/S.gpg-agent",
opts: UnixForwardingOptions{AllowedDirectories: []string{"/home/user"}},
wantClean: "/home/user/.gnupg/S.gpg-agent",
},
{
name: "gpg agent socket systemd path",
path: "/run/user/1000/gnupg/S.gpg-agent",
opts: UnixForwardingOptions{AllowedDirectories: []string{"/run/user/1000"}},
wantClean: "/run/user/1000/gnupg/S.gpg-agent",
},
{
name: "vscode remote socket",
path: "/tmp/code-d0fd2e91-ed82-46dd-8394-87ac5cde31c3.sock",
opts: UnixForwardingOptions{AllowedDirectories: []string{"/tmp"}},
wantClean: "/tmp/code-d0fd2e91-ed82-46dd-8394-87ac5cde31c3.sock",
},
{
name: "ssh agent socket",
path: "/tmp/ssh-XXXXXXXXXX/agent.12345",
opts: UnixForwardingOptions{AllowedDirectories: []string{"/tmp"}},
wantClean: "/tmp/ssh-XXXXXXXXXX/agent.12345",
},
{
name: "docker socket denied even when /var/run allowed",
path: "/var/run/docker.sock",
opts: UnixForwardingOptions{AllowedDirectories: []string{"/var/run"}, DeniedPrefixes: []string{"/var/run/docker.sock"}},
wantErr: true,
errSubstr: "is denied",
wantType: ErrRejected,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
cleaned, err := validateSocketPath(tt.path, tt.opts)
if tt.wantErr {
if err == nil {
t.Fatalf("validateSocketPath(%q) = %q, nil; want error containing %q", tt.path, cleaned, tt.errSubstr)
}
if tt.errSubstr != "" && !strings.Contains(err.Error(), tt.errSubstr) {
t.Fatalf("validateSocketPath(%q) error = %q; want substring %q", tt.path, err.Error(), tt.errSubstr)
}
if tt.wantType != nil && !errors.Is(err, tt.wantType) {
t.Fatalf("validateSocketPath(%q) error type = %T; want errors.Is(%v)", tt.path, err, tt.wantType)
}
return
}
if err != nil {
t.Fatalf("validateSocketPath(%q) = error %q; want %q", tt.path, err, tt.wantClean)
}
if cleaned != tt.wantClean {
t.Fatalf("validateSocketPath(%q) = %q; want %q", tt.path, cleaned, tt.wantClean)
}
})
}
}
func TestRejectedMessage(t *testing.T) {
t.Parallel()
tests := []struct {
name string
err error
want string
}{
{
name: "bare ErrRejected gives generic message",
err: ErrRejected,
want: "unix forwarding is disabled",
},
{
name: "rejectionError gives descriptive message",
err: &rejectionError{reason: "socket path must be absolute"},
want: "socket path must be absolute",
},
{
name: "wrapped ErrRejected gives wrapper message",
err: fmt.Errorf("custom reason: %w", ErrRejected),
want: "custom reason: ssh: rejected",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got := rejectedMessage(tt.err)
if got != tt.want {
t.Fatalf("rejectedMessage(%v) = %q; want %q", tt.err, got, tt.want)
}
})
}
}
func TestUserSocketDirectories(t *testing.T) {
t.Parallel()
dirs := UserSocketDirectories("/home/testuser", "1000")
want := []string{"/home/testuser", "/tmp", "/run/user/1000"}
if len(dirs) != len(want) {
t.Fatalf("UserSocketDirectories returned %d dirs; want %d", len(dirs), len(want))
}
for i, d := range dirs {
if d != want[i] {
t.Fatalf("UserSocketDirectories()[%d] = %q; want %q", i, d, want[i])
}
}
}
func TestNewLocalUnixForwardingCallbackValidation(t *testing.T) {
t.Parallel()
tests := []struct {
name string
opts UnixForwardingOptions
path string
wantErr bool
errSubstr string
}{
{
name: "AllowAll accepts any absolute path",
opts: UnixForwardingOptions{AllowAll: true},
path: "/var/run/docker.sock",
},
{
name: "AllowAll rejects relative path",
opts: UnixForwardingOptions{AllowAll: true},
path: "relative.sock",
wantErr: true,
errSubstr: "must be absolute",
},
{
name: "restricted rejects path outside allowed dirs",
opts: UnixForwardingOptions{AllowedDirectories: []string{"/tmp"}},
path: "/var/run/docker.sock",
wantErr: true,
errSubstr: "not in an allowed directory",
},
{
name: "restricted accepts path in allowed dir",
opts: UnixForwardingOptions{AllowedDirectories: []string{"/tmp"}},
path: "/tmp/test.sock",
},
{
name: "PathValidator is called and can reject",
opts: UnixForwardingOptions{
AllowAll: true,
PathValidator: func(_ Context, _ string) error {
return &rejectionError{reason: "custom validator rejected"}
},
},
path: "/tmp/test.sock",
wantErr: true,
errSubstr: "custom validator rejected",
},
{
name: "PathValidator receives cleaned path",
opts: UnixForwardingOptions{
AllowAll: true,
PathValidator: func(_ Context, path string) error {
if path != "/tmp/test.sock" {
return fmt.Errorf("expected /tmp/test.sock, got %s", path)
}
return nil
},
},
path: "/tmp/foo/../test.sock",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
ctx, cancel := newContext(nil)
defer cancel()
cb := NewLocalUnixForwardingCallback(tt.opts)
// The callback tries to dial the socket, which will fail for
// non-existent paths. We only care about the validation errors
// (which wrap ErrRejected), not dial errors.
_, err := cb(ctx, tt.path)
if tt.wantErr {
if err == nil {
t.Fatal("expected error but got nil")
}
if tt.errSubstr != "" && !strings.Contains(err.Error(), tt.errSubstr) {
t.Fatalf("error = %q; want substring %q", err.Error(), tt.errSubstr)
}
if !errors.Is(err, ErrRejected) {
t.Fatalf("expected ErrRejected, got %T: %v", err, err)
}
return
}
// For valid paths, the error should either be nil (socket
// exists) or a dial error (socket doesn't exist), but NOT
// a validation/rejection error.
if err != nil && errors.Is(err, ErrRejected) {
t.Fatalf("unexpected rejection error: %v", err)
}
})
}
}
func TestNewReverseUnixForwardingCallbackValidation(t *testing.T) {
t.Parallel()
tests := []struct {
name string
opts UnixForwardingOptions
path string
wantErr bool
errSubstr string
}{
{
name: "rejects relative path",
opts: UnixForwardingOptions{AllowAll: true},
path: "relative.sock",
wantErr: true,
errSubstr: "must be absolute",
},
{
name: "rejects path outside allowed dirs",
opts: UnixForwardingOptions{AllowedDirectories: []string{"/tmp"}},
path: "/var/run/test.sock",
wantErr: true,
errSubstr: "not in an allowed directory",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
ctx, cancel := newContext(nil)
defer cancel()
cb := NewReverseUnixForwardingCallback(tt.opts)
_, err := cb(ctx, tt.path)
if tt.wantErr {
if err == nil {
t.Fatal("expected error but got nil")
}
if tt.errSubstr != "" && !strings.Contains(err.Error(), tt.errSubstr) {
t.Fatalf("error = %q; want substring %q", err.Error(), tt.errSubstr)
}
if !errors.Is(err, ErrRejected) {
t.Fatalf("expected ErrRejected, got %T: %v", err, err)
}
return
}
if err != nil && errors.Is(err, ErrRejected) {
t.Fatalf("unexpected rejection error: %v", err)
}
})
}
}
func TestNewReverseUnixForwardingCallbackBindUnlink(t *testing.T) {
t.Parallel()
ctx, cancel := newContext(nil)
defer cancel()
dir := tempDirUnixSocket(t)
sockPath := filepath.Join(dir, "test.sock")
// Create an existing socket. Keep the listener open so the socket
// file persists (Go's UnixListener.Close removes the file).
oldLn, err := net.Listen("unix", sockPath)
if err != nil {
t.Fatalf("failed to create socket: %v", err)
}
defer oldLn.Close() //nolint:errcheck
// Without BindUnlink, listening should fail because socket exists.
cbNoUnlink := NewReverseUnixForwardingCallback(UnixForwardingOptions{
AllowAll: true,
})
_, err = cbNoUnlink(ctx, sockPath)
if err == nil {
t.Fatal("expected listen to fail on existing socket without BindUnlink")
}
// With BindUnlink, the old socket is removed and we can listen.
cbUnlink := NewReverseUnixForwardingCallback(UnixForwardingOptions{
AllowAll: true,
BindUnlink: true,
})
newLn, err := cbUnlink(ctx, sockPath)
if err != nil {
t.Fatalf("expected listen to succeed with BindUnlink, got: %v", err)
}
_ = newLn.Close()
}
func TestNewReverseUnixForwardingCallbackBindUnlinkSkipsNonSocket(t *testing.T) {
t.Parallel()
ctx, cancel := newContext(nil)
defer cancel()
dir := tempDirUnixSocket(t)
filePath := filepath.Join(dir, "regular.file")
// Create a regular file at the path.
if err := os.WriteFile(filePath, []byte("data"), 0600); err != nil {
t.Fatalf("failed to create regular file: %v", err)
}
// BindUnlink should NOT remove regular files. Listen should fail.
cb := NewReverseUnixForwardingCallback(UnixForwardingOptions{
AllowAll: true,
BindUnlink: true,
})
_, err := cb(ctx, filePath)
if err == nil {
t.Fatal("expected listen to fail on regular file even with BindUnlink")
}
// Regular file should still exist.
if _, err := os.Stat(filePath); err != nil {
t.Fatalf("regular file should not have been deleted: %v", err)
}
}
func TestNewReverseUnixForwardingCallbackSocketPermissions(t *testing.T) {
t.Parallel()
tests := []struct {
name string
mask *os.FileMode
wantPerm os.FileMode
}{
{name: "default mask 0177 gives mode 0600", mask: nil, wantPerm: 0600},
{name: "custom mask 0117 gives mode 0660", mask: fileMode(0117), wantPerm: 0660},
{name: "zero mask gives mode 0666", mask: fileMode(0), wantPerm: 0666},
}
for i, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
ctx, cancel := newContext(nil)
defer cancel()
// Use a short /tmp path to stay under sun_path limits
// even when the test framework creates long temp paths.
dir, err := os.MkdirTemp("/tmp", "ssh-perm-")
if err != nil {
t.Fatalf("create temp dir: %v", err)
}
t.Cleanup(func() { _ = os.RemoveAll(dir) })
sockPath := filepath.Join(dir, fmt.Sprintf("p%d.s", i))
cb := NewReverseUnixForwardingCallback(UnixForwardingOptions{
AllowAll: true,
BindMask: tt.mask,
})
ln, err := cb(ctx, sockPath)
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
defer ln.Close() //nolint:errcheck
info, err := os.Stat(sockPath)
if err != nil {
t.Fatalf("failed to stat socket: %v", err)
}
perm := info.Mode().Perm()
if perm != tt.wantPerm {
t.Fatalf("socket permissions = %04o; want %04o", perm, tt.wantPerm)
}
})
}
}
func fileMode(m os.FileMode) *os.FileMode { return &m }
func TestReverseUnixForwardingRespectsCallback(t *testing.T) {
t.Parallel()
remoteSocketPath := filepath.Join(tempDirUnixSocket(t), "remote.sock")
var called int64
_, client, cleanup := newTestSession(t, &Server{
Handler: func(s Session) {},
ReverseUnixForwardingCallback: func(ctx Context, socketPath string) (net.Listener, error) {
atomic.AddInt64(&called, 1)
if socketPath != remoteSocketPath {
panic("unexpected socket path: " + socketPath)
}
return nil, ErrRejected
},
}, nil)
defer cleanup()
_, err := client.ListenUnix(remoteSocketPath)
if err == nil {
t.Fatalf("Expected error listening on %q but it succeeded", remoteSocketPath)
}
if atomic.LoadInt64(&called) != 1 {
t.Fatalf("Expected callback to be called once but it was called %d times", called)
}
}