Debian Codegraph @

pkg/detectors/keyword/keyword_detector.go

raw symbols SCIP
1 package keyword
2
3 import (
4 "fmt"
5 "strconv"
6 "strings"
7
8 "github.com/DefangLabs/secret-detector/pkg/detectors/generic"
9
10 "github.com/DefangLabs/secret-detector/pkg/detectors/helpers"
11 "github.com/DefangLabs/secret-detector/pkg/secrets"
12 )
13
14 const (
15 Name = "keyword"
16
17 // ValuesRegex exclude values starting with $ because they are usually variables
18 // exclude values surrounded by {} because they are usually computed expressions
19 ValuesRegex = `[^${\s].+[^}\s]`
20 )
21
22 func init() {
23 secrets.GetDetectorFactory().Register(Name, NewDetector)
24 }
25
26 var suspiciousKeysRegex = []string{
27 `api[-_]?key`,
28 `access[-_]?key`,
29 `auth[-_]?key`,
30 `service[-_]?key`,
31 `account[-_]?key`,
32 `db[-_]?key`,
33 `database[-_]?key`,
34 `priv[-_]?key`,
35 `private[-_]?key`,
36 `client[-_]?key`,
37 `db[-_]?pass`,
38 `database[-_]?pass`,
39 `key[-_]?pass`,
40 `password`,
41 `passwd`,
42 `pwd`,
43 `secret`,
44 `token`,
45 `contraseƱa`,
46 `contrasena`,
47 }
48
49 // detector scans for secret-sounding variable names.
50 type detector struct {
51 keyValueRegex *helpers.KeyValueRegex
52 keyRegex *helpers.ValueRegex
53 valueRegex *helpers.ValueRegex
54 valueEntropyThreshold float64
55 }
56
57 func NewDetector(config ...string) secrets.Detector {
58 keyRegex := fmt.Sprintf(`[\.\[~\-\w]*(?i)(?:%s)(?-i)[\.\[\]~\-\w]*`, strings.Join(suspiciousKeysRegex, "|"))
59
60 detector := &detector{
61 keyValueRegex: helpers.NewKeyValueRegex(keyRegex, ValuesRegex),
62 keyRegex: helpers.NewKeyRegex(keyRegex),
63 valueRegex: helpers.NewValueRegex(ValuesRegex),
64 }
65
66 if config != nil && len(config) > 0 {
67 threshold, err := strconv.ParseFloat(config[0], 64)
68 if err == nil {
69 detector.valueEntropyThreshold = threshold
70 }
71 }
72 return detector
73 }
74
75 func (_ *detector) SecretType() string {
76 return "Keyword Detector"
77 }
78
79 func (d *detector) Scan(in string) ([]secrets.DetectedSecret, error) {
80 res := make([]secrets.DetectedSecret, 0)
81 matches, err := d.keyValueRegex.FindAll(in)
82 for _, match := range matches {
83 if generic.CalcShannonEntropy(match.Value) >= d.valueEntropyThreshold {
84 res = append(res, secrets.DetectedSecret{Key: match.Key, Type: d.SecretType(), Value: match.Value})
85 }
86 }
87 return res, err
88 }
89
90 func (d *detector) ScanMap(keyValueMap map[string]string) ([]secrets.DetectedSecret, error) {
91 res := make([]secrets.DetectedSecret, 0)
92 for key, value := range keyValueMap {
93 if d.keyRegex.Match(key) && d.valueRegex.Match(value) {
94 if generic.CalcShannonEntropy(value) >= d.valueEntropyThreshold {
95 res = append(res, secrets.DetectedSecret{Key: key, Type: d.SecretType(), Value: value})
96 }
97 }
98 }
99 return res, nil
100 }