-
Notifications
You must be signed in to change notification settings - Fork 346
/
ssh.go
408 lines (350 loc) · 8.59 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
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
package server
import (
"errors"
"fmt"
"io"
"net"
"os"
"os/exec"
"os/user"
"strings"
"sync"
"time"
"github.com/loft-sh/devpod/pkg/command"
"github.com/loft-sh/devpod/pkg/shell"
"github.com/loft-sh/log"
"github.com/loft-sh/ssh"
perrors "github.com/pkg/errors"
"github.com/pkg/sftp"
"github.com/sirupsen/logrus"
)
var DefaultPort = 8022
func NewServer(addr string, hostKey []byte, keys []ssh.PublicKey, workdir string, log log.Logger) (*Server, error) {
sh, err := shell.GetShell("")
if err != nil {
return nil, err
}
currentUser, err := user.Current()
if err != nil {
return nil, err
}
forwardHandler := &ssh.ForwardedTCPHandler{}
forwardedUnixHandler := &ssh.ForwardedUnixHandler{}
server := &Server{
shell: sh,
workdir: workdir,
log: log,
currentUser: currentUser.Username,
sshServer: ssh.Server{
Addr: addr,
LocalPortForwardingCallback: func(ctx ssh.Context, dhost string, dport uint32) bool {
log.Debugf("Accepted forward: %s:%d", dhost, dport)
return true
},
ReversePortForwardingCallback: func(ctx ssh.Context, host string, port uint32) bool {
log.Debugf("attempt to bind %s:%d - %s", host, port, "granted")
return true
},
ReverseUnixForwardingCallback: func(ctx ssh.Context, socketPath string) bool {
log.Debugf("attempt to bind socket %s", socketPath)
_, err := os.Stat(socketPath)
if err == nil {
log.Debugf("%s already exists, removing", socketPath)
_ = os.Remove(socketPath)
}
return true
},
ChannelHandlers: map[string]ssh.ChannelHandler{
"direct-tcpip": ssh.DirectTCPIPHandler,
"[email protected]": ssh.DirectStreamLocalHandler,
"session": ssh.DefaultSessionHandler,
},
RequestHandlers: map[string]ssh.RequestHandler{
"tcpip-forward": forwardHandler.HandleSSHRequest,
"[email protected]": forwardedUnixHandler.HandleSSHRequest,
"[email protected]": forwardedUnixHandler.HandleSSHRequest,
"cancel-tcpip-forward": forwardHandler.HandleSSHRequest,
},
SubsystemHandlers: map[string]ssh.SubsystemHandler{
"sftp": func(s ssh.Session) {
SftpHandler(s, currentUser.Username, log)
},
},
},
}
if len(keys) > 0 {
server.sshServer.PublicKeyHandler = func(ctx ssh.Context, key ssh.PublicKey) bool {
for _, k := range keys {
if ssh.KeysEqual(k, key) {
return true
}
}
log.Debugf("Declined public key")
return false
}
}
if len(hostKey) > 0 {
err = server.sshServer.SetOption(ssh.HostKeyPEM(hostKey))
if err != nil {
return nil, err
}
}
server.sshServer.Handler = server.handler
return server, nil
}
type Server struct {
currentUser string
shell []string
workdir string
sshServer ssh.Server
log log.Logger
}
func (s *Server) handler(sess ssh.Session) {
ptyReq, winCh, isPty := sess.Pty()
cmd := s.getCommand(sess, isPty)
if ssh.AgentRequested(sess) {
// on some systems (like containers) /tmp may not exists, this ensures
// that we have a compliant directory structure
err := os.MkdirAll("/tmp", 0o777)
if err != nil {
s.exitWithError(sess, perrors.Wrap(err, "creating /tmp dir"))
return
}
l, err := ssh.NewAgentListener()
if err != nil {
s.exitWithError(sess, perrors.Wrap(err, "start agent"))
return
}
defer l.Close()
go ssh.ForwardAgentConnections(l, sess)
cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", "SSH_AUTH_SOCK", l.Addr().String()))
}
// start shell session
var err error
if isPty {
s.log.Debugf("Execute SSH server PTY command: %s", strings.Join(cmd.Args, " "))
err = s.HandlePTY(sess, ptyReq, winCh, cmd, nil)
} else {
s.log.Debugf("Execute SSH server command: %s", strings.Join(cmd.Args, " "))
err = s.HandleNonPTY(sess, cmd)
}
// exit session
s.exitWithError(sess, err)
}
func (s *Server) HandleNonPTY(sess ssh.Session, cmd *exec.Cmd) (err error) {
// init pipes
stdin, err := cmd.StdinPipe()
if err != nil {
return err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
// start the command
err = cmd.Start()
if err != nil {
return perrors.Wrap(err, "start command")
}
go func() {
defer stdin.Close()
_, err := io.Copy(stdin, sess)
if err != nil {
s.log.Debugf("Error piping stdin: %v", err)
}
}()
waitGroup := sync.WaitGroup{}
waitGroup.Add(1)
go func() {
defer waitGroup.Done()
_, err := io.Copy(sess, stdout)
if err != nil {
s.log.Debugf("Error piping stdout: %v", err)
}
}()
waitGroup.Add(1)
go func() {
defer waitGroup.Done()
_, err := io.Copy(sess.Stderr(), stderr)
if err != nil {
s.log.Debugf("Error piping stderr: %v", err)
}
}()
// order is important here!
err = cmd.Wait()
waitGroup.Wait()
if err != nil {
return err
}
return nil
}
func (s *Server) HandlePTY(
sess ssh.Session,
ptyReq ssh.Pty,
winCh <-chan ssh.Window,
cmd *exec.Cmd,
decorateReader func(reader io.Reader) io.Reader,
) (err error) {
cmd.Env = append(cmd.Env, fmt.Sprintf("TERM=%s", ptyReq.Term))
f, err := startPTY(cmd)
if err != nil {
return perrors.Wrap(err, "start pty")
}
defer f.Close()
go func() {
for win := range winCh {
setWinSize(f, win.Width, win.Height)
}
}()
go func() {
defer f.Close()
// copy stdin
_, _ = io.Copy(f, sess)
}()
stdoutDoneChan := make(chan struct{})
go func() {
defer f.Close()
defer close(stdoutDoneChan)
var reader io.Reader = f
if decorateReader != nil {
reader = decorateReader(f)
}
// copy stdout
_, _ = io.Copy(sess, reader)
}()
err = cmd.Wait()
if err != nil {
return err
}
select {
case <-stdoutDoneChan:
case <-time.After(time.Second):
}
return nil
}
func (s *Server) getCommand(sess ssh.Session, isPty bool) *exec.Cmd {
var cmd *exec.Cmd
user := sess.User()
if user == s.currentUser {
user = ""
}
// has user set?
if user != "" {
args := []string{}
// is pty?
if isPty {
args = append(args, "-")
}
// add user
args = append(args, sess.User())
// is there a command?
if len(sess.RawCommand()) > 0 {
args = append(args, "-c", sess.RawCommand())
}
cmd = exec.Command("su", args...)
} else {
args := []string{}
args = append(args, s.shell[1:]...)
if isPty {
args = append(args, "-l")
}
if len(sess.RawCommand()) == 0 {
cmd = exec.Command(s.shell[0], args...)
} else {
args = append(args, "-c", sess.RawCommand())
cmd = exec.Command(s.shell[0], args...)
}
}
var workdir string
// check if requested workdir exists
if s.workdir != "" {
if _, err := os.Stat(s.workdir); err == nil {
workdir = s.workdir
}
}
// fall back to home directory
if workdir == "" {
home, _ := command.GetHome(user)
if _, err := os.Stat(home); err == nil {
workdir = home
}
}
// switch default directory
if workdir != "" {
cmd.Dir = workdir
}
cmd.Env = append(cmd.Env, os.Environ()...)
cmd.Env = append(cmd.Env, sess.Environ()...)
return cmd
}
func (s *Server) exitWithError(sess ssh.Session, err error) {
if err != nil {
var exitError *exec.ExitError
if !errors.As(perrors.Cause(err), &exitError) {
s.log.Errorf("Exit error: %v", err)
msg := strings.TrimPrefix(err.Error(), "exec: ")
if _, err := sess.Stderr().Write([]byte(msg)); err != nil {
s.log.Errorf("failed to write error to session: %v", err)
}
}
}
// always exit session
err = sess.Exit(ExitCode(err))
if err != nil {
s.log.Errorf("session failed to exit: %v", err)
}
}
func SftpHandler(sess ssh.Session, currentUser string, log log.Logger) {
writer := log.Writer(logrus.DebugLevel, false)
defer writer.Close()
user := sess.User()
if user == currentUser {
user = ""
}
workingDir, _ := command.GetHome(user)
serverOptions := []sftp.ServerOption{
sftp.WithDebug(writer),
sftp.WithServerWorkingDirectory(workingDir),
}
server, err := sftp.NewServer(
sess,
serverOptions...,
)
if err != nil {
log.Debugf("sftp server init error: %s\n", err)
return
}
defer server.Close()
// serve
err = server.Serve()
if errors.Is(err, io.EOF) {
_ = sess.Exit(0)
return
}
if err != nil {
log.Debugf("sftp server completed with error: %v", err)
}
_ = sess.Exit(1)
}
func ExitCode(err error) int {
err = perrors.Cause(err)
if err == nil {
return 0
}
var exitErr *exec.ExitError
if !errors.As(err, &exitErr) {
return 1
}
return exitErr.ExitCode()
}
func (s *Server) Serve(listener net.Listener) error {
return s.sshServer.Serve(listener)
}
func (s *Server) ListenAndServe() error {
s.log.Debugf("Start ssh server on %s", s.sshServer.Addr)
return s.sshServer.ListenAndServe()
}