Skip to content

Commit

Permalink
[bug] - Add ASCII validation check for base64 decoding (#2671)
Browse files Browse the repository at this point in the history
* Correclt handle invalid base64 with ascii check

* remove parallel
  • Loading branch information
ahrav authored Apr 4, 2024
1 parent 4153315 commit 3cb7aed
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
19 changes: 13 additions & 6 deletions pkg/decoders/base64.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package decoders
import (
"bytes"
"encoding/base64"
"unicode"

"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"
"github.com/trufflesecurity/trufflehog/v3/pkg/sources"
Expand Down Expand Up @@ -33,15 +34,12 @@ func (d *Base64) FromChunk(chunk *sources.Chunk) *DecodableChunk {

for _, str := range encodedSubstrings {
dec, err := base64.StdEncoding.DecodeString(str)
if err == nil {
if len(dec) > 0 {
decodedSubstrings[str] = dec
}
continue
if err == nil && len(dec) > 0 && isASCII(dec) {
decodedSubstrings[str] = dec
}

dec, err = base64.RawURLEncoding.DecodeString(str)
if err == nil && len(dec) > 0 {
if err == nil && len(dec) > 0 && isASCII(dec) {
decodedSubstrings[str] = dec
}
}
Expand Down Expand Up @@ -69,6 +67,15 @@ func (d *Base64) FromChunk(chunk *sources.Chunk) *DecodableChunk {
return nil
}

func isASCII(b []byte) bool {
for i := 0; i < len(b); i++ {
if b[i] > unicode.MaxASCII {
return false
}
}
return true
}

func getSubstringsOfCharacterSet(data []byte, threshold int, charsetMapping [128]bool, endChars string) []string {
if len(data) == 0 {
return nil
Expand Down
7 changes: 7 additions & 0 deletions pkg/decoders/base64_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,14 @@ func TestBase64_FromChunk(t *testing.T) {
Data: []byte(`b64urlsafe-test-secret-underscores??`),
},
},
{
name: "invalid base64 string",
chunk: &sources.Chunk{
Data: []byte(`a3d3fa7c2bb99e469ba55e5834ce79ee4853a8a3`),
},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
d := &Base64{}
Expand Down

0 comments on commit 3cb7aed

Please sign in to comment.