-
-
Notifications
You must be signed in to change notification settings - Fork 315
/
Copy pathconsole.go
433 lines (352 loc) · 10.7 KB
/
console.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
422
423
424
425
426
427
428
429
430
431
432
433
package utils
import (
"encoding/base64"
"fmt"
"log"
"net"
"net/http"
"strings"
"github.com/antoniomika/syncmap"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/spf13/viper"
"github.com/vulcand/oxy/roundrobin"
)
// upgrader is the default WS upgrader that we use for webconsole clients.
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
// WebClient represents a primitive web console client. It maintains
// references that allow us to communicate and track a client connection.
type WebClient struct {
Conn *websocket.Conn
Console *WebConsole
Send chan []byte
Route string
}
// WebConsole represents the data structure that stores web console client information.
type WebConsole struct {
Clients *syncmap.Map[string, []*WebClient]
RouteTokens *syncmap.Map[string, string]
State *State
}
// NewWebConsole sets up the WebConsole.
func NewWebConsole() *WebConsole {
return &WebConsole{
Clients: syncmap.New[string, []*WebClient](),
RouteTokens: syncmap.New[string, string](),
}
}
// HandleRequest handles an incoming web request, handles auth, and then routes it.
func (c *WebConsole) HandleRequest(proxyUrl string, hostIsRoot bool, g *gin.Context) {
userAuthed := false
userIsAdmin := false
if (viper.GetBool("admin-console") && viper.GetString("admin-console-token") != "") && (g.Request.URL.Query().Get("x-authorization") == viper.GetString("admin-console-token") || g.Request.Header.Get("x-authorization") == viper.GetString("admin-console-token")) {
userIsAdmin = true
userAuthed = true
}
tokenInterface, ok := c.RouteTokens.Load(proxyUrl)
if ok {
routeToken := tokenInterface
if routeToken == "" {
ok = false
}
if viper.GetBool("service-console") && ok && (g.Request.URL.Query().Get("x-authorization") == routeToken || g.Request.Header.Get("x-authorization") == routeToken) {
userAuthed = true
}
}
if strings.HasPrefix(g.Request.URL.Path, "/_sish/console/ws") && userAuthed {
c.HandleWebSocket(proxyUrl, g)
return
} else if strings.HasPrefix(g.Request.URL.Path, "/_sish/console") && userAuthed {
c.HandleTemplate(proxyUrl, hostIsRoot, userIsAdmin, g)
return
} else if strings.HasPrefix(g.Request.URL.Path, "/_sish/api/disconnectclient/") && userIsAdmin {
c.HandleDisconnectClient(proxyUrl, g)
return
} else if strings.HasPrefix(g.Request.URL.Path, "/_sish/api/disconnectroute/") && userIsAdmin {
c.HandleDisconnectRoute(proxyUrl, g)
return
} else if strings.HasPrefix(g.Request.URL.Path, "/_sish/api/clients") && hostIsRoot && userIsAdmin {
c.HandleClients(proxyUrl, g)
return
}
}
// HandleTemplate handles rendering the console templates.
func (c *WebConsole) HandleTemplate(proxyUrl string, hostIsRoot bool, userIsAdmin bool, g *gin.Context) {
if hostIsRoot && userIsAdmin {
g.HTML(http.StatusOK, "routes", nil)
return
}
if c.RouteExists(proxyUrl) {
g.HTML(http.StatusOK, "console", nil)
return
}
err := g.AbortWithError(http.StatusNotFound, fmt.Errorf("cannot find connection for host: %s", proxyUrl))
if err != nil {
log.Println("Aborting with error", err)
}
}
// HandleWebSocket handles the websocket route.
func (c *WebConsole) HandleWebSocket(proxyUrl string, g *gin.Context) {
conn, err := upgrader.Upgrade(g.Writer, g.Request, nil)
if err != nil {
log.Println(err)
return
}
client := &WebClient{
Conn: conn,
Console: c,
Send: make(chan []byte),
Route: proxyUrl,
}
c.AddClient(proxyUrl, client)
go client.Handle()
}
// HandleDisconnectClient handles the disconnection request for a SSH client.
func (c *WebConsole) HandleDisconnectClient(proxyUrl string, g *gin.Context) {
client := strings.TrimPrefix(g.Request.URL.Path, "/_sish/api/disconnectclient/")
c.State.SSHConnections.Range(func(clientName string, holderConn *SSHConnection) bool {
if clientName == client {
holderConn.CleanUp(c.State)
return false
}
return true
})
data := map[string]any{
"status": true,
}
g.JSON(http.StatusOK, data)
}
// HandleDisconnectRoute handles the disconnection request for a forwarded route.
func (c *WebConsole) HandleDisconnectRoute(proxyUrl string, g *gin.Context) {
route := strings.Split(strings.TrimPrefix(g.Request.URL.Path, "/_sish/api/disconnectroute/"), "/")
encRouteName := route[1]
decRouteName, err := base64.StdEncoding.DecodeString(encRouteName)
if err != nil {
log.Println("Error decoding route name:", err)
err := g.AbortWithError(http.StatusInternalServerError, err)
if err != nil {
log.Println("Error aborting with error:", err)
}
return
}
routeName := string(decRouteName)
listenerTmp, ok := c.State.Listeners.Load(routeName)
if ok {
listener, ok := listenerTmp.(*ListenerHolder)
if ok {
listener.Close()
}
}
data := map[string]any{
"status": true,
}
g.JSON(http.StatusOK, data)
}
// HandleClients handles returning all connected SSH clients. This will
// also go through all of the forwarded connections for the SSH client and
// return them.
func (c *WebConsole) HandleClients(proxyUrl string, g *gin.Context) {
data := map[string]any{
"status": true,
}
clients := map[string]map[string]any{}
c.State.SSHConnections.Range(func(clientName string, sshConn *SSHConnection) bool {
listeners := []string{}
routeListeners := map[string]map[string]any{}
sshConn.Listeners.Range(func(name string, val net.Listener) bool {
ok := true
if name == "" {
ok = false
}
if ok {
listeners = append(listeners, name)
}
return true
})
tcpAliases := map[string]any{}
c.State.AliasListeners.Range(func(tcpAlias string, aliasHolder *AliasHolder) bool {
for _, v := range listeners {
for _, server := range aliasHolder.Balancer.Servers() {
serverAddr, err := base64.StdEncoding.DecodeString(server.Host)
if err != nil {
log.Println("Error decoding server host:", err)
continue
}
aliasAddress := string(serverAddr)
if v == aliasAddress {
tcpAliases[tcpAlias] = aliasAddress
}
}
}
return true
})
listenerParts := map[string]any{}
c.State.TCPListeners.Range(func(tcpAlias string, aliasHolder *TCPHolder) bool {
for _, v := range listeners {
aliasHolder.Balancers.Range(func(ikey string, balancer *roundrobin.RoundRobin) bool {
if aliasHolder.SNIProxy {
tcpAlias = fmt.Sprintf("%s-%s", tcpAlias, ikey)
}
for _, server := range balancer.Servers() {
serverAddr, err := base64.StdEncoding.DecodeString(server.Host)
if err != nil {
log.Println("Error decoding server host:", err)
continue
}
aliasAddress := string(serverAddr)
if v == aliasAddress {
listenerParts[tcpAlias] = aliasAddress
}
}
return true
})
}
return true
})
httpListeners := map[string]any{}
c.State.HTTPListeners.Range(func(key string, httpHolder *HTTPHolder) bool {
listenerHandlers := []string{}
httpHolder.SSHConnections.Range(func(httpAddr string, val *SSHConnection) bool {
for _, v := range listeners {
if v == httpAddr {
listenerHandlers = append(listenerHandlers, httpAddr)
}
}
return true
})
if len(listenerHandlers) > 0 {
var userPass string
password, _ := httpHolder.HTTPUrl.User.Password()
if httpHolder.HTTPUrl.User.Username() != "" || password != "" {
userPass = fmt.Sprintf("%s:%s@", httpHolder.HTTPUrl.User.Username(), password)
}
httpListeners[fmt.Sprintf("%s%s%s", userPass, httpHolder.HTTPUrl.Hostname(), httpHolder.HTTPUrl.Path)] = listenerHandlers
}
return true
})
routeListeners["tcpAliases"] = tcpAliases
routeListeners["listeners"] = listenerParts
routeListeners["httpListeners"] = httpListeners
pubKey := ""
pubKeyFingerprint := ""
if sshConn.SSHConn.Permissions != nil {
if _, ok := sshConn.SSHConn.Permissions.Extensions["pubKey"]; ok {
pubKey = sshConn.SSHConn.Permissions.Extensions["pubKey"]
pubKeyFingerprint = sshConn.SSHConn.Permissions.Extensions["pubKeyFingerprint"]
}
}
clients[clientName] = map[string]any{
"remoteAddr": sshConn.SSHConn.RemoteAddr().String(),
"user": sshConn.SSHConn.User(),
"version": string(sshConn.SSHConn.ClientVersion()),
"session": sshConn.SSHConn.SessionID(),
"pubKey": pubKey,
"pubKeyFingerprint": pubKeyFingerprint,
"listeners": listeners,
"routeListeners": routeListeners,
}
return true
})
data["clients"] = clients
g.JSON(http.StatusOK, data)
}
// RouteToken returns the route token for a specific route.
func (c *WebConsole) RouteToken(route string) (string, bool) {
token, ok := c.RouteTokens.Load(route)
routeToken := ""
if ok {
routeToken = token
}
return routeToken, ok
}
// RouteExists check if a route token exists.
func (c *WebConsole) RouteExists(route string) bool {
_, ok := c.RouteToken(route)
return ok
}
// AddRoute adds a route token to the console.
func (c *WebConsole) AddRoute(route string, token string) {
c.Clients.LoadOrStore(route, []*WebClient{})
c.RouteTokens.Store(route, token)
}
// RemoveRoute removes a route token from the console.
func (c *WebConsole) RemoveRoute(route string) {
clients, ok := c.Clients.Load(route)
if !ok {
return
}
for _, client := range clients {
client.Conn.Close()
}
c.Clients.Delete(route)
c.RouteTokens.Delete(route)
}
// AddClient adds a client to the console route.
func (c *WebConsole) AddClient(route string, w *WebClient) {
clients, ok := c.Clients.Load(route)
if !ok {
return
}
clients = append(clients, w)
c.Clients.Store(route, clients)
}
// RemoveClient removes a client from the console route.
func (c *WebConsole) RemoveClient(route string, w *WebClient) {
clients, ok := c.Clients.Load(route)
if !ok {
return
}
found := false
toRemove := 0
for i, client := range clients {
if client == w {
found = true
toRemove = i
break
}
}
if found {
clients[toRemove] = clients[len(clients)-1]
c.Clients.Store(route, clients[:len(clients)-1])
}
}
// BroadcastRoute sends a message to all clients on a route.
func (c *WebConsole) BroadcastRoute(route string, message []byte) {
clients, ok := c.Clients.Load(route)
if !ok {
return
}
for _, client := range clients {
client.Send <- message
}
}
// Handle is the only place socket reads and writes happen.
func (c *WebClient) Handle() {
defer func() {
c.Conn.Close()
c.Console.RemoveClient(c.Route, c)
}()
for message := range c.Send {
w, err := c.Conn.NextWriter(websocket.TextMessage)
if err != nil {
return
}
_, err = w.Write(message)
if err != nil {
return
}
if err := w.Close(); err != nil {
return
}
}
err := c.Conn.WriteMessage(websocket.CloseMessage, []byte{})
if err != nil {
log.Println("Error writing to websocket:", err)
}
}