Skip to content

Commit f63faa2

Browse files
committed
Made random statistics work properly through the detection system
1 parent 9ae44b3 commit f63faa2

File tree

3 files changed

+87
-13
lines changed

3 files changed

+87
-13
lines changed

db-connector.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12453,7 +12453,7 @@ func UpdateDetectionStats(ctx context.Context, cacheData CacheKeyData) {
1245312453
}
1245412454

1245512455
detectionStatname := fmt.Sprintf("detection_rule_%s", strings.TrimSpace(strings.ToLower(strings.ReplaceAll(ruleName, " ", "_"))))
12456-
IncrementCache(ctx, cacheData.OrgId, detectionStatname, 10)
12456+
IncrementCache(ctx, cacheData.OrgId, detectionStatname, 1)
1245712457
if debug {
1245812458
log.Printf("[DEBUG] Incremented detection stat '%s' for org %s", detectionStatname, cacheData.OrgId)
1245912459
}

detection.go

Lines changed: 39 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,18 @@
11
package shuffle
22

33
import (
4-
"context"
5-
"encoding/json"
64
"fmt"
7-
"io/ioutil"
85
"log"
6+
"context"
97
"net/http"
8+
"io/ioutil"
9+
"crypto/sha1"
10+
"encoding/json"
1011

11-
"errors"
1212
"sort"
13-
"strings"
1413
"time"
14+
"errors"
15+
"strings"
1516

1617
uuid "github.com/satori/go.uuid"
1718
"gopkg.in/yaml.v2"
@@ -562,15 +563,43 @@ func HandleDetectionAutoConnect(resp http.ResponseWriter, request *http.Request)
562563

563564
log.Printf("[AUDIT] User '%s' (%s) is trying to detection-connect to %s", user.Username, user.Id, strings.ToUpper(detectionType))
564565

566+
// Uses the same system we are using in the ai.go standard workflow creation
565567
workflow := Workflow{}
566-
if detectionType == "siem" {
568+
if detectionType == "siem" || detectionType == "sigma" {
569+
categoryAction := CategoryAction{
570+
Label: "Ingest Tickets_webhook",
571+
Category: "cases",
572+
}
573+
574+
seedString := fmt.Sprintf("%s_%s", user.ActiveOrg.Id, categoryAction.Label)
575+
hash := sha1.New()
576+
hash.Write([]byte(seedString))
577+
hashBytes := hash.Sum(nil)
578+
579+
uuidBytes := make([]byte, 16)
580+
copy(uuidBytes, hashBytes)
581+
workflowId := uuid.Must(uuid.FromBytes(uuidBytes)).String()
567582

568583
ctx := GetContext(request)
569-
workflow, err = ConfigureDetectionWorkflow(ctx, user.ActiveOrg.Id, "TENZIR-SIGMA")
570-
if err != nil {
571-
log.Printf("[ERROR] Failed to create Sigma handling workflow: %s", err)
584+
foundWorkflow, err := GetWorkflow(ctx, workflowId)
585+
if err != nil || workflow.ID == "" {
586+
log.Printf("[WARNING] Failed to get workflow by ID '%s' in GenerateSingulWorkflows: %s", workflowId, err)
587+
//initialising = true
588+
newWorkflow, err := GetDefaultWorkflowByType(*foundWorkflow, user.ActiveOrg.Id, categoryAction)
589+
if err != nil {
590+
log.Printf("[ERROR] Failed to get default workflow in GenerateSingulWorkflows: %s", err)
591+
resp.WriteHeader(http.StatusInternalServerError)
592+
resp.Write([]byte(`{"success": false, "reason": "Failed to get default workflow for this category. Please contact [email protected]"}`))
593+
return
594+
}
595+
596+
workflow = newWorkflow
597+
} else {
598+
workflow = *foundWorkflow
572599
}
573600

601+
workflow.ID = workflowId
602+
574603
log.Printf("[DEBUG] Sending orborus request to start Sigma handling IF an available environment is found.")
575604

576605
execType := "START_TENZIR"
@@ -942,6 +971,7 @@ func ConfigureDetectionWorkflow(ctx context.Context, orgId, workflowType string)
942971

943972
// FIXME: Add a changeout for ANY schemaless node to use the correct
944973
// action in it
974+
workflow.BackgroundProcessing = true
945975
log.Printf("[DEBUG] Saving workflow for org %s", orgId)
946976
err = SetWorkflow(ctx, workflow, workflow.ID)
947977
if err != nil {

stats.go

Lines changed: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -433,7 +433,7 @@ func GetSpecificStats(resp http.ResponseWriter, request *http.Request) {
433433
statEntries = mergedEntries
434434

435435
// Check if entries exist for the last X statDays
436-
// Backfill any missing ones
436+
// Backfill any missing ones so that the number is correct
437437
if len(statEntries) < statDays {
438438
// Find the missing days
439439
missingDays := []time.Time{}
@@ -468,16 +468,43 @@ func GetSpecificStats(resp http.ResponseWriter, request *http.Request) {
468468
statEntries = append(statEntries, toAppend...)
469469
}
470470

471+
// Append cache for right now as it may not be in the DB yet
472+
for statEntryIndex, statEntry := range statEntries {
473+
if statEntry.Date.Day() == time.Now().Day() && statEntry.Date.Month() == time.Now().Month() && statEntry.Date.Year() == time.Now().Year() {
474+
for _, addition := range info.Additions {
475+
if addition.Key != statsKey {
476+
continue
477+
}
478+
479+
key := fmt.Sprintf("cache_%s_%s", orgId, addition.Key)
480+
cacheItem, err := GetCache(ctx, key)
481+
if err == nil {
482+
parsedItem := []byte(cacheItem.([]uint8))
483+
increment, err := strconv.Atoi(string(parsedItem))
484+
if err == nil {
485+
statEntries[statEntryIndex].Value += int64(increment)
486+
totalValue += int(increment)
487+
}
488+
}
489+
490+
break
491+
}
492+
}
493+
}
494+
471495
// Sort statentries by date
472496
sort.Slice(statEntries, func(i, j int) bool {
473497
return statEntries[i].Date.Before(statEntries[j].Date)
474498
})
475499

500+
// For debugging stats that don't show up by injecting them
501+
/*
476502
if debug && totalValue == 0 {
477503
log.Printf("[DEBUG] Found %d entries for '%s' with 0 in data. Force-adding data to first entry.", len(statEntries), statsKey)
478504
chosenIndex := rand.Intn(len(statEntries))
479505
statEntries[chosenIndex].Value = int64(rand.Intn(10) + 1)
480506
}
507+
*/
481508

482509
marshalledEntries, err := json.Marshal(statEntries)
483510
if err != nil {
@@ -631,6 +658,24 @@ func HandleGetStatistics(resp http.ResponseWriter, request *http.Request) {
631658
}
632659
}
633660

661+
for additionCnt, addition := range info.Additions {
662+
663+
key := fmt.Sprintf("cache_%s_%s", orgId, addition.Key)
664+
cacheItem, err = GetCache(ctx, key)
665+
if err == nil {
666+
parsedItem := []byte(cacheItem.([]uint8))
667+
increment, err := strconv.Atoi(string(parsedItem))
668+
if err == nil {
669+
info.Additions[additionCnt].Value += int64(increment)
670+
}
671+
}
672+
673+
// In case a lot of use
674+
if additionCnt > 10 {
675+
break
676+
}
677+
}
678+
634679
if len(statsKey) > 0 {
635680
log.Printf("[INFO] Should get stats for key %s", statsKey)
636681
}
@@ -1232,7 +1277,6 @@ func IncrementCache(ctx context.Context, orgId, dataType string, amount ...int)
12321277

12331278
} else {
12341279
// Get the cache, but use requestCache instead of memcache
1235-
//log.Printf("[DEBUG] Incrementing cache for %s with amount %d", key, incrementAmount)
12361280
foundItem := 1
12371281
item, err := GetCache(ctx, key)
12381282
if err != nil {
@@ -1269,7 +1313,7 @@ func IncrementCache(ctx context.Context, orgId, dataType string, amount ...int)
12691313

12701314
if foundItem >= int(dbDumpInterval) {
12711315
// Memcache dump first to keep the counter going for other executions
1272-
go SetCache(ctx, key, []byte(fmt.Sprintf("%x", 0)), 86400)
1316+
go SetCache(context.Background(), key, []byte(fmt.Sprintf("%x", 0)), 86400)
12731317
IncrementCacheDump(ctx, orgId, dataType, foundItem)
12741318

12751319
//log.Printf("[DEBUG] Dumping cache for %s with amount %d", key, foundItem)

0 commit comments

Comments
 (0)