mirror of
https://github.com/gitleaks/gitleaks.git
synced 2026-11-29 04:34:46 +01:00
Merge branch 'master' of github.com:gitleaks/gitleaks into archive-handling
This commit is contained in:
commit
56e409d9f1
85 files changed
+2603
-1239
No files matched your search
@@ -0,0 +1,34 @@
|
||||
package codec
|
||||
|
||||
var printableASCII [256]bool
|
||||
|
||||
func init() {
|
||||
for b := 0; b < len(printableASCII); b++ {
|
||||
if '\x08' < b && b < '\x7f' {
|
||||
printableASCII[b] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// isPrintableASCII returns true if all bytes are printable ASCII
|
||||
func isPrintableASCII(b []byte) bool {
|
||||
for _, c := range b {
|
||||
if !printableASCII[c] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// hasByte can be used to check if a string has at least one of the provided
|
||||
// bytes. Note: make sure byteset is long enough to handle the largest byte in
|
||||
// the string.
|
||||
func hasByte(data string, byteset []bool) bool {
|
||||
for i := 0; i < len(data); i++ {
|
||||
if byteset[data[i]] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package codec
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
)
|
||||
|
||||
// likelyBase64Chars is a set of characters that you would expect to find at
|
||||
// least one of in base64 encoded data. This risks missing about 1% of
|
||||
// base64 encoded data that doesn't contain these characters, but gives you
|
||||
// the performance gain of not trying to decode a lot of long symbols in code.
|
||||
var likelyBase64Chars = make([]bool, 256)
|
||||
|
||||
func init() {
|
||||
for _, c := range `0123456789+/-_` {
|
||||
likelyBase64Chars[c] = true
|
||||
}
|
||||
}
|
||||
|
||||
// decodeBase64 decodes base64 encoded printable ASCII characters
|
||||
func decodeBase64(encodedValue string) string {
|
||||
// Exit early if it doesn't seem like base64
|
||||
if !hasByte(encodedValue, likelyBase64Chars) {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Try standard base64 decoding
|
||||
decodedValue, err := base64.StdEncoding.DecodeString(encodedValue)
|
||||
if err == nil && isPrintableASCII(decodedValue) {
|
||||
return string(decodedValue)
|
||||
}
|
||||
|
||||
// Try base64url decoding
|
||||
decodedValue, err = base64.RawURLEncoding.DecodeString(encodedValue)
|
||||
if err == nil && isPrintableASCII(decodedValue) {
|
||||
return string(decodedValue)
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package codec
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
)
|
||||
|
||||
// Decoder decodes various types of data in place
|
||||
type Decoder struct {
|
||||
decodedMap map[string]string
|
||||
}
|
||||
|
||||
// NewDecoder creates a default decoder struct
|
||||
func NewDecoder() *Decoder {
|
||||
return &Decoder{
|
||||
decodedMap: make(map[string]string),
|
||||
}
|
||||
}
|
||||
|
||||
// Decode returns the data with the values decoded in place along with the
|
||||
// encoded segment meta data for the next pass of decoding
|
||||
func (d *Decoder) Decode(data string, predecessors []*EncodedSegment) (string, []*EncodedSegment) {
|
||||
segments := d.findEncodedSegments(data, predecessors)
|
||||
|
||||
if len(segments) > 0 {
|
||||
result := bytes.NewBuffer(make([]byte, 0, len(data)))
|
||||
encodedStart := 0
|
||||
for _, segment := range segments {
|
||||
result.WriteString(data[encodedStart:segment.encoded.start])
|
||||
result.WriteString(segment.decodedValue)
|
||||
encodedStart = segment.encoded.end
|
||||
}
|
||||
|
||||
result.WriteString(data[encodedStart:])
|
||||
return result.String(), segments
|
||||
}
|
||||
|
||||
return data, segments
|
||||
}
|
||||
|
||||
// findEncodedSegments finds the encoded segments in the data
|
||||
func (d *Decoder) findEncodedSegments(data string, predecessors []*EncodedSegment) []*EncodedSegment {
|
||||
if len(data) == 0 {
|
||||
return []*EncodedSegment{}
|
||||
}
|
||||
|
||||
decodedShift := 0
|
||||
encodingMatches := findEncodingMatches(data)
|
||||
segments := make([]*EncodedSegment, 0, len(encodingMatches))
|
||||
for _, m := range encodingMatches {
|
||||
encodedValue := data[m.start:m.end]
|
||||
decodedValue, alreadyDecoded := d.decodedMap[encodedValue]
|
||||
|
||||
if !alreadyDecoded {
|
||||
decodedValue = m.encoding.decode(encodedValue)
|
||||
d.decodedMap[encodedValue] = decodedValue
|
||||
}
|
||||
|
||||
if len(decodedValue) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
segment := &EncodedSegment{
|
||||
predecessors: predecessors,
|
||||
original: toOriginal(predecessors, m.startEnd),
|
||||
encoded: m.startEnd,
|
||||
decoded: startEnd{
|
||||
m.start + decodedShift,
|
||||
m.start + decodedShift + len(decodedValue),
|
||||
},
|
||||
decodedValue: decodedValue,
|
||||
encodings: m.encoding.kind,
|
||||
depth: 1,
|
||||
}
|
||||
|
||||
// Shift decoded start and ends based on size changes
|
||||
decodedShift += len(decodedValue) - len(encodedValue)
|
||||
|
||||
// Adjust depth and encoding if applicable
|
||||
if len(segment.predecessors) != 0 {
|
||||
// Set the depth based on the predecessors' depth in the previous pass
|
||||
segment.depth = 1 + segment.predecessors[0].depth
|
||||
// Adjust encodings
|
||||
for _, p := range segment.predecessors {
|
||||
if segment.encoded.overlaps(p.decoded) {
|
||||
segment.encodings |= p.encodings
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
segments = append(segments, segment)
|
||||
logging.Debug().
|
||||
Str("decoder", m.encoding.kind.String()).
|
||||
Msgf(
|
||||
"segment found: original=%s pos=%s: %q -> %q",
|
||||
segment.original,
|
||||
segment.encoded,
|
||||
encodedValue,
|
||||
segment.decodedValue,
|
||||
)
|
||||
}
|
||||
|
||||
return segments
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
package detect
|
||||
package codec
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"encoding/hex"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDecode(t *testing.T) {
|
||||
@@ -66,8 +67,8 @@ func TestDecode(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "b64-url-safe: hyphen url b64",
|
||||
chunk: `dHJ1ZmZsZWhvZz4-ZmluZHMtc2VjcmV0cw`,
|
||||
expected: `trufflehog>>finds-secrets`,
|
||||
chunk: `Z2l0bGVha3M-PmZpbmRzLXNlY3JldHM`,
|
||||
expected: `gitleaks>>finds-secrets`,
|
||||
},
|
||||
{
|
||||
name: "b64-url-safe: underscore url b64",
|
||||
@@ -79,13 +80,49 @@ func TestDecode(t *testing.T) {
|
||||
chunk: `a3d3fa7c2bb99e469ba55e5834ce79ee4853a8a3`,
|
||||
expected: `a3d3fa7c2bb99e469ba55e5834ce79ee4853a8a3`,
|
||||
},
|
||||
{
|
||||
name: "url encoded value",
|
||||
chunk: `secret%3D%22q%24%21%40%23%24%25%5E%26%2A%28%20asdf%22`,
|
||||
expected: `secret="q$!@#$%^&*( asdf"`,
|
||||
},
|
||||
{
|
||||
name: "hex encoded value",
|
||||
chunk: `secret="466973684D617048756E6B79212121363334"`,
|
||||
expected: `secret="FishMapHunky!!!634"`,
|
||||
},
|
||||
}
|
||||
|
||||
decoder := NewDecoder()
|
||||
fullDecode := func(data string) string {
|
||||
segments := []*EncodedSegment{}
|
||||
for {
|
||||
data, segments = decoder.Decode(data, segments)
|
||||
if len(segments) == 0 {
|
||||
return data
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Test value decoding
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
decoded, _ := decoder.decode(tt.chunk, []EncodedSegment{})
|
||||
assert.Equal(t, tt.expected, decoded)
|
||||
assert.Equal(t, tt.expected, fullDecode(tt.chunk))
|
||||
})
|
||||
}
|
||||
|
||||
// Percent encode the values to test percent decoding
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
encodedChunk := url.PathEscape(tt.chunk)
|
||||
assert.Equal(t, tt.expected, fullDecode(encodedChunk))
|
||||
})
|
||||
}
|
||||
|
||||
// Hex encode the values to test hex decoding
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
encodedChunk := hex.EncodeToString([]byte(tt.chunk))
|
||||
assert.Equal(t, tt.expected, fullDecode(encodedChunk))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package codec
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
// encodingsRe is a regex built by combining all the encoding patterns
|
||||
// into named capture groups so that a single pass can detect multiple
|
||||
// encodings
|
||||
encodingsRe *regexp.Regexp
|
||||
// encodings contains all the encoding configurations for the detector.
|
||||
// The precedence is important. You want more specific encodings to
|
||||
// have a higher precedence or encodings that partially encode the
|
||||
// values (e.g. percent) unlike encodings that fully encode the string
|
||||
// (e.g. base64). If two encoding matches overlap the decoder will use
|
||||
// this order to determine which encoding should wait till the next pass.
|
||||
encodings = []*encoding{
|
||||
&encoding{
|
||||
kind: percentKind,
|
||||
pattern: `%[0-9A-Fa-f]{2}(?:.*%[0-9A-Fa-f]{2})?`,
|
||||
decode: decodePercent,
|
||||
},
|
||||
&encoding{
|
||||
kind: hexKind,
|
||||
pattern: `[0-9A-Fa-f]{32,}`,
|
||||
decode: decodeHex,
|
||||
},
|
||||
&encoding{
|
||||
kind: base64Kind,
|
||||
pattern: `[\w\/+-]{16,}={0,2}`,
|
||||
decode: decodeBase64,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// encodingNames is used to map the encodingKinds to their name
|
||||
var encodingNames = []string{
|
||||
"percent",
|
||||
"hex",
|
||||
"base64",
|
||||
}
|
||||
|
||||
// encodingKind can be or'd together to capture all of the unique encodings
|
||||
// that were present in a segment
|
||||
type encodingKind int
|
||||
|
||||
var (
|
||||
// make sure these go up by powers of 2
|
||||
percentKind = encodingKind(1)
|
||||
hexKind = encodingKind(2)
|
||||
base64Kind = encodingKind(4)
|
||||
)
|
||||
|
||||
func (e encodingKind) String() string {
|
||||
i := int(math.Log2(float64(e)))
|
||||
if i >= len(encodingNames) {
|
||||
return ""
|
||||
}
|
||||
return encodingNames[i]
|
||||
}
|
||||
|
||||
// kinds returns a list of encodingKinds combined in this one
|
||||
func (e encodingKind) kinds() []encodingKind {
|
||||
kinds := []encodingKind{}
|
||||
|
||||
for i := 0; i < len(encodingNames); i++ {
|
||||
if kind := int(e) & int(math.Pow(2, float64(i))); kind != 0 {
|
||||
kinds = append(kinds, encodingKind(kind))
|
||||
}
|
||||
}
|
||||
|
||||
return kinds
|
||||
}
|
||||
|
||||
// encodingMatch represents a match of an encoding in the text
|
||||
type encodingMatch struct {
|
||||
encoding *encoding
|
||||
startEnd
|
||||
}
|
||||
|
||||
// encoding represent a type of coding supported by the decoder.
|
||||
type encoding struct {
|
||||
// the kind of decoding (e.g. base64, etc)
|
||||
kind encodingKind
|
||||
// the regex pattern that matches the encoding format
|
||||
pattern string
|
||||
// take the match and return the decoded value
|
||||
decode func(string) string
|
||||
// determine which encoding should win out when two overlap
|
||||
precedence int
|
||||
}
|
||||
|
||||
func init() {
|
||||
count := len(encodings)
|
||||
namedPatterns := make([]string, count)
|
||||
for i, encoding := range encodings {
|
||||
encoding.precedence = count - i
|
||||
namedPatterns[i] = fmt.Sprintf(
|
||||
"(?P<%s>%s)",
|
||||
encoding.kind,
|
||||
encoding.pattern,
|
||||
)
|
||||
}
|
||||
encodingsRe = regexp.MustCompile(strings.Join(namedPatterns, "|"))
|
||||
}
|
||||
|
||||
// findEncodingMatches finds as many encodings as it can for this pass
|
||||
func findEncodingMatches(data string) []encodingMatch {
|
||||
var all []encodingMatch
|
||||
for _, matchIndex := range encodingsRe.FindAllStringSubmatchIndex(data, -1) {
|
||||
// Add the encodingMatch with its proper encoding
|
||||
for i, j := 2, 0; i < len(matchIndex); i, j = i+2, j+1 {
|
||||
if matchIndex[i] > -1 {
|
||||
all = append(all, encodingMatch{
|
||||
encoding: encodings[j],
|
||||
startEnd: startEnd{
|
||||
start: matchIndex[i],
|
||||
end: matchIndex[i+1],
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
totalMatches := len(all)
|
||||
if totalMatches == 1 {
|
||||
return all
|
||||
}
|
||||
|
||||
// filter out lower precedence ones that overlap their neigbors
|
||||
filtered := make([]encodingMatch, 0, len(all))
|
||||
for i, m := range all {
|
||||
if i > 0 {
|
||||
prev := all[i-1]
|
||||
if m.overlaps(prev.startEnd) && prev.encoding.precedence > m.encoding.precedence {
|
||||
continue // skip this one
|
||||
}
|
||||
}
|
||||
if i+1 < totalMatches {
|
||||
next := all[i+1]
|
||||
if m.overlaps(next.startEnd) && next.encoding.precedence > m.encoding.precedence {
|
||||
continue // skip this one
|
||||
}
|
||||
}
|
||||
filtered = append(filtered, m)
|
||||
}
|
||||
|
||||
return filtered
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package codec
|
||||
|
||||
// hexMap is a precalculated map of hex nibbles
|
||||
const hexMap = "" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\x0a\x0b\x0c\x0d\x0e\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\x0a\x0b\x0c\x0d\x0e\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"
|
||||
|
||||
// likelyHexChars is a set of characters that you would expect to find at
|
||||
// least one of in hex encoded data. This risks missing some hex data that
|
||||
// doesn't contain these characters, but gives you the performance gain of not
|
||||
// trying to decode a lot of long symbols in code.
|
||||
var likelyHexChars = make([]bool, 256)
|
||||
|
||||
func init() {
|
||||
for _, c := range `0123456789` {
|
||||
likelyHexChars[c] = true
|
||||
}
|
||||
}
|
||||
|
||||
// decodeHex decodes hex data
|
||||
func decodeHex(encodedValue string) string {
|
||||
size := len(encodedValue)
|
||||
// hex should have two characters per byte
|
||||
if size%2 != 0 {
|
||||
return ""
|
||||
}
|
||||
if !hasByte(encodedValue, likelyHexChars) {
|
||||
return ""
|
||||
}
|
||||
|
||||
decodedValue := make([]byte, size/2)
|
||||
for i := 0; i < size; i += 2 {
|
||||
n1 := hexMap[encodedValue[i]]
|
||||
n2 := hexMap[encodedValue[i+1]]
|
||||
if n1|n2 == '\xff' {
|
||||
return ""
|
||||
}
|
||||
b := byte(n1<<4 | n2)
|
||||
if !printableASCII[b] {
|
||||
return ""
|
||||
}
|
||||
decodedValue[i/2] = b
|
||||
}
|
||||
|
||||
return string(decodedValue)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package codec
|
||||
|
||||
// decodePercent decodes percent encoded strings
|
||||
func decodePercent(encodedValue string) string {
|
||||
encLen := len(encodedValue)
|
||||
decodedValue := make([]byte, encLen)
|
||||
decIndex := 0
|
||||
encIndex := 0
|
||||
|
||||
for encIndex < encLen {
|
||||
if encodedValue[encIndex] == '%' && encIndex+2 < encLen {
|
||||
n1 := hexMap[encodedValue[encIndex+1]]
|
||||
n2 := hexMap[encodedValue[encIndex+2]]
|
||||
// Make sure they're hex characters
|
||||
if n1|n2 != '\xff' {
|
||||
b := byte(n1<<4 | n2)
|
||||
if !printableASCII[b] {
|
||||
return ""
|
||||
}
|
||||
|
||||
decodedValue[decIndex] = b
|
||||
encIndex += 3
|
||||
decIndex += 1
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
decodedValue[decIndex] = encodedValue[encIndex]
|
||||
encIndex += 1
|
||||
decIndex += 1
|
||||
}
|
||||
|
||||
return string(decodedValue[:decIndex])
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package codec
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// EncodedSegment represents a portion of text that is encoded in some way.
|
||||
type EncodedSegment struct {
|
||||
// predecessors are all of the segments from the previous decoding pass
|
||||
predecessors []*EncodedSegment
|
||||
|
||||
// original start/end indices before decoding
|
||||
original startEnd
|
||||
|
||||
// encoded start/end indices relative to the previous decoding pass.
|
||||
// If it's a top level segment, original and encoded will be the
|
||||
// same.
|
||||
encoded startEnd
|
||||
|
||||
// decoded start/end indices in this pass after decoding
|
||||
decoded startEnd
|
||||
|
||||
// decodedValue contains the decoded string for this segment
|
||||
decodedValue string
|
||||
|
||||
// encodings is the encodings that make up this segment. encodingKind
|
||||
// can be or'd together to hold multiple encodings
|
||||
encodings encodingKind
|
||||
|
||||
// depth is how many decoding passes it took to decode this segment
|
||||
depth int
|
||||
}
|
||||
|
||||
// Tags returns additional meta data tags related to the types of segments
|
||||
func Tags(segments []*EncodedSegment) []string {
|
||||
// Return an empty list if we don't have any segments
|
||||
if len(segments) == 0 {
|
||||
return []string{}
|
||||
}
|
||||
|
||||
// Since decoding is done in passes, the depth of all the segments
|
||||
// should be the same
|
||||
depth := segments[0].depth
|
||||
|
||||
// Collect the encodings from the segments
|
||||
encodings := segments[0].encodings
|
||||
for i := 1; i < len(segments); i++ {
|
||||
encodings |= segments[i].encodings
|
||||
}
|
||||
|
||||
kinds := encodings.kinds()
|
||||
tags := make([]string, len(kinds)+1)
|
||||
|
||||
tags[len(tags)-1] = fmt.Sprintf("decode-depth:%d", depth)
|
||||
for i, kind := range kinds {
|
||||
tags[i] = fmt.Sprintf("decoded:%s", kind)
|
||||
}
|
||||
|
||||
return tags
|
||||
}
|
||||
|
||||
// CurrentLine returns from the start of the line containing the segments
|
||||
// to the end of the line where the segment ends.
|
||||
func CurrentLine(segments []*EncodedSegment, currentRaw string) string {
|
||||
// Return the whole thing if no segments are provided
|
||||
if len(segments) == 0 {
|
||||
return currentRaw
|
||||
}
|
||||
|
||||
start := 0
|
||||
end := len(currentRaw)
|
||||
|
||||
// Merge the ranges together into a single decoded value
|
||||
decoded := segments[0].decoded
|
||||
for i := 1; i < len(segments); i++ {
|
||||
decoded = decoded.merge(segments[i].decoded)
|
||||
}
|
||||
|
||||
// Find the start of the range
|
||||
for i := decoded.start; i > -1; i-- {
|
||||
c := currentRaw[i]
|
||||
if c == '\n' {
|
||||
start = i
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Find the end of the range
|
||||
for i := decoded.end; i < end; i++ {
|
||||
c := currentRaw[i]
|
||||
if c == '\n' {
|
||||
end = i
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return currentRaw[start:end]
|
||||
}
|
||||
|
||||
// AdjustMatchIndex maps a match index from the current decode pass back to
|
||||
// its location in the original text
|
||||
func AdjustMatchIndex(segments []*EncodedSegment, matchIndex []int) []int {
|
||||
// Don't adjust if we're not provided any segments
|
||||
if len(segments) == 0 {
|
||||
return matchIndex
|
||||
}
|
||||
|
||||
// Map the match to the location in the original text
|
||||
match := startEnd{matchIndex[0], matchIndex[1]}
|
||||
|
||||
// Map the match to its orignal location
|
||||
adjusted := toOriginal(segments, match)
|
||||
|
||||
// Return the adjusted match index
|
||||
return []int{
|
||||
adjusted.start,
|
||||
adjusted.end,
|
||||
}
|
||||
}
|
||||
|
||||
// SegmentsWithDecodedOverlap the segments where the start and end overlap its
|
||||
// decoded range
|
||||
func SegmentsWithDecodedOverlap(segments []*EncodedSegment, start, end int) []*EncodedSegment {
|
||||
se := startEnd{start, end}
|
||||
overlaps := []*EncodedSegment{}
|
||||
|
||||
for _, segment := range segments {
|
||||
if segment.decoded.overlaps(se) {
|
||||
overlaps = append(overlaps, segment)
|
||||
}
|
||||
}
|
||||
|
||||
return overlaps
|
||||
}
|
||||
|
||||
// toOriginal maps a start/end to its start/end in the original text
|
||||
// the provided start/end should be relative to the segment's decoded value
|
||||
func toOriginal(predecessors []*EncodedSegment, decoded startEnd) startEnd {
|
||||
if len(predecessors) == 0 {
|
||||
return decoded
|
||||
}
|
||||
|
||||
// Map the decoded value one level up where it was encoded
|
||||
encoded := startEnd{}
|
||||
|
||||
for _, p := range predecessors {
|
||||
if !p.decoded.overlaps(decoded) {
|
||||
continue // Not in scope
|
||||
}
|
||||
|
||||
// If fully contained, return the segments original start/end
|
||||
if p.decoded.contains(decoded) {
|
||||
return p.original
|
||||
}
|
||||
|
||||
// Map the value to be relative to the predecessors's decoded values
|
||||
if encoded.end == 0 {
|
||||
encoded = p.encoded.add(p.decoded.overflow(decoded))
|
||||
} else {
|
||||
encoded = encoded.merge(p.encoded.add(p.decoded.overflow(decoded)))
|
||||
}
|
||||
}
|
||||
|
||||
// Should only get here if the thing passed in wasn't in a decoded
|
||||
// value. This shouldn't be the case
|
||||
if encoded.end == 0 {
|
||||
return decoded
|
||||
}
|
||||
|
||||
// Climb up another level
|
||||
// (NOTE: each segment references all the predecessors)
|
||||
return toOriginal(predecessors[0].predecessors, encoded)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package codec
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// startEnd represents the start and end of some data. It mainly exists as a
|
||||
// helper when referencing the values
|
||||
type startEnd struct {
|
||||
start int
|
||||
end int
|
||||
}
|
||||
|
||||
// sub subtracts the values of two startEnds
|
||||
func (s startEnd) sub(o startEnd) startEnd {
|
||||
return startEnd{
|
||||
s.start - o.start,
|
||||
s.end - o.end,
|
||||
}
|
||||
}
|
||||
|
||||
// add adds the values of two startEnds
|
||||
func (s startEnd) add(o startEnd) startEnd {
|
||||
return startEnd{
|
||||
s.start + o.start,
|
||||
s.end + o.end,
|
||||
}
|
||||
}
|
||||
|
||||
// overlaps returns true if two startEnds overlap
|
||||
func (s startEnd) overlaps(o startEnd) bool {
|
||||
return o.start <= s.end && o.end >= s.start
|
||||
}
|
||||
|
||||
// contains returns true if the other is fully contained within this one
|
||||
func (s startEnd) contains(o startEnd) bool {
|
||||
return s.start <= o.start && o.end <= s.end
|
||||
}
|
||||
|
||||
// overflow returns a startEnd that tells how much the other goes outside the
|
||||
// bounds of this one
|
||||
func (s startEnd) overflow(o startEnd) startEnd {
|
||||
return s.merge(o).sub(s)
|
||||
}
|
||||
|
||||
// merge takes two start/ends and returns a single one that encompases both
|
||||
func (s startEnd) merge(o startEnd) startEnd {
|
||||
return startEnd{
|
||||
min(s.start, o.start),
|
||||
max(s.end, o.end),
|
||||
}
|
||||
}
|
||||
|
||||
// String returns a string representation for clearer debugging
|
||||
func (s startEnd) String() string {
|
||||
return fmt.Sprintf("[%d,%d]", s.start, s.end)
|
||||
}
|
||||
@@ -1,306 +0,0 @@
|
||||
package detect
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"unicode"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
)
|
||||
|
||||
var b64LikelyChars [128]byte
|
||||
var b64Regexp = regexp.MustCompile(`[\w/+-]{16,}={0,3}`)
|
||||
var decoders = []func(string) ([]byte, error){
|
||||
base64.StdEncoding.DecodeString,
|
||||
base64.RawURLEncoding.DecodeString,
|
||||
}
|
||||
|
||||
func init() {
|
||||
// Basically look for anything that isn't just letters
|
||||
for _, c := range `0123456789+/-_` {
|
||||
b64LikelyChars[c] = 1
|
||||
}
|
||||
}
|
||||
|
||||
// EncodedSegment represents a portion of text that is encoded in some way.
|
||||
// `decode` supports recusive decoding and can result in "segment trees".
|
||||
// There can be multiple segments in the original text, so each can be thought
|
||||
// of as its own tree with the root being the original segment.
|
||||
type EncodedSegment struct {
|
||||
// The parent segment in a segment tree. If nil, it is a root segment
|
||||
parent *EncodedSegment
|
||||
|
||||
// Relative start/end are the bounds of the encoded value in the current pass.
|
||||
relativeStart int
|
||||
relativeEnd int
|
||||
|
||||
// Absolute start/end refer to the bounds of the root segment in this segment
|
||||
// tree
|
||||
absoluteStart int
|
||||
absoluteEnd int
|
||||
|
||||
// Decoded start/end refer to the bounds of the decoded value in the current
|
||||
// pass. These can differ from relative values because decoding can shrink
|
||||
// or grow the size of the segment.
|
||||
decodedStart int
|
||||
decodedEnd int
|
||||
|
||||
// This is the actual decoded content in the segment
|
||||
decodedValue string
|
||||
|
||||
// This is the type of encoding
|
||||
encoding string
|
||||
}
|
||||
|
||||
// isChildOf inspects the bounds of two segments to determine
|
||||
// if one should be the child of another
|
||||
func (s EncodedSegment) isChildOf(parent EncodedSegment) bool {
|
||||
return parent.decodedStart <= s.relativeStart && parent.decodedEnd >= s.relativeEnd
|
||||
}
|
||||
|
||||
// decodedOverlaps checks if the decoded bounds of the segment overlaps a range
|
||||
func (s EncodedSegment) decodedOverlaps(start, end int) bool {
|
||||
return start <= s.decodedEnd && end >= s.decodedStart
|
||||
}
|
||||
|
||||
// adjustMatchIndex takes the matchIndex from the current decoding pass and
|
||||
// updates it to match the absolute matchIndex in the original text.
|
||||
func (s EncodedSegment) adjustMatchIndex(matchIndex []int) []int {
|
||||
// The match is within the bounds of the segment so we just return
|
||||
// the absolute start and end of the root segment.
|
||||
if s.decodedStart <= matchIndex[0] && matchIndex[1] <= s.decodedEnd {
|
||||
return []int{
|
||||
s.absoluteStart,
|
||||
s.absoluteEnd,
|
||||
}
|
||||
}
|
||||
|
||||
// Since it overlaps one side and/or the other, we're going to have to adjust
|
||||
// and climb parents until we're either at the root or we've determined
|
||||
// we're fully inside one of the parent segments.
|
||||
adjustedMatchIndex := make([]int, 2)
|
||||
|
||||
if matchIndex[0] < s.decodedStart {
|
||||
// It starts before the encoded segment so adjust the start to match
|
||||
// the location before it was decoded
|
||||
matchStartDelta := s.decodedStart - matchIndex[0]
|
||||
adjustedMatchIndex[0] = s.relativeStart - matchStartDelta
|
||||
} else {
|
||||
// It starts within the encoded segment so set the bound to the
|
||||
// relative start
|
||||
adjustedMatchIndex[0] = s.relativeStart
|
||||
}
|
||||
|
||||
if matchIndex[1] > s.decodedEnd {
|
||||
// It ends after the encoded segment so adjust the end to match
|
||||
// the location before it was decoded
|
||||
matchEndDelta := matchIndex[1] - s.decodedEnd
|
||||
adjustedMatchIndex[1] = s.relativeEnd + matchEndDelta
|
||||
} else {
|
||||
// It ends within the encoded segment so set the bound to the relative end
|
||||
adjustedMatchIndex[1] = s.relativeEnd
|
||||
}
|
||||
|
||||
// We're still not at a root segment so we'll need to keep on adjusting
|
||||
if s.parent != nil {
|
||||
return s.parent.adjustMatchIndex(adjustedMatchIndex)
|
||||
}
|
||||
|
||||
return adjustedMatchIndex
|
||||
}
|
||||
|
||||
// depth reports how many levels of decoding needed to be done (default is 1)
|
||||
func (s EncodedSegment) depth() int {
|
||||
depth := 1
|
||||
|
||||
// Climb the tree and increment the depth
|
||||
for current := &s; current.parent != nil; current = current.parent {
|
||||
depth++
|
||||
}
|
||||
|
||||
return depth
|
||||
}
|
||||
|
||||
// tags returns additional meta data tags related to the types of segments
|
||||
func (s EncodedSegment) tags() []string {
|
||||
return []string{
|
||||
fmt.Sprintf("decoded:%s", s.encoding),
|
||||
fmt.Sprintf("decode-depth:%d", s.depth()),
|
||||
}
|
||||
}
|
||||
|
||||
// Decoder decodes various types of data in place
|
||||
type Decoder struct {
|
||||
decodedMap map[string]string
|
||||
}
|
||||
|
||||
// NewDecoder creates a default decoder struct
|
||||
func NewDecoder() *Decoder {
|
||||
return &Decoder{
|
||||
decodedMap: make(map[string]string),
|
||||
}
|
||||
}
|
||||
|
||||
// decode returns the data with the values decoded in-place
|
||||
func (d *Decoder) decode(data string, parentSegments []EncodedSegment) (string, []EncodedSegment) {
|
||||
segments := d.findEncodedSegments(data, parentSegments)
|
||||
|
||||
if len(segments) > 0 {
|
||||
result := bytes.NewBuffer(make([]byte, 0, len(data)))
|
||||
|
||||
relativeStart := 0
|
||||
for _, segment := range segments {
|
||||
result.WriteString(data[relativeStart:segment.relativeStart])
|
||||
result.WriteString(segment.decodedValue)
|
||||
relativeStart = segment.relativeEnd
|
||||
}
|
||||
result.WriteString(data[relativeStart:])
|
||||
|
||||
return result.String(), segments
|
||||
}
|
||||
|
||||
return data, segments
|
||||
}
|
||||
|
||||
// findEncodedSegments finds the encoded segments in the data and updates the
|
||||
// segment tree for this pass
|
||||
func (d *Decoder) findEncodedSegments(data string, parentSegments []EncodedSegment) []EncodedSegment {
|
||||
if len(data) == 0 {
|
||||
return []EncodedSegment{}
|
||||
}
|
||||
|
||||
matchIndices := b64Regexp.FindAllStringIndex(data, -1)
|
||||
if matchIndices == nil {
|
||||
return []EncodedSegment{}
|
||||
}
|
||||
|
||||
segments := make([]EncodedSegment, 0, len(matchIndices))
|
||||
|
||||
// Keeps up with offsets from the text changing size as things are decoded
|
||||
decodedShift := 0
|
||||
|
||||
for _, matchIndex := range matchIndices {
|
||||
encodedValue := data[matchIndex[0]:matchIndex[1]]
|
||||
|
||||
if !isLikelyB64(encodedValue) {
|
||||
d.decodedMap[encodedValue] = ""
|
||||
continue
|
||||
}
|
||||
|
||||
decodedValue, alreadyDecoded := d.decodedMap[encodedValue]
|
||||
|
||||
// We haven't decoded this yet, so go ahead and decode it
|
||||
if !alreadyDecoded {
|
||||
decodedValue = decodeValue(encodedValue)
|
||||
d.decodedMap[encodedValue] = decodedValue
|
||||
}
|
||||
|
||||
// Skip this segment because there was nothing to check
|
||||
if len(decodedValue) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// Create a segment for the encoded data
|
||||
segment := EncodedSegment{
|
||||
relativeStart: matchIndex[0],
|
||||
relativeEnd: matchIndex[1],
|
||||
absoluteStart: matchIndex[0],
|
||||
absoluteEnd: matchIndex[1],
|
||||
decodedStart: matchIndex[0] + decodedShift,
|
||||
decodedEnd: matchIndex[0] + decodedShift + len(decodedValue),
|
||||
decodedValue: decodedValue,
|
||||
encoding: "base64",
|
||||
}
|
||||
|
||||
// Shift decoded start and ends based on size changes
|
||||
decodedShift += len(decodedValue) - len(encodedValue)
|
||||
|
||||
// Adjust the absolute position of segments contained in parent segments
|
||||
for _, parentSegment := range parentSegments {
|
||||
if segment.isChildOf(parentSegment) {
|
||||
segment.absoluteStart = parentSegment.absoluteStart
|
||||
segment.absoluteEnd = parentSegment.absoluteEnd
|
||||
segment.parent = &parentSegment
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
logging.Debug().Msgf("segment found: %#v", segment)
|
||||
segments = append(segments, segment)
|
||||
}
|
||||
|
||||
return segments
|
||||
}
|
||||
|
||||
// decoders tries a list of decoders and returns the first successful one
|
||||
func decodeValue(encodedValue string) string {
|
||||
for _, decoder := range decoders {
|
||||
decodedValue, err := decoder(encodedValue)
|
||||
|
||||
if err == nil && len(decodedValue) > 0 && isASCII(decodedValue) {
|
||||
return string(decodedValue)
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func isASCII(b []byte) bool {
|
||||
for i := 0; i < len(b); i++ {
|
||||
if b[i] > unicode.MaxASCII || b[i] < '\t' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Skip a lot of method signatures and things at the risk of missing about
|
||||
// 1% of base64
|
||||
func isLikelyB64(s string) bool {
|
||||
for _, c := range s {
|
||||
if b64LikelyChars[c] != 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// Find a segment where the decoded bounds overlaps a range
|
||||
func segmentWithDecodedOverlap(encodedSegments []EncodedSegment, start, end int) *EncodedSegment {
|
||||
for _, segment := range encodedSegments {
|
||||
if segment.decodedOverlaps(start, end) {
|
||||
return &segment
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s EncodedSegment) currentLine(currentRaw string) string {
|
||||
start := 0
|
||||
end := len(currentRaw)
|
||||
|
||||
// Find the start of the range
|
||||
for i := s.decodedStart; i > -1; i-- {
|
||||
c := currentRaw[i]
|
||||
if c == '\n' {
|
||||
start = i
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Find the end of the range
|
||||
for i := s.decodedEnd; i < end; i++ {
|
||||
c := currentRaw[i]
|
||||
if c == '\n' {
|
||||
end = i
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return currentRaw[start:end]
|
||||
}
|
||||
+183
-148
@@ -9,8 +9,10 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/detect/codec"
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
@@ -25,6 +27,10 @@ import (
|
||||
const (
|
||||
gitleaksAllowSignature = "gitleaks:allow"
|
||||
chunkSize = 100 * 1_000 // 100kb
|
||||
|
||||
// SlowWarningThreshold is the amount of time to wait before logging that a file is slow.
|
||||
// This is useful for identifying problematic files and tuning the allowlist.
|
||||
SlowWarningThreshold = 5 * time.Second
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -212,26 +218,39 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding {
|
||||
}
|
||||
d.TotalBytes.Add(uint64(len(fragment.Bytes)))
|
||||
|
||||
var findings []report.Finding
|
||||
var (
|
||||
findings []report.Finding
|
||||
logger = func() zerolog.Logger {
|
||||
l := logging.With().Str("path", fragment.FilePath)
|
||||
if fragment.CommitSHA != "" {
|
||||
l = l.Str("commit", fragment.CommitSHA)
|
||||
}
|
||||
return l.Logger()
|
||||
}()
|
||||
)
|
||||
|
||||
// check if filepath is allowed
|
||||
if fragment.FilePath != "" {
|
||||
// is the path our config or baseline file?
|
||||
if fragment.FilePath == d.Config.Path || (d.baselinePath != "" && fragment.FilePath == d.baselinePath) ||
|
||||
// is the path excluded by the global allowlist?
|
||||
(d.Config.Allowlist.PathAllowed(fragment.FilePath) || (fragment.WindowsFilePath != "" && d.Config.Allowlist.PathAllowed(fragment.WindowsFilePath))) {
|
||||
if fragment.FilePath == d.Config.Path || (d.baselinePath != "" && fragment.FilePath == d.baselinePath) {
|
||||
logging.Trace().Msg("skipping file: matches config or baseline path")
|
||||
return findings
|
||||
}
|
||||
}
|
||||
// check if commit or filepath is allowed.
|
||||
if isAllowed, event := checkCommitOrPathAllowed(logger, fragment, d.Config.Allowlists); isAllowed {
|
||||
event.Msg("skipping file: global allowlist")
|
||||
return findings
|
||||
}
|
||||
|
||||
// add newline indices for location calculation in detectRule
|
||||
fragment.newlineIndices = newLineRegexp.FindAllStringIndex(fragment.Raw, -1)
|
||||
|
||||
// setup variables to handle different decoding passes
|
||||
currentRaw := fragment.Raw
|
||||
encodedSegments := []EncodedSegment{}
|
||||
encodedSegments := []*codec.EncodedSegment{}
|
||||
currentDecodeDepth := 0
|
||||
decoder := NewDecoder()
|
||||
decoder := codec.NewDecoder()
|
||||
|
||||
for {
|
||||
// build keyword map for prefiltering rules
|
||||
@@ -268,7 +287,7 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding {
|
||||
}
|
||||
|
||||
// decode the currentRaw for the next pass
|
||||
currentRaw, encodedSegments = decoder.decode(currentRaw, encodedSegments)
|
||||
currentRaw, encodedSegments = decoder.Decode(currentRaw, encodedSegments)
|
||||
|
||||
// stop the loop when there's nothing else to decode
|
||||
if len(encodedSegments) == 0 {
|
||||
@@ -280,7 +299,7 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding {
|
||||
}
|
||||
|
||||
// detectRule scans the given fragment for the given rule and returns a list of findings
|
||||
func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rule, encodedSegments []EncodedSegment) []report.Finding {
|
||||
func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rule, encodedSegments []*codec.EncodedSegment) []report.Finding {
|
||||
var (
|
||||
findings []report.Finding
|
||||
logger = func() zerolog.Logger {
|
||||
@@ -292,46 +311,10 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
|
||||
}()
|
||||
)
|
||||
|
||||
// check if filepath or commit is allowed for this rule
|
||||
for _, a := range r.Allowlists {
|
||||
var (
|
||||
isAllowed bool
|
||||
commitAllowed, commit = a.CommitAllowed(fragment.CommitSHA)
|
||||
pathAllowed = a.PathAllowed(fragment.FilePath) || (fragment.WindowsFilePath != "" && a.PathAllowed(fragment.WindowsFilePath))
|
||||
)
|
||||
if a.MatchCondition == config.AllowlistMatchAnd {
|
||||
// Determine applicable checks.
|
||||
var allowlistChecks []bool
|
||||
if len(a.Commits) > 0 {
|
||||
allowlistChecks = append(allowlistChecks, commitAllowed)
|
||||
}
|
||||
if len(a.Paths) > 0 {
|
||||
allowlistChecks = append(allowlistChecks, pathAllowed)
|
||||
}
|
||||
// These will be checked later.
|
||||
if len(a.Regexes) > 0 {
|
||||
allowlistChecks = append(allowlistChecks, false)
|
||||
}
|
||||
if len(a.StopWords) > 0 {
|
||||
allowlistChecks = append(allowlistChecks, false)
|
||||
}
|
||||
|
||||
// Check if allowed.
|
||||
isAllowed = allTrue(allowlistChecks)
|
||||
} else {
|
||||
isAllowed = commitAllowed || pathAllowed
|
||||
}
|
||||
if isAllowed {
|
||||
event := logger.Trace().Str("condition", a.MatchCondition.String())
|
||||
if commitAllowed {
|
||||
event.Str("allowed-commit", commit)
|
||||
}
|
||||
if pathAllowed {
|
||||
event.Bool("allowed-path", pathAllowed)
|
||||
}
|
||||
event.Msg("skipping file: rule allowlist")
|
||||
return findings
|
||||
}
|
||||
// check if commit or file is allowed for this rule.
|
||||
if isAllowed, event := checkCommitOrPathAllowed(logger, fragment, r.Allowlists); isAllowed {
|
||||
event.Msg("skipping file: rule allowlist")
|
||||
return findings
|
||||
}
|
||||
|
||||
if r.Path != nil {
|
||||
@@ -377,7 +360,6 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
|
||||
|
||||
// use currentRaw instead of fragment.Raw since this represents the current
|
||||
// decoding pass on the text
|
||||
MatchLoop:
|
||||
for _, matchIndex := range r.Regex.FindAllStringIndex(currentRaw, -1) {
|
||||
// Extract secret from match
|
||||
secret := strings.Trim(currentRaw[matchIndex[0]:matchIndex[1]], "\n")
|
||||
@@ -389,14 +371,15 @@ MatchLoop:
|
||||
// Check if the decoded portions of the segment overlap with the match
|
||||
// to see if its potentially a new match
|
||||
if len(encodedSegments) > 0 {
|
||||
if segment := segmentWithDecodedOverlap(encodedSegments, matchIndex[0], matchIndex[1]); segment != nil {
|
||||
matchIndex = segment.adjustMatchIndex(matchIndex)
|
||||
metaTags = append(metaTags, segment.tags()...)
|
||||
currentLine = segment.currentLine(currentRaw)
|
||||
} else {
|
||||
segments := codec.SegmentsWithDecodedOverlap(encodedSegments, matchIndex[0], matchIndex[1])
|
||||
if len(segments) == 0 {
|
||||
// This item has already been added to a finding
|
||||
continue
|
||||
}
|
||||
|
||||
matchIndex = codec.AdjustMatchIndex(segments, matchIndex)
|
||||
metaTags = append(metaTags, codec.Tags(segments)...)
|
||||
currentLine = codec.CurrentLine(segments, currentRaw)
|
||||
} else {
|
||||
// Fixes: https://github.com/gitleaks/gitleaks/issues/1352
|
||||
// removes the incorrectly following line that was detected by regex expression '\n'
|
||||
@@ -474,109 +457,22 @@ MatchLoop:
|
||||
}
|
||||
}
|
||||
|
||||
if d.Config.Allowlist != nil {
|
||||
// check if the regexTarget is defined in the allowlist "regexes" entry
|
||||
// or if the secret is in the list of stopwords
|
||||
globalAllowlistTarget := finding.Secret
|
||||
switch d.Config.Allowlist.RegexTarget {
|
||||
case "match":
|
||||
globalAllowlistTarget = finding.Match
|
||||
case "line":
|
||||
globalAllowlistTarget = currentLine
|
||||
}
|
||||
if d.Config.Allowlist.RegexAllowed(globalAllowlistTarget) {
|
||||
logger.Trace().
|
||||
Str("finding", globalAllowlistTarget).
|
||||
Msg("skipping finding: global allowlist regex")
|
||||
continue
|
||||
} else if ok, word := d.Config.Allowlist.ContainsStopWord(finding.Secret); ok {
|
||||
logger.Trace().
|
||||
Str("finding", finding.Secret).
|
||||
Str("allowed-stopword", word).
|
||||
Msg("skipping finding: global allowlist stopword")
|
||||
continue
|
||||
}
|
||||
// check if the result matches any of the global allowlists.
|
||||
if isAllowed, event := checkFindingAllowed(logger, finding, fragment, currentLine, d.Config.Allowlists); isAllowed {
|
||||
event.Msg("skipping finding: global allowlist")
|
||||
continue
|
||||
}
|
||||
|
||||
// check if the result matches any of the rule allowlists.
|
||||
for _, a := range r.Allowlists {
|
||||
allowlistTarget := finding.Secret
|
||||
switch a.RegexTarget {
|
||||
case "match":
|
||||
allowlistTarget = finding.Match
|
||||
case "line":
|
||||
allowlistTarget = currentLine
|
||||
}
|
||||
|
||||
var (
|
||||
isAllowed bool
|
||||
commitAllowed bool
|
||||
commit string
|
||||
pathAllowed bool
|
||||
regexAllowed = a.RegexAllowed(allowlistTarget)
|
||||
containsStopword, word = a.ContainsStopWord(finding.Secret)
|
||||
)
|
||||
// check if the secret is in the list of stopwords
|
||||
if a.MatchCondition == config.AllowlistMatchAnd {
|
||||
// Determine applicable checks.
|
||||
var allowlistChecks []bool
|
||||
if len(a.Commits) > 0 {
|
||||
commitAllowed, commit = a.CommitAllowed(fragment.CommitSHA)
|
||||
allowlistChecks = append(allowlistChecks, commitAllowed)
|
||||
}
|
||||
if len(a.Paths) > 0 {
|
||||
pathAllowed = a.PathAllowed(fragment.FilePath) || (fragment.WindowsFilePath != "" && a.PathAllowed(fragment.WindowsFilePath))
|
||||
allowlistChecks = append(allowlistChecks, pathAllowed)
|
||||
}
|
||||
if len(a.Regexes) > 0 {
|
||||
allowlistChecks = append(allowlistChecks, regexAllowed)
|
||||
}
|
||||
if len(a.StopWords) > 0 {
|
||||
allowlistChecks = append(allowlistChecks, containsStopword)
|
||||
}
|
||||
|
||||
// Check if allowed.
|
||||
isAllowed = allTrue(allowlistChecks)
|
||||
} else {
|
||||
isAllowed = regexAllowed || containsStopword
|
||||
}
|
||||
|
||||
if isAllowed {
|
||||
event := logger.Trace().
|
||||
Str("finding", finding.Secret).
|
||||
Str("condition", a.MatchCondition.String())
|
||||
if commitAllowed {
|
||||
event.Str("allowed-commit", commit)
|
||||
}
|
||||
if pathAllowed {
|
||||
event.Bool("allowed-path", pathAllowed)
|
||||
}
|
||||
if regexAllowed {
|
||||
event.Bool("allowed-regex", regexAllowed)
|
||||
}
|
||||
if containsStopword {
|
||||
event.Str("allowed-stopword", word)
|
||||
}
|
||||
event.Msg("skipping finding: rule allowlist")
|
||||
continue MatchLoop
|
||||
}
|
||||
if isAllowed, event := checkFindingAllowed(logger, finding, fragment, currentLine, r.Allowlists); isAllowed {
|
||||
event.Msg("skipping finding: rule allowlist")
|
||||
continue
|
||||
}
|
||||
findings = append(findings, finding)
|
||||
}
|
||||
return findings
|
||||
}
|
||||
|
||||
func allTrue(bools []bool) bool {
|
||||
allMatch := true
|
||||
for _, check := range bools {
|
||||
if !check {
|
||||
allMatch = false
|
||||
break
|
||||
}
|
||||
}
|
||||
return allMatch
|
||||
}
|
||||
|
||||
// AddFinding synchronously adds a finding to the findings slice
|
||||
func (d *Detector) AddFinding(finding report.Finding) {
|
||||
globalFingerprint := fmt.Sprintf("%s:%s:%d", finding.File, finding.RuleID, finding.StartLine)
|
||||
@@ -627,3 +523,142 @@ func (d *Detector) Findings() []report.Finding {
|
||||
func (d *Detector) addCommit(commit string) {
|
||||
d.commitMap[commit] = true
|
||||
}
|
||||
|
||||
// checkCommitOrPathAllowed evaluates |fragment| against all provided |allowlists|.
|
||||
//
|
||||
// If the match condition is "OR", only commit and path are checked.
|
||||
// Otherwise, if regexes or stopwords are defined this will fail.
|
||||
func checkCommitOrPathAllowed(
|
||||
logger zerolog.Logger,
|
||||
fragment Fragment,
|
||||
allowlists []*config.Allowlist,
|
||||
) (bool, *zerolog.Event) {
|
||||
if fragment.FilePath == "" && fragment.CommitSHA == "" {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
for _, a := range allowlists {
|
||||
var (
|
||||
isAllowed bool
|
||||
allowlistChecks []bool
|
||||
commitAllowed, _ = a.CommitAllowed(fragment.CommitSHA)
|
||||
pathAllowed = a.PathAllowed(fragment.FilePath) || (fragment.WindowsFilePath != "" && a.PathAllowed(fragment.WindowsFilePath))
|
||||
)
|
||||
// If the condition is "AND" we need to check all conditions.
|
||||
if a.MatchCondition == config.AllowlistMatchAnd {
|
||||
if len(a.Commits) > 0 {
|
||||
allowlistChecks = append(allowlistChecks, commitAllowed)
|
||||
}
|
||||
if len(a.Paths) > 0 {
|
||||
allowlistChecks = append(allowlistChecks, pathAllowed)
|
||||
}
|
||||
// These will be checked later.
|
||||
if len(a.Regexes) > 0 {
|
||||
continue
|
||||
}
|
||||
if len(a.StopWords) > 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
isAllowed = allTrue(allowlistChecks)
|
||||
} else {
|
||||
isAllowed = commitAllowed || pathAllowed
|
||||
}
|
||||
if isAllowed {
|
||||
event := logger.Trace().Str("condition", a.MatchCondition.String())
|
||||
if commitAllowed {
|
||||
event.Bool("allowed-commit", commitAllowed)
|
||||
}
|
||||
if pathAllowed {
|
||||
event.Bool("allowed-path", pathAllowed)
|
||||
}
|
||||
return true, event
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// checkFindingAllowed evaluates |finding| against all provided |allowlists|.
|
||||
//
|
||||
// If the match condition is "OR", only regex and stopwords are run. (Commit and path should be handled separately).
|
||||
// Otherwise, all conditions are checked.
|
||||
//
|
||||
// TODO: The method signature is awkward. I can't think of a better way to log helpful info.
|
||||
func checkFindingAllowed(
|
||||
logger zerolog.Logger,
|
||||
finding report.Finding,
|
||||
fragment Fragment,
|
||||
currentLine string,
|
||||
allowlists []*config.Allowlist,
|
||||
) (bool, *zerolog.Event) {
|
||||
for _, a := range allowlists {
|
||||
allowlistTarget := finding.Secret
|
||||
switch a.RegexTarget {
|
||||
case "match":
|
||||
allowlistTarget = finding.Match
|
||||
case "line":
|
||||
allowlistTarget = currentLine
|
||||
}
|
||||
|
||||
var (
|
||||
checks []bool
|
||||
isAllowed bool
|
||||
commitAllowed bool
|
||||
commit string
|
||||
pathAllowed bool
|
||||
regexAllowed = a.RegexAllowed(allowlistTarget)
|
||||
containsStopword, word = a.ContainsStopWord(finding.Secret)
|
||||
)
|
||||
// If the condition is "AND" we need to check all conditions.
|
||||
if a.MatchCondition == config.AllowlistMatchAnd {
|
||||
// Determine applicable checks.
|
||||
if len(a.Commits) > 0 {
|
||||
commitAllowed, commit = a.CommitAllowed(fragment.CommitSHA)
|
||||
checks = append(checks, commitAllowed)
|
||||
}
|
||||
if len(a.Paths) > 0 {
|
||||
pathAllowed = a.PathAllowed(fragment.FilePath) || (fragment.WindowsFilePath != "" && a.PathAllowed(fragment.WindowsFilePath))
|
||||
checks = append(checks, pathAllowed)
|
||||
}
|
||||
if len(a.Regexes) > 0 {
|
||||
checks = append(checks, regexAllowed)
|
||||
}
|
||||
if len(a.StopWords) > 0 {
|
||||
checks = append(checks, containsStopword)
|
||||
}
|
||||
|
||||
isAllowed = allTrue(checks)
|
||||
} else {
|
||||
isAllowed = regexAllowed || containsStopword
|
||||
}
|
||||
|
||||
if isAllowed {
|
||||
event := logger.Trace().
|
||||
Str("finding", finding.Secret).
|
||||
Str("condition", a.MatchCondition.String())
|
||||
if commitAllowed {
|
||||
event.Str("allowed-commit", commit)
|
||||
}
|
||||
if pathAllowed {
|
||||
event.Bool("allowed-path", pathAllowed)
|
||||
}
|
||||
if regexAllowed {
|
||||
event.Bool("allowed-regex", regexAllowed)
|
||||
}
|
||||
if containsStopword {
|
||||
event.Str("allowed-stopword", word)
|
||||
}
|
||||
return true, event
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func allTrue(bools []bool) bool {
|
||||
for _, check := range bools {
|
||||
if !check {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
+398
-175
@@ -17,6 +17,7 @@ import (
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/scm"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/detect/codec"
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
@@ -26,7 +27,7 @@ import (
|
||||
const maxDecodeDepth = 8
|
||||
const configPath = "../testdata/config/"
|
||||
const repoBasePath = "../testdata/repos/"
|
||||
const b64TestValues = `
|
||||
const encodedTestValues = `
|
||||
# Decoded
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
135f/bRUBHrbHqLY/xS3I7Oth+8rgG+0tBwfMcbk05Sgxq6QUzSYIQAop+WvsTwk2sR+C38g0Mnb
|
||||
@@ -44,16 +45,48 @@ eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiY29uZmlnIjoiVzJ
|
||||
c21hbGwtc2VjcmV0
|
||||
|
||||
# This tests how it handles when the match bounds go outside the decoded value
|
||||
secret=ZGVjb2RlZC1zZWNyZXQtdmFsdWU=
|
||||
secret=ZGVjb2RlZC1zZWNyZXQtdmFsdWUwMA==
|
||||
# The above encoded again
|
||||
c2VjcmV0PVpHVmpiMlJsWkMxelpXTnlaWFF0ZG1Gc2RXVT0=
|
||||
|
||||
# Confirm you can ignore on the decoded value
|
||||
password="bFJxQkstejVrZjQtcGxlYXNlLWlnbm9yZS1tZS1YLVhJSk0yUGRkdw=="
|
||||
|
||||
# This tests that it can do hex encoded data
|
||||
secret=6465636F6465642D7365637265742D76616C756576484558
|
||||
|
||||
# This tests that it can do percent encoded data
|
||||
## partial encoded data
|
||||
secret=decoded-%73%65%63%72%65%74-valuev2
|
||||
## scattered encoded
|
||||
secret=%64%65coded-%73%65%63%72%65%74-valuev3
|
||||
|
||||
# Test multi levels of encoding where the source is a partal encoding
|
||||
# it is important that the bounds of the predecessors are properly
|
||||
# considered
|
||||
## single percent encoding in the middle of multi layer b64
|
||||
c2VjcmV0PVpHVmpiMl%4AsWkMxelpXTnlaWFF0ZG1Gc2RXVjJOQT09
|
||||
## single percent encoding at the beginning of hex
|
||||
secret%3d6465636F6465642D7365637265742D76616C75657635
|
||||
## multiple percent encodings in a single layer base64
|
||||
secret=ZGVjb2%52lZC1zZWNyZXQtdm%46sdWV4ODY= # ends in x86
|
||||
## base64 encoded partially percent encoded value
|
||||
secret=ZGVjb2RlZC0lNzMlNjUlNjMlNzIlNjUlNzQtdmFsdWU=
|
||||
## one of the lines above that went through... a lot
|
||||
## and there's surrounding text around it
|
||||
Look at this value: %4EjMzMjU2NkE2MzZENTYzMDUwNTY3MDQ4%4eTY2RDcwNjk0RDY5NTUzMTRENkQ3ODYx%25%34%65TE3QTQ2MzY1NzZDNjQ0RjY1NTY3MDU5NTU1ODUyNkI2MjUzNTUzMDRFNkU0RTZCNTYzMTU1MzkwQQ== # isn't it crazy?
|
||||
## Multi percent encode two random characters close to the bounds of the base64
|
||||
## encoded data to make sure that the bounds are still correctly calculated
|
||||
secret=ZG%25%32%35%25%33%32%25%33%35%25%32%35%25%33%33%25%33%35%25%32%35%25%33%33%25%33%36%25%32%35%25%33%32%25%33%35%25%32%35%25%33%33%25%33%36%25%32%35%25%33%36%25%33%31%25%32%35%25%33%32%25%33%35%25%32%35%25%33%33%25%33%36%25%32%35%25%33%33%25%33%322RlZC1zZWNyZXQtd%25%36%64%25%34%36%25%37%33dWU=
|
||||
## The similar to the above but also touching the edge of the base64
|
||||
secret=%25%35%61%25%34%37%25%35%36jb2RlZC1zZWNyZXQtdmFsdWU%25%32%35%25%33%33%25%36%34
|
||||
## The similar to the above but also touching and overlapping the base64
|
||||
secret%3D%25%35%61%25%34%37%25%35%36jb2RlZC1zZWNyZXQtdmFsdWU%25%32%35%25%33%33%25%36%34
|
||||
`
|
||||
|
||||
func TestDetect(t *testing.T) {
|
||||
tests := []struct {
|
||||
logging.Logger = logging.Logger.Level(zerolog.TraceLevel)
|
||||
tests := map[string]struct {
|
||||
cfgName string
|
||||
baselinePath string
|
||||
fragment Fragment
|
||||
@@ -65,14 +98,15 @@ func TestDetect(t *testing.T) {
|
||||
expectedFindings []report.Finding
|
||||
wantError error
|
||||
}{
|
||||
{
|
||||
// General
|
||||
"valid allow comment (1)": {
|
||||
cfgName: "simple",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \"AKIALALEMEL33243OKIA\ // gitleaks:allow"`,
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
},
|
||||
{
|
||||
"valid allow comment (2)": {
|
||||
cfgName: "simple",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \
|
||||
@@ -83,7 +117,7 @@ func TestDetect(t *testing.T) {
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
},
|
||||
{
|
||||
"invalid allow comment": {
|
||||
cfgName: "simple",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \"AKIALALEMEL33243OKIA\"
|
||||
@@ -110,30 +144,7 @@ func TestDetect(t *testing.T) {
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "escaped_character_group",
|
||||
fragment: Fragment{
|
||||
Raw: `pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB`,
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
Description: "PyPI upload token",
|
||||
Secret: "pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB",
|
||||
Match: "pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB",
|
||||
Line: `pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB`,
|
||||
File: "tmp.go",
|
||||
RuleID: "pypi-upload-token",
|
||||
Tags: []string{"key", "pypi"},
|
||||
StartLine: 0,
|
||||
EndLine: 0,
|
||||
StartColumn: 1,
|
||||
EndColumn: 86,
|
||||
Entropy: 1.9606875,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"detect finding - aws": {
|
||||
cfgName: "simple",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||
@@ -141,22 +152,22 @@ func TestDetect(t *testing.T) {
|
||||
},
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
Description: "AWS Access Key",
|
||||
Secret: "AKIALALEMEL33243OLIA",
|
||||
Match: "AKIALALEMEL33243OLIA",
|
||||
Line: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||
File: "tmp.go",
|
||||
RuleID: "aws-access-key",
|
||||
Tags: []string{"key", "AWS"},
|
||||
Description: "AWS Access Key",
|
||||
File: "tmp.go",
|
||||
Line: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||
Match: "AKIALALEMEL33243OLIA",
|
||||
Secret: "AKIALALEMEL33243OLIA",
|
||||
Entropy: 3.0841837,
|
||||
StartLine: 0,
|
||||
EndLine: 0,
|
||||
StartColumn: 15,
|
||||
EndColumn: 34,
|
||||
Entropy: 3.0841837,
|
||||
Tags: []string{"key", "AWS"},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"detect finding - sidekiq env var": {
|
||||
cfgName: "simple",
|
||||
fragment: Fragment{
|
||||
Raw: `export BUNDLE_ENTERPRISE__CONTRIBSYS__COM=cafebabe:deadbeef;`,
|
||||
@@ -164,22 +175,22 @@ func TestDetect(t *testing.T) {
|
||||
},
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
RuleID: "sidekiq-secret",
|
||||
Description: "Sidekiq Secret",
|
||||
File: "tmp.sh",
|
||||
Line: `export BUNDLE_ENTERPRISE__CONTRIBSYS__COM=cafebabe:deadbeef;`,
|
||||
Match: "BUNDLE_ENTERPRISE__CONTRIBSYS__COM=cafebabe:deadbeef;",
|
||||
Secret: "cafebabe:deadbeef",
|
||||
Line: `export BUNDLE_ENTERPRISE__CONTRIBSYS__COM=cafebabe:deadbeef;`,
|
||||
File: "tmp.sh",
|
||||
RuleID: "sidekiq-secret",
|
||||
Tags: []string{},
|
||||
Entropy: 2.6098502,
|
||||
StartLine: 0,
|
||||
EndLine: 0,
|
||||
StartColumn: 8,
|
||||
EndColumn: 60,
|
||||
Tags: []string{},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"detect finding - sidekiq env var, semicolon": {
|
||||
cfgName: "simple",
|
||||
fragment: Fragment{
|
||||
Raw: `echo hello1; export BUNDLE_ENTERPRISE__CONTRIBSYS__COM="cafebabe:deadbeef" && echo hello2`,
|
||||
@@ -187,22 +198,22 @@ func TestDetect(t *testing.T) {
|
||||
},
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
RuleID: "sidekiq-secret",
|
||||
Description: "Sidekiq Secret",
|
||||
Match: "BUNDLE_ENTERPRISE__CONTRIBSYS__COM=\"cafebabe:deadbeef\"",
|
||||
Secret: "cafebabe:deadbeef",
|
||||
File: "tmp.sh",
|
||||
Line: `echo hello1; export BUNDLE_ENTERPRISE__CONTRIBSYS__COM="cafebabe:deadbeef" && echo hello2`,
|
||||
RuleID: "sidekiq-secret",
|
||||
Tags: []string{},
|
||||
Match: "BUNDLE_ENTERPRISE__CONTRIBSYS__COM=\"cafebabe:deadbeef\"",
|
||||
Secret: "cafebabe:deadbeef",
|
||||
Entropy: 2.6098502,
|
||||
StartLine: 0,
|
||||
EndLine: 0,
|
||||
StartColumn: 21,
|
||||
EndColumn: 74,
|
||||
Tags: []string{},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"detect finding - sidekiq url": {
|
||||
cfgName: "simple",
|
||||
fragment: Fragment{
|
||||
Raw: `url = "http://cafeb4b3:d3adb33f@enterprise.contribsys.com:80/path?param1=true¶m2=false#heading1"`,
|
||||
@@ -210,74 +221,36 @@ func TestDetect(t *testing.T) {
|
||||
},
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
RuleID: "sidekiq-sensitive-url",
|
||||
Description: "Sidekiq Sensitive URL",
|
||||
Match: "http://cafeb4b3:d3adb33f@enterprise.contribsys.com:",
|
||||
Secret: "cafeb4b3:d3adb33f",
|
||||
File: "tmp.sh",
|
||||
Line: `url = "http://cafeb4b3:d3adb33f@enterprise.contribsys.com:80/path?param1=true¶m2=false#heading1"`,
|
||||
RuleID: "sidekiq-sensitive-url",
|
||||
Tags: []string{},
|
||||
Match: "http://cafeb4b3:d3adb33f@enterprise.contribsys.com:",
|
||||
Secret: "cafeb4b3:d3adb33f",
|
||||
Entropy: 2.984234,
|
||||
StartLine: 0,
|
||||
EndLine: 0,
|
||||
StartColumn: 8,
|
||||
EndColumn: 58,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "allow_aws_re",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "allow_path",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "allow_commit",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||
FilePath: "tmp.go",
|
||||
CommitSHA: "allowthiscommit",
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "entropy_group",
|
||||
fragment: Fragment{
|
||||
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
Description: "Discord API key",
|
||||
Match: "Discord_Public_Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
|
||||
Secret: "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5",
|
||||
Line: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||
File: "tmp.go",
|
||||
RuleID: "discord-api-key",
|
||||
Tags: []string{},
|
||||
Entropy: 3.7906237,
|
||||
StartLine: 0,
|
||||
EndLine: 0,
|
||||
StartColumn: 7,
|
||||
EndColumn: 93,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"ignore finding - our config file": {
|
||||
cfgName: "simple",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||
FilePath: filepath.Join(configPath, "simple.toml"),
|
||||
},
|
||||
},
|
||||
"ignore finding - doesn't match path": {
|
||||
cfgName: "generic_with_py_path",
|
||||
fragment: Fragment{
|
||||
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
},
|
||||
{
|
||||
"detect finding - matches path,regex,entropy": {
|
||||
cfgName: "generic_with_py_path",
|
||||
fragment: Fragment{
|
||||
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||
@@ -285,23 +258,40 @@ func TestDetect(t *testing.T) {
|
||||
},
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
RuleID: "generic-api-key",
|
||||
Description: "Generic API Key",
|
||||
File: "tmp.py",
|
||||
Line: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||
Match: "Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
|
||||
Secret: "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5",
|
||||
Line: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||
File: "tmp.py",
|
||||
RuleID: "generic-api-key",
|
||||
Tags: []string{},
|
||||
Entropy: 3.7906237,
|
||||
StartLine: 0,
|
||||
EndLine: 0,
|
||||
StartColumn: 22,
|
||||
EndColumn: 93,
|
||||
Tags: []string{},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "path_only",
|
||||
"ignore finding - allowlist regex": {
|
||||
cfgName: "generic_with_py_path",
|
||||
fragment: Fragment{
|
||||
Raw: `const Discord_Public_Key = "load2523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||
FilePath: "tmp.py",
|
||||
},
|
||||
},
|
||||
|
||||
// Rule
|
||||
"rule - ignore path": {
|
||||
cfgName: "valid/rule_path_only",
|
||||
baselinePath: ".baseline.json",
|
||||
fragment: Fragment{
|
||||
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||
FilePath: ".baseline.json",
|
||||
},
|
||||
},
|
||||
"rule - detect path ": {
|
||||
cfgName: "valid/rule_path_only",
|
||||
fragment: Fragment{
|
||||
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||
FilePath: "tmp.py",
|
||||
@@ -316,47 +306,127 @@ func TestDetect(t *testing.T) {
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "bad_entropy_group",
|
||||
"rule - match based on entropy": {
|
||||
cfgName: "valid/rule_entropy_group",
|
||||
fragment: Fragment{
|
||||
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"
|
||||
//const Discord_Public_Key = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||
`,
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
wantError: fmt.Errorf("discord-api-key: invalid regex secret group 5, max regex secret group 3"),
|
||||
},
|
||||
{
|
||||
cfgName: "simple",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||
FilePath: filepath.Join(configPath, "simple.toml"),
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
RuleID: "discord-api-key",
|
||||
Description: "Discord API key",
|
||||
File: "tmp.go",
|
||||
Line: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||
Match: "Discord_Public_Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
|
||||
Secret: "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5",
|
||||
Entropy: 3.7906237,
|
||||
StartLine: 0,
|
||||
EndLine: 0,
|
||||
StartColumn: 7,
|
||||
EndColumn: 93,
|
||||
Tags: []string{},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "allow_global_aws_re",
|
||||
|
||||
// Allowlists
|
||||
"global allowlist - ignore regex": {
|
||||
cfgName: "valid/allowlist_global_regex",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "generic_with_py_path",
|
||||
"global allowlist - detect, doesn't match all conditions": {
|
||||
cfgName: "valid/allowlist_global_multiple",
|
||||
fragment: Fragment{
|
||||
Raw: `const Discord_Public_Key = "load2523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||
FilePath: "tmp.py",
|
||||
Raw: `
|
||||
const token = "mockSecret";
|
||||
// const token = "changeit";`,
|
||||
FilePath: "config.txt",
|
||||
},
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
RuleID: "test",
|
||||
File: "config.txt",
|
||||
Line: "\nconst token = \"mockSecret\";",
|
||||
Match: `token = "mockSecret"`,
|
||||
Secret: "mockSecret",
|
||||
Entropy: 2.9219282,
|
||||
StartLine: 1,
|
||||
EndLine: 1,
|
||||
StartColumn: 8,
|
||||
EndColumn: 27,
|
||||
Tags: []string{},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "path_only",
|
||||
baselinePath: ".baseline.json",
|
||||
"global allowlist - ignore, matches all conditions": {
|
||||
cfgName: "valid/allowlist_global_multiple",
|
||||
fragment: Fragment{
|
||||
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||
FilePath: ".baseline.json",
|
||||
Raw: `token := "mockSecret";`,
|
||||
FilePath: "node_modules/config.txt",
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "base64_encoded",
|
||||
"global allowlist - detect path, doesn't match all conditions": {
|
||||
cfgName: "valid/allowlist_global_multiple",
|
||||
fragment: Fragment{
|
||||
Raw: b64TestValues,
|
||||
Raw: `var token = "fakeSecret";`,
|
||||
FilePath: "node_modules/config.txt",
|
||||
},
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
RuleID: "test",
|
||||
File: "node_modules/config.txt",
|
||||
Line: "var token = \"fakeSecret\";",
|
||||
Match: `token = "fakeSecret"`,
|
||||
Secret: "fakeSecret",
|
||||
Entropy: 2.8464394,
|
||||
StartLine: 0,
|
||||
EndLine: 0,
|
||||
StartColumn: 5,
|
||||
EndColumn: 24,
|
||||
Tags: []string{},
|
||||
},
|
||||
},
|
||||
},
|
||||
"allowlist - ignore commit": {
|
||||
cfgName: "valid/allowlist_rule_commit",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||
FilePath: "tmp.go",
|
||||
CommitSHA: "allowthiscommit",
|
||||
},
|
||||
},
|
||||
"allowlist - ignore path": {
|
||||
cfgName: "valid/allowlist_rule_path",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
},
|
||||
"allowlist - ignore path when extending": {
|
||||
cfgName: "valid/allowlist_rule_extend_default",
|
||||
fragment: Fragment{
|
||||
Raw: `token = "aebfab88-7596-481d-82e8-c60c8f7de0c0"`,
|
||||
FilePath: "path/to/your/problematic/file.js",
|
||||
},
|
||||
},
|
||||
"allowlist - ignore regex": {
|
||||
cfgName: "valid/allowlist_rule_regex",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
},
|
||||
// Decoding
|
||||
"detect encoded": {
|
||||
cfgName: "encoded",
|
||||
fragment: Fragment{
|
||||
Raw: encodedTestValues,
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
expectedFindings: []report.Finding{
|
||||
@@ -402,6 +472,90 @@ func TestDetect(t *testing.T) {
|
||||
EndColumn: 207,
|
||||
Entropy: 5.350665,
|
||||
},
|
||||
{ // Encoded Small secret at the end to make sure it's picked up by the decoding
|
||||
Description: "Small Secret",
|
||||
Secret: "small-secret",
|
||||
Match: "small-secret",
|
||||
File: "tmp.go",
|
||||
Line: "\nc21hbGwtc2VjcmV0",
|
||||
RuleID: "small-secret",
|
||||
Tags: []string{"small", "secret", "decoded:base64", "decode-depth:1"},
|
||||
StartLine: 15,
|
||||
EndLine: 15,
|
||||
StartColumn: 2,
|
||||
EndColumn: 17,
|
||||
Entropy: 3.0849626,
|
||||
},
|
||||
{ // Secret where the decoded match goes outside the encoded value
|
||||
Description: "Overlapping",
|
||||
Secret: "decoded-secret-value00",
|
||||
Match: "secret=decoded-secret-value00",
|
||||
File: "tmp.go",
|
||||
Line: "\nsecret=ZGVjb2RlZC1zZWNyZXQtdmFsdWUwMA==",
|
||||
RuleID: "overlapping",
|
||||
Tags: []string{"overlapping", "decoded:base64", "decode-depth:1"},
|
||||
StartLine: 18,
|
||||
EndLine: 18,
|
||||
StartColumn: 2,
|
||||
EndColumn: 40,
|
||||
Entropy: 3.4428623,
|
||||
},
|
||||
{ // This just confirms that with no allowlist the pattern is detected (i.e. the regex is good)
|
||||
Description: "Make sure this would be detected with no allowlist",
|
||||
Secret: "lRqBK-z5kf4-please-ignore-me-X-XIJM2Pddw",
|
||||
Match: "password=\"lRqBK-z5kf4-please-ignore-me-X-XIJM2Pddw\"",
|
||||
File: "tmp.go",
|
||||
Line: "\npassword=\"bFJxQkstejVrZjQtcGxlYXNlLWlnbm9yZS1tZS1YLVhJSk0yUGRkdw==\"",
|
||||
RuleID: "decoded-password-dont-ignore",
|
||||
Tags: []string{"decode-ignore", "decoded:base64", "decode-depth:1"},
|
||||
StartLine: 23,
|
||||
EndLine: 23,
|
||||
StartColumn: 2,
|
||||
EndColumn: 68,
|
||||
Entropy: 4.5841837,
|
||||
},
|
||||
{ // Hex encoded data check
|
||||
Description: "Overlapping",
|
||||
Secret: "decoded-secret-valuevHEX",
|
||||
Match: "secret=decoded-secret-valuevHEX",
|
||||
File: "tmp.go",
|
||||
Line: "\nsecret=6465636F6465642D7365637265742D76616C756576484558",
|
||||
RuleID: "overlapping",
|
||||
Tags: []string{"overlapping", "decoded:hex", "decode-depth:1"},
|
||||
StartLine: 26,
|
||||
EndLine: 26,
|
||||
StartColumn: 2,
|
||||
EndColumn: 56,
|
||||
Entropy: 3.6531072,
|
||||
},
|
||||
{ // handle partial encoded percent data
|
||||
Description: "Overlapping",
|
||||
Secret: "decoded-secret-valuev2",
|
||||
Match: "secret=decoded-secret-valuev2",
|
||||
File: "tmp.go",
|
||||
Line: "\nsecret=decoded-%73%65%63%72%65%74-valuev2",
|
||||
RuleID: "overlapping",
|
||||
Tags: []string{"overlapping", "decoded:percent", "decode-depth:1"},
|
||||
StartLine: 30,
|
||||
EndLine: 30,
|
||||
StartColumn: 2,
|
||||
EndColumn: 42,
|
||||
Entropy: 3.4428623,
|
||||
},
|
||||
{ // handle partial encoded percent data
|
||||
Description: "Overlapping",
|
||||
Secret: "decoded-secret-valuev3",
|
||||
Match: "secret=decoded-secret-valuev3",
|
||||
File: "tmp.go",
|
||||
Line: "\nsecret=%64%65coded-%73%65%63%72%65%74-valuev3",
|
||||
RuleID: "overlapping",
|
||||
Tags: []string{"overlapping", "decoded:percent", "decode-depth:1"},
|
||||
StartLine: 32,
|
||||
EndLine: 32,
|
||||
StartColumn: 2,
|
||||
EndColumn: 46,
|
||||
Entropy: 3.4428623,
|
||||
},
|
||||
{ // Encoded AWS config with a access key id inside a JWT
|
||||
Description: "AWS IAM Unique Identifier",
|
||||
Secret: "ASIAIOSFODNN7LXM10JI",
|
||||
@@ -430,34 +584,6 @@ func TestDetect(t *testing.T) {
|
||||
EndColumn: 344,
|
||||
Entropy: 4.721928,
|
||||
},
|
||||
{ // Encoded Small secret at the end to make sure it's picked up by the decoding
|
||||
Description: "Small Secret",
|
||||
Secret: "small-secret",
|
||||
Match: "small-secret",
|
||||
File: "tmp.go",
|
||||
Line: "\nc21hbGwtc2VjcmV0",
|
||||
RuleID: "small-secret",
|
||||
Tags: []string{"small", "secret", "decoded:base64", "decode-depth:1"},
|
||||
StartLine: 15,
|
||||
EndLine: 15,
|
||||
StartColumn: 2,
|
||||
EndColumn: 17,
|
||||
Entropy: 3.0849626,
|
||||
},
|
||||
{ // Secret where the decoded match goes outside the encoded value
|
||||
Description: "Overlapping",
|
||||
Secret: "decoded-secret-value",
|
||||
Match: "secret=decoded-secret-value",
|
||||
File: "tmp.go",
|
||||
Line: "\nsecret=ZGVjb2RlZC1zZWNyZXQtdmFsdWU=",
|
||||
RuleID: "overlapping",
|
||||
Tags: []string{"overlapping", "decoded:base64", "decode-depth:1"},
|
||||
StartLine: 18,
|
||||
EndLine: 18,
|
||||
StartColumn: 2,
|
||||
EndColumn: 36,
|
||||
Entropy: 3.3037016,
|
||||
},
|
||||
{ // Secret where the decoded match goes outside the encoded value and then encoded again
|
||||
Description: "Overlapping",
|
||||
Secret: "decoded-secret-value",
|
||||
@@ -472,26 +598,124 @@ func TestDetect(t *testing.T) {
|
||||
EndColumn: 49,
|
||||
Entropy: 3.3037016,
|
||||
},
|
||||
{ // This just confirms that with no allowlist the pattern is detected (i.e. the regex is good)
|
||||
Description: "Make sure this would be detected with no allowlist",
|
||||
Secret: "lRqBK-z5kf4-please-ignore-me-X-XIJM2Pddw",
|
||||
Match: "password=\"lRqBK-z5kf4-please-ignore-me-X-XIJM2Pddw\"",
|
||||
{ // handle encodings that touch eachother
|
||||
Description: "Overlapping",
|
||||
Secret: "decoded-secret-valuev5",
|
||||
Match: "secret=decoded-secret-valuev5",
|
||||
File: "tmp.go",
|
||||
Line: "\npassword=\"bFJxQkstejVrZjQtcGxlYXNlLWlnbm9yZS1tZS1YLVhJSk0yUGRkdw==\"",
|
||||
RuleID: "decoded-password-dont-ignore",
|
||||
Tags: []string{"decode-ignore", "decoded:base64", "decode-depth:1"},
|
||||
StartLine: 23,
|
||||
EndLine: 23,
|
||||
Line: "\nsecret%3d6465636F6465642D7365637265742D76616C75657635",
|
||||
RuleID: "overlapping",
|
||||
Tags: []string{"overlapping", "decoded:percent", "decoded:hex", "decode-depth:2"},
|
||||
StartLine: 40,
|
||||
EndLine: 40,
|
||||
StartColumn: 2,
|
||||
EndColumn: 68,
|
||||
Entropy: 4.5841837,
|
||||
EndColumn: 54,
|
||||
Entropy: 3.4428623,
|
||||
},
|
||||
{ // handle partial encoded percent data465642D7365637265742D76616C75657635
|
||||
Description: "Overlapping",
|
||||
Secret: "decoded-secret-valuev4",
|
||||
Match: "secret=decoded-secret-valuev4",
|
||||
File: "tmp.go",
|
||||
Line: "\nc2VjcmV0PVpHVmpiMl%4AsWkMxelpXTnlaWFF0ZG1Gc2RXVjJOQT09",
|
||||
RuleID: "overlapping",
|
||||
Tags: []string{"overlapping", "decoded:percent", "decoded:base64", "decode-depth:3"},
|
||||
StartLine: 38,
|
||||
EndLine: 38,
|
||||
StartColumn: 2,
|
||||
EndColumn: 55,
|
||||
Entropy: 3.4428623,
|
||||
},
|
||||
{ // multiple percent encodings in a single layer base64
|
||||
Description: "Overlapping",
|
||||
Secret: "decoded-secret-valuex86",
|
||||
Match: "secret=decoded-secret-valuex86",
|
||||
File: "tmp.go",
|
||||
Line: "\nsecret=ZGVjb2%52lZC1zZWNyZXQtdm%46sdWV4ODY= # ends in x86",
|
||||
RuleID: "overlapping",
|
||||
Tags: []string{"overlapping", "decoded:percent", "decoded:base64", "decode-depth:2"},
|
||||
StartLine: 42,
|
||||
EndLine: 42,
|
||||
StartColumn: 2,
|
||||
EndColumn: 44,
|
||||
Entropy: 3.6381476,
|
||||
},
|
||||
{ // base64 encoded partially percent encoded value
|
||||
Description: "Overlapping",
|
||||
Secret: "decoded-secret-value",
|
||||
Match: "secret=decoded-secret-value",
|
||||
File: "tmp.go",
|
||||
Line: "\nsecret=ZGVjb2RlZC0lNzMlNjUlNjMlNzIlNjUlNzQtdmFsdWU=",
|
||||
RuleID: "overlapping",
|
||||
Tags: []string{"overlapping", "decoded:percent", "decoded:base64", "decode-depth:2"},
|
||||
StartLine: 44,
|
||||
EndLine: 44,
|
||||
StartColumn: 2,
|
||||
EndColumn: 52,
|
||||
Entropy: 3.3037016,
|
||||
},
|
||||
{ // one of the lines above that went through... a lot
|
||||
Description: "Overlapping",
|
||||
Secret: "decoded-secret-value",
|
||||
Match: "secret=decoded-secret-value",
|
||||
File: "tmp.go",
|
||||
Line: "\nLook at this value: %4EjMzMjU2NkE2MzZENTYzMDUwNTY3MDQ4%4eTY2RDcwNjk0RDY5NTUzMTRENkQ3ODYx%25%34%65TE3QTQ2MzY1NzZDNjQ0RjY1NTY3MDU5NTU1ODUyNkI2MjUzNTUzMDRFNkU0RTZCNTYzMTU1MzkwQQ== # isn't it crazy?",
|
||||
RuleID: "overlapping",
|
||||
Tags: []string{"overlapping", "decoded:percent", "decoded:hex", "decoded:base64", "decode-depth:7"},
|
||||
StartLine: 47,
|
||||
EndLine: 47,
|
||||
StartColumn: 22,
|
||||
EndColumn: 177,
|
||||
Entropy: 3.3037016,
|
||||
},
|
||||
{ // Multi percent encode two random characters close to the bounds of the base64
|
||||
Description: "Overlapping",
|
||||
Secret: "decoded-secret-value",
|
||||
Match: "secret=decoded-secret-value",
|
||||
File: "tmp.go",
|
||||
Line: "\nsecret=ZG%25%32%35%25%33%32%25%33%35%25%32%35%25%33%33%25%33%35%25%32%35%25%33%33%25%33%36%25%32%35%25%33%32%25%33%35%25%32%35%25%33%33%25%33%36%25%32%35%25%33%36%25%33%31%25%32%35%25%33%32%25%33%35%25%32%35%25%33%33%25%33%36%25%32%35%25%33%33%25%33%322RlZC1zZWNyZXQtd%25%36%64%25%34%36%25%37%33dWU=",
|
||||
RuleID: "overlapping",
|
||||
Tags: []string{"overlapping", "decoded:percent", "decoded:base64", "decode-depth:5"},
|
||||
StartLine: 50,
|
||||
EndLine: 50,
|
||||
StartColumn: 2,
|
||||
EndColumn: 300,
|
||||
Entropy: 3.3037016,
|
||||
},
|
||||
{ // The similar to the above but also touching the edge of the base64
|
||||
Description: "Overlapping",
|
||||
Secret: "decoded-secret-value",
|
||||
Match: "secret=decoded-secret-value",
|
||||
File: "tmp.go",
|
||||
Line: "\nsecret=%25%35%61%25%34%37%25%35%36jb2RlZC1zZWNyZXQtdmFsdWU%25%32%35%25%33%33%25%36%34",
|
||||
RuleID: "overlapping",
|
||||
Tags: []string{"overlapping", "decoded:percent", "decoded:base64", "decode-depth:4"},
|
||||
StartLine: 52,
|
||||
EndLine: 52,
|
||||
StartColumn: 2,
|
||||
EndColumn: 86,
|
||||
Entropy: 3.3037016,
|
||||
},
|
||||
{ // The similar to the above but also touching and overlapping the base64
|
||||
Description: "Overlapping",
|
||||
Secret: "decoded-secret-value",
|
||||
Match: "secret=decoded-secret-value",
|
||||
File: "tmp.go",
|
||||
Line: "\nsecret%3D%25%35%61%25%34%37%25%35%36jb2RlZC1zZWNyZXQtdmFsdWU%25%32%35%25%33%33%25%36%34",
|
||||
RuleID: "overlapping",
|
||||
Tags: []string{"overlapping", "decoded:percent", "decoded:base64", "decode-depth:4"},
|
||||
StartLine: 54,
|
||||
EndLine: 54,
|
||||
StartColumn: 2,
|
||||
EndColumn: 88,
|
||||
Entropy: 3.3037016,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(fmt.Sprintf("%s - %s", tt.cfgName, tt.fragment.FilePath), func(t *testing.T) {
|
||||
for name, tt := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
viper.Reset()
|
||||
viper.AddConfigPath(configPath)
|
||||
viper.SetConfigName(tt.cfgName)
|
||||
@@ -851,7 +1075,7 @@ func TestFromFiles(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
|
||||
detector.FollowSymlinks = true
|
||||
paths, err := sources.DirectoryTargets(tt.source, detector.Sema, true, cfg.Allowlist.PathAllowed)
|
||||
paths, err := sources.DirectoryTargets(tt.source, detector.Sema, true, cfg.Allowlists)
|
||||
require.NoError(t, err)
|
||||
|
||||
findings, err := detector.DetectFiles(paths)
|
||||
@@ -925,7 +1149,7 @@ func TestDetectWithSymlinks(t *testing.T) {
|
||||
cfg, _ := vc.Translate()
|
||||
detector := NewDetector(cfg)
|
||||
detector.FollowSymlinks = true
|
||||
paths, err := sources.DirectoryTargets(tt.source, detector.Sema, true, cfg.Allowlist.PathAllowed)
|
||||
paths, err := sources.DirectoryTargets(tt.source, detector.Sema, true, cfg.Allowlists)
|
||||
require.NoError(t, err)
|
||||
|
||||
findings, err := detector.DetectFiles(paths)
|
||||
@@ -1157,7 +1381,7 @@ let password = 'Summer2024!';`
|
||||
|
||||
f := tc.fragment
|
||||
f.Raw = raw
|
||||
actual := d.detectRule(f, raw, rule, []EncodedSegment{})
|
||||
actual := d.detectRule(f, raw, rule, []*codec.EncodedSegment{})
|
||||
if diff := cmp.Diff(tc.expected, actual); diff != "" {
|
||||
t.Errorf("diff: (-want +got)\n%s", diff)
|
||||
}
|
||||
@@ -1211,7 +1435,6 @@ func TestNormalizeGitleaksIgnorePaths(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestWindowsFileSeparator_RulePath(t *testing.T) {
|
||||
logging.Logger = logging.Logger.Level(zerolog.TraceLevel)
|
||||
unixRule := config.Rule{
|
||||
RuleID: "test-rule",
|
||||
Path: regexp.MustCompile(`(^|/)\.m2/settings\.xml`),
|
||||
@@ -1319,7 +1542,7 @@ func TestWindowsFileSeparator_RulePath(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
for name, test := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
actual := d.detectRule(test.fragment, test.fragment.Raw, test.rule, []EncodedSegment{})
|
||||
actual := d.detectRule(test.fragment, test.fragment.Raw, test.rule, []*codec.EncodedSegment{})
|
||||
if diff := cmp.Diff(test.expected, actual); diff != "" {
|
||||
t.Errorf("diff: (-want +got)\n%s", diff)
|
||||
}
|
||||
@@ -1505,7 +1728,7 @@ func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
for name, test := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
actual := d.detectRule(test.fragment, test.fragment.Raw, test.rule, []EncodedSegment{})
|
||||
actual := d.detectRule(test.fragment, test.fragment.Raw, test.rule, []*codec.EncodedSegment{})
|
||||
if diff := cmp.Diff(test.expected, actual); diff != "" {
|
||||
t.Errorf("diff: (-want +got)\n%s", diff)
|
||||
}
|
||||
|
||||
+4
-6
@@ -20,9 +20,8 @@ const maxPeekSize = 25 * 1_000 // 10kb
|
||||
// DetectFiles schedules each ScanTarget—file or archive—for concurrent scanning.
|
||||
func (d *Detector) DetectFiles(paths <-chan sources.ScanTarget) ([]report.Finding, error) {
|
||||
for pa := range paths {
|
||||
pa := pa // capture
|
||||
d.Sema.Go(func() error {
|
||||
return d.DetectScanTarget(pa)
|
||||
return d.detectScanTarget(pa)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -32,10 +31,9 @@ func (d *Detector) DetectFiles(paths <-chan sources.ScanTarget) ([]report.Findin
|
||||
return d.findings, nil
|
||||
}
|
||||
|
||||
// DetectScanTarget handles one ScanTarget: it unpacks archives recursively
|
||||
// detectScanTarget handles one ScanTarget: it unpacks archives recursively
|
||||
// or scans a regular file, always using VirtualPath for reporting.
|
||||
// TODO maybe find a better solution for this? relying on `scanTarget` seems off.
|
||||
func (d *Detector) DetectScanTarget(scanTarget sources.ScanTarget) error {
|
||||
func (d *Detector) detectScanTarget(scanTarget sources.ScanTarget) error {
|
||||
// Choose display path: either VirtualPath (archive chain) or on-disk path.
|
||||
display := scanTarget.Path
|
||||
if scanTarget.VirtualPath != "" {
|
||||
@@ -71,7 +69,7 @@ func (d *Detector) DetectScanTarget(scanTarget sources.ScanTarget) error {
|
||||
}
|
||||
|
||||
d.Sema.Go(func() error {
|
||||
return d.DetectScanTarget(t)
|
||||
return d.detectScanTarget(t)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+16
-4
@@ -38,9 +38,11 @@ func (d *Detector) DetectGit(cmd *sources.GitCmd, remote *RemoteInfo) ([]report.
|
||||
commitSHA := ""
|
||||
if gitdiffFile.PatchHeader != nil {
|
||||
commitSHA = gitdiffFile.PatchHeader.SHA
|
||||
if ok, c := d.Config.Allowlist.CommitAllowed(gitdiffFile.PatchHeader.SHA); ok {
|
||||
logging.Trace().Str("allowed-commit", c).Msg("skipping commit: global allowlist")
|
||||
continue
|
||||
for _, a := range d.Config.Allowlists {
|
||||
if ok, c := a.CommitAllowed(gitdiffFile.PatchHeader.SHA); ok {
|
||||
logging.Trace().Str("allowed-commit", c).Msg("skipping commit: global allowlist")
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,7 +87,7 @@ func (d *Detector) DetectGit(cmd *sources.GitCmd, remote *RemoteInfo) ([]report.
|
||||
t.GitInfo.Message = gitdiffFile.PatchHeader.Message()
|
||||
t.GitInfo.Email = gitdiffFile.PatchHeader.Author.Email
|
||||
|
||||
d.DetectScanTarget(t)
|
||||
d.detectScanTarget(t)
|
||||
}
|
||||
os.RemoveAll(tmpDir)
|
||||
return nil
|
||||
@@ -111,9 +113,19 @@ func (d *Detector) DetectGit(cmd *sources.GitCmd, remote *RemoteInfo) ([]report.
|
||||
FilePath: gitdiffFile.NewName,
|
||||
}
|
||||
|
||||
timer := time.AfterFunc(SlowWarningThreshold, func() {
|
||||
logging.Debug().
|
||||
Str("commit", commitSHA[:7]).
|
||||
Str("path", fragment.FilePath).
|
||||
Msgf("Taking longer than %s to inspect fragment", SlowWarningThreshold.String())
|
||||
})
|
||||
for _, finding := range d.Detect(fragment) {
|
||||
d.AddFinding(augmentGitFinding(remote, finding, textFragment, gitdiffFile))
|
||||
}
|
||||
if timer != nil {
|
||||
timer.Stop()
|
||||
timer = nil
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user