-
-
Notifications
You must be signed in to change notification settings - Fork 146
/
Copy pathsession.go
267 lines (215 loc) · 8.56 KB
/
session.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
package channels
import (
"strings"
gliderssh "github.com/gliderlabs/ssh"
"github.com/shellhub-io/shellhub/ssh/session"
log "github.com/sirupsen/logrus"
gossh "golang.org/x/crypto/ssh"
)
// KeepAliveRequestTypePrefix Through the time, the [KeepAliveRequestType] type sent from agent to server changed its
// name, but always keeping the prefix "keepalive". So, to maintain the retro compatibility, we check if this prefix
// exists and perform the necessary operations.
const KeepAliveRequestTypePrefix string = "keepalive"
const (
// Once the session has been set up, a program is started at the remote end. The program can be a shell, an
// application program, or a subsystem with a host-independent name. Only one of these requests can succeed per
// channel
//
// https://www.rfc-editor.org/rfc/rfc4254#section-6.5
ShellRequestType = "shell"
// This message will request that the server start the execution of the given command. The 'command' string may
// contain a path. Normal precautions MUST be taken to prevent the execution of unauthorized commands.
//
// https://www.rfc-editor.org/rfc/rfc4254#section-6.5
ExecRequestType = "exec"
// This last form executes a predefined subsystem. It is expected that these will include a general file transfer
// mechanism, and possibly other features. Implementations may also allow configuring more such mechanisms. As
// the user's shell is usually used to execute the subsystem, it is advisable for the subsystem protocol to have a
// "magic cookie" at the beginning of the protocol transaction to distinguish it from arbitrary output generated
// by shell initialization scripts, etc. This spurious output from the shell may be filtered out either at the
// server or at the client.
//
// https://www.rfc-editor.org/rfc/rfc4254#section-6.5
SubsystemRequestType = "subsystem"
// A pseudo-terminal can be allocated for the session by sending the following message.
//
// The 'encoded terminal modes' are described in Section 8. Zero dimension parameters MUST be ignored. The
// character/row dimensions override the pixel dimensions (when nonzero). Pixel dimensions refer to the drawable
// area of the window.
//
// https://www.rfc-editor.org/rfc/rfc4254#section-6.2
PtyRequestType = "pty-req"
// When the window (terminal) size changes on the client side, it MAY send a message to the other side to inform it
// of the new dimensions.
//
// https://www.rfc-editor.org/rfc/rfc4254#section-6.7
WindowChangeRequestType = "window-change"
// In a defined interval, the Agent sends a keepalive request to maintain the session apoint, even when no data is
// send.
KeepAliveRequestType = KeepAliveRequestTypePrefix + "@shellhub.io"
)
type DefaultSessionHandlerOptions struct {
RecordURL string
}
// DefaultSessionHandler is the default handler for session's channel.
//
// A session is a remote execution of a program. The program may be a shell, an application, a system command, or some
// built-in subsystem. It may or may not have a tty, and may or may not involve X11 forwarding.
//
// https://www.rfc-editor.org/rfc/rfc4254#section-6
func DefaultSessionHandler(opts DefaultSessionHandlerOptions) gliderssh.ChannelHandler {
return func(_ *gliderssh.Server, conn *gossh.ServerConn, newChan gossh.NewChannel, ctx gliderssh.Context) {
sess, _ := session.ObtainSession(ctx)
go func() {
// NOTICE: As [gossh.ServerConn] is shared by all channels calls, close it after a channel close block any
// other channel involkation. To avoid it, we wait for the connection be closed to finish the sesison.
conn.Wait() //nolint:errcheck
sess.Finish() //nolint:errcheck
}()
logger := log.WithFields(
log.Fields{
"uid": sess.UID,
"sshid": sess.SSHID,
"device": sess.Device.UID,
"username": sess.Target.Username,
"ip": sess.IPAddress,
})
reject := func(err error, msg string) {
logger.WithError(err).Error(msg)
newChan.Reject(gossh.ConnectionFailed, msg) //nolint:errcheck
}
logger.Info("session channel started")
defer logger.Info("session channel done")
client, clientReqs, err := newChan.Accept()
if err != nil {
reject(err, "failed to accept the channel opening")
return
}
defer client.Close()
agent, agentReqs, err := sess.AgentClient.OpenChannel(SessionChannel, nil)
if err != nil {
reject(err, "failed to open the 'session' channel on agent")
return
}
defer agent.Close()
for {
select {
case <-ctx.Done():
logger.Info("context has done")
return
case req, ok := <-sess.AgentGlobalReqs:
if !ok {
logger.Trace("global requests is closed")
return
}
logger.Debugf("global request from agent: %s", req.Type)
switch {
// NOTICE: The Agent sends "keepalive" requests to the server to avoid the Web Socket being closed due
// to inactivity. Through the time, the request type sent from agent to server changed its name, but
// always keeping the prefix "keepalive". So, to maintain the retro compatibility, we check if this
// prefix exists and perform the necessary operations.
case strings.HasPrefix(req.Type, KeepAliveRequestTypePrefix):
wantReply, err := client.SendRequest(KeepAliveRequestType, req.WantReply, req.Payload)
if err != nil {
logger.Error("failed to send the keepalive request received from agent to client")
return
}
if err := req.Reply(wantReply, nil); err != nil {
logger.WithError(err).Error("failed to send the keepalive response back to agent")
return
}
if err := sess.KeepAlive(); err != nil {
logger.WithError(err).Error("failed to send the API request to inform that the session is open")
return
}
default:
if req.WantReply {
if err := req.Reply(false, nil); err != nil {
logger.WithError(err).Error(err)
}
}
}
case req, ok := <-clientReqs:
if !ok {
logger.Trace("client requests is closed")
return
}
logger.Debugf("request from client to agent: %s", req.Type)
ok, err := agent.SendRequest(req.Type, req.WantReply, req.Payload)
if err != nil {
logger.WithError(err).Error("failed to send the request from client to agent")
continue
}
switch req.Type {
case ShellRequestType, ExecRequestType, SubsystemRequestType:
if err := req.Reply(ok, nil); err != nil {
logger.WithError(err).Error("failed to reply the client with right response for pipe request type")
return
}
logger.Info("session type set")
if req.Type == ShellRequestType && sess.Pty.Term != "" {
if err := sess.Announce(client); err != nil {
logger.WithError(err).Warn("failed to get the namespace announcement")
}
}
// The server SHOULD NOT halt the execution of the protocol stack when starting a shell or a
// program. All input and output from these SHOULD be redirected to the channel or to the
// encrypted tunnel.
//
// https://www.rfc-editor.org/rfc/rfc4254#section-6.5
go pipe(sess, client, agent, req.Type, opts)
case PtyRequestType:
var pty session.Pty
if err := gossh.Unmarshal(req.Payload, &pty); err != nil {
reject(nil, "failed to recover the session dimensions")
}
sess.Pty = pty
if req.WantReply {
// req.Reply(ok, nil) //nolint:errcheck
if err := req.Reply(ok, nil); err != nil {
logger.WithError(err).Error("failed to reply for pty-req")
return
}
}
case WindowChangeRequestType:
var dimensions session.Dimensions
if err := gossh.Unmarshal(req.Payload, &dimensions); err != nil {
reject(nil, "failed to recover the session dimensions")
}
sess.Pty.Columns = dimensions.Columns
sess.Pty.Rows = dimensions.Rows
if req.WantReply {
if err := req.Reply(ok, nil); err != nil {
logger.Error("failed to reply for window-change")
return
}
}
default:
if req.WantReply {
if err := req.Reply(ok, nil); err != nil {
logger.WithError(err).Error("failed to reply")
return
}
}
}
case req, ok := <-agentReqs:
if !ok {
logger.Trace("agent requests is closed")
return
}
logger.Debugf("request from agent to client: %s", req.Type)
ok, err := client.SendRequest(req.Type, req.WantReply, req.Payload)
if err != nil {
logger.WithError(err).Error("failed to send the request from agent to client")
continue
}
if req.WantReply {
if err := req.Reply(ok, nil); err != nil {
logger.WithError(err).Error("failed to reply the agent request")
return
}
}
}
}
}
}