-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathclient.go
578 lines (495 loc) · 15 KB
/
client.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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
package main
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httputil"
"sync"
"sync/atomic"
"time"
)
type Client struct {
ClientId string
ClientCountry string
ClientIp string
mu *sync.Mutex
TerminalsCount *atomic.Int32
DesktopActive *atomic.Bool // Whether a active desktop ws connection exists
MaxTerms int32
MaxSharedDesktopConn int32
SSHConnection *SSHConnection
FileBrowserProxy *httputil.ReverseProxy
FileBrowserServiceActive *atomic.Bool
ShareDesktop *atomic.Bool // Whether desktop sharing is active
SharedDesktopIsViewOnly *atomic.Bool
SharedDesktopSecret string
SharedDesktopConn chan interface{} // Channel when closed kills all shared desktop connections
SharedDesktopConnCount *atomic.Int32 // No of active connections to shared desktop
// Channel when closed prevents master SSH connection from being killed by RemoveClientIfInactive,
// that is unless a ClientInactivityTimeout is first reached, open channel indicates a inactive client
// closed channel indicates a active client
ClientConn chan interface{}
ClientActive *atomic.Bool // Atleast one active connection exists
// Random value supplied by client during login , helps to identify duplicate sessions
TabId *string
Deleted *atomic.Bool
ConnectedOn time.Time
ClientAlive chan interface{}
}
var AcceptClients = true
var clients = make(map[string]Client) // Clients DB
var cmu = &sync.Mutex{} // Synchronize access to the clients DB above
var randVal = RandomStr(10) // Random str for deriving clientId, doesnt change unless sfui is restarted
// Return a new client, prepare necessary sockets
func (sfui *SfUI) NewClient(ClientSecret string, ClientIp string) (Client, error) {
isBanned, reason := BanDB.IsBanned(ClientIp)
if isBanned {
return Client{}, errors.New(reason)
}
// Make and return a new client
tabId := ""
client := Client{
ClientId: getClientId(ClientSecret),
mu: &sync.Mutex{},
TerminalsCount: &atomic.Int32{},
MaxTerms: int32(sfui.MaxWsTerminals),
MaxSharedDesktopConn: int32(sfui.MaxSharedDesktopConn),
ClientConn: make(chan interface{}), // Initially no active connections exist
ClientActive: &atomic.Bool{},
DesktopActive: &atomic.Bool{},
FileBrowserServiceActive: &atomic.Bool{},
ShareDesktop: &atomic.Bool{},
SharedDesktopConn: make(chan interface{}),
SharedDesktopIsViewOnly: &atomic.Bool{},
SharedDesktopConnCount: &atomic.Int32{},
Deleted: &atomic.Bool{},
TabId: &tabId,
ClientCountry: GetCountryByIp(ClientIp),
ClientIp: ClientIp,
ConnectedOn: time.Now(),
ClientAlive: make(chan interface{}),
}
if !AcceptClients {
return client, errors.New("not accepting new clients")
}
// Prevent use of a unprepared client
client.mu.Lock()
defer client.mu.Unlock()
// Make a inital entry in the clients DB, this is to prevent a race condition
// where multiple SSH connection would be created when a master SSH connection
// is still being established.
cmu.Lock()
endpointAddress, actualSecret := sfui.getEndpointAndSecret(ClientSecret)
sshConnection := SSHConnection{
Connected: &atomic.Bool{},
Host: endpointAddress,
ControlTerminalActive: &atomic.Bool{},
Port: "22",
Username: sfui.SegfaultSSHUsername,
Password: sfui.SegfaultSSHPassword,
UseSSHKey: sfui.SegfaultUseSSHKey,
SSHKeyPath: sfui.SegfaultSSHKeyPath,
ClientIpAddress: ClientIp,
Secret: actualSecret,
Timeout: 1 * time.Minute,
ForwardedConnections: make(map[uint16]*net.Conn),
}
client.SSHConnection = &sshConnection
clients[client.ClientId] = client
cmu.Unlock()
if cerr := sshConnection.StartSSHConnection(); cerr != nil {
sfui.RemoveClient(&client)
return client, cerr
}
client.ClientActive.Store(true)
cmu.Lock()
clients[client.ClientId] = client
cmu.Unlock()
go func() {
timeout := time.NewTimer(time.Minute * time.Duration(sfui.WSTimeout))
select {
case <-timeout.C:
// After hard timeout
if client.mu != nil {
sfui.RemoveClient(&client)
}
break
case _, ok := <-client.ClientAlive:
// Client was stopped
if !ok {
break
}
timeout.Stop()
}
}()
return client, nil
}
func (sfui *SfUI) RemoveClient(client *Client) {
if client.Deleted == nil || client.ClientActive == nil {
return
}
if client.Deleted.CompareAndSwap(false, true) {
if !client.ClientActive.Load() {
close(client.ClientConn) // Stop RemoveClientIfInactive if running
close(client.ClientAlive) // Mark client as dead
}
if client.SSHConnection != nil {
client.SSHConnection.StopSSHConnection()
}
if sfui.EnableMetricLogging {
go MLogger.AddLogEntry(&Metric{
Type: "Logout",
UserUid: getClientId(client.ClientIp),
Country: client.ClientCountry,
SessionDuration: fmt.Sprintf("%.0f", time.Since(client.ConnectedOn).Minutes()),
})
}
cmu.Lock()
delete(clients, client.ClientId)
cmu.Unlock()
}
}
// If a client has no active terminals or a GUI connection
// consider them as inactive , wait for ClientInactivityTimeout
// and then tear down the master SSH connection
func (sfui *SfUI) RemoveClientIfInactive(clientSecret string) {
go func() {
// Obtain a fresh copy of the client
client, err := sfui.GetClient(clientSecret)
if err == nil {
if client.TerminalsCount != nil && client.DesktopActive != nil {
if client.TerminalsCount.Load() == 0 && !client.DesktopActive.Load() {
timeout := time.NewTimer(time.Minute * time.Duration(sfui.ClientInactivityTimeout))
select {
case <-timeout.C:
// After timeout
if client.mu != nil {
sfui.RemoveClient(&client)
}
break
case _, ok := <-client.ClientConn:
// New connection from client
if !ok {
break
}
timeout.Stop()
}
}
}
}
}()
}
func (sfui *SfUI) GetExistingClientOrMakeNew(ClientSecret string, ClientIp string) (Client, error) {
client, cerr := sfui.GetClient(ClientSecret)
if cerr != nil {
return sfui.NewClient(ClientSecret, ClientIp)
}
if client.SSHConnection == nil {
return client, errors.New("client does not exist")
}
if !client.SSHConnection.Connected.Load() {
werr := client.SSHConnection.WaitForConnection(2, 5*time.Second)
if werr != nil {
return client, werr
}
// serialize access to client, since it can be updated inbetween by NewClient()
client.mu.Lock()
defer client.mu.Unlock()
// master SSH socket is now active, grab a fresh copy of the client
client, cerr = sfui.GetClient(ClientSecret)
}
return client, cerr
}
func (sfui *SfUI) GetClient(ClientSecret string) (Client, error) {
cmu.Lock()
defer cmu.Unlock()
client, ok := clients[getClientId(ClientSecret)]
if ok {
return client, nil
}
return client, errors.New("no such client")
}
func (sfui *SfUI) GetClientUnsafe(ClientSecret string) (Client, error) {
client, ok := clients[getClientId(ClientSecret)]
if ok {
return client, nil
}
return client, errors.New("no such client")
}
func (sfui *SfUI) GetClientById(ClientId string) (Client, error) {
cmu.Lock()
defer cmu.Unlock()
client, ok := clients[ClientId]
if ok {
return client, nil
}
return client, errors.New("no such client")
}
func (sfui *SfUI) GetClientByIdUnsafe(ClientId string) (Client, error) {
client, ok := clients[ClientId]
if ok {
return client, nil
}
return client, errors.New("no such client")
}
// Derive a client id from secret
func getClientId(ClientSecret string) string {
h := sha256.New()
h.Write([]byte(ClientSecret))
h.Write([]byte(randVal))
return hex.EncodeToString(h.Sum(nil))
}
func (client *Client) IncTermCount() error {
defer client.MarkClientIfActive()
if client.TerminalsCount != nil {
if client.TerminalsCount.Load() >= client.MaxTerms {
return errors.New("max terminals allocated")
}
client.TerminalsCount.Add(1)
}
return nil
}
func (client *Client) DecTermCount() {
defer client.MarkClientIfInactive()
if client.TerminalsCount != nil {
if client.TerminalsCount.Load() > 0 {
client.TerminalsCount.Add(-1)
}
}
}
func (client *Client) IncSharedDesktopConnCount() error {
defer client.MarkClientIfActive()
if client.SharedDesktopConnCount != nil {
if client.SharedDesktopConnCount.Load() >= client.MaxSharedDesktopConn {
return errors.New("max shares reached")
}
client.SharedDesktopConnCount.Add(1)
}
return nil
}
func (client *Client) DecSharedDesktopConnCount() {
defer client.MarkClientIfInactive()
if client.SharedDesktopConnCount != nil {
if client.SharedDesktopConnCount.Load() > 0 {
client.SharedDesktopConnCount.Add(-1)
}
}
}
func (client *Client) ActivateDesktop() {
defer client.MarkClientIfActive()
if client.DesktopActive != nil {
client.DesktopActive.Store(true)
}
}
func (client *Client) DeActivateDesktop() {
defer client.MarkClientIfActive()
if client.DesktopActive != nil {
client.DesktopActive.Store(false)
}
}
func (client *Client) ActivateDesktopSharing(viewOnly bool, SharedSecret string) (AlreadyShared bool) {
if client.mu != nil {
// client is stale, but mu is a pointer, it locks the original Client entry in "clients"
// first lock then read the fresh copy to prevent a dirty read
client.mu.Lock()
defer client.mu.Unlock()
// get a fresh copy of client
fclient := clients[client.ClientId]
if fclient.ShareDesktop.CompareAndSwap(false, true) {
fclient.SharedDesktopIsViewOnly.Store(viewOnly)
fclient.SharedDesktopSecret = SharedSecret
if fclient.Deleted != nil {
if !fclient.Deleted.Load() {
fclient.SharedDesktopConn = make(chan interface{})
clients[client.ClientId] = fclient
}
}
return false
}
}
return true // Already shared
}
func (client *Client) DeactivateDesktopSharing() {
if client.mu == nil {
return
}
// client is stale, but mu is a pointer, it locks the original Client entry in "clients"
// first lock then read the fresh copy to prevent a dirty read
client.mu.Lock()
defer client.mu.Unlock()
if client.ShareDesktop == nil {
return
}
if !client.ShareDesktop.Load() {
return
}
// get a fresh copy of client
cmu.Lock()
fclient, ok := clients[client.ClientId]
cmu.Unlock()
if !ok {
return
}
if fclient.Deleted == nil {
return
}
if !fclient.Deleted.Load() {
if fclient.ShareDesktop.CompareAndSwap(true, false) {
close(fclient.SharedDesktopConn)
clients[client.ClientId] = fclient
}
}
}
// If no active client connection exist, open the ClientConn channel
func (client *Client) MarkClientIfInactive() {
if client.mu != nil && client.TerminalsCount != nil && client.DesktopActive != nil {
if client.TerminalsCount.Load() == 0 && !client.DesktopActive.Load() {
if client.ClientActive.CompareAndSwap(true, false) {
cmu.Lock()
defer cmu.Unlock()
client.mu.Lock()
defer client.mu.Unlock()
fclient := clients[client.ClientId]
if fclient.Deleted != nil {
if !fclient.Deleted.Load() {
fclient.ClientConn = make(chan interface{})
clients[client.ClientId] = fclient
}
}
}
}
}
}
// If no active client connection exist, close the ClientConn channel
func (client *Client) MarkClientIfActive() {
if client.mu != nil && client.TerminalsCount != nil && client.DesktopActive != nil {
if client.TerminalsCount.Load() > 0 || client.DesktopActive.Load() {
if client.ClientActive.CompareAndSwap(false, true) {
cmu.Lock()
defer cmu.Unlock()
client.mu.Lock()
defer client.mu.Unlock()
fclient := clients[client.ClientId]
if fclient.Deleted != nil {
if !fclient.Deleted.Load() {
close(fclient.ClientConn)
clients[client.ClientId] = fclient
}
}
}
}
}
}
func (client *Client) SetTabId(TabId string) {
if client.mu != nil {
client.mu.Lock()
defer client.mu.Unlock()
cmu.Lock()
defer cmu.Unlock()
fclient := clients[client.ClientId]
fclient.TabId = &TabId
clients[client.ClientId] = fclient
}
}
// Stop New Clients from obtaining service
func (sfui *SfUI) DisableClientAccess() {
cmu.Lock()
AcceptClients = false
cmu.Unlock()
}
// Disable client access before calling this function
func (sfui *SfUI) RemoveAllClients() {
for cid := range clients {
client := clients[cid]
sfui.RemoveClient(&client)
}
}
type ClientStats struct {
ClientCount int `json:"client_count"`
Clients []ClientStat `json:"clients"`
}
type ClientStat struct {
ClientId string `json:"client_id"`
IpId string `json:"ip_id"`
Ip string `json:"ip"`
Country string `json:"country"`
ConnectedOn string `json:"connected_on"`
Age string `json:"age"`
TermCount int `json:"term_count"`
DesktopActive bool `json:"desktop_active"`
}
func (sfui *SfUI) handleClientStats(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
MtSecret := r.Header.Get("X-Mt-Secret")
if MtSecret != sfui.MaintenanceSecret {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"status":"denied"}`))
return
}
stats := ClientStats{
ClientCount: 0,
}
cmu.Lock()
for _, client := range clients {
nClient := ClientStat{
ClientId: client.ClientId,
IpId: getClientId(client.ClientIp),
Ip: client.ClientIp,
TermCount: int(client.TerminalsCount.Load()),
Country: client.ClientCountry,
ConnectedOn: client.ConnectedOn.UTC().String(),
Age: time.Since(client.ConnectedOn).String(),
DesktopActive: client.DesktopActive.Load(),
}
stats.Clients = append(stats.Clients, nClient)
stats.ClientCount++
}
cmu.Unlock()
jb, err := json.Marshal(stats)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.WriteHeader(http.StatusOK)
w.Write(jb)
}
type AdminOp struct {
ClientId string `json:"client_id"`
}
func (sfui *SfUI) handleKillClient(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
MtSecret := r.Header.Get("X-Mt-Secret")
if MtSecret != sfui.MaintenanceSecret {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"status":"denied"}`))
return
}
data, err := io.ReadAll(io.LimitReader(r.Body, 2048))
if err == nil {
adminRequest := AdminOp{}
if json.Unmarshal(data, &adminRequest) == nil {
if adminRequest.ClientId != "" {
cmu.Lock()
client, ok := clients[adminRequest.ClientId]
cmu.Unlock()
if ok {
sfui.RemoveClient(&client)
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status":"ok"}`))
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status":"no such client"}`))
return
}
}
}
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(`{"status":"error"}`))
}