forked from Shuffle/shuffle-shared
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathblobs.go
More file actions
2439 lines (2210 loc) · 490 KB
/
blobs.go
File metadata and controls
2439 lines (2210 loc) · 490 KB
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
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package shuffle
/*
This file is for blobs that we use throughout Shuffle in many locations. If we want to optimise Shuffle, we need to use structured data stored somewhere, but just creating blobs is a quick way to get a lot of things up and running until it needs proper fixing
*/
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"strings"
uuid "github.com/satori/go.uuid"
)
func HandleSingulWorkflowEnablement(ctx context.Context, workflow Workflow, user User, categoryAction CategoryAction) error {
if len(user.ActiveOrg.Id) == 0 {
return errors.New("Organization ID is empty. Can't generate workflow.")
}
actionType := strings.ReplaceAll(strings.ToLower(categoryAction.Label), " ", "_")
if actionType == "forward_tickets" || actionType == "forward_incidents" {
categoryCheck := "shuffle-security_incidents"
categoryConfig, err := GetDatastoreCategoryConfig(ctx, user.ActiveOrg.Id, categoryCheck)
if err != nil {
if strings.Contains(err.Error(), "not found") {
categoryConfig = &DatastoreCategoryUpdate{
OrgId: user.ActiveOrg.Id,
Category: categoryCheck,
Automations: []DatastoreAutomation{},
Settings: DatastoreCategorySettings{},
}
} else {
return err
}
}
datastoreCategoryConfigEdited := false
foundRunWorkflow := DatastoreAutomation{
Name: "Run workflow",
Description: "Runs one or more workflows with the updated value as runtime argument",
Options: []DatastoreAutomationOption{
DatastoreAutomationOption{
Key: "workflow_id",
Value: workflow.ID,
},
},
Icon: "",
Enabled: true,
}
automationFound := false
if len(categoryConfig.Automations) > 0 {
for automationIndex, automation := range categoryConfig.Automations {
if automation.Name != "Run workflow" {
continue
}
//if datastoreCategoryConfigEdited {
for optionIndex, option := range automation.Options {
if option.Key != "workflow_id" {
continue
}
if !strings.Contains(option.Value, workflow.ID) {
categoryConfig.Automations[automationIndex].Options[optionIndex].Value = workflow.ID
datastoreCategoryConfigEdited = true
}
automationFound = true
break
}
}
}
if !automationFound {
categoryConfig.Automations = append(categoryConfig.Automations, foundRunWorkflow)
datastoreCategoryConfigEdited = true
}
if datastoreCategoryConfigEdited {
err := SetDatastoreCategoryConfig(ctx, *categoryConfig)
if err != nil {
log.Printf("[ERROR] Failed to update category config for automation enablement: %s", err)
}
}
} else if actionType == "ingest_tickets" {
// Enables the automation IF it is not already enabled
categoryCheck := "shuffle-security_incidents"
categoryConfig, err := GetDatastoreCategoryConfig(ctx, user.ActiveOrg.Id, categoryCheck)
if err != nil {
if strings.Contains(err.Error(), "not found") {
categoryConfig = &DatastoreCategoryUpdate{
OrgId: user.ActiveOrg.Id,
Category: categoryCheck,
Automations: []DatastoreAutomation{},
Settings: DatastoreCategorySettings{},
}
} else {
return err
}
}
datastoreCategoryConfigEdited := false
// 3 year retention
if categoryConfig.Settings.Timeout == 0 {
categoryConfig.Settings.Timeout = 946080000
datastoreCategoryConfigEdited = true
}
// JUST first time
automationEnabled := false
if len(categoryConfig.Automations) > 0 {
for _, automation := range categoryConfig.Automations {
if automation.Enabled && automation.Name != "Run workflow" && automation.Name != "Send to webhook" {
automationEnabled = true
break
}
}
}
if !automationEnabled {
agentAutomation := DatastoreAutomation{
Name: "Run AI Agent",
Description: "Runs an AI Agent to process the updated value. Uses built-in ShuffleAI configs. Learn more: https://shuffler.io/docs/AI",
Options: []DatastoreAutomationOption{
DatastoreAutomationOption{
Key: "action",
Value: "Provide a short triage plan for the incident in english and update it in the internal shuffle datastore with the same key and category 'shuffle-security_incidents'. Make sure it is JSON formatted like {\"tasks\": []} so that we can inject it in existing data. Some incidents are duds and should be closed quickly. Others are important ones. Others are missing important details. Use the following format for each task, and ONLY update the relevant fields: [{\"assignee\": \"AI Agent\", \"title\": \"Title of the task\", \"category\": \"triage/containment/recovery/communication/documentation\", \"completed\": false, \"createdBy\": \"ai-agent@shuffler.io\"}]. ONLY output as JSON and nothing more. If the incident has RELEVANT tasks that are not finished, modify them if necessary. Change the \"severity\" at the same time if relevant. When done, ALWAYS make sure the \"status\" is inProgress.",
Disabled: false,
},
DatastoreAutomationOption{
Key: "action-2",
Value: "Go through each task one by one if there are any. When starting them, self-assign yourself to make it clear you are working on it. Go in the order of incident response relevance, which is typically in order. If a task is irrelevant, set \"disabled\": true as a value for it. Before starting, get key \"agent_permissions\" from category \"shuffle-security_configuration\". This has a list of permissions you NEED to follow if it exists. This extends the reach of tools and capabilities you are allowed to use. ONLY use the permissions that are enabled. If permissions do not exist, continue as per normal guidance.",
Disabled: false,
},
},
Type: "singul",
Beta: true,
Disabled: false,
Enabled: true,
}
enrichAutomation:= DatastoreAutomation{
Name: "Enrich",
Description: "Enriches the data. Only runs on valid JSON data AND if the 'enrichment' field does not exist.",
Type: "singul",
Icon: "/images/logos/singul.svg",
Beta: false,
Disabled: false,
Enabled: true,
}
securityRuleAutomation := DatastoreAutomation{
Name: "Security Rules",
Description: "Describes security rules that are validated BEFORE an update occurs. This is in order for bad writes to be avoided. Control: allow, deny, merge, overwrite. Logic: if, or, and. Functions: same_shape, is_superset, has_deleted_field",
Options: []DatastoreAutomationOption{
DatastoreAutomationOption{
Key: "rule",
Value: "merge if always; deny if has_deleted_field",
},
},
Type: "",
Icon: "",
Beta: false,
Disabled: false,
Enabled: true,
}
// Adding them all
categoryConfig.Automations = []DatastoreAutomation{agentAutomation, enrichAutomation, securityRuleAutomation}
datastoreCategoryConfigEdited = true
}
if datastoreCategoryConfigEdited {
err := SetDatastoreCategoryConfig(ctx, *categoryConfig)
if err != nil {
log.Printf("[ERROR] Failed to update category config for automation enablement: %s", err)
}
}
}
return nil
}
// These are just specific examples for specific cases
// FIXME: Should these be loaded from public workflows?
// I kind of think so ~
// That means each algorithm needs to be written as if-statements to
// replace a specific part of a workflow :thinking:
// Should workflows be written as YAML and be text-editable?
func GetDefaultWorkflowByType(workflow Workflow, orgId string, categoryAction CategoryAction) (Workflow, error) {
actionType := categoryAction.Label
appNames := categoryAction.AppName
if len(orgId) == 0 {
return workflow, errors.New("Organization ID is empty. Can't generate workflow.")
}
parsedActiontype := strings.ReplaceAll(strings.ToLower(actionType), " ", "_")
if strings.Contains(strings.ToLower(actionType), "threat feed") {
parsedActiontype = "threatlist_monitor"
}
// If-else with specific rules per workflow
// Make sure it uses workflow -> copies data, as
startActionId := uuid.NewV4().String()
startTriggerId := workflow.ID
if len(startTriggerId) == 0 {
startTriggerId = uuid.NewV4().String()
}
actionEnv := "Cloud"
triggerEnv := "Cloud"
ctx := context.Background()
if project.Environment != "cloud" {
triggerEnv = "onprem"
envs, err := GetEnvironments(ctx, orgId)
if err == nil {
for _, env := range envs {
if env.Default {
actionEnv = env.Name
break
}
}
} else {
actionEnv = "Shuffle"
}
}
if parsedActiontype == "correlate_categories" {
defaultWorkflow := Workflow{
Name: actionType,
Description: "Correlates Datastore categories in Shuffle. The point is to graph data",
OrgId: orgId,
Start: startActionId,
Actions: []Action{
Action{
ID: startActionId,
Name: "repeat_back_to_me",
AppName: "Shuffle Tools",
AppVersion: "1.2.0",
Environment: actionEnv,
Label: "Start",
IsStartNode: true,
Position: Position{
X: 250,
Y: 0,
},
Parameters: []WorkflowAppActionParameter{
WorkflowAppActionParameter{
Name: "call",
Value: "Some code here hello",
Multiline: true,
},
},
},
},
}
workflow = defaultWorkflow
workflow.OrgId = orgId
} else if parsedActiontype == "forward_tickets" || parsedActiontype == "forward_incidents" {
currentAction := WorkflowAppActionParameter{
Name: "action",
Value: "Create ticket",
Options: []string{
"List tickets",
"Create ticket",
"Close ticket",
"Add comment",
},
}
actionName := "Cases"
defaultWorkflow := Workflow{
Name: actionType,
Description: "Create tickets in different systems as to forward them",
OrgId: orgId,
Start: startActionId,
UsecaseIds: []string{"forward"},
Tags: []string{"forward", "automatic"},
Actions: []Action{
Action{
Name: actionName,
AppID: "integration",
AppName: "Singul",
LargeImage: getSingulLogo(),
ID: startActionId,
AppVersion: "1.0.0",
Environment: actionEnv,
Label: currentAction.Value,
Parameters: []WorkflowAppActionParameter{
WorkflowAppActionParameter{
Name: "app_name",
Value: "",
},
currentAction,
WorkflowAppActionParameter{
Name: "fields",
Value: "",
Multiline: true,
},
},
},
},
Triggers: []Trigger{
Trigger{
ID: startTriggerId,
Name: "Webhook",
TriggerType: "WEBHOOK",
Label: "Ingest",
Environment: triggerEnv,
Parameters: []WorkflowAppActionParameter{
WorkflowAppActionParameter{
Name: "url",
Value: "",
},
WorkflowAppActionParameter{
Name: "tmp",
Value: "",
},
WorkflowAppActionParameter{
Name: "auth_header",
Value: "",
},
WorkflowAppActionParameter{
Name: "custom_response_body",
Value: "",
},
WorkflowAppActionParameter{
Name: "await_response",
Value: "",
},
},
},
},
}
workflow = defaultWorkflow
workflow.OrgId = orgId
} else if parsedActiontype == "ingest_tickets" || parsedActiontype == "ingest_assets" || parsedActiontype == "ingest_users" {
actionName := "Cases"
currentAction := WorkflowAppActionParameter{
Name: "action",
Value: "List tickets",
Options: []string{
"List tickets",
"Create ticket",
"Close ticket",
"Add comment",
},
}
if parsedActiontype == "ingest_assets" {
actionName = "Assets"
currentAction.Value = "List assets"
currentAction.Options = []string{
"List assets",
"Get asset",
"Search assets",
"Create asset",
}
} else if parsedActiontype == "ingest_users" {
actionName = "IAM"
currentAction.Value = "List users"
currentAction.Options = []string{
"List users",
"Get users",
"Search users",
"Create user",
}
}
defaultWorkflow := Workflow{
Name: actionType,
Description: "List tickets from different systems and ingest them",
OrgId: orgId,
Start: startActionId,
UsecaseIds: []string{"SIEM to ticket"},
Tags: []string{"ingest", "automatic"},
Actions: []Action{
Action{
Name: actionName,
AppID: "integration",
AppName: "Singul",
LargeImage: getSingulLogo(),
ID: startActionId,
AppVersion: "1.0.0",
Environment: actionEnv,
Label: currentAction.Value,
Parameters: []WorkflowAppActionParameter{
WorkflowAppActionParameter{
Name: "app_name",
Value: "",
},
currentAction,
WorkflowAppActionParameter{
Name: "fields",
Value: "amount=10",
Multiline: true,
},
},
},
},
Triggers: []Trigger{
Trigger{
ID: startTriggerId,
Name: "Schedule",
TriggerType: "SCHEDULE",
Label: "Ingest tickets",
Environment: triggerEnv,
Parameters: []WorkflowAppActionParameter{
WorkflowAppActionParameter{
Name: "cron",
Value: "*/30 * * * *",
},
WorkflowAppActionParameter{
Name: "execution_argument",
Value: "Automatically configured by Shuffle",
},
},
},
},
}
workflow = defaultWorkflow
workflow.OrgId = orgId
} else if parsedActiontype == "ingest_tickets_webhook" {
defaultWorkflow := Workflow{
Name: "Ingestion Webhook",
Description: "Ingest tickets through a webhook",
OrgId: orgId,
Start: startActionId,
UsecaseIds: []string{"SIEM to ticket"},
Tags: []string{"ingest", "webhook", "automatic"},
Actions: []Action{
Action{
Name: "Translate standard",
AppID: "integration",
AppName: "Singul",
LargeImage: getSingulLogo(),
ID: startActionId,
AppVersion: "1.0.0",
Environment: actionEnv,
Label: "Ingest Ticket from Webhook",
Parameters: []WorkflowAppActionParameter{
WorkflowAppActionParameter{
Name: "source_data",
Value: "$exec",
Multiline: true,
},
WorkflowAppActionParameter{
Name: "standard",
Description: "The standard to use from https://github.com/Shuffle/standards/tree/main",
Value: "OCSF",
Multiline: false,
},
},
},
},
Triggers: []Trigger{
Trigger{
ID: startTriggerId,
Name: "Webhook",
TriggerType: "WEBHOOK",
Label: "Ingest",
Environment: triggerEnv,
Parameters: []WorkflowAppActionParameter{
WorkflowAppActionParameter{
Name: "url",
Value: "",
},
WorkflowAppActionParameter{
Name: "tmp",
Value: "",
},
WorkflowAppActionParameter{
Name: "auth_header",
Value: "",
},
WorkflowAppActionParameter{
Name: "custom_response_body",
Value: "",
},
WorkflowAppActionParameter{
Name: "await_response",
Value: "",
},
},
},
},
}
workflow = defaultWorkflow
workflow.OrgId = orgId
baseUrl := ""
if len(os.Getenv("BASE_URL")) > 0 {
baseUrl = os.Getenv("BASE_URL")
}
if len(os.Getenv("SHUFFLE_CLOUDRUN_URL")) > 0 {
baseUrl = os.Getenv("SHUFFLE_CLOUDRUN_URL")
}
// } else if parsedActiontype == "ingest_tickets_webhook" {
// Force starting pipelines if possible as well
environments, err := GetEnvironments(ctx, orgId)
if err == nil && len(baseUrl) > 0 {
foundEnv := ""
for _, env := range environments {
if env.Archived {
continue
}
if strings.ToLower(env.Type) == "cloud" {
continue
}
foundEnv = env.Name
if env.DataLake.Enabled {
break
}
}
if len(foundEnv) > 0 {
commands := []string{
"load_tcp \"0.0.0.0:1514\" { read_syslog } | import",
fmt.Sprintf("export live=true | sigma \"/tmp/sigma_rules\" | to \"%s/api/v1/hooks/webhook_%s\"", baseUrl, startTriggerId),
}
for _, command := range commands {
pipeline := &Pipeline{
ID: uuid.NewV4().String(),
Name: command,
Type: "START",
OrgId: orgId,
Command: command,
Environment: foundEnv,
}
pipeline.PipelineId = pipeline.ID
formattedType := fmt.Sprintf("PIPELINE_START")
execRequest := ExecutionRequest{
Type: formattedType,
ExecutionId: pipeline.ID,
ExecutionSource: pipeline.Name,
ExecutionArgument: pipeline.Command,
Priority: 11,
}
parsedEnv := fmt.Sprintf("%s_%s", strings.ToLower(strings.ReplaceAll(strings.ReplaceAll(pipeline.Environment, " ", "-"), "_", "-")), orgId)
if project.Environment != "cloud" {
parsedEnv = strings.ToLower(strings.ReplaceAll(strings.ReplaceAll(pipeline.Environment, " ", "-"), "_", "-"))
}
log.Printf("[INFO] Starting pipeline '%s' in env '%s'", command, parsedEnv)
err = SetWorkflowQueue(ctx, execRequest, parsedEnv)
if err != nil {
log.Printf("[ERROR] Failed setting workflow queue for env: %s", err)
}
}
}
}
} else if parsedActiontype == "threatlist_monitor" {
secondActionId := uuid.NewV4().String()
defaultWorkflow := Workflow{
Name: actionType,
Description: "Monitor threatlists and ingest regularly",
OrgId: orgId,
Start: startActionId,
UsecaseIds: []string{"External Enrichment"},
Tags: []string{"ingest", "feeds", "automatic"},
Actions: []Action{
Action{
Name: "GET",
AppID: "HTTP",
AppName: "HTTP",
ID: startActionId,
AppVersion: "1.4.0",
Environment: actionEnv,
Label: "Get threatlist URLs",
Parameters: []WorkflowAppActionParameter{
WorkflowAppActionParameter{
Name: "url",
Value: "$shuffle_cache.threatlist_urls.value.#",
},
WorkflowAppActionParameter{
Name: "headers",
Multiline: true,
Value: "",
},
},
},
Action{
Name: "execute_python",
AppID: "Shuffle Tools",
AppName: "Shuffle Tools",
ID: secondActionId,
AppVersion: "1.2.0",
Environment: actionEnv,
Label: "Ingest IOCs",
Parameters: []WorkflowAppActionParameter{
WorkflowAppActionParameter{
Name: "code",
Multiline: true,
Required: true,
Value: getIocIngestionScript(orgId),
},
},
},
},
Triggers: []Trigger{
Trigger{
ID: startTriggerId,
Name: "Schedule",
TriggerType: "SCHEDULE",
Label: "Pull threatlist URLs",
Environment: triggerEnv,
Parameters: []WorkflowAppActionParameter{
WorkflowAppActionParameter{
Name: "cron",
Value: "0 0 * * *",
},
WorkflowAppActionParameter{
Name: "execution_argument",
Value: "Automatically configured by Shuffle",
},
},
},
},
Branches: []Branch{
Branch{
SourceID: startTriggerId,
DestinationID: startActionId,
ID: uuid.NewV4().String(),
},
Branch{
SourceID: startActionId,
DestinationID: secondActionId,
ID: uuid.NewV4().String(),
Conditions: []Condition{
Condition{
Source: WorkflowAppActionParameter{
Name: "source",
Value: "{{ $get_threatlist_urls | size }}",
},
Condition: WorkflowAppActionParameter{
Name: "condition",
Value: "larger than",
},
Destination: WorkflowAppActionParameter{
Name: "destination",
Value: "0",
},
},
},
},
},
}
// For now while testing
workflow = defaultWorkflow
workflow.OrgId = orgId
/*
if len(workflow.WorkflowVariables) == 0 {
workflow.WorkflowVariables = defaultWorkflow.WorkflowVariables
}
if len(workflow.Actions) == 0 {
workflow.Actions = defaultWorkflow.Actions
}
// Rules specific to this one
if len(workflow.Triggers) == 0 {
workflow.Triggers = defaultWorkflow.Triggers
}
*/
// Get the item with key "threatlist_urls" from datastore
ctx := GetContext(nil)
_, err := GetDatastoreKey(ctx, "threatlist_urls", "")
if err != nil {
//log.Printf("[INFO] Failed to get threatlist URLs from datastore. Making it.: %s", err)
urls := []string{
"https://sslbl.abuse.ch/blacklist/sslblacklist.csv",
}
jsonMarshalled, err := json.Marshal(urls)
if err != nil {
log.Printf("[ERROR] Failed to marshal threatlist URLs: %s", err)
} else {
key := CacheKeyData{
Key: "threatlist_urls",
Value: fmt.Sprintf(`%s`, string(jsonMarshalled)),
OrgId: orgId,
}
err = SetDatastoreKey(ctx, key)
if err != nil {
log.Printf("[ERROR] Failed to set threatlist URLs in datastore: %s", err)
} else {
log.Printf("[INFO] Successfully set threatlist URLs in datastore")
}
}
}
}
if len(workflow.Name) == 0 || len(workflow.Actions) == 0 {
return workflow, errors.New("Workflow name or ID is empty")
}
// Appends actions in the workflow
// This is done specifically for Singul ingests
positionAddition := float64(250)
//if debug {
//log.Printf("ACTIONS: %d, TRIGGERS: %d, APPNAMES: %d, FIRSTACTION: %s, TRIGGER: %s", len(workflow.Actions), len(workflow.Triggers), len(appNames), workflow.Actions[0].AppName, workflow.Triggers[0].TriggerType)
//os.Exit(3)
//}
if len(workflow.Actions) == 1 && (workflow.Actions[0].AppName == "Singul" || workflow.Actions[0].AppID == "integration") && len(workflow.Triggers) == 1 && workflow.Triggers[0].TriggerType == "SCHEDULE" {
actionTemplate := workflow.Actions[0]
// Pre-defining it with a startnode that does nothing
workflow.Actions = []Action{
Action{
ID: startActionId,
Name: "repeat_back_to_me",
AppName: "Shuffle Tools",
AppVersion: "1.2.0",
Environment: actionEnv,
Label: "Start",
IsStartNode: true,
Position: Position{
X: 250,
Y: 0,
},
Parameters: []WorkflowAppActionParameter{
WorkflowAppActionParameter{
Name: "call",
Value: "",
Multiline: true,
},
},
},
}
// Point from trigger(s) to startnode (repeater)
for _, trigger := range workflow.Triggers {
newBranch := Branch{
SourceID: trigger.ID,
DestinationID: workflow.Start,
ID: uuid.NewV4().String(),
}
workflow.Branches = append(workflow.Branches, newBranch)
}
// Replicator
appNameSplit := strings.Split(appNames, ",")
for appIndex, appName := range appNameSplit {
if len(appName) == 0 {
continue
}
newAction := actionTemplate
newAction.ID = uuid.NewV4().String()
newAction.Parameters = append([]WorkflowAppActionParameter(nil), actionTemplate.Parameters...)
// Positioning
newAction.Position.X = positionAddition * float64(appIndex)
newAction.Position.Y = positionAddition
// Point from startnode to current one
newBranch := Branch{
SourceID: workflow.Start,
DestinationID: newAction.ID,
ID: uuid.NewV4().String(),
}
workflow.Branches = append(workflow.Branches, newBranch)
appNameIndex := -1
for paramIndex, param := range actionTemplate.Parameters {
if param.Name == "app_name" || param.Name == "appName" {
appNameIndex = paramIndex
break
}
}
//newAction.Label += " " + appName
newAction.Label = appName
if appNameIndex >= 0 {
newAction.Parameters[appNameIndex].Value = appName
} else {
newAction.Parameters = append(newAction.Parameters, WorkflowAppActionParameter{
Name: "app_name",
Value: appName,
})
appNameIndex = len(newAction.Parameters) - 1
}
workflow.Actions = append(workflow.Actions, newAction)
}
}
if workflow.Actions[0].Position.X == 0 && workflow.Actions[0].Position.Y == 0 {
startXPosition := float64(0)
startYPosition := float64(0)
for triggerIndex, _ := range workflow.Triggers {
workflow.Triggers[triggerIndex].Position = Position{
X: startXPosition,
Y: startYPosition,
}
startXPosition += positionAddition
}
for actionIndex, _ := range workflow.Actions {
workflow.Actions[actionIndex].Position = Position{
X: startXPosition,
Y: startYPosition,
}
startXPosition += positionAddition
}
}
if len(workflow.Actions) > 0 {
for _, action := range workflow.Actions {
if action.AppID == "integration" || action.AppName == "Singul" {
for _, param := range action.Parameters {
if (param.Name == "app_name" || param.Name == "appName") && len(param.Value) == 0 {
log.Printf("[DEBUG] Should verify if an app of type '%s' exists", action.Name)
}
}
}
}
}
if len(workflow.Actions)+len(workflow.Triggers) > 1 {
if len(workflow.Branches) == 0 {
// Connect from trigger -> action
sourceId := ""
destId := ""
if len(workflow.Triggers) == 1 {
sourceId = workflow.Triggers[0].ID
destId = workflow.Start
}
newBranch := Branch{
SourceID: sourceId,
DestinationID: destId,
ID: uuid.NewV4().String(),
}
workflow.Branches = append(workflow.Branches, newBranch)
}
}
// Check if the action has branches at all
// This is not efficientm but ensures they all at least run
for actionIndex, action := range workflow.Actions {
if actionIndex == 0 {
continue
}
found := false
for _, branch := range workflow.Branches {
if branch.SourceID == action.ID || branch.DestinationID == action.ID {
found = true
break
}
}
if !found {
log.Printf("Missing branch: %s", action.ID)
// Create a branch from the previous action to this one
workflow.Branches = append(workflow.Branches, Branch{
SourceID: workflow.Actions[actionIndex-1].ID,
DestinationID: action.ID,
ID: uuid.NewV4().String(),
})
}
}
// API-available, but not UI visible by default
//workflow.Hidden = true
return workflow, nil
}
func getSingulLogo() string {
return "/images/singul_green.png"
}
func GetPublicDetections() []DetectionResponse {
return []DetectionResponse{
DetectionResponse{
Title: "Sigma SIEM Detections",
DetectionName: "Sigma",
Category: "SIEM",
DetectionInfo: []DetectionFileInfo{},
FolderDisabled: false,
IsConnectorActive: false,
DownloadRepo: "https://github.com/shuffle/security-rules",
},
DetectionResponse{
Title: "Sublime Email Detection",
DetectionName: "Sublime",
Category: "Email",
DetectionInfo: []DetectionFileInfo{},
FolderDisabled: false,
IsConnectorActive: false,
DownloadRepo: "https://github.com/shuffle/security-rules",
},
DetectionResponse{
Title: "File Detection",
DetectionName: "Yara",
Category: "Files",
DetectionInfo: []DetectionFileInfo{},
FolderDisabled: false,
IsConnectorActive: false,
DownloadRepo: "https://github.com/shuffle/security-rules",
},
}
}
func GetBaseDockerfile() []byte {
return []byte(`FROM frikky/shuffle:app_sdk as base
# We're going to stage away all of the bloat from the build tools so lets create a builder stage
FROM base as builder
# Install all alpine build tools needed for our pip installs
RUN apk --no-cache add --update alpine-sdk libffi libffi-dev musl-dev openssl-dev git
# Install all of our pip packages in a single directory that we can copy to our base image later
RUN mkdir /install
WORKDIR /install
COPY requirements.txt /requirements.txt
RUN pip install --no-cache-dir --upgrade --prefix="/install" -r /requirements.txt
# Switch back to our base image and copy in all of our built packages and source code
FROM base
COPY --from=builder /install /usr/local
COPY src /app
# Install any binary dependencies needed in our final image
# RUN apk --no-cache add --update my_binary_dependency
RUN apk --no-cache add jq git curl
# Finally, lets run our app!
WORKDIR /app
CMD ["python", "app.py", "--log-level", "DEBUG"]`)
}
// For now, just keeping it as a blob.
func GetAppCategories() []AppCategory {
return []AppCategory{
AppCategory{
Name: "Communication",
Color: "#FFC107",
Icon: "communication",
ActionLabels: []string{"List Messages", "Send Message", "Get Message", "Search messages", "List Attachments", "Get Attachment", "Get Contact"},
},
AppCategory{
Name: "SIEM",
Color: "#FFC107",
Icon: "siem",
ActionLabels: []string{"Search", "List Alerts", "Close Alert", "Get Alert", "Create detection", "Add to lookup list", "Isolate endpoint"},
},
AppCategory{
Name: "Eradication",
Color: "#FFC107",
Icon: "eradication",
ActionLabels: []string{"List Alerts", "Close Alert", "Get Alert", "Create detection", "Block hash", "Search Hosts", "Isolate host", "Unisolate host", "Trigger host scan"},