-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.go
75 lines (62 loc) · 1.73 KB
/
auth.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
package telshell
import (
"context"
"fmt"
"io"
"os"
"regexp"
"github.com/pkg/errors"
"go.uber.org/zap"
)
const MaxLoginChars = 32
var nameRegex = regexp.MustCompile(`(?m)^[A-Za-z0-9\.\-\_]+$`)
// AuthShellHandler is shell handler that requires username and password
type AuthShellHandler struct {
IOParams
shellPath string
shellArgs []string
log *zap.SugaredLogger
}
// NewAuthShellHandler creates new authorized shell handler
func NewAuthShellHandler(params IOParams, shell string, args ...string) AuthShellHandler {
return AuthShellHandler{
IOParams: params,
shellPath: shell,
shellArgs: args,
log: zap.S().Named("auth_shell"),
}
}
// Handle implements telshell.Handler
func (h AuthShellHandler) Handle(ctx context.Context, rw io.ReadWriter) error {
fmt.Fprint(rw, "Username:")
// Read output and match string
buff := make([]byte, MaxLoginChars*4)
_, _ = rw.Read(buff)
// Sanitize input
buff = TrimCLRF(buff)
if len(buff) == 0 || !nameRegex.Match(buff) {
// Ignore empty prompt response or invalid username format
fmt.Fprintln(rw, "Access denied")
return nil
}
username := string(buff)
return h.startUserShell(ctx, username, rw)
}
func (h AuthShellHandler) startUserShell(ctx context.Context, user string, rw io.ReadWriter) error {
wrapCtx, cancelFn := context.WithCancel(ctx)
wrapper := NewTerminalWrapper(h.log, rw, h.IOParams)
cmd := runShellAs(ctx, user, h.shellPath, h.shellArgs...)
cmd.Env = os.Environ()
if err := wrapper.Listen(wrapCtx, cmd); err != nil {
return err
}
h.log.Debugw("login shell start",
"command", cmd.Path,
"args", cmd.Args,
)
if err := cmd.Start(); err != nil {
return errors.Wrap(err, "failed to start shell instance")
}
defer cancelFn()
return cmd.Wait()
}