-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathssh.go
117 lines (92 loc) · 2.22 KB
/
ssh.go
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
package sshforward
import (
"context"
"net"
"os"
"path/filepath"
"github.com/moby/buildkit/session"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
"google.golang.org/grpc/metadata"
)
// DefaultID is the default ssh ID
const DefaultID = "default"
const KeySSHID = "buildkit.ssh.id"
type server struct {
caller session.Caller
}
func (s *server) run(ctx context.Context, l net.Listener, id string) error {
eg, ctx := errgroup.WithContext(ctx)
eg.Go(func() error {
<-ctx.Done()
return ctx.Err()
})
eg.Go(func() error {
for {
conn, err := l.Accept()
if err != nil {
return err
}
client := NewSSHClient(s.caller.Conn())
opts := make(map[string][]string)
opts[KeySSHID] = []string{id}
ctx = metadata.NewOutgoingContext(ctx, opts)
stream, err := client.ForwardAgent(ctx)
if err != nil {
conn.Close()
return err
}
go Copy(ctx, conn, stream, stream.CloseSend)
}
})
return eg.Wait()
}
type SocketOpt struct {
ID string
UID int
GID int
Mode int
}
func MountSSHSocket(ctx context.Context, c session.Caller, opt SocketOpt) (sockPath string, closer func() error, err error) {
dir, err := os.MkdirTemp("", ".buildkit-ssh-sock")
if err != nil {
return "", nil, errors.WithStack(err)
}
defer func() {
if err != nil {
os.RemoveAll(dir)
}
}()
if err := os.Chmod(dir, 0711); err != nil {
return "", nil, errors.WithStack(err)
}
sockPath = filepath.Join(dir, "ssh_auth_sock")
l, err := net.Listen("unix", sockPath)
if err != nil {
return "", nil, errors.WithStack(err)
}
if err := os.Chown(sockPath, opt.UID, opt.GID); err != nil {
l.Close()
return "", nil, errors.WithStack(err)
}
if err := os.Chmod(sockPath, os.FileMode(opt.Mode)); err != nil {
l.Close()
return "", nil, errors.WithStack(err)
}
s := &server{caller: c}
id := opt.ID
if id == "" {
id = DefaultID
}
go s.run(ctx, l, id) // erroring per connection allowed
return sockPath, func() error {
err := l.Close()
os.RemoveAll(sockPath)
return errors.WithStack(err)
}, nil
}
func CheckSSHID(ctx context.Context, c session.Caller, id string) error {
client := NewSSHClient(c.Conn())
_, err := client.CheckAgent(ctx, &CheckAgentRequest{ID: id})
return errors.WithStack(err)
}