-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssh.go
421 lines (358 loc) · 9.43 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
409
410
411
412
413
414
415
416
417
418
419
420
421
package bunker
import (
"context"
"encoding/hex"
"errors"
"fmt"
"io"
"net"
"strings"
"sync"
"time"
"github.com/git-lfs/wildmatch"
"github.com/yankeguo/bunker/model"
"github.com/yankeguo/bunker/model/dao"
"github.com/yankeguo/ufx"
"go.uber.org/fx"
"go.uber.org/zap"
"golang.org/x/crypto/ssh"
"gorm.io/gorm"
)
const (
sshExtKeyUserID = "bunker.user_id"
sshExtKeyServerID = "bunker.server_id"
sshExtKeyServerUser = "bunker.server_user"
sshExtKeyServerAddress = "bunker.server_address"
)
type SSHServer struct {
dataDir string
listen string
db *gorm.DB
signers *Signers
loggers *zap.SugaredLogger
listener *net.TCPListener
}
type sshServerParams struct {
Listen string `json:"listen" default:":8022" validate:"required"`
}
type SSHServerOptions struct {
fx.In
Lifecycle fx.Lifecycle
Conf ufx.Conf
DataDir DataDir
DB *gorm.DB
Signers *Signers
Logger *zap.SugaredLogger
}
func CreateSSHServer(opts SSHServerOptions) (s *SSHServer, err error) {
var p sshServerParams
if err = opts.Conf.Bind(&p, "ssh_server"); err != nil {
return
}
s = &SSHServer{
dataDir: opts.DataDir.String(),
listen: p.Listen,
signers: opts.Signers,
loggers: opts.Logger,
db: opts.DB,
}
if opts.Lifecycle != nil {
opts.Lifecycle.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
chErr := make(chan error, 1)
go func() {
chErr <- s.ListenAndServe()
}()
select {
case err := <-chErr:
return err
case <-ctx.Done():
return s.Shutdown(ctx)
case <-time.After(time.Second * 3):
return nil
}
},
OnStop: func(ctx context.Context) error {
time.Sleep(time.Second * 3)
return s.Shutdown(ctx)
},
})
}
return
}
func (s *SSHServer) AuthLogCallback(conn ssh.ConnMetadata, method string, err error) {
s.loggers.With(
"remote_addr", conn.RemoteAddr().String(),
"method", method,
"error", err,
).Info("ssh auth")
}
func (s *SSHServer) PublicKeyCallback(conn ssh.ConnMetadata, _key ssh.PublicKey) (perm *ssh.Permissions, err error) {
db := dao.Use(s.db)
// find key and user
var key *model.Key
if key, err = db.Key.Where(db.Key.ID.Eq(
ssh.FingerprintSHA256(_key),
)).Preload(db.Key.User).First(); err != nil {
return nil, err
}
if key.User.ID == "" {
err = errors.New("key is not associated with any user")
return
}
if key.User.IsBlocked {
err = errors.New("user is blocked")
return
}
// find server
splits := strings.Split(conn.User(), "@")
if len(splits) != 2 {
err = errors.New("invalid user format, should be server_user@server_id")
return
}
var (
serverUser = splits[0]
serverID = splits[1]
)
var server *model.Server
if server, err = db.Server.Where(db.Server.ID.Eq(serverID)).First(); err != nil {
return
}
// find grants
var grants = []*model.Grant{}
if grants, err = db.Grant.Where(db.Grant.UserID.Eq(key.User.ID)).Find(); err != nil {
return
}
var granted bool
// check if user is granted
for _, grant := range grants {
var (
mServerUser = wildmatch.NewWildmatch(grant.ServerUser, wildmatch.Basename, wildmatch.CaseFold)
mServerID = wildmatch.NewWildmatch(grant.ServerID, wildmatch.Basename, wildmatch.CaseFold)
)
if mServerUser.Match(serverUser) && mServerID.Match(serverID) {
granted = true
break
}
}
if !granted {
err = errors.New("no grant found")
return
}
perm = &ssh.Permissions{
Extensions: map[string]string{
sshExtKeyUserID: key.User.ID,
sshExtKeyServerID: server.ID,
sshExtKeyServerAddress: server.Address,
sshExtKeyServerUser: serverUser,
},
}
return
}
func (s *SSHServer) BannerCallback(conn ssh.ConnMetadata) string {
return fmt.Sprintf(
"bunker: welcome user %s from %s, session: %s\n",
conn.User(),
conn.RemoteAddr().String(),
hex.EncodeToString(conn.SessionID()),
)
}
func (s *SSHServer) createServerConfig() *ssh.ServerConfig {
cfg := &ssh.ServerConfig{
AuthLogCallback: s.AuthLogCallback,
PublicKeyCallback: s.PublicKeyCallback,
BannerCallback: s.BannerCallback,
}
for _, sgn := range s.signers.Host {
cfg.AddHostKey(sgn)
}
return cfg
}
func (s *SSHServer) HandleServerConn(conn net.Conn) {
defer conn.Close()
var err error
var (
userConn *ssh.ServerConn
chUserNewChannel <-chan ssh.NewChannel
chUserRequest <-chan *ssh.Request
)
if userConn, chUserNewChannel, chUserRequest, err = ssh.NewServerConn(conn, s.createServerConfig()); err != nil {
return
}
defer userConn.Close()
var (
serverUser = userConn.Permissions.Extensions[sshExtKeyServerUser]
serverAddress = userConn.Permissions.Extensions[sshExtKeyServerAddress]
)
if _, port, _ := net.SplitHostPort(serverAddress); port == "" {
serverAddress = net.JoinHostPort(serverAddress, "22")
}
log := s.loggers.With(
"remote_addr", conn.RemoteAddr().String(),
"server_user", serverUser,
"server_address", serverAddress,
"server_id", userConn.Permissions.Extensions[sshExtKeyServerID],
"session_id", hex.EncodeToString(userConn.SessionID()),
)
var client *ssh.Client
if client, err = ssh.Dial("tcp", serverAddress, &ssh.ClientConfig{
User: serverUser,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(s.signers.Client...),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}); err != nil {
log.With("error", err).Error("ssh dial")
go func() {
for nc := range chUserNewChannel {
//discard all new channels
nc.Reject(ssh.ConnectionFailed, err.Error())
}
}()
go func() {
for req := range chUserRequest {
//discard all requests
if req.WantReply {
req.Reply(false, nil)
}
}
}()
return
}
defer client.Close()
log.Info("ssh connection established")
PipeSSH(log, client, userConn, chUserNewChannel, chUserRequest)
}
func (s *SSHServer) ListenAndServe() (err error) {
if s.listener != nil {
err = errors.New("listener is already initialized")
return
}
var addr *net.TCPAddr
if addr, err = net.ResolveTCPAddr("tcp", s.listen); err != nil {
return
}
if s.listener, err = net.ListenTCP("tcp", addr); err != nil {
return
}
defer s.listener.Close()
for {
var conn net.Conn
if conn, err = s.listener.Accept(); err != nil {
return
}
go s.HandleServerConn(conn)
}
}
func (s *SSHServer) Shutdown(ctx context.Context) (err error) {
l := s.listener
if l == nil {
return
}
err = l.Close()
return
}
func PipeSSH(log *zap.SugaredLogger, target *ssh.Client, userConn *ssh.ServerConn, chUserNewChannel <-chan ssh.NewChannel, chUserRequest <-chan *ssh.Request) {
// handle user request for new channel
handleUserNewChannel := func(wg *sync.WaitGroup, userNewChannel ssh.NewChannel) {
defer wg.Done()
log := log.With("channel_type", userNewChannel.ChannelType())
// create target channel and target request channel
targetChannel, chTargetRequest, err1 := target.OpenChannel(userNewChannel.ChannelType(), userNewChannel.ExtraData())
if err1 != nil {
log.With("error", err1).Error("ssh open target channel")
if errOpenFailed, ok := err1.(*ssh.OpenChannelError); ok {
userNewChannel.Reject(errOpenFailed.Reason, errOpenFailed.Message)
} else {
userNewChannel.Reject(ssh.ConnectionFailed, err1.Error())
}
return
}
defer log.Info("channel end")
defer targetChannel.Close()
userChannel, chUserRequest, err1 := userNewChannel.Accept()
if err1 != nil {
log.With("error", err1).Error("ssh accept user channel")
return
}
wg1 := &sync.WaitGroup{}
wg1.Add(1)
go func() {
defer wg1.Done()
defer log.Info("channel pipe end: from target")
defer userChannel.Close()
io.Copy(userChannel, targetChannel)
}()
wg1.Add(1)
go func() {
defer wg1.Done()
defer log.Info("channel pipe end: from user")
defer targetChannel.Close()
io.Copy(targetChannel, userChannel)
}()
wg1.Add(1)
go func() {
defer wg1.Done()
defer log.Info("channel request end: from target")
for targetRequest := range chTargetRequest {
ok, err2 := userChannel.SendRequest(targetRequest.Type, targetRequest.WantReply, targetRequest.Payload)
if targetRequest.WantReply {
targetRequest.Reply(ok, nil)
}
if err2 != nil {
log.With("error", err2).Error("ssh send target request")
}
}
}()
wg1.Add(1)
go func() {
defer wg1.Done()
defer log.Info("channel request end: from user")
for userRequest := range chUserRequest {
ok, err2 := targetChannel.SendRequest(userRequest.Type, userRequest.WantReply, userRequest.Payload)
if userRequest.WantReply {
userRequest.Reply(ok, nil)
}
if err2 != nil {
log.With("error", err2).Error("ssh send user request")
}
}
}()
wg1.Wait()
}
handleUserRequest := func(wg *sync.WaitGroup, userRequest *ssh.Request) {
defer wg.Done()
log.With("request_type", userRequest.Type).Info("user global request")
ok, buf, err1 := target.SendRequest(userRequest.Type, userRequest.WantReply, userRequest.Payload)
if userRequest.WantReply {
userRequest.Reply(ok, buf)
}
if err1 != nil {
log.With("error", err1).Error("ssh send global user request")
}
}
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
defer log.Info("user new chan end")
wg1 := &sync.WaitGroup{}
for userNewChannel := range chUserNewChannel {
wg1.Add(1)
go handleUserNewChannel(wg1, userNewChannel)
}
wg1.Wait()
}()
wg.Add(1)
go func() {
defer wg.Done()
defer log.Info("user request end")
wg1 := &sync.WaitGroup{}
for userRequest := range chUserRequest {
wg1.Add(1)
go handleUserRequest(wg1, userRequest)
}
wg1.Wait()
}()
wg.Wait()
}