This repository has been archived by the owner on Mar 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 68
/
storeAuthEvents.go
625 lines (501 loc) · 16.4 KB
/
storeAuthEvents.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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
package stats
import (
"database/sql"
"fmt"
"github.com/seknox/trasa/server/global"
"net"
"strconv"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/huandu/go-sqlbuilder"
"github.com/seknox/trasa/server/api/misc"
"github.com/seknox/trasa/server/utils"
)
//select sum(array_length(string_to_array(managed_accounts,','),1)) from servicesv1;
func (s statStore) GetAggregatedLoginFails(entityType, entityID, orgID, timezone, timeFilter string) (reasons []FailedReasonsByType, err error) {
reasons = make([]FailedReasonsByType, 0)
loc, err := time.LoadLocation(timezone)
if err != nil {
return reasons, err
}
now := time.Now().In(loc)
sb := sqlbuilder.NewSelectBuilder()
sb.Select(`count(*)`, `failed_reason`)
sb.From("auth_logs")
if entityType == "service" {
sb.Where(sb.Equal("service_id", entityID))
} else if entityType == "user" {
sb.Where(sb.Equal("user_id", entityID))
}
sb.Where(sb.Equal(`org_id`, orgID))
sb.Where(sb.Equal(`status`, false))
sb.GroupBy(`failed_reason`)
sb.OrderBy(`failed_reason`)
sb.Limit(7)
*sb = addTimeFilter(timeFilter, now, *sb)
sqlStr, args := sb.BuildWithFlavor(sqlbuilder.PostgreSQL)
rows, err := s.DB.Query(sqlStr, args...)
//rows, err := s.DB.Query(`select count(*),failed_reason from auth_logs where status=false AND org_id=$1 GROUP BY failed_reason ORDER BY failed_reason`, orgID)
if err != nil {
return reasons, err
}
for rows.Next() {
var reason FailedReasonsByType
err = rows.Scan(&reason.Value, &reason.Name)
reason.Label = reason.Name
if err != nil {
return reasons, err
}
reasons = append(reasons, reason)
}
return reasons, err
}
func (s statStore) GetAggregatedLoginHours(entityType, entityID, timezone, orgID, timeFilter, statusFilter string) (logins []LoginsByHour, err error) {
logins = make([]LoginsByHour, 0)
loc, err := time.LoadLocation(timezone)
if err != nil {
return logins, err
}
now := time.Now().In(loc)
_, tzOffset := now.Zone()
tzOffset = tzOffset + 3600
sb := sqlbuilder.NewSelectBuilder()
sb.From("auth_logs")
if entityType == "service" {
sb.Where(sb.Equal("service_id", entityID))
} else if entityType == "user" {
sb.Where(sb.Equal("user_id", entityID))
}
sb.Where(sb.Equal(`org_id`, orgID))
if global.GetConfig().Database.Dbtype == "cockroachdb" {
sb.Select(sb.As(fmt.Sprintf(`EXTRACT('hour',timezone(timezone((login_time/1000000000)::int::timestamp,'UTC'),%s))`, sb.Var(timezone)), `hour `), sb.As(`count(*)`, `c`))
} else {
//postgres
sb.Select(sb.As(fmt.Sprintf(`extract(HOURS FROM (to_timestamp(login_time/1000000000) at time zone %s))`, sb.Var(timezone)), `hour`), sb.As(`count(*)`, `c`))
}
sb.GroupBy(`hour`)
sb.OrderBy(`hour`)
switch statusFilter {
case "Success":
sb.Where(sb.Equal(`status`, true))
case "Failed":
sb.Where(sb.Equal(`status`, false))
}
*sb = addTimeFilter(timeFilter, now, *sb)
sqlStr, args := sb.BuildWithFlavor(sqlbuilder.PostgreSQL)
rows, err := s.DB.Query(sqlStr, args...)
if err != nil {
return logins, err
}
for rows.Next() {
//TODO break the logic into new function
var login LoginsByHour
err = rows.Scan(&login.Hour, &login.Count)
if err != nil {
return logins, err
}
logins = append(logins, login)
}
out:
for i := 0; i < 24; i++ {
for j := i; j >= 0; j-- {
if len(logins) < i+1 {
break
}
if strconv.Itoa(i) == logins[j].Hour {
continue out
}
}
temp1 := make([]LoginsByHour, len(logins[:i]))
copy(temp1, logins[:i])
temp := append(temp1, LoginsByHour{Hour: strconv.Itoa(i), Count: "0"})
logins = append(temp, logins[i:]...)
}
return logins, err
}
func (s statStore) GetAggregatedIPs(entityType, entityID, orgID, timezone, timeFilter, statusFilter string) (AggIps, error) {
var ippool AggIps
loc, err := time.LoadLocation(timezone)
if err != nil {
return ippool, err
}
now := time.Now().In(loc)
sb := sqlbuilder.NewSelectBuilder()
sb.From("auth_logs")
if entityType == "service" {
sb.Where(sb.Equal("service_id", entityID))
} else if entityType == "user" {
sb.Where(sb.Equal("user_id", entityID))
}
sb.Where(sb.Equal(`org_id`, orgID))
sb.Select(`count(*)`, `user_ip`)
sb.GroupBy(`user_ip`)
sb.OrderBy(`user_ip`)
switch statusFilter {
case "Success":
sb.Where(sb.Equal(`status`, true))
case "Failed":
sb.Where(sb.Equal(`status`, false))
}
*sb = addTimeFilter(timeFilter, now, *sb)
sqlStr, args := sb.BuildWithFlavor(sqlbuilder.PostgreSQL)
rows, err := s.DB.Query(sqlStr, args...)
if err != nil {
return ippool, err
}
//TODO move this logic outside
var tmpArr []ipcount
for rows.Next() {
var tmp ipcount
err = rows.Scan(&tmp.Count, &tmp.IP)
if err != nil {
return ippool, err
}
tmpArr = append(tmpArr, tmp)
}
ippool.Children = sortIps(tmpArr)
ippool.Name = "TRASA"
return ippool, nil
}
type ipcount struct {
Count int
IP string
}
func sortIps(arr []ipcount) []firstOctet {
var firstOctets = make([]firstOctet, 0)
for _, t := range arr {
var temp1, temp2, temp3, temp4 string
userIP := t.IP
count := t.Count
splitted := strings.Split(userIP, ".")
if len(splitted) != 4 {
continue
}
temp1 = splitted[0]
temp2 = splitted[1]
temp3 = splitted[2]
temp4 = splitted[3]
fourth := fourthOctet{Key: temp4, Value: count, Name: temp1 + "." + temp2 + "." + temp3 + "." + temp4}
third := thirdOctet{Key: temp3, Name: temp1 + "." + temp2 + "." + temp3 + ".0/24"}
second := secondOctet{Key: temp2, Name: temp1 + "." + temp2 + ".0.0/16"}
first := firstOctet{Key: temp1, Name: temp1 + ".0.0.0/8"}
firstOctetEndIndex := len(firstOctets) - 1
if (len(firstOctets) == 0) || (firstOctets[firstOctetEndIndex].Key != first.Key) {
third.Children = append(third.Children, fourth)
second.Children = append(second.Children, third)
first.Children = append(first.Children, second)
firstOctets = append(firstOctets, first)
continue
}
secondOctetEndIndex := len(firstOctets[firstOctetEndIndex].Children) - 1
if firstOctets[firstOctetEndIndex].Children[secondOctetEndIndex].Key != second.Key {
third.Children = append(third.Children, fourth)
second.Children = append(second.Children, third)
firstOctets[firstOctetEndIndex].Children = append(firstOctets[firstOctetEndIndex].Children, second)
continue
}
thirdOctetEndIndex := len(firstOctets[firstOctetEndIndex].Children[secondOctetEndIndex].Children) - 1
if firstOctets[firstOctetEndIndex].Children[secondOctetEndIndex].Children[thirdOctetEndIndex].Key != third.Key {
third.Children = append(third.Children, fourth)
firstOctets[firstOctetEndIndex].Children[secondOctetEndIndex].Children = append(firstOctets[firstOctetEndIndex].Children[secondOctetEndIndex].Children, third)
continue
}
fourthOctetEndIndex := len(firstOctets[firstOctetEndIndex].Children[secondOctetEndIndex].Children[thirdOctetEndIndex].Children) - 1
if firstOctets[firstOctetEndIndex].Children[secondOctetEndIndex].Children[thirdOctetEndIndex].Children[fourthOctetEndIndex].Key != fourth.Key {
firstOctets[firstOctetEndIndex].Children[secondOctetEndIndex].Children[thirdOctetEndIndex].Children = append(firstOctets[firstOctetEndIndex].Children[secondOctetEndIndex].Children[thirdOctetEndIndex].Children, fourth)
continue
}
}
return firstOctets
}
func (s statStore) GetLoginsByType(entityType, entityID, orgID, timezone, timeFilter, statusFilter string) (logins []nameValue, err error) {
logins = make([]nameValue, 0)
loc, err := time.LoadLocation(timezone)
if err != nil {
return logins, err
}
now := time.Now().In(loc)
sb := sqlbuilder.NewSelectBuilder()
sb.Select(`count(*)`, `COALESCE(service_type,'Other')`)
sb.From("auth_logs")
if entityType == "service" {
sb.Where(sb.Equal("service_id", entityID))
} else if entityType == "user" {
sb.Where(sb.Equal("user_id", entityID))
}
if statusFilter == "success" {
sb.Where(sb.Equal("status", true))
} else if statusFilter == "failed" {
sb.Where(sb.Equal("status", false))
}
sb.Where(sb.Equal(`org_id`, orgID))
sb.GroupBy(`service_type`)
*sb = addTimeFilter(timeFilter, now, *sb)
sqlStr, args := sb.BuildWithFlavor(sqlbuilder.PostgreSQL)
rows, err := s.DB.Query(sqlStr, args...)
//rows, err := s.DB.Query(`select count(*),failed_reason from auth_logs where status=false AND org_id=$1 GROUP BY failed_reason ORDER BY failed_reason`, orgID)
if err != nil {
return logins, err
}
//TODO separate function
for rows.Next() {
var reason nameValue
err = rows.Scan(&reason.Value, &reason.Name)
if err != nil {
return logins, err
}
logins = append(logins, reason)
}
out:
for _, typ := range []string{"rdp", "ssh", "db", "dashboard", "http"} {
for _, l := range logins {
if l.Name == typ {
continue out
}
}
logins = append(logins, nameValue{Name: typ, Value: 0})
}
return logins, err
}
func (s statStore) SortLoginByCity(entityType, entityID, orgID, timezone, timeFilter, statusFilter string) ([]geoDataType, error) {
var dat geoDataType
var docs []geoDataType = make([]geoDataType, 0)
loc, err := time.LoadLocation(timezone)
if err != nil {
return docs, err
}
now := time.Now().In(loc)
sb := sqlbuilder.NewSelectBuilder()
sb.From("auth_logs")
if entityType == "service" {
sb.Where(sb.Equal("service_id", entityID))
} else if entityType == "user" {
sb.Where(sb.Equal("user_id", entityID))
}
sb.Where(sb.Equal(`org_id`, orgID))
sb.Select(`count(*)`, `user_ip`)
sb.GroupBy(`user_ip`)
sb.OrderBy(`user_ip`)
switch statusFilter {
case "Success":
sb.Where(sb.Equal(`status`, true))
case "Failed":
sb.Where(sb.Equal(`status`, false))
}
*sb = addTimeFilter(timeFilter, now, *sb)
sqlStr, args := sb.BuildWithFlavor(sqlbuilder.PostgreSQL)
rows, err := s.DB.Query(sqlStr, args...)
if err != nil {
return nil, err
}
for rows.Next() {
var ipStr string
var count int64
err := rows.Scan(&count, &ipStr)
if err != nil {
return docs, err
}
ip := net.ParseIP(ipStr)
if utils.IsPrivateIP(ip) == false {
loc, err := misc.Store.GetGeoLocation(ipStr)
if err != nil {
logrus.Debugf("get geo location: %v", err)
continue
}
//country, city, coordinates := loc.
dat.Name = loc.Country
dat.City = loc.City
dat.Value = count
dat.Coordinates = loc.Location
docs = append(docs, dat)
}
}
return docs, err
//docsStr, err := json.Marshal(docs)
//return string(docsStr), err
}
func (s statStore) GetAllAuthEventsByEntityType(entityType, entityID, timeFilter, timezone string) (totalEventsAuthEvents, error) {
var events totalEventsAuthEvents
// events.TotalLogins = &new(int64)
// events.successfulogins = new(int64)
// events.FailedLogins = new(int64)
loc, err := time.LoadLocation(timezone)
if err != nil {
return events, err
}
now := time.Now().In(loc)
sb := sqlbuilder.NewSelectBuilder()
sb.Select("count(status)", "status")
sb.From("auth_logs")
if entityType == "service" {
sb.Where(sb.Equal("service_id", entityID))
} else if entityType == "user" {
sb.Where(sb.Equal("user_id", entityID))
}
*sb = addTimeFilter(timeFilter, now, *sb)
sb.GroupBy("status")
sqlStr, args := sb.BuildWithFlavor(sqlbuilder.PostgreSQL)
rows, err := s.DB.Query(sqlStr, args...)
if err != nil {
return events, err
}
defer rows.Close()
for rows.Next() {
var count int64
var status bool
err = rows.Scan(&count, &status)
if err != nil {
return events, err
}
if status {
events.SuccessfulLogins = count
} else if !status {
events.FailedLogins = count
}
}
events.TotalLogins = events.SuccessfulLogins + events.FailedLogins
return events, err
}
func (s statStore) GetTodayHexaLoginEvents(entityType, entityID, orgID, statusFilter, timezone string) ([]todayHexa, error) {
var hexas = make([]todayHexa, 0)
loc, err := time.LoadLocation(timezone)
if err != nil {
return hexas, err
}
now := time.Now().In(loc)
todayStart := now.Add(-time.Hour*time.Duration(now.Hour()) - time.Minute*time.Duration(now.Minute()))
sb := sqlbuilder.NewSelectBuilder()
sb.From("auth_logs")
if entityType == "service" {
sb.Where(sb.Equal("service_id", entityID))
} else if entityType == "user" {
sb.Where(sb.Equal("user_id", entityID))
}
sb.Where(sb.Equal(`org_id`, orgID))
sb.Select(`org_id`, `email`, `service_name`, `service_id`, `login_time`, `status`)
sb.Where(sb.GreaterThan(`login_time`, todayStart.UnixNano()))
switch statusFilter {
case "Success":
sb.Where(sb.Equal(`status`, true))
case "Failed":
sb.Where(sb.Equal(`status`, false))
}
sqlStr, args := sb.BuildWithFlavor(sqlbuilder.PostgreSQL)
rows, err := s.DB.Query(sqlStr, args...)
if err != nil {
return hexas, err
}
for rows.Next() {
var hexa todayHexa
//var loginTime int64
err := rows.Scan(&hexa.OrgID, &hexa.User, &hexa.AppName, &hexa.serviceID, &hexa.LoginTime, &hexa.Status)
if err != nil {
return hexas, err
}
hexas = append(hexas, hexa)
}
return hexas, nil
}
// GetTotalLoginsByDate generates time range based on current time and delta (start time for organization)
// and returns json array of total login events per day.
func (s statStore) GetTotalLoginsByDate(entityType, entityID, orgID, timezone string) ([]totalEventsByDate, error) {
var events []totalEventsByDate
loc, err := time.LoadLocation(timezone)
if err != nil {
return events, err
}
now := time.Now().In(loc)
limitTime := now.Add(-time.Hour * 24 * 46)
var rows *sql.Rows
if entityType == "service" {
rows, err = s.DB.Query(`select count(*) as c,
login_day,
sum(case when status then 1 else 0 end) as success,
sum(case when status then 0 else 1 end) as fail
from (
SELECT floor(login_time/86400000000000) as login_day ,status from auth_logs WHERE login_time>$1 AND org_id=$2 AND service_id=$3
)
GROUP BY login_day ORDER BY login_day DESC LIMIT 45;`, limitTime.UnixNano(), orgID, entityID)
} else if entityType == "user" {
rows, err = s.DB.Query(`select count(*) as c,
login_day,
sum(case when status then 1 else 0 end) as success,
sum(case when status then 0 else 1 end) as fail
from (
SELECT floor(login_time/86400000000000) as login_day ,status from auth_logs WHERE login_time>$1 AND org_id=$2 AND service_id=$3
)
GROUP BY login_day ORDER BY login_day DESC LIMIT 45;`, limitTime.UnixNano(), orgID, entityID)
} else {
rows, err = s.DB.Query(`select count(*) as c,
login_day,
sum(case when status then 1 else 0 end) as success,
sum(case when status then 0 else 1 end) as fail
from (
SELECT floor(login_time/86400000000000) as login_day ,status from auth_logs WHERE login_time>$1 AND org_id=$2
)
GROUP BY login_day ORDER BY login_day DESC LIMIT 45;`, limitTime.UnixNano(), orgID)
}
if err != nil {
return events, err
}
var nextDay int64 = 0
for rows.Next() {
var event totalEventsByDate
var day int64
err = rows.Scan(&event.TotalLogins, &day, &event.SuccessfulLogins, &event.FailedLogins)
if err != nil {
return events, err
}
//TODO move this logic to different testable function
event.Date = time.Unix(0, day*86400000000000).In(loc).Format(time.RFC3339)
event.TotalLogins = event.SuccessfulLogins + event.FailedLogins
//Filling Missing days
if nextDay != 0 {
gap := nextDay - day - 1
// logger.Trace(gap)
for i := gap; i > 0; i-- {
events = append(events, totalEventsByDate{
Date: time.Unix(0, (day+i)*86400000000000).In(loc).Format(time.RFC3339),
TotalLogins: 0,
SuccessfulLogins: 0,
FailedLogins: 0,
})
}
}
events = append(events, event)
nextDay = day
}
return events, err
}
func (s statStore) GetRemoteAppCount(entityType, entityID, orgID, timezone, timeFilter, statusFilter string) (count int, err error) {
loc, err := time.LoadLocation(timezone)
if err != nil {
return count, err
}
now := time.Now().In(loc)
sb := sqlbuilder.NewSelectBuilder()
sb.Select(`count(*)`)
sb.From("auth_logs")
if entityType == "service" {
sb.Where(sb.Equal("service_id", entityID))
} else if entityType == "user" {
sb.Where(sb.Equal("user_id", entityID))
}
if statusFilter == "success" {
sb.Where(sb.Equal("status", true))
} else if statusFilter == "failed" {
sb.Where(sb.Equal("status", false))
}
sb.Where(sb.Equal(`org_id`, orgID))
sb.Where(sb.Equal(`endpoint`, "remoteApp"))
sb.Where(sb.Equal(`service_type`, "rdp"))
*sb = addTimeFilter(timeFilter, now, *sb)
sqlStr, args := sb.BuildWithFlavor(sqlbuilder.PostgreSQL)
err = s.DB.QueryRow(sqlStr, args...).Scan(&count)
//rows, err := s.DB.Query(`select count(*),failed_reason from orgloginsv1 where status=false AND org_id=$1 GROUP BY failed_reason ORDER BY failed_reason`, orgID)
if err != nil {
return count, err
}
return count, err
}