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
|
package handlers
import (
"context"
"encoding/base64"
"strings"
"sync/atomic"
"github.com/mimecast/dtail/internal"
"github.com/mimecast/dtail/internal/config"
"github.com/mimecast/dtail/internal/io/dlog"
"github.com/mimecast/dtail/internal/io/line"
"github.com/mimecast/dtail/internal/lcontext"
"github.com/mimecast/dtail/internal/omode"
"github.com/mimecast/dtail/internal/protocol"
sshserver "github.com/mimecast/dtail/internal/ssh/server"
user "github.com/mimecast/dtail/internal/user/server"
gossh "golang.org/x/crypto/ssh"
)
// ServerHandler implements the Reader and Writer interfaces to handle
// the Bi-directional communication between SSH client and server.
// This handler implements the handler of the SSH server.
type ServerHandler struct {
baseHandler
catLimiter chan struct{}
tailLimiter chan struct{}
serverCfg *config.ServerConfig
authKeyStore *sshserver.AuthKeyStore
regex string
commands map[string]commandHandler
sessionState sessionCommandState
// Track pending files waiting for limiter slots
pendingFiles int32
}
type commandHandler func(context.Context, lcontext.LContext, int, []string, func())
var _ Handler = (*ServerHandler)(nil)
// NewServerHandler returns the server handler.
func NewServerHandler(user *user.User, catLimiter,
tailLimiter chan struct{}, serverCfg *config.ServerConfig,
authKeyStore *sshserver.AuthKeyStore) *ServerHandler {
dlog.Server.Debug(user, "Creating new server handler")
if serverCfg == nil {
dlog.Server.FatalPanic("Missing server config in NewServerHandler")
}
h := ServerHandler{
baseHandler: baseHandler{
done: internal.NewDone(),
lines: make(chan *line.Line, 100),
serverMessages: make(chan string, 10),
maprMessages: make(chan string, 10),
ackCloseReceived: make(chan struct{}),
user: user,
codec: newProtocolCodec(user),
},
catLimiter: catLimiter,
tailLimiter: tailLimiter,
serverCfg: serverCfg,
authKeyStore: authKeyStore,
regex: ".",
}
if h.authKeyStore == nil {
h.authKeyStore = sshserver.AuthKeys()
}
h.handleCommandCb = h.handleUserCommand
h.commands = h.newCommandRegistry()
h.turbo.configure(h.turboManagerConfig())
fqdn, err := config.Hostname()
if err != nil {
dlog.Server.FatalPanic(err)
}
s := strings.Split(fqdn, ".")
h.hostname = s[0]
h.send(h.serverMessages, protocol.HiddenCapabilitiesPrefix+protocol.CapabilityQueryUpdateV1)
return &h
}
func (h *ServerHandler) handleUserCommand(ctx context.Context, ltx lcontext.LContext,
argc int, args []string, commandName string) {
dlog.Server.Debug(h.user, "Handling user command", argc, args)
shutdownOnCompletion := shouldShutdownOnCommandCompletion(commandName)
h.incrementActiveCommands()
commandFinished := func() {
activeCommands := h.decrementActiveCommands()
pendingFiles := atomic.LoadInt32(&h.pendingFiles)
dlog.Server.Debug(h.user, "Command finished", "activeCommands", activeCommands, "pendingFiles", pendingFiles)
// Only shutdown if no active commands AND no pending files.
// AUTHKEY is a session-side effect command and should not terminate the shell
// because user commands may still follow in the same session.
if shutdownOnCompletion && activeCommands == 0 && pendingFiles == 0 && !h.sessionState.keepAlive() {
h.shutdown()
}
}
handler, found := h.commands[commandName]
if !found {
h.sendln(h.serverMessages, dlog.Server.Error(h.user,
"Received unknown user command", commandName, argc, args))
commandFinished()
return
}
handler(ctx, ltx, argc, args, commandFinished)
}
func shouldShutdownOnCommandCompletion(commandName string) bool {
switch {
case strings.EqualFold(commandName, "AUTHKEY"):
return false
case strings.EqualFold(commandName, "SESSION"):
return false
default:
return true
}
}
func (h *ServerHandler) newCommandRegistry() map[string]commandHandler {
return map[string]commandHandler{
"grep": h.makeReadCommandHandler(omode.GrepClient, 1),
"cat": h.makeReadCommandHandler(omode.CatClient, 1),
"tail": h.makeReadCommandHandler(omode.TailClient, 10),
"map": h.handleMapCommand,
".ack": h.handleAckUserCommand,
"AUTHKEY": h.handleAuthKeyCommand,
"SESSION": h.handleSessionCommand,
"authkey": h.handleAuthKeyCommand,
"session": h.handleSessionCommand,
}
}
func (h *ServerHandler) makeReadCommandHandler(mode omode.Mode, tailBackoff int) commandHandler {
return func(ctx context.Context, ltx lcontext.LContext, argc int, args []string, commandFinished func()) {
command := newReadCommand(h, mode)
go func() {
command.Start(ctx, ltx, argc, args, tailBackoff)
commandFinished()
}()
}
}
func (h *ServerHandler) handleMapCommand(ctx context.Context, _ lcontext.LContext, argc int, args []string, commandFinished func()) {
command, aggregate, turboAggregate, err := newMapCommand(h, argc, args)
if err != nil {
h.sendln(h.serverMessages, err.Error())
dlog.Server.Error(h.user, err)
commandFinished()
return
}
h.aggregate = aggregate
h.turboAggregate = turboAggregate
go func() {
command.Start(ctx, h.maprMessages)
commandFinished()
}()
}
func (h *ServerHandler) handleAckUserCommand(_ context.Context, _ lcontext.LContext, argc int, args []string, commandFinished func()) {
h.handleAckCommand(argc, args)
commandFinished()
}
func (h *ServerHandler) handleAuthKeyCommand(_ context.Context, _ lcontext.LContext,
argc int, args []string, commandFinished func()) {
defer commandFinished()
if !h.serverCfg.AuthKeyEnabled {
h.sendln(h.serverMessages, "AUTHKEY ERR feature disabled")
return
}
if argc < 2 || strings.TrimSpace(args[1]) == "" {
h.sendln(h.serverMessages, "AUTHKEY ERR missing public key")
return
}
decodedPubKey, err := base64.StdEncoding.DecodeString(args[1])
if err != nil {
h.sendln(h.serverMessages, "AUTHKEY ERR invalid base64")
return
}
pubKey, err := gossh.ParsePublicKey(decodedPubKey)
if err != nil {
h.sendln(h.serverMessages, "AUTHKEY ERR invalid public key")
return
}
if h.authKeyStore == nil {
h.sendln(h.serverMessages, "AUTHKEY ERR internal key store unavailable")
return
}
h.authKeyStore.Add(h.user.Name, pubKey)
h.sendln(h.serverMessages, "AUTHKEY OK")
}
|