Debian Codegraph @

pkg/detectors/generic/high_entropy_string_detector.go

raw symbols SCIP
1 package generic
2
3 import (
4 "math"
5 "regexp"
6 "strconv"
7 "strings"
8
9 "github.com/DefangLabs/secret-detector/pkg/detectors/helpers"
10 "github.com/DefangLabs/secret-detector/pkg/secrets"
11 )
12
13 const (
14 HighEntropyStringDetectorName = "high_entropy_string"
15 highEntropyStringDetectorSecretType = "High entropy string"
16
17 // hexEntropyThreshold and base64EntropyThreshold are magic numbers that were selected by trial & error.
18 // A low threshold might cause more false positive detections.
19 // A high threshold might cause more missed detections (false negative).
20 // We'll might want to change those numbers in the future according to results in production.
21 //
22 // min possible entropy level = all characters are similar = 0
23 // max possible entropy level = log2(len(charset))
24 // hex max = log2(16) = 4.0
25 // base64 max = log2(64) = 6.0
26 hexEntropyThreshold = 3.0
27 base64EntropyThreshold = 4.0
28
29 // base64Regex represents a regex that matches a valid base64 string.
30 // The minimum length allowed is 16 characters, not including padding.
31 //
32 // Note: this regex will also catch hexadecimal strings, since it is a subset of base64.
33 base64Regex = `(?:[a-zA-Z0-9+/]{16,}|[a-zA-Z0-9_-]{16,})={0,2}`
34
35 // hexExactRegex represents a regex that matches a valid hexadecimal string, with optional '0x' prefix.
36 hexExactRegex = `^(?:0x)?[0-9a-f]+$`
37 )
38
39 func init() {
40 secrets.GetDetectorFactory().Register(HighEntropyStringDetectorName, NewHighEntropyStringDetector)
41 }
42
43 type highEntropyStringDetector struct {
44 secrets.Detector
45 hexRegex *regexp.Regexp
46 entropyThreshold float64
47 }
48
49 func NewHighEntropyStringDetector(config ...string) secrets.Detector {
50 d := &highEntropyStringDetector{}
51 d.hexRegex = regexp.MustCompile(hexExactRegex)
52 d.Detector = helpers.NewRegexDetectorBuilder(highEntropyStringDetectorSecretType, base64Regex).WithVerifier(d.isHighEntropyString).Build()
53 if config != nil && len(config) > 0 {
54 threshold, err := strconv.ParseFloat(config[0], 64)
55 if err == nil {
56 d.entropyThreshold = threshold
57 }
58 }
59 return d
60 }
61
62 func (d *highEntropyStringDetector) isHighEntropyString(_, s string) bool {
63 // ignore digit only strings
64 if isNumeric(s) {
65 return false
66 }
67
68 entropyThreshold := 0.0
69 if d.entropyThreshold != 0.0 {
70 entropyThreshold = d.entropyThreshold
71 } else {
72 s = strings.TrimRight(s, "=")
73 entropyThreshold = base64EntropyThreshold
74 if d.isHexadecimal(s) {
75 entropyThreshold = hexEntropyThreshold
76 }
77 }
78
79 return CalcShannonEntropy(s) > entropyThreshold
80 }
81
82 func (d *highEntropyStringDetector) isHexadecimal(s string) bool {
83 return d.hexRegex.MatchString(s)
84 }
85
86 // CalcShannonEntropy calculates how random a string is.
87 // Minimal possible level is 0, which means that all characters in the string are similar.
88 // Maximal possible level is log2(len(s)), which means that all characters in the string are different from one another.
89 //
90 // Formula: sum( frequency(char) * log2(frequency(char)) )
91 // See more https://en.wikipedia.org/wiki/Entropy_(information_theory)
92 func CalcShannonEntropy(s string) float64 {
93 length := float64(len(s))
94 charCounts := make(map[rune]float64)
95 for _, c := range s {
96 charCounts[c]++
97 }
98
99 var sumFrequencies float64
100 for _, count := range charCounts {
101 f := count / length
102 sumFrequencies += -f * math.Log2(f)
103 }
104 return sumFrequencies
105 }
106
107 func isNumeric(s string) bool {
108 _, err := strconv.ParseFloat(s, 64)
109 return err == nil
110 }