-
Notifications
You must be signed in to change notification settings - Fork 22
/
detection.go
974 lines (821 loc) · 25.9 KB
/
detection.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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
package shuffle
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"errors"
"sort"
"strings"
"time"
uuid "github.com/satori/go.uuid"
"gopkg.in/yaml.v2"
)
func HandleGetDetectionRules(resp http.ResponseWriter, request *http.Request) {
cors := HandleCors(resp, request)
if cors {
return
}
user, err := HandleApiAuthentication(resp, request)
if err != nil {
log.Printf("[WARNING] Api authentication failed in get detection rules: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
// Extract detection_type
location := strings.Split(request.URL.String(), "/")
if len(location) < 5 {
log.Printf("[WARNING] Path too short: %d", len(location))
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
detectionType := strings.ToLower(location[4])
log.Printf("[AUDIT] User '%s' (%s) is trying to get detections from namespace %#v", user.Username, user.Id, detectionType)
ctx := GetContext(request)
files, err := GetAllFiles(ctx, user.ActiveOrg.Id, detectionType)
if err != nil && len(files) == 0 {
log.Printf("[ERROR] Failed to get files: %s", err)
resp.WriteHeader(500)
resp.Write([]byte(`{"success": false, "reason": "Error getting files."}`))
return
}
log.Printf("[DEBUG] Loaded %d files for user %s from namespace %s", len(files), user.Username, detectionType)
disabledRules, err := GetDisabledRules(ctx, user.ActiveOrg.Id)
if err != nil && err.Error() != "rules doesn't exist" {
log.Printf("[ERROR] Failed to get disabled rules: %s", err)
//resp.WriteHeader(500)
//resp.Write([]byte(`{"success": false, "reason": "Error getting disabled rules."}`))
//return
}
sort.Slice(files[:], func(i, j int) bool {
return files[i].UpdatedAt > files[j].UpdatedAt
})
var sigmaFileInfo []DetectionFileInfo
for _, file := range files {
if file.OrgId != user.ActiveOrg.Id {
continue
}
var fileContent []byte
if file.Encrypted {
if project.Environment == "cloud" || file.StorageArea == "google_storage" {
log.Printf("[ERROR] No namespace handler for cloud decryption (detection)!")
//continue
} else {
Openfile, err := os.Open(file.DownloadPath)
if err != nil {
log.Printf("[ERROR] Failed to open file %s: %s", file.Filename, err)
continue
}
defer Openfile.Close()
allText := []byte{}
buf := make([]byte, 1024)
for {
n, err := Openfile.Read(buf)
if err == io.EOF {
break
}
if err != nil {
log.Printf("[ERROR] Failed to read file %s: %s", file.Filename, err)
continue
}
if n > 0 {
allText = append(allText, buf[:n]...)
}
}
passphrase := fmt.Sprintf("%s_%s", user.ActiveOrg.Id, file.Id)
if len(file.ReferenceFileId) > 0 {
passphrase = fmt.Sprintf("%s_%s", user.ActiveOrg.Id, file.ReferenceFileId)
}
decryptedData, err := HandleKeyDecryption(allText, passphrase)
if err != nil {
log.Printf("[ERROR] Failed decrypting file %s: %s", file.Filename, err)
continue
}
fileContent = []byte(decryptedData)
}
} else {
fileContent, err = ioutil.ReadFile(file.DownloadPath)
if err != nil {
log.Printf("[ERROR] Failed to read file %s: %s", file.Filename, err)
continue
}
}
var rule DetectionFileInfo
err = yaml.Unmarshal(fileContent, &rule)
if err != nil {
log.Printf("[ERROR] Failed to parse YAML file %s: %s", file.Filename, err)
continue
}
isDisabled := disabledRules.DisabledFolder
found := false
if isDisabled {
rule.IsEnabled = false
} else {
for _, disabledFile := range disabledRules.Files {
if disabledFile.Id == file.Id {
found = true
break
}
}
if found {
rule.IsEnabled = false
} else {
rule.IsEnabled = true
}
}
rule.FileId = file.Id
rule.FileName = strings.Trim(file.Filename, ".yml")
sigmaFileInfo = append(sigmaFileInfo, rule)
}
var isTenzirAlive bool
if time.Now().Unix() > disabledRules.LastActive+10 {
isTenzirAlive = false
} else {
isTenzirAlive = true
}
response := DetectionResponse{
DetectionName: detectionType,
Category: "",
OrgId: user.ActiveOrg.Id,
DetectionInfo: sigmaFileInfo,
FolderDisabled: disabledRules.DisabledFolder,
IsConnectorActive: isTenzirAlive,
}
detections := GetPublicDetections()
for _, detection := range detections {
if strings.ToLower(detection.DetectionName) != strings.ToLower(response.DetectionName) {
continue
}
response.Title = detection.Title
response.Category = detection.Category
response.DownloadRepo = detection.DownloadRepo
break
}
responseData, err := json.Marshal(response)
if err != nil {
log.Printf("[ERROR] Failed to marshal response data: %s", err)
resp.WriteHeader(500)
resp.Write([]byte(`{"success": false, "reason": "Error processing rules."}`))
return
}
resp.WriteHeader(200)
resp.Write(responseData)
}
func HandleToggleRule(resp http.ResponseWriter, request *http.Request) {
cors := HandleCors(resp, request)
if cors {
return
}
var fileId string
location := strings.Split(request.URL.String(), "/")
if location[1] == "api" {
if len(location) <= 4 {
log.Printf("Path too short: %d", len(location))
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
fileId = location[5]
}
ctx := GetContext(request)
if len(fileId) != 36 && !strings.HasPrefix(fileId, "file_") {
log.Printf("[WARNING] Bad format for fileId %s", fileId)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Badly formatted fileId"}`))
return
}
user, err := HandleApiAuthentication(resp, request)
if err != nil {
log.Printf("[WARNING] Api authentication failed in toggle rule: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
file, err := GetFile(ctx, fileId)
if err != nil {
log.Printf("[ERROR] File %s not found: %s", fileId, err)
resp.WriteHeader(400)
resp.Write([]byte(`{"success": false, "reason": "File not found"}`))
return
}
if user.Role == "org-reader" {
log.Printf("[WARNING] Org-reader doesn't have access to delete files: %s (%s)", user.Username, user.Id)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Read only user"}`))
return
}
var action string
switch location[6] {
case "disable_rule":
action = "disable"
case "enable_rule":
action = "enable"
default:
log.Printf("[WARNING] path not found: %s", location[6])
resp.WriteHeader(404)
resp.Write([]byte(`{"success": false, "message": "The URL doesn't exist or is not allowed."}`))
return
}
if action == "disable" {
err := disableRule(*file)
if err != nil {
log.Printf("[ERROR] Failed to %s file", action)
resp.WriteHeader(500)
resp.Write([]byte(`{"success": false}`))
return
}
} else if action == "enable" {
err := enableRule(*file)
if err != nil {
if err.Error() != "rules doesn't exist" {
log.Printf("[ERROR] Failed to %s file, reason: %s", action, err)
resp.WriteHeader(404)
resp.Write([]byte(`{"success": false}`))
return
} else {
log.Printf("[ERROR] Failed to %s file, reason: %s", action, err)
resp.WriteHeader(500)
resp.Write([]byte(`{"success": false}`))
return
}
}
}
var execType string
if action == "disable" {
execType = "DISABLE_SIGMA_FILE"
} else if action == "enable" {
execType = "ENABLE_SIGMA_FILE"
}
err = SetDetectionOrborusRequest(ctx, user.ActiveOrg.Id, execType, file.Filename, "SIGMA", "SHUFFLE_DISCOVER")
if err != nil {
log.Printf("[ERROR] Failed setting workflow queue for env: %s", err)
resp.WriteHeader(500)
resp.Write([]byte(`{"success": false}`))
return
}
resp.WriteHeader(200)
resp.Write([]byte((`{"success": true}`)))
}
func HandleFolderToggle(resp http.ResponseWriter, request *http.Request) {
cors := HandleCors(resp, request)
if cors {
return
}
user, err := HandleApiAuthentication(resp, request)
if err != nil {
log.Printf("[WARNING] Api authentication failed in toggle folder: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
if user.Role == "org-reader" {
log.Printf("[WARNING] Org-reader doesn't have access to toggle folder: %s (%s)", user.Username, user.Id)
resp.WriteHeader(403)
resp.Write([]byte(`{"success": false, "reason": "Read only user"}`))
return
}
location := strings.Split(request.URL.String(), "/")
if location[1] != "api" || len(location) < 6 {
log.Printf("Path too short or incorrect: %s", request.URL.String())
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
ctx := GetContext(request)
action := location[5]
rules, err := GetDisabledRules(ctx, user.ActiveOrg.Id)
if err != nil {
log.Printf("[WARNING] Cannot get the rules, reason %s", err)
resp.WriteHeader(404)
resp.Write([]byte(`{"success": false}`))
return
}
if action == "disable_folder" {
rules.DisabledFolder = true
} else if action == "enable_folder" {
rules.DisabledFolder = false
} else {
log.Printf("[WARNING] path not found: %s", action)
resp.WriteHeader(404)
resp.Write([]byte(`{"success": false, "message": "The URL doesn't exist or is not allowed."}`))
return
}
err = StoreDisabledRules(ctx, *rules)
if err != nil {
log.Printf("[ERROR] Failed to store disabled rules: %s", err)
resp.WriteHeader(500)
resp.Write([]byte(`{"success": false}`))
return
}
var execType string
if action == "disable_folder" {
execType = "DISABLE_SIGMA_FOLDER"
} else {
execType = "CATEGORY_UPDATE"
}
err = SetDetectionOrborusRequest(ctx, user.ActiveOrg.Id, execType, "", "SIGMA", "SHUFFLE_DISCOVER")
if err != nil {
log.Printf("[ERROR] Failed setting workflow queue for env: %s", err)
resp.WriteHeader(500)
resp.Write([]byte(`{"success": false}`))
return
}
resp.WriteHeader(200)
resp.Write([]byte(`{"success": true}`))
}
func disableRule(file File) error {
ctx := context.Background()
resp, err := GetDisabledRules(ctx, file.OrgId)
if err != nil {
if err.Error() == "rules doesn't exist" {
// FIX ME :- code duplication : (
disabRules := &DisabledRules{}
disabRules.Files = append(disabRules.Files, file)
err = StoreDisabledRules(ctx, *disabRules)
if err != nil {
return err
}
log.Printf("[INFO] file with ID %s is disabled successfully", file.Id)
return nil
} else {
return err
}
}
resp.Files = append(resp.Files, file)
err = StoreDisabledRules(ctx, *resp)
if err != nil {
return err
}
log.Printf("[INFO] file with ID %s is disabled successfully", file.Id)
return nil
}
func enableRule(file File) error {
ctx := context.Background()
resp, err := GetDisabledRules(ctx, file.OrgId)
if err != nil {
return err
}
// Check if resp.Files is empty
if len(resp.Files) == 0 {
log.Printf("[INFO] No disabled rules found.")
return nil
}
found := false
for i, innerFile := range resp.Files {
if innerFile.Id == file.Id {
resp.Files = append(resp.Files[:i], resp.Files[i+1:]...)
found = true
break
}
}
if !found {
log.Printf("[INFO] File with ID %s not found in disabled rules", file.Id)
return nil
}
err = StoreDisabledRules(ctx, *resp)
if err != nil {
return err
}
log.Printf("[INFO] File with ID %s is enabled successfully", file.Id)
return nil
}
func HandleGetSelectedRules(resp http.ResponseWriter, request *http.Request) {
cors := HandleCors(resp, request)
if cors {
return
}
_, err := HandleApiAuthentication(resp, request)
if err != nil {
log.Printf("[WARNING] Api authentication failed in get env stats executions: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
var triggerId string
location := strings.Split(request.URL.String(), "/")
if len(location) < 5 || location[1] != "api" {
log.Printf("[INFO] Path too short or incorrect: %d", len(location))
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
triggerId = location[4]
selectedRules, err := GetSelectedRules(request.Context(), triggerId)
if err != nil {
if err.Error() != "rules doesnt exists" {
log.Printf("[ERROR] Error getting selected rules for %s: %s", triggerId, err)
resp.WriteHeader(http.StatusInternalServerError)
resp.Write([]byte(`{"success": false}`))
return
}
}
responseData, err := json.Marshal(selectedRules)
if err != nil {
log.Printf("[ERROR] Failed to marshal response data: %s", err)
resp.WriteHeader(500)
resp.Write([]byte(`{"success": false"}`))
return
}
resp.WriteHeader(200)
resp.Write(responseData)
}
func HandleSaveSelectedRules(resp http.ResponseWriter, request *http.Request) {
cors := HandleCors(resp, request)
if cors {
return
}
user, err := HandleApiAuthentication(resp, request)
if err != nil {
log.Printf("[WARNING] Api authentication failed in save selected rules: %s", err)
resp.WriteHeader(http.StatusUnauthorized)
resp.Write([]byte(`{"success": false}`))
return
}
if user.Role == "org-reader" {
log.Printf("[WARNING] Org-reader doesn't have access to save rules: %s (%s)", user.Username, user.Id)
resp.WriteHeader(http.StatusForbidden)
resp.Write([]byte(`{"success": false, "reason": "Read only user"}`))
return
}
location := strings.Split(request.URL.String(), "/")
if len(location) < 5 || location[1] != "api" {
log.Printf("[INFO] Path too short or incorrect: %d", len(location))
resp.WriteHeader(http.StatusBadRequest)
resp.Write([]byte(`{"success": false}`))
return
}
triggerId := location[4]
selectedRules := SelectedDetectionRules{}
decoder := json.NewDecoder(request.Body)
err = decoder.Decode(&selectedRules)
if err != nil {
log.Printf("[ERROR] Failed to decode request body: %s", err)
resp.WriteHeader(http.StatusBadRequest)
resp.Write([]byte(`{"success": false, "reason": "Invalid request body"}`))
return
}
err = StoreSelectedRules(request.Context(), triggerId, selectedRules)
if err != nil {
log.Printf("[ERROR] Error storing selected rules for %s: %s", triggerId, err)
resp.WriteHeader(http.StatusInternalServerError)
resp.Write([]byte(`{"success": false}`))
return
}
responseData, err := json.Marshal(selectedRules)
if err != nil {
log.Printf("[ERROR] Failed to marshal response data: %s", err)
resp.WriteHeader(http.StatusInternalServerError)
resp.Write([]byte(`{"success": false}`))
return
}
resp.WriteHeader(http.StatusOK)
resp.Write(responseData)
}
// FIXME: Should be generic - not just for SIEM/Sigma
// E.g. try for Email/Sublime
func HandleDetectionAutoConnect(resp http.ResponseWriter, request *http.Request) {
cors := HandleCors(resp, request)
if cors {
return
}
user, err := HandleApiAuthentication(resp, request)
if err != nil {
log.Printf("[WARNING] Api authentication failed in conenct siem: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
if user.Role == "org-reader" {
resp.WriteHeader(403)
resp.Write([]byte(`{"success": false, "reason": "Org reader does not have permission to connect to SIEM"}`))
return
}
// Check if url is /api/v1/detections/siem/
location := strings.Split(request.URL.String(), "/")
if len(location) < 5 {
log.Printf("[WARNING] Path too short: %d", len(location))
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
detectionType := strings.ToLower(location[4])
log.Printf("[DEBUG] Validating if the org %s (%s) has a %s sandbox handling workflow/system", user.ActiveOrg.Name, user.ActiveOrg.Id, detectionType)
log.Printf("[AUDIT] User '%s' (%s) is trying to detection-connect to %s", user.Username, user.Id, strings.ToUpper(detectionType))
workflow := Workflow{}
if detectionType == "siem" {
ctx := GetContext(request)
workflow, err = ConfigureDetectionWorkflow(ctx, user.ActiveOrg.Id, "TENZIR-SIGMA")
if err != nil {
log.Printf("\n\n\n[ERROR] Failed to create Sigma handling workflow: %s\n\n\n", err)
}
log.Printf("[DEBUG] Sending orborus request to start Sigma handling workflow")
execType := "START_TENZIR"
err = SetDetectionOrborusRequest(ctx, user.ActiveOrg.Id, execType, "", "SIGMA", "SHUFFLE_DISCOVER")
if err != nil {
if strings.Contains(strings.ToLower(err.Error()), "must be started") {
resp.WriteHeader(200)
resp.Write([]byte(`{"success": true, "reason": "Please start the environment by running the relevant command.", "action": "environment_start"}`))
return
}
log.Printf("[ERROR] Failed setting workflow queue for env: %s", err)
if strings.Contains(strings.ToLower(err.Error()), "no valid environments") {
resp.WriteHeader(400)
resp.Write([]byte(`{"success": false, "reason": "No valid environments found. Go to /admin?tab=environments to create one.", "action": "environment_create"}`))
return
}
resp.WriteHeader(500)
resp.Write([]byte(`{"success": false}`))
return
}
} else if detectionType == "email" {
// FIXME:
// 1. Can we track if it's active based on a workflow + validation?
// 2. The workflow should get email
// 3. It should track unread AND read emails separately
// 4. When a new email is received, we should automatically track the statistics for it
ctx := GetContext(request)
workflow, err = ConfigureDetectionWorkflow(ctx, user.ActiveOrg.Id, "EMAIL-DETECTION")
if err != nil {
log.Printf("\n\n\n[ERROR] Failed to create email handling workflow: %s\n\n\n", err)
resp.WriteHeader(500)
resp.Write([]byte(`{"success": false, "reason": "Failed to create email handling workflow. Please try again or contact [email protected]"}`))
return
}
} else {
resp.WriteHeader(400)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Detection Type '%s' not implemented"}`, detectionType)))
return
}
success := true
if len(workflow.ID) == 0 {
success = false
}
log.Printf("[INFO] '%s' detection workflow in org '%s' ID: %s", detectionType, workflow.OrgId, workflow.ID)
resp.WriteHeader(200)
resp.Write([]byte(fmt.Sprintf(`{"success": %v, "workflow_id": "%s", "workflow_valid": %v}`, success, workflow.ID, workflow.Validation.Valid)))
}
func SetDetectionOrborusRequest(ctx context.Context, orgId, execType, fileName, executionSource, environmentName string) error {
if len(orgId) == 0 {
return fmt.Errorf("No org ID provided")
}
environments, err := GetEnvironments(ctx, orgId)
if err != nil {
log.Printf("[ERROR] Failed to get environments: %s", err)
return err
}
lakeNodes := 0
selectedEnvironments := []Environment{}
for _, env := range environments {
if env.Archived {
continue
}
if env.Type == "cloud" {
continue
}
if env.Name != environmentName && environmentName != "SHUFFLE_DISCOVER" {
continue
}
cacheKey := fmt.Sprintf("queueconfig-%s-%s", env.Name, env.OrgId)
cache, err := GetCache(ctx, cacheKey)
if err == nil {
newEnv := OrborusStats{}
err = json.Unmarshal(cache.([]uint8), &newEnv)
if err == nil {
// No point in adding a job if the lake is already running
if env.DataLake.Enabled && execType == "START_TENZIR" {
lakeNodes += 1
continue
}
}
}
selectedEnvironments = append(selectedEnvironments, env)
}
if len(selectedEnvironments) == 0 {
if lakeNodes > 0 {
//log.Printf("[ERROR] No environments needing a lake. Found lake nodes: %d", lakeNodes)
return nil
} else {
return fmt.Errorf("No valid environments found")
}
}
log.Printf("[DEBUG] Found %d potentially valid environment(s)", len(selectedEnvironments))
deployedToActiveEnv := false
for _, env := range selectedEnvironments {
execRequest := ExecutionRequest{
Type: execType,
ExecutionId: uuid.NewV4().String(),
ExecutionSource: executionSource,
ExecutionArgument: fileName,
Priority: 11,
}
parsedEnv := fmt.Sprintf("%s_%s", strings.ToLower(strings.ReplaceAll(strings.ReplaceAll(env.Name, " ", "-"), "_", "-")), orgId)
if project.Environment != "cloud" {
parsedEnv = strings.ToLower(strings.ReplaceAll(strings.ReplaceAll(env.Name, " ", "-"), "_", "-"))
}
err = SetWorkflowQueue(ctx, execRequest, parsedEnv)
if err != nil {
log.Printf("[ERROR] Failed to set workflow queue: %s", err)
return err
} else {
if env.RunningIp != "" {
deployedToActiveEnv = true
}
}
}
if !deployedToActiveEnv {
return errors.New("This environment must be started first. Please start the environment by running it onprem")
}
go DeleteCache(ctx, fmt.Sprintf("environments_%s", orgId))
return nil
}
func HandleListDetectionCategories(resp http.ResponseWriter, request *http.Request) {
cors := HandleCors(resp, request)
if cors {
return
}
/*
user, err := HandleApiAuthentication(resp, request)
if err != nil {
log.Printf("[WARNING] Api authentication failed in get detection rules: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
*/
publicDetections := GetPublicDetections()
data, err := json.Marshal(publicDetections)
if err != nil {
resp.WriteHeader(500)
resp.Write([]byte(fmt.Sprintf(`{"success": false}`)))
return
}
resp.WriteHeader(200)
resp.Write(data)
}
func ConfigureDetectionWorkflow(ctx context.Context, orgId, workflowType string) (Workflow, error) {
log.Printf("\n\n[DEBUG] Creating detection workflow for org %s (not implemented)\n\n", orgId)
/*
// FIXME: Use Org to find the correct tools according to the Usecase
// SHOULD map usecase from workflowType -> actual Usecase in blobs
foundOrg, err := GetOrg(ctx, orgId)
if err != nil {
log.Printf("[ERROR] Failed to get org '%s' during detection workflow creation: %s", err)
return err
}
*/
user := User{
Role: "admin",
ActiveOrg: OrgMini{
Id: orgId,
},
}
workflows, err := GetAllWorkflowsByQuery(ctx, user, 250, "")
if err != nil && len(workflows) == 0 {
log.Printf("[ERROR] Failed to loading workflows to validate email: %s", err)
return Workflow{}, err
}
workflow := Workflow{}
workflowValid := false
for _, foundworkflow := range workflows {
if foundworkflow.WorkflowType != workflowType {
continue
}
if foundworkflow.Validation.Valid {
workflowValid = true
}
workflow = foundworkflow
break
}
_ = workflowValid
if len(workflow.ID) > 0 {
return workflow, nil
}
workflow = Workflow{
WorkflowType: workflowType,
Actions: []Action{},
Triggers: []Trigger{},
}
// Do this based on public workflows
cloudWorkflowId := ""
usecaseNames := []string{}
if workflowType == "TENZIR-SIGMA" {
log.Printf("[INFO] Creating SIEM handling workflow for org %s", orgId)
} else if workflowType == "EMAIL-DETECTION" {
// How do we check what email tool they use?
//log.Printf("[INFO] Creating email handling workflow for org %s", orgId)
cloudWorkflowId = "31d1a492-9fe0-4c4a-807d-b44d9cb81fc0"
usecaseNames = []string{"Search emails (Sublime)"}
}
if len(cloudWorkflowId) == 0 {
return workflow, errors.New("No valid workflow found")
}
// Load it in from cloud with a normal GET request
url := fmt.Sprintf("https://shuffler.io/api/v1/workflows/%s", cloudWorkflowId)
client := GetExternalClient(url)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Printf("[ERROR] Failed to create request for workflow: %s", err)
return workflow, err
}
resp, err := client.Do(req)
if err != nil {
log.Printf("[ERROR] Failed to get workflow from cloud: %s", err)
return workflow, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
log.Printf("[ERROR] Failed to get workflow from cloud: %s", resp.Status)
return workflow, errors.New("Failed to get workflow from cloud")
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("[ERROR] Failed to read response body: %s", err)
return workflow, err
}
err = json.Unmarshal(body, &workflow)
if err != nil {
log.Printf("[ERROR] Failed to unmarshal response body: %s", err)
return workflow, err
}
// Clear out and reset IDs
workflow.Created = time.Now().Unix()
workflow.ID = uuid.NewV4().String()
workflow.OrgId = orgId
workflow.Org = []OrgMini{
OrgMini{
Id: orgId,
},
}
workflow.ExecutingOrg = OrgMini{
Id: orgId,
}
workflow.Public = false
workflow.WorkflowType = workflowType
workflow.Validation = TypeValidation{}
for _, usecaseName := range usecaseNames {
workflow.UsecaseIds = append(workflow.UsecaseIds, usecaseName)
}
workflow.ParentWorkflowId = ""
for actionIndex, _ := range workflow.Actions {
newId := uuid.NewV4().String()
if workflow.Start == workflow.Actions[actionIndex].ID {
workflow.Start = newId
}
for branchIndex, _ := range workflow.Branches {
if workflow.Actions[actionIndex].ID == workflow.Branches[branchIndex].SourceID {
workflow.Branches[branchIndex].SourceID = newId
}
if workflow.Actions[actionIndex].ID == workflow.Branches[branchIndex].DestinationID {
workflow.Branches[branchIndex].DestinationID = newId
}
}
workflow.Actions[actionIndex].ID = newId
}
for triggerIndex, _ := range workflow.Triggers {
newId := uuid.NewV4().String()
for branchIndex, _ := range workflow.Branches {
if workflow.Triggers[triggerIndex].ID == workflow.Branches[branchIndex].SourceID {
workflow.Branches[branchIndex].SourceID = newId
}
if workflow.Triggers[triggerIndex].ID == workflow.Branches[branchIndex].DestinationID {
workflow.Branches[branchIndex].DestinationID = newId
}
}
workflow.Triggers[triggerIndex].ID = newId
// FIXME: Check if it's a schedule, then set the interval + start it
if workflow.Triggers[triggerIndex].TriggerType == "schedule" {
//workflow.Triggers[triggerIndex].Interval = 60
for paramIndex, param := range workflow.Triggers[triggerIndex].Parameters {
if param.Name == "interval" {
if project.Environment == "cloud" {
param.Value = "*/5 * * * *"
} else {
param.Value = "300"
}
}
workflow.Triggers[triggerIndex].Parameters[paramIndex] = param
}
// FIXME: Start the schedule automatically
}
}
/*
for branchIndex, _ := range workflow.Branches {
workflow.Branches[branchIndex].ID = uuid.NewV4().String()
}
*/
// FIXME: Add a changeout for ANY schemaless node to use the correct
// action in it
log.Printf("[DEBUG] Saving workflow for org %s", orgId)
err = SetWorkflow(ctx, workflow, workflow.ID)
if err != nil {
log.Printf("[ERROR] Failed to set workflow during detection save: %s", err)
return Workflow{}, err
}
return workflow, nil
}