-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathcorrelations.go
More file actions
1484 lines (1256 loc) · 41.9 KB
/
correlations.go
File metadata and controls
1484 lines (1256 loc) · 41.9 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
import (
"net/http"
"net/url"
"fmt"
"strconv"
"io/ioutil"
"encoding/json"
"log"
"time"
"strings"
"context"
"errors"
"math/rand"
"os"
"regexp"
"bytes"
"io"
"net"
uuid "github.com/satori/go.uuid"
// For BOM scans
//"github.com/CycloneDX/cyclonedx-gomod/pkg/generate/app"
//"github.com/CycloneDX/cyclonedx-gomod/pkg/generate/mod"
)
func GetCorrelations(resp http.ResponseWriter, request *http.Request) {
cors := HandleCors(resp, request)
if cors {
return
}
user, err := HandleApiAuthentication(resp, request)
if err != nil {
log.Printf("[AUDIT] Authentication failed in GetCorrelations: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Authentication failed"}`))
return
}
body, err := ioutil.ReadAll(request.Body)
if err != nil {
log.Printf("[WARNING] Failed to read body in GetCorrelations: %s", err)
resp.WriteHeader(400)
resp.Write([]byte(`{"success": false, "reason": "Invalid input body"}`))
return
}
correlationData := CorrelationRequest{}
err = json.Unmarshal(body, &correlationData)
if err != nil {
log.Printf("[WARNING] Failed to parse JSON in GetCorrelations: %s", err)
resp.WriteHeader(400)
resp.Write([]byte(`{"success": false, "reason": "Invalid JSON format"}`))
return
}
ctx := GetContext(request)
correlations := []NGramItem{}
if len(correlationData.Category) == 0 {
searchKey := fmt.Sprintf("%s", correlationData.Key)
if !strings.HasPrefix(correlationData.Key, user.ActiveOrg.Id) {
searchKey = fmt.Sprintf("%s_%s", user.ActiveOrg.Id, correlationData.Key)
}
ngramItem, err := GetDatastoreNGramItem(ctx, searchKey)
if err != nil {
log.Printf("[WARNING] Failed to get ngram item in GetCorrelations for '%s': %s", searchKey, err)
resp.WriteHeader(404)
resp.Write([]byte(`{"success": false, "reason": "No correlations found"}`))
return
}
correlations = []NGramItem{*ngramItem}
} else {
searchKey := fmt.Sprintf("%s|%s", correlationData.Category, correlationData.Key)
availableTypes := []string{"datastore"}
if len(correlationData.Type) == 0 {
correlationData.Type = "datastore"
}
if correlationData.Type == "datastore" {
// Nothing to do as we have the right key already
} else {
log.Printf("[WARNING] Invalid type in GetCorrelations: %#v. Available types: %#v", correlationData.Type, strings.Join(availableTypes, ", "))
resp.WriteHeader(400)
resp.Write([]byte(`{"success": false, "reason": "Invalid type"}`))
return
}
correlations, err = GetDatastoreNgramItems(ctx, user.ActiveOrg.Id, searchKey, 50)
if err != nil {
log.Printf("[ERROR] Failed to get correlations from DB in GetCorrelations: %s", err)
resp.WriteHeader(500)
resp.Write([]byte(`{"success": false, "reason": "Internal server error"}`))
return
}
}
newCorrelations := []NGramItem{}
for _, item := range correlations {
if item.OrgId != user.ActiveOrg.Id {
continue
}
item.OrgId = ""
newCorrelations = append(newCorrelations, item)
}
correlations = newCorrelations
marshalledCorrelations, err := json.Marshal(correlations)
if err != nil {
log.Printf("[ERROR] Failed to marshal correlations in GetCorrelations: %s", err)
resp.WriteHeader(500)
resp.Write([]byte(`{"success": false, "reason": "Internal server error: Failed to marshal correlations"}`))
return
}
resp.WriteHeader(200)
resp.Write([]byte(marshalledCorrelations))
}
// Used to cross-correlate data
// Not YET doing proper ngram by breaking everything down, but it's easy to
// Modify this into doing that as well
// Issues:
// Only does strings
// Only does top-level in JSON (no recursion)
func crossCorrelateNGrams(ctx context.Context, orgId, category, datastoreKey, value string, enrichments []Observable, enrichmentsOnly bool) error {
if len(orgId) == 0 || len(category) == 0 || len(datastoreKey) == 0 || len(value) == 0 {
if debug {
log.Printf("\n\n[ERROR] Invalid parameters for cross-correlate ngrams. All parameters must be set. orgId, category, key, value\n\n")
}
return errors.New("Invalid parameters for cross-correlate ngrams. All parameters must be set. orgId, category, key, value")
}
// Skipping searchability for protected keys
if strings.ToLower(category) == "protected" {
return nil
}
amountAdded := 0
if !enrichmentsOnly {
// Random sleeptime between 0-1000ms because we're inside a goroutine
// and want to ensure there aren't a ton of concurrent writes to the datastore
time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)
unmarshalled := map[string]interface{}{}
if err := json.Unmarshal([]byte(value), &unmarshalled); err != nil {
log.Printf("[WARNING] Failed unmarshalling value for cross-correlate ngrams: %s. Storing the key directly.", err)
unmarshalled = map[string]interface{}{
"key": value,
}
}
// Simple workaround for dates
// hardcoded for now just to remove certain things
skippableKeys := []string{"spec_version", "version", "pattern_type", "created", "edited", "creation", "status"}
// Types and patterns
skippableValues := []string{"indicator", "stix", "active", "false", "true", "inprogress", "new", "closed", "resolved", "escalated", "incidentfinding", "domain", "ip", "url", "file", "cve", "vulnerability", "threat-actor", "tool", "attack-pattern", "campaign", "malware", "indicator", "observable"}
invalidStarts := []string{"[", "{", "$", "202", "203", "204"} // Specific for timestamps
//for jsonKey, val := range unmarshalled {
maxAmountToAdd := 5
for jsonKey, val := range unmarshalled {
if ArrayContains(skippableKeys, jsonKey) {
continue
}
// Only handle strings for now
if val == nil {
continue
}
if _, ok := val.(string); !ok {
// FIXME: Check here if it's a map, then recurse down
// to find more string
continue
}
parsedValue := val.(string)
// FIXME: Arbitrary limits
// About ngram: We will want to do additional splitting,
// but to start with, we just do the whole thing
if len(parsedValue) > 70 || len(parsedValue) < 2 {
continue
}
skip := false
for _, invalidStart := range invalidStarts {
if strings.HasPrefix(parsedValue, invalidStart) {
skip = true
break
}
}
if skip {
continue
}
if strings.HasPrefix(parsedValue, "$") {
continue
}
// Make sure we don't add more than 5 items (for now)
if amountAdded > maxAmountToAdd {
break
}
parsedValue = strings.ToLower(strings.TrimSpace(
strings.ReplaceAll(
strings.ReplaceAll(
parsedValue, "\n", "",
), " ", "",
),
))
if ArrayContains(skippableValues, strings.ToLower(parsedValue)) {
continue
}
// Check if the value is a unix timestamp or uuid
if _, err := strconv.ParseInt(parsedValue, 10, 64); err == nil {
continue
}
u, err := uuid.FromString(parsedValue)
if err == nil || u == uuid.Nil {
continue
}
parsedCategory := strings.ToLower(strings.ReplaceAll(category, " ", "_"))
// Doing it WITHOUT the JSON key & Org, as we only want to partially cross-correlate to find items among each other
referenceKey := fmt.Sprintf("%s|%s", parsedCategory, datastoreKey)
// FIXME: May need to hash the parsedValue to make search work well
// as we are doing the full string right now
ngramSearchKey := fmt.Sprintf("%s_%s", orgId, parsedValue)
ngramItem, err := GetDatastoreNGramItem(ctx, ngramSearchKey)
// FIXME: Key may disappear/be overwritten if connectivity to backend fails briefly?
if err != nil || ngramItem == nil || ngramItem.Key == "" {
ngramItem = &NGramItem{
Key: parsedValue,
OrgId: orgId,
Amount: 1,
Ref: []string{
referenceKey,
},
}
err = SetDatastoreNGramItem(ctx, ngramSearchKey, ngramItem)
if err != nil {
log.Printf("[WARNING] Failed setting ngram item for cross-correlate: %s", err)
}
amountAdded += 1
if debug {
log.Printf("[DEBUG] Created new ngram item for %s with key '%s'", ngramSearchKey, parsedValue)
}
continue
}
if ArrayContains(ngramItem.Ref, referenceKey) {
continue
}
// Add the reference to the ngram item
amountAdded += 1
ngramItem.Ref = append(ngramItem.Ref, referenceKey)
ngramItem.Amount = len(ngramItem.Ref)
err = SetDatastoreNGramItem(ctx, ngramSearchKey, ngramItem)
if err != nil {
log.Printf("[WARNING] Failed setting ngram item for cross-correlate: %s", err)
} else {
if debug {
log.Printf("[DEBUG] Updated ngram item for %s with key %s", ngramSearchKey, parsedValue)
}
}
}
}
if debug && len(enrichments) > 0 {
log.Printf("\n\n[DEBUG] Enrichments (%s): %d\n\n", datastoreKey, len(enrichments))
}
for enrichmentCnt, enrichment := range enrichments {
if enrichmentCnt > 100 {
break
}
go func(enrichment Observable) {
parsedValue := strings.ToLower(strings.TrimSpace(
strings.ReplaceAll(
strings.ReplaceAll(
enrichment.Value, "\n", "",
), " ", "",
),
))
parsedCategory := strings.ToLower(strings.ReplaceAll(category, " ", "_"))
// Doing it WITHOUT the JSON key & Org, as we only want to partially cross-correlate to find items among each other
referenceKey := fmt.Sprintf("%s|%s", parsedCategory, datastoreKey)
// FIXME: Key may disappear/be overwritten if connectivity to backend fails briefly?
// FIXME: May need to hash the parsedValue to make search work well
// as we are doing the full string right now
ngramSearchKey := fmt.Sprintf("%s_%s", orgId, parsedValue)
ngramItem, err := GetDatastoreNGramItem(ctx, ngramSearchKey)
if err != nil || ngramItem == nil || ngramItem.Key == "" {
ngramItem = &NGramItem{
Key: parsedValue,
OrgId: orgId,
Amount: 1,
Ref: []string{
referenceKey,
},
}
err = SetDatastoreNGramItem(ctx, ngramSearchKey, ngramItem)
if err != nil {
log.Printf("[WARNING] Failed setting ngram item for cross-correlate: %s", err)
}
amountAdded += 1
if debug {
log.Printf("[DEBUG] Created new ngram item for %s with key '%s'", ngramSearchKey, parsedValue)
}
return
}
if ArrayContains(ngramItem.Ref, referenceKey) {
return
}
// Add the reference to the ngram item
amountAdded += 1
ngramItem.Ref = append(ngramItem.Ref, referenceKey)
ngramItem.Amount = len(ngramItem.Ref)
err = SetDatastoreNGramItem(ctx, ngramSearchKey, ngramItem)
if err != nil {
log.Printf("[WARNING] Failed setting ngram item for cross-correlate: %s", err)
} else {
if debug {
log.Printf("[DEBUG] Updated ngram item for %s with key %s", ngramSearchKey, parsedValue)
}
}
}(enrichment)
}
return nil
}
func parseInt(s string) int {
s = strings.TrimSpace(s)
val, err := strconv.Atoi(s)
if err != nil {
return 0 // default to 0 if parse fails
}
return val
}
func isValidSerial(s string) bool {
s = strings.ToLower(strings.TrimSpace(s))
if s == "" {
return false
}
bad := []string{
"to be filled",
"default string",
"o.e.m",
"unknown",
}
for _, b := range bad {
if strings.Contains(s, b) {
return false
}
}
return true
}
// MINOR validation:
// RCECleanup sanitizes a command string to reduce attack surface
// It removes/escapes shell metacharacters and dangerous patterns
func RCECleanup(command string) string {
if strings.HasPrefix(command, "script:") {
return command
}
// Not allowing large commands at all (for now)
maxCommandSize := 50
if os.Getenv("RCE_MAX_COMMAND_SIZE") != "" {
envSize := parseInt(os.Getenv("RCE_MAX_COMMAND_SIZE"))
if envSize > 0 {
maxCommandSize = envSize
}
}
if len(command) > maxCommandSize {
return ""
}
// Trim whitespace
command = strings.TrimSpace(command)
// Remove shell operators
dangerous := []string{
";", // Command chaining
"|", // Pipes
"&", // Background/AND
">", // Redirect
"<", // Redirect
"`", // Command substitution
"$", // Variable expansion
"\\", // Escape character
}
for _, char := range dangerous {
command = strings.ReplaceAll(command, char, "")
}
// Remove control characters (0x00-0x1F except tab/newline)
re := regexp.MustCompile(`[\x00-\x08\x0B-\x1F\x7F]`)
command = re.ReplaceAllString(command, "")
// Collapse multiple spaces
command = strings.Join(strings.Fields(command), " ")
return command
}
func HandleSensorResponseAction(hostname string, sensorDetails SensorMode, incRequest ExecutionRequest) {
if len(incRequest.ExecutionId) == 0 || len(incRequest.Authorization) == 0 {
log.Printf("[WARNING] Invalid execution request: missing execution ID or action")
return
}
if sensorDetails.ResponseActions != "controlled" && sensorDetails.ResponseActions != "full" {
return
}
if incRequest.Start == "" {
log.Printf("[WARNING] Invalid execution request: missing start ID for action reference")
return
}
// From Orborus
backendUrl := os.Getenv("BASE_URL")
if backendUrl == "" {
log.Printf("[ERROR] BASE_URL environment variable not set. Cannot execute response action.")
return
}
startTime := time.Now().Unix()
command := incRequest.ExecutionArgument
if sensorDetails.ResponseActions == "controlled" {
if !strings.HasPrefix(command, "script:") {
log.Printf("[WARNING] Invalid execution argument for controlled response action: %s. Must start with 'script:', which points to a valid cloud script.", command)
return
}
}
command = RCECleanup(command)
var out string
var err error
if strings.HasPrefix(strings.ToLower(command), "script:") {
if strings.HasPrefix(command, "script:isolate") {
allowedIPs := []string{}
// Nslookup the current backendUrl
if backendUrl != "" {
parsedUrl, err := url.Parse(backendUrl)
if err != nil {
log.Printf("[ERROR] Failed to parse backend URL '%s': %s", backendUrl, err)
} else {
host := parsedUrl.Hostname()
ips, err := net.LookupIP(host)
if err != nil {
log.Printf("[ERROR] Failed to lookup IP for host '%s': %s", host, err)
} else {
for _, ip := range ips {
if ip.String() == "::1" || strings.HasPrefix(ip.String(), "127.0.0") {
continue
}
allowedIPs = append(allowedIPs, ip.String())
}
}
}
}
if len(allowedIPs) == 0 {
out = "Failed to determine allowed IPs for isolation. Host isolation requires at least one allowed IP to be determined."
} else {
log.Printf("[WARNING] Isolating with URL %s. Allowed IPs: %#v", backendUrl, allowedIPs)
err := isolateHost(allowedIPs)
if err != nil {
log.Printf("[ERROR] Failed to isolate host: %s", err)
out = fmt.Sprintf("Failed to isolate host: %s", err.Error())
} else {
out = "Host isolated successfully"
err = nil
os.Setenv("HOST_ISOLATED", "true")
}
}
} else if strings.HasPrefix(command, "script:unisolate") {
err := unisolateHost()
if err != nil {
log.Printf("[ERROR] Failed to un-isolate host: %s", err)
} else {
out = "Host un-isolated successfully"
os.Setenv("HOST_ISOLATED", "false")
}
} else if strings.HasPrefix(command, "script:cbom ") {
filepath := strings.TrimPrefix(command, "script:cbom ")
out = fmt.Sprintf("CBOM scan of '%s' is not available yet", filepath)
err = nil
// For scanning a module at a specific path:
//app.NewGenerator(moduleDir) - For scanning applications
//bin.NewGenerator(binaryPath) - For scanning compiled binaries
//generator, err := mod.NewGenerator(
/*
generator, err := app.NewGenerator(
filepath,
)
if err != nil {
log.Printf("[ERROR] Failed to create CBOM generator: %s", err)
out = fmt.Sprintf("Failed to create CBOM gen: %s", err.Error())
} else {
bom, err := generator.Generate()
if err != nil {
log.Printf("[ERROR] Failed to generate CBOM: %s", err)
out = fmt.Sprintf("Failed run cbom generate: %s", err.Error())
} else {
outBytes, err := json.Marshal(bom)
if err != nil {
log.Printf("[ERROR] Failed to marshal CBOM output: %s", err)
out = fmt.Sprintf("Failed to marshal CBOM: %s", err.Error())
} else {
out = string(outBytes)
}
}
}
*/
} else {
log.Printf("[ERROR] Script-based response actions are not yet available. Cannot execute script: %s", command)
out = "Not available yet"
err = fmt.Errorf("script-based response actions are not available yet")
}
} else {
if len(command) == 0 {
return
}
if debug {
log.Printf("[DEBUG] RUNNING COMMAND '%s'", command)
}
out, err = RunCommandString(
command,
10*time.Second,
func(line string) {
if debug {
fmt.Println("DEBUG STREAM:", command, line)
}
},
)
}
if debug {
log.Printf("[DEBUG] Command output: '%s'. Error: %s", out, err)
}
parsedResult := RCEResult{
Success: true,
Hostname: hostname,
Command: command,
Output: out,
Error: "",
}
if err != nil {
parsedResult.Success = false
parsedResult.Error = err.Error()
}
marshalledResult, err := json.Marshal(parsedResult)
if err != nil {
log.Printf("[ERROR][%s] Failed to marshal RCE result: %s", incRequest.ExecutionId, err)
return
}
// From Orborus
fullUrl := fmt.Sprintf("%s/api/v1/streams", backendUrl)
topClient := GetExternalClient(fullUrl)
if debug {
log.Printf("[DEBUG] INCREQUEST: %#v", incRequest)
}
fullResult := ActionResult{
ExecutionId: incRequest.ExecutionId,
Authorization: incRequest.Authorization,
Action: Action{
AppName: "sensor",
AppID: "sensor",
ID: incRequest.Start,
},
StartedAt: startTime,
CompletedAt: time.Now().Unix(),
Result: string(marshalledResult),
}
fullResultData, err := json.Marshal(fullResult)
if err != nil {
log.Printf("[ERROR][%s] Failed to marshal action result: %s", incRequest.ExecutionId, err)
return
}
req, err := http.NewRequest(
"POST",
fullUrl,
bytes.NewBuffer([]byte(fullResultData)),
)
if err != nil {
log.Printf("[ERROR][%s] Failed to create HTTP request for response action result: %s", incRequest.ExecutionId, err)
return
}
req.Header.Set("Content-Type", "application/json")
resp, err := topClient.Do(req)
if err != nil {
log.Printf("[ERROR][%s] Failed to send response action result: %s", incRequest.ExecutionId, err)
return
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
log.Printf("[ERROR][%s] Failed to read response body after sending action result: %s", incRequest.ExecutionId, err)
return
}
if resp.StatusCode != 200 {
log.Printf("[ERROR][%s] Received non-200 response when sending action result to %s: %d. Body: %s", fullUrl, incRequest.ExecutionId, resp.StatusCode, string(respBody))
return
}
log.Printf("[INFO][%s] Successfully sent command action result. Status: %d, Result: %s. Bytes sent: %d", incRequest.ExecutionId, resp.StatusCode, string(respBody), len(fullResultData))
}
type StreamFn func(line string)
func truncateString(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n] + "…"
}
func sanitizePURL(name string) string {
return strings.ToLower(strings.ReplaceAll(name, " ", "-"))
}
func nvdTagsToOSVRefType(tags []string) string {
for _, tag := range tags {
switch strings.ToLower(tag) {
case "patch", "fix":
return "FIX"
case "exploit":
return "EVIDENCE"
case "issue tracking", "third party advisory":
return "REPORT"
case "vendor advisory":
return "ADVISORY"
case "mailing list", "technical description":
return "ARTICLE"
}
}
return "WEB"
}
// cvssScoreToSeverity maps a CVSS base score to a severity label.
func cvssScoreToSeverity(score float64) string {
switch {
case score >= 9.0:
return "CRITICAL"
case score >= 7.0:
return "HIGH"
case score >= 4.0:
return "MEDIUM"
case score > 0:
return "LOW"
default:
return "UNKNOWN"
}
}
func stripNoise(name string) string {
noiseTokens := []string{
"(x64)", "(x86)", "(arm64)", "(aarch64)",
"64-bit", "32-bit", "arm64", "aarch64",
" sdk", " runtime", " redistributable",
" service pack", " update", " patch",
".app", ".exe",
}
lower := strings.ToLower(name)
for _, tok := range noiseTokens {
lower = strings.ReplaceAll(lower, tok, "")
}
return strings.TrimSpace(lower)
}
// replaceCPEVersion swaps the version field (part [5]) in a CPE 2.3 string.
func replaceCPEVersion(cpe, version string) string {
if version == "" {
return cpe
}
parts := strings.Split(cpe, ":")
// cpe:2.3:type:vendor:product:VERSION:...
// 0 1 2 3 4 5
if len(parts) < 6 {
return cpe
}
parts[5] = version
return strings.Join(parts, ":")
}
// Special NVD handler
func (c *NVDClient) get(endpoint string, params url.Values) (*http.Response, error) {
u := "https://services.nvd.nist.gov/rest/json/" + endpoint + "?" + params.Encode()
req, err := http.NewRequest("GET", u, nil)
if err != nil {
return nil, err
}
if c.apiKey != "" {
req.Header.Set("apiKey", c.apiKey)
}
// NVD recommends a short sleep between requests when paginating.
// With an API key you get 50 req/30s; without, 5 req/30s.
// Caller is responsible for rate-limiting across concurrent use.
return c.httpClient.Do(req)
}
func (c *NVDClient) resolveCPE(name, version string) (string, error) {
cleaned := stripNoise(name)
params := url.Values{}
params.Set("keywordSearch", cleaned)
params.Set("resultsPerPage", "100")
resp, err := c.get("cpes/2.0", params)
if err != nil {
log.Printf("[ERROR] CPE search request failed for query %q: %s", cleaned, err)
return "", fmt.Errorf("CPE search request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Printf("[ERROR] CPE search HTTP %d for query %q", resp.StatusCode, cleaned)
return "", fmt.Errorf("CPE search HTTP %d", resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("[ERROR] CPE search read body failed for query %q: %s", cleaned, err)
return "", fmt.Errorf("CPE search read body: %w", err)
}
var result NVDCPEResponse
err = json.Unmarshal(body, &result)
if err != nil {
log.Printf("[ERROR] CPE search decode failed for query %q: %s", cleaned, err)
return "", fmt.Errorf("CPE search decode: %w", err)
}
if len(result.Products) == 0 {
log.Printf("[INFO] No CPEs found for query %q", cleaned)
return "", fmt.Errorf("no CPE found for %q", name)
}
// Pick the CPE whose product segment most closely matches our name,
// then inject the caller-supplied version into the CPE string.
best := result.Products[0].CPE.CPEName
bestScore := 0
cleanedWords := strings.Fields(cleaned)
// FIXME: Use the oldest version from the last 10 years somehow?
// Or how should it be done? The goal is to grab as many CVEs as possible
// IF the version itself can't be found
for _, p := range result.Products {
if len(version) > 5 && strings.Contains(strings.ToLower(p.CPE.CPEName), cleaned) && strings.Contains(strings.ToLower(p.CPE.CPEName), version) {
return p.CPE.CPEName, nil
}
// Has to be within the last 10 years
// Parse it from string first (2026-04-18T15:27:02.827)
lastModified, err := time.Parse("2006-01-02T15:04:05.999", p.CPE.LastModified)
if err != nil {
log.Printf("[ERROR] Failed to parse last modified date for CPE %s. Date: %s: %s", p.CPE.CPEName, p.CPE.LastModified, err)
continue
}
if lastModified.Before(time.Now().AddDate(-10, 0, 0)) {
continue
}
cpe := p.CPE.CPEName
score := 0
cpeLower := strings.ToLower(cpe)
for _, word := range cleanedWords {
if strings.Contains(cpeLower, word) {
score++
}
}
if score > bestScore {
bestScore = score
best = cpe
}
}
// CPE format: cpe:2.3:a:vendor:product:VERSION:...
// Replace the version segment (index 5) with the supplied version.
return replaceCPEVersion(best, version), nil
}
// buildOSVRange converts an NVD CPE match string into an OSV ECOSYSTEM range.
func buildOSVRange(match NVDCPEMatch) *OSVRange {
var events []OSVEvent
introduced := match.VersionStartIncluding
if introduced == "" && match.VersionStartExcluding == "" {
introduced = "0" // open-ended start
}
if introduced != "" {
events = append(events, OSVEvent{Introduced: introduced})
} else if match.VersionStartExcluding != "" {
// OSV doesn't have a direct "start excluding" — use introduced="0"
// and note this is an approximation.
events = append(events, OSVEvent{Introduced: "0"})
}
if match.VersionEndExcluding != "" {
events = append(events, OSVEvent{Fixed: match.VersionEndExcluding})
} else if match.VersionEndIncluding != "" {
events = append(events, OSVEvent{LastAffected: match.VersionEndIncluding})
}
if len(events) == 0 {
return nil
}
return &OSVRange{
Type: "ECOSYSTEM",
Events: events,
}
}
type NVDClient struct {
apiKey string
httpClient *http.Client
}
func NewNVDClient() *NVDClient {
return &NVDClient{
apiKey: os.Getenv("NVD_APIKEY"),
httpClient: &http.Client{
Timeout: 10 * time.Second,
},
}
}
func NVDToOSV(nvd NVDCVEDetail, softwareName, version string) OSVVulnerability {
lastModified, err := time.Parse("2006-01-02T15:04:05.999", nvd.LastModified)
if err != nil {
log.Printf("[ERROR] Failed to parse last modified date for CVE %s: %s", nvd.ID, err)
}
published, err := time.Parse("2006-01-02T15:04:05.999", nvd.Published)
if err != nil {
log.Printf("[ERROR] Failed to parse published date for CVE %s: %s", nvd.ID, err)
}
osv := OSVVulnerability{
SchemaVersion: "1.4.0",
ID: nvd.ID,
Modified: lastModified,
Published: published,
}
// Summary = first English description (truncated to ~120 chars for the field).
for _, d := range nvd.Descriptions {
if d.Lang == "en" {
osv.Summary = truncateString(d.Value, 120)
osv.Details = d.Value
break
}
}
// Aliases: NVD ID is authoritative; no additional aliases from this API.
// (If you have GHSA data, you'd add them here.)
// References — map NVD tags to OSV reference types.
for _, ref := range nvd.References {
osv.References = append(osv.References, OSVReference{
Type: nvdTagsToOSVRefType(ref.Tags),
URL: ref.URL,
})
}
// Always add the NVD page itself.
osv.References = append(osv.References, OSVReference{
Type: "ADVISORY",
URL: "https://nvd.nist.gov/vuln/detail/" + nvd.ID,
})
// Severity — prefer CVSS v3.1, fall back to v3.0, then v2.
var cvssVector string
var cvssScore float64
var cvssType string
switch {
case len(nvd.Metrics.CVSSMetricV31) > 0:
m := nvd.Metrics.CVSSMetricV31[0]
cvssVector = m.CVSSData.VectorString
cvssScore = m.CVSSData.BaseScore
cvssType = "CVSS_V3"
case len(nvd.Metrics.CVSSMetricV30) > 0:
m := nvd.Metrics.CVSSMetricV30[0]
cvssVector = m.CVSSData.VectorString
cvssScore = m.CVSSData.BaseScore
cvssType = "CVSS_V3"
case len(nvd.Metrics.CVSSMetricV2) > 0:
m := nvd.Metrics.CVSSMetricV2[0]
cvssVector = m.CVSSData.VectorString
cvssScore = m.CVSSData.BaseScore
cvssType = "CVSS_V2"
}
if cvssVector != "" {
osv.Severity = []OSVSeverity{{Type: cvssType, Score: cvssVector}}
}
// Affected block — one entry per software item.
affected := OSVAffected{
Package: OSVPackage{
Name: softwareName,
Ecosystem: "NVD",
Purl: fmt.Sprintf("pkg:generic/%s@%s", sanitizePURL(softwareName), version),
},
EcosystemSpecific: OSVEcosystemSpecific{
Severity: cvssScoreToSeverity(cvssScore),
},
DatabaseSpecific: OSVDatabaseSpecific{
Source: "https://nvd.nist.gov/vuln/detail/" + nvd.ID,
},
}
// Version ranges from CPE match data.
var ranges []OSVRange
for _, config := range nvd.Configurations {
for _, node := range config.Nodes {
for _, match := range node.CPEMatch {
if !match.Vulnerable {
continue
}
r := buildOSVRange(match)
if r != nil {
ranges = append(ranges, *r)
}