forked from yankeguo-deprecated/bastion-ae6ab0f8
/
bridge.go
273 lines (266 loc) · 8.36 KB
/
bridge.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
package sshd
import (
"context"
"fmt"
"github.com/kballard/go-shellquote"
"github.com/guoyk93/bastion/sshd/recorder"
"github.com/guoyk93/bastion/sshd/sandbox"
"github.com/guoyk93/bastion/types"
"github.com/guoyk93/bastion/utils"
"golang.org/x/crypto/ssh"
"io"
"net"
"sync"
)
func handleLv1RawIPDirectTCPIPChannel(conn *ssh.ServerConn, sc ssh.Channel, address string, port int) (err error) {
ILog(conn).Str("channel", ChannelTypeDirectTCPIP).Msg("channel opened")
defer ILog(conn).Str("channel", ChannelTypeDirectTCPIP).Err(err).Msg("channel finished")
// remember to close channel
defer sc.Close()
// dial direct ip
var c net.Conn
if c, err = net.Dial("tcp", fmt.Sprintf("%s:%d", address, port)); err != nil {
ELog(conn).Str("channel", ChannelTypeDirectTCPIP).Err(err).Msg("failed to dial direct IP ssh tunnel connection")
return
}
defer c.Close()
// bi-copy streams
if err = utils.DualCopy(c, sc); err != nil {
ELog(conn).Str("channel", ChannelTypeDirectTCPIP).Err(err).Msg("failed to pipe bridge connection")
return
}
return
}
func handleLv1DirectTCPIPChannel(conn *ssh.ServerConn, sc ssh.Channel, tp *TunnelPool, address string, port int) (err error) {
ILog(conn).Str("channel", ChannelTypeDirectTCPIP).Msg("channel opened")
defer ILog(conn).Str("channel", ChannelTypeDirectTCPIP).Err(err).Msg("channel finished")
// remember to close channel
defer sc.Close()
// dial remote address
var c net.Conn
if c, err = tp.Dial(address, port); err != nil {
ELog(conn).Str("channel", ChannelTypeDirectTCPIP).Err(err).Msg("failed to dial ssh tunnel connection")
return
}
defer c.Close()
// bi-copy streams
if err = utils.DualCopy(c, sc); err != nil {
ELog(conn).Str("channel", ChannelTypeDirectTCPIP).Err(err).Msg("failed to pipe bridge connection")
return
}
return
}
func handleLv1SessionChannel(conn *ssh.ServerConn, sc ssh.Channel, srchan <-chan *ssh.Request, sb sandbox.Sandbox, account string, ss types.SessionServiceClient, rs types.ReplayServiceClient) (err error) {
ILog(conn).Str("channel", ChannelTypeSession).Msg("channel opened")
defer ILog(conn).Str("channel", ChannelTypeSession).Err(err).Msg("channel finished")
// remember to close channel
defer sc.Close()
// variables
cmd, cmdReady, cmdMissing, cmdCond := "", false, false, sync.NewCond(&sync.Mutex{})
env := make([]string, 0)
pty, ptyCols, ptyRows, term, wch := false, uint32(0), uint32(0), "", make(chan sandbox.Window, 4)
// remember to close wch/rwch
defer close(wch)
// range all requests
go func() {
for req := range srchan {
DLog(conn).Str("channel", ChannelTypeSession).Str("request", req.Type).Msg("request received from user")
switch req.Type {
case RequestTypePtyReq:
var pl PtyRequestPayload
if err = ssh.Unmarshal(req.Payload, &pl); err != nil {
ELog(conn).Str("channel", ChannelTypeSession).Str("request", req.Type).Err(err).Msg("failed to decode payload")
continue
}
pty, ptyCols, ptyRows, term = true, pl.Cols, pl.Rows, pl.Term
wch <- sandbox.Window{
Width: uint(pl.Cols),
Height: uint(pl.Rows),
}
if req.WantReply {
req.Reply(true, nil)
}
case RequestTypeEnv:
var pl EnvRequestPayload
if err = ssh.Unmarshal(req.Payload, &pl); err != nil {
ELog(conn).Str("channel", ChannelTypeSession).Str("request", req.Type).Err(err).Msg("failed to decode payload")
continue
}
env = append(env, fmt.Sprintf("%s=%s", pl.Name, pl.Value))
if req.WantReply {
req.Reply(true, nil)
}
case RequestTypeWindowChange:
var pl WindowChangeRequestPayload
if err = ssh.Unmarshal(req.Payload, &pl); err != nil {
ELog(conn).Str("channel", ChannelTypeSession).Str("request", req.Type).Err(err).Msg("failed to decode payload")
continue
}
wch <- sandbox.Window{
Width: uint(pl.Cols),
Height: uint(pl.Rows),
}
if req.WantReply {
req.Reply(true, nil)
}
case RequestTypeExec, RequestTypeShell:
// decode exec command
if req.Type == RequestTypeExec {
var pl ExecRequestPayload
if err = ssh.Unmarshal(req.Payload, &pl); err != nil {
ELog(conn).Str("channel", ChannelTypeSession).Str("request", req.Type).Err(err).Msg("failed to decode payload")
continue
}
cmd = pl.Command
}
if req.WantReply {
req.Reply(true, nil)
}
// signal cmdCond
cmdReady = true
cmdCond.Signal()
default:
if req.WantReply {
req.Reply(false, nil)
}
}
}
// if cmdReady not set, then cmd is missing, ensure cmdCond is always signaled
if !cmdReady {
cmdMissing = true
cmdCond.Signal()
}
}()
// wait for cmdCond
cmdCond.L.Lock()
for !cmdReady && !cmdMissing {
cmdCond.Wait()
}
cmdCond.L.Unlock()
// check if cmd is missing
if cmdMissing {
ELog(conn).Msg("command is missing")
return
}
// split the command
var cmds []string
if cmds, err = shellquote.Split(cmd); err != nil {
ELog(conn).Err(err).Str("command", cmd).Msg("failed to split command")
return
}
// determine should be recorded
isRecorded := shouldCommandBeRecorded(cmds)
// start session
var sRes *types.CreateSessionResponse
if sRes, err = ss.CreateSession(context.Background(), &types.CreateSessionRequest{
Account: account,
Command: cmd,
IsRecorded: isRecorded,
}); err != nil {
ELog(conn).Err(err).Msg("failed to create session")
return
}
ILog(conn).Int64("sessionId", sRes.Session.Id).Msg("session allocated")
// build the exec options
opts := sandbox.ExecAttachOptions{
Env: env,
Command: cmds,
Stdin: sc,
Stdout: sc,
Stderr: sc.Stderr(),
}
if pty {
opts.IsPty = true
opts.Term = term
opts.WindowChan = wch
}
// wrap options if isRecorded
if isRecorded {
ILog(conn).Int64("sessionId", sRes.Session.Id).Msg("session is recorded")
r := recorder.StartRecording(&opts, sRes.Session.Id, rs)
defer r.Close()
}
// execute and returns exit status
es := ExitStatusRequestPayload{}
if err = sb.ExecAttach(opts); err != nil {
ELog(conn).Err(err).Msg("exec attach returns error")
es.Code = 1
}
// finish session
ss.FinishSession(context.Background(), &types.FinishSessionRequest{Id: sRes.Session.Id})
ILog(conn).Int64("sessionId", sRes.Session.Id).Msg("session finished")
// send exit-status
sc.SendRequest(RequestTypeExitStatus, false, ssh.Marshal(&es))
return
}
func handleLv2SessionChannel(conn *ssh.ServerConn, sc ssh.Channel, srchan <-chan *ssh.Request, tc ssh.Channel, trchan <-chan *ssh.Request, user string) (err error) {
ILog(conn).Str("channel", ChannelTypeSession).Msg("channel opened")
defer ILog(conn).Str("channel", ChannelTypeSession).Err(err).Msg("channel finished")
// remember to close channels
defer sc.Close()
defer tc.Close()
// stream stdin, stdout, stderr, srchan <-> trchan
wr := &sync.WaitGroup{}
wr.Add(3)
// srchan -> trchan
go func() {
for req := range srchan {
DLog(conn).Str("channel", ChannelTypeSession).Str("request", req.Type).Msg("request received from user")
// modify request with sudo
switch req.Type {
case RequestTypeExec:
var pl ExecRequestPayload
if err = ssh.Unmarshal(req.Payload, &pl); err != nil {
ELog(conn).Str("channel", ChannelTypeSession).Str("request", req.Type).Err(err).Msg("failed to decode payload")
continue
}
// switch user
pl.Command = commandSwitchUser(user, pl.Command)
// change payload
req.Payload = ssh.Marshal(&pl)
case RequestTypeShell:
pl := ExecRequestPayload{
Command: commandSwitchUser(user, ""),
}
// change request type to "exec" and update payload
req.Type = RequestTypeExec
req.Payload = ssh.Marshal(&pl)
}
// ban "x11-req", "subsystem" requests
switch req.Type {
case RequestTypeX11Req, RequestTypeSubsystem:
{
if req.WantReply {
req.Reply(false, nil)
}
}
default:
ok, _ := tc.SendRequest(req.Type, req.WantReply, req.Payload)
if req.WantReply {
req.Reply(ok, nil)
}
}
}
// not track srchan
}()
// trchan -> srchan
go func() {
// transparent bridge requests
for req := range trchan {
DLog(conn).Str("channel", ChannelTypeSession).Str("request", req.Type).Msg("request received from remote server")
ok, _ := sc.SendRequest(req.Type, req.WantReply, req.Payload)
if req.WantReply {
req.Reply(ok, nil)
}
}
// track trchan
wr.Done()
}()
// track sc <- tc
go utils.CopyWG(sc, tc, wr, &err)
go utils.CopyWG(sc.Stderr(), tc.Stderr(), wr, &err)
// not track sc -> tc
go io.Copy(tc, sc)
wr.Wait()
return
}