| 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 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
hexEntropyThreshold = 3.0 |
| 27 |
base64EntropyThreshold = 4.0 |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
base64Regex = `(?:[a-zA-Z0-9+/]{16,}|[a-zA-Z0-9_-]{16,})={0,2}` |
| 34 |
|
| 35 |
|
| 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 |
|
| 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 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 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 |
} |