-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.go
193 lines (159 loc) · 4.42 KB
/
server.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
package server
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"errors"
"fmt"
"os"
"os/exec"
"os/user"
"regexp"
"runtime"
"strconv"
"strings"
"github.com/gliderlabs/ssh"
"go.uber.org/zap"
gossh "golang.org/x/crypto/ssh"
)
type options struct {
username string
}
// Option represents a configuration option for the ssh server.
type Option func(*options)
// WithUsername is the option to override the ssh username.
func WithUsername(username string) Option { return func(o *options) { o.username = username } }
// NewServer returns a new ssh server.
func NewServer(logger *zap.Logger, ca string, opts ...Option) (*ssh.Server, error) {
o := &options{}
for _, opt := range opts {
opt(o)
}
handler := ssh.Handler(func(s ssh.Session) {
username := s.User()
if o.username != "" {
username = o.username
}
user, err := user.Lookup(username)
if err != nil {
logger.Sugar().Errorf("could not find user \"%s\": %v", username, err)
return
}
shell, err := GetShell(user)
if err != nil {
logger.Sugar().Errorf("could not get user shell: %s", err)
return
}
var cmd exec.Cmd
cmd.Path = shell
cmd.Args = []string{shell}
pubKey := s.PublicKey()
cert, ok := pubKey.(*gossh.Certificate)
if !ok {
logger.Sugar().Errorf("could not get user certificate")
return
}
logger.Sugar().Infof("new ssh session for %s (as user %s)", cert.KeyId, username)
uid, _ := strconv.ParseUint(user.Uid, 10, 32)
gid, _ := strconv.ParseUint(user.Gid, 10, 32)
cmd.Env = []string{
"LANG=en_US.UTF-8",
"HOME=" + user.HomeDir,
"USER=" + user.Username,
"SHELL=" + shell,
}
cmd.Dir = user.HomeDir
execCmd(s, cmd, uid, gid, username)
})
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, fmt.Errorf("could not generate rsa key: %s", err)
}
signer, err := gossh.NewSignerFromKey(key)
if err != nil {
return nil, fmt.Errorf("could not generate signer: %s", err)
}
return &ssh.Server{
Version: "Border0-ssh-server",
HostSigners: []ssh.Signer{signer},
Handler: handler,
PublicKeyHandler: func(ctx ssh.Context, key ssh.PublicKey) bool {
pubCert, _, _, _, err := ssh.ParseAuthorizedKey([]byte(ca))
if err != nil {
logger.Error("error parsing public key", zap.Error(err))
return false
}
cert, ok := key.(*gossh.Certificate)
if !ok {
return false
}
if !bytes.Equal(cert.SignatureKey.Marshal(), pubCert.Marshal()) {
return false
}
var certChecker gossh.CertChecker
err = certChecker.CheckCert("mysocket_ssh_signed", cert)
if err != nil {
logger.Error("error validating certificate", zap.Error(err))
return false
}
return true
},
SubsystemHandlers: map[string]ssh.SubsystemHandler{
"sftp": func(s ssh.Session) {
pubKey := s.PublicKey()
cert, ok := pubKey.(*gossh.Certificate)
if !ok {
logger.Sugar().Errorf("could not get user certificate")
return
}
logger.Sugar().Infof("new sftp session for %s (as user %s)", cert.KeyId, s.User())
username := s.User()
if o.username != "" {
username = o.username
}
if err := StartChildProcess(s.Context(), s, "sftp", username); err != nil {
logger.Error("error starting sftp child process", zap.Error(err))
}
},
},
}, nil
}
func GetShell(user *user.User) (string, error) {
switch runtime.GOOS {
case "linux", "openbsd", "freebsd":
if _, err := exec.LookPath("getent"); err != nil {
return "/bin/sh", nil
}
out, err := exec.Command("getent", "passwd", user.Uid).Output()
if err != nil {
return "", err
}
ent := strings.Split(strings.TrimSuffix(string(out), "\n"), ":")
return ent[6], nil
case "darwin":
dir := "Local/Default/Users/" + user.Username
out, err := exec.Command("dscl", "localhost", "-read", dir, "UserShell").Output()
if err != nil {
return "", err
}
re := regexp.MustCompile("UserShell: (/[^ ]+)\n")
matched := re.FindStringSubmatch(string(out))
shell := matched[1]
if shell == "" {
return "", fmt.Errorf("invalid output: %s", string(out))
}
return shell, nil
case "windows":
consoleApp := os.Getenv("COMSPEC")
if consoleApp == "" {
consoleApp = "cmd.exe"
}
return consoleApp, nil
}
return "", errors.New("unsupported platform")
}
func execCmd(s ssh.Session, cmd exec.Cmd, uid, gid uint64, username string) {
pty, winCh, isPty := s.Pty()
exitCode := ExecCmd(s.Context(), s, s.RawCommand(), pty.Term, isPty, winCh, cmd, uid, gid, username)
s.Exit(exitCode)
}