Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
fix: fixed verification endpoint and verification logic for brand fetch (#3470)
Sahil Silareed6d045b4664
diff --git a/pkg/detectors/brandfetch/v1/brandfetch.go b/pkg/detectors/brandfetch/v1/brandfetch.gonew file mode 100644index 000000000..8236972bb--- /dev/null+++ b/pkg/detectors/brandfetch/v1/brandfetch.go@@ -0,0 +1,80 @@+package brandfetch++import (+ "context"+ "net/http"+ "strconv"++ regexp "github.com/wasilibs/go-re2"++ "github.com/trufflesecurity/trufflehog/v3/pkg/common"+ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors"+ v2 "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/brandfetch/v2"+ "github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"+)++type Scanner struct {+ client *http.Client+}++func (s Scanner) Version() int { return 1 }++var (+ // Ensure the Scanner satisfies the interface at compile time.+ _ detectors.Detector = (*Scanner)(nil)+ _ detectors.Versioner = (*Scanner)(nil)+ defaultClient = common.SaneHttpClient()++ // Make sure that your group is surrounded in boundary characters such as below to reduce false positives.+ keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"brandfetch"}) + `\b([0-9A-Za-z]{40})\b`)+)++// Keywords are used for efficiently pre-filtering chunks.+// Use identifiers in the secret preferably, or the provider name.+func (s Scanner) Keywords() []string {+ return []string{"brandfetch"}+}++func (s Scanner) Type() detectorspb.DetectorType {+ return detectorspb.DetectorType_Brandfetch+}++func (s Scanner) Description() string {+ return "Brandfetch is a service that provides brand data, including logos, colors, fonts, and more. Brandfetch API keys can be used to access this data."+}++func (s Scanner) getClient() *http.Client {+ if s.client != nil {+ return s.client+ }++ return defaultClient+}++// FromData will find and optionally verify Brandfetch secrets in a given set of bytes.+func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {+ dataStr := string(data)++ uniqueTokenMatches := make(map[string]struct{})+ for _, match := range keyPat.FindAllStringSubmatch(dataStr, -1) {+ uniqueTokenMatches[match[1]] = struct{}{}+ }++ for match := range uniqueTokenMatches {+ s1 := detectors.Result{+ DetectorType: detectorspb.DetectorType_Brandfetch,+ Raw: []byte(match),+ ExtraData: map[string]string{"version": strconv.Itoa(s.Version())},+ }++ if verify {+ isVerified, verificationErr := v2.VerifyMatch(ctx, s.getClient(), match)+ s1.Verified = isVerified+ s1.SetVerificationError(verificationErr, match)+ }++ results = append(results, s1)+ }++ return+}diff --git a/pkg/detectors/brandfetch/brandfetch_integration_test.go b/pkg/detectors/brandfetch/v1/brandfetch_integration_test.gosimilarity index 99%rename from pkg/detectors/brandfetch/brandfetch_integration_test.gorename to pkg/detectors/brandfetch/v1/brandfetch_integration_test.goindex 76fe755e3..b77f50c0c 100644--- a/pkg/detectors/brandfetch/brandfetch_integration_test.go+++ b/pkg/detectors/brandfetch/v1/brandfetch_integration_test.go@@ -95,6 +95,7 @@ func TestBrandfetch_FromChunk(t *testing.T) {t.Fatalf("no raw secret present: \n %+v", got[i])}got[i].Raw = nil+ got[i].ExtraData = nil}if diff := pretty.Compare(got, tt.want); diff != "" {t.Errorf("Brandfetch.FromData() %s diff: (-got +want)\n%s", tt.name, diff)diff --git a/pkg/detectors/brandfetch/brandfetch_test.go b/pkg/detectors/brandfetch/v1/brandfetch_test.gosimilarity index 100%rename from pkg/detectors/brandfetch/brandfetch_test.gorename to pkg/detectors/brandfetch/v1/brandfetch_test.godiff --git a/pkg/detectors/brandfetch/brandfetch.go b/pkg/detectors/brandfetch/v2/brandfetch.gosimilarity index 55%rename from pkg/detectors/brandfetch/brandfetch.gorename to pkg/detectors/brandfetch/v2/brandfetch.goindex eabb97b16..ce92f93d2 100644--- a/pkg/detectors/brandfetch/brandfetch.go+++ b/pkg/detectors/brandfetch/v2/brandfetch.go@@ -3,8 +3,8 @@ package brandfetchimport ("context""fmt"- "io""net/http"+ "strconv""strings"regexp "github.com/wasilibs/go-re2"@@ -14,16 +14,20 @@ import ("github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb")-type Scanner struct{}+type Scanner struct {+ client *http.Client+}-// Ensure the Scanner satisfies the interface at compile time.-var _ detectors.Detector = (*Scanner)(nil)+func (s Scanner) Version() int { return 2 }var (- client = common.SaneHttpClient()+ // Ensure the Scanner satisfies the interface at compile time.+ _ detectors.Detector = (*Scanner)(nil)+ _ detectors.Versioner = (*Scanner)(nil)+ defaultClient = common.SaneHttpClient()// Make sure that your group is surrounded in boundary characters such as below to reduce false positives.- keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"brandfetch"}) + `\b([0-9A-Za-z]{40})\b`)+ keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"brandfetch"}) + `([a-zA-Z0-9=+/\-_!@#$%^&*()]{43}=)`))// Keywords are used for efficiently pre-filtering chunks.@@ -32,63 +36,65 @@ func (s Scanner) Keywords() []string {return []string{"brandfetch"}}+func (s Scanner) Type() detectorspb.DetectorType {+ return detectorspb.DetectorType_Brandfetch+}++func (s Scanner) Description() string {+ return "Brandfetch is a service that provides brand data, including logos, colors, fonts, and more. Brandfetch API keys can be used to access this data."+}++func (s Scanner) getClient() *http.Client {+ if s.client != nil {+ return s.client+ }++ return defaultClient+}+// FromData will find and optionally verify Brandfetch secrets in a given set of bytes.func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {dataStr := string(data)- matches := keyPat.FindAllStringSubmatch(dataStr, -1)-- for _, match := range matches {- resMatch := strings.TrimSpace(match[1])+ uniqueMatches := make(map[string]struct{})+ for _, match := range keyPat.FindAllStringSubmatch(dataStr, -1) {+ uniqueMatches[strings.TrimSpace(match[1])] = struct{}{}+ }+ for match := range uniqueMatches {s1 := detectors.Result{DetectorType: detectorspb.DetectorType_Brandfetch,- Raw: []byte(resMatch),+ Raw: []byte(match),+ ExtraData: map[string]string{"version": strconv.Itoa(s.Version())},}if verify {- isVerified, verificationErr := verifyBrandFetch(ctx, client, resMatch)+ isVerified, verificationErr := VerifyMatch(ctx, s.getClient(), match)s1.Verified = isVerified- s1.SetVerificationError(verificationErr)+ s1.SetVerificationError(verificationErr, match)}results = append(results, s1)}- return results, nil+ return}-func (s Scanner) Type() detectorspb.DetectorType {- return detectorspb.DetectorType_Brandfetch-}--func (s Scanner) Description() string {- return "Brandfetch is a service that provides brand data, including logos, colors, fonts, and more. Brandfetch API keys can be used to access this data."-}--// docs: https://docs.brandfetch.com/docs/brand-api#overview-func verifyBrandFetch(ctx context.Context, client *http.Client, key string) (bool, error) {- payload := strings.NewReader(`{- "domain": "www.example.com"- }`)-- req, err := http.NewRequestWithContext(ctx, "POST", "https://api.brandfetch.io/v1/color", payload)+// verifyMatch checks if the provided Brandfetch token is valid by making a request to the Brandfetch API.+// https://docs.brandfetch.com/docs/getting-started+func VerifyMatch(ctx context.Context, client *http.Client, token string) (bool, error) {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.brandfetch.io/v2/brands/google.com", http.NoBody)if err != nil {return false, err}req.Header.Add("Content-Type", "application/json")- req.Header.Add("x-api-key", key)-+ req.Header.Add("Authorization", "Bearer "+token)resp, err := client.Do(req)if err != nil {return false, err}-- defer func() {- _, _ = io.Copy(io.Discard, resp.Body)- _ = resp.Body.Close()- }()+ defer resp.Body.Close()switch resp.StatusCode {case http.StatusOK:diff --git a/pkg/detectors/brandfetch/v2/brandfetch_integration_test.go b/pkg/detectors/brandfetch/v2/brandfetch_integration_test.gonew file mode 100644index 000000000..ac1b015b2--- /dev/null+++ b/pkg/detectors/brandfetch/v2/brandfetch_integration_test.go@@ -0,0 +1,121 @@+//go:build detectors+// +build detectors++package brandfetch++import (+ "context"+ "fmt"+ "testing"+ "time"++ "github.com/kylelemons/godebug/pretty"+ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors"++ "github.com/trufflesecurity/trufflehog/v3/pkg/common"+ "github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"+)++func TestBrandfetch_FromChunk(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)+ defer cancel()+ testSecrets, err := common.GetSecret(ctx, "trufflehog-testing", "detectors6")+ if err != nil {+ t.Fatalf("could not get test secrets from GCP: %s", err)+ }+ secret := testSecrets.MustGetField("BRANDFETCH_V2")+ inactiveSecret := testSecrets.MustGetField("BRANDFETCH_V2_INACTIVE")++ type args struct {+ ctx context.Context+ data []byte+ verify bool+ }+ tests := []struct {+ name string+ s Scanner+ args args+ want []detectors.Result+ wantErr bool+ }{+ {+ name: "found, verified",+ s: Scanner{},+ args: args{+ ctx: context.Background(),+ data: []byte(fmt.Sprintf("You can find a brandfetch secret %s within", secret)),+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detectorspb.DetectorType_Brandfetch,+ Verified: true,+ },+ },+ wantErr: false,+ },+ {+ name: "found, unverified",+ s: Scanner{},+ args: args{+ ctx: context.Background(),+ data: []byte(fmt.Sprintf("You can find a brandfetch secret %s within but not valid", inactiveSecret)), // the secret would satisfy the regex but not pass validation+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detectorspb.DetectorType_Brandfetch,+ Verified: false,+ },+ },+ wantErr: false,+ },+ {+ name: "not found",+ s: Scanner{},+ args: args{+ ctx: context.Background(),+ data: []byte("You cannot find the secret within"),+ verify: true,+ },+ want: nil,+ wantErr: false,+ },+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ s := Scanner{}+ got, err := s.FromData(tt.args.ctx, tt.args.verify, tt.args.data)+ if (err != nil) != tt.wantErr {+ t.Errorf("Brandfetch.FromData() error = %v, wantErr %v", err, tt.wantErr)+ return+ }+ for i := range got {+ if len(got[i].Raw) == 0 {+ t.Fatalf("no raw secret present: \n %+v", got[i])+ }+ got[i].Raw = nil+ got[i].ExtraData = nil+ }+ if diff := pretty.Compare(got, tt.want); diff != "" {+ t.Errorf("Brandfetch.FromData() %s diff: (-got +want)\n%s", tt.name, diff)+ }+ })+ }+}++func BenchmarkFromData(benchmark *testing.B) {+ ctx := context.Background()+ s := Scanner{}+ for name, data := range detectors.MustGetBenchmarkData() {+ benchmark.Run(name, func(b *testing.B) {+ b.ResetTimer()+ for n := 0; n < b.N; n++ {+ _, err := s.FromData(ctx, false, data)+ if err != nil {+ b.Fatal(err)+ }+ }+ })+ }+}diff --git a/pkg/detectors/brandfetch/v2/brandfetch_test.go b/pkg/detectors/brandfetch/v2/brandfetch_test.gonew file mode 100644index 000000000..e991b6c92--- /dev/null+++ b/pkg/detectors/brandfetch/v2/brandfetch_test.go@@ -0,0 +1,149 @@+package brandfetch++import (+ "context"+ "testing"++ "github.com/google/go-cmp/cmp"+ "github.com/stretchr/testify/require"++ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors"+ "github.com/trufflesecurity/trufflehog/v3/pkg/engine/ahocorasick"+)++func TestBrandFetch_Pattern(t *testing.T) {+ d := Scanner{}+ ahoCorasickCore := ahocorasick.NewAhoCorasickCore([]detectors.Detector{d})++ tests := []struct {+ name string+ input string+ want []string+ }{+ {+ name: "valid pattern",+ input: "brandfetch credentials: ZUfake+eKo3qNxLDfake/6vqjOtr4fa6u5wShfakes8=",+ want: []string{"ZUfake+eKo3qNxLDfake/6vqjOtr4fa6u5wShfakes8="},+ },+ {+ name: "valid pattern - assignment format",+ input: "BRANDFETCH_API_KEY=msCwufakeod43s2ad/D0em/LbIBpZqFAKE9P+H3UTno=",+ want: []string{"msCwufakeod43s2ad/D0em/LbIBpZqFAKE9P+H3UTno="},+ },+ {+ name: "valid pattern - complex",+ input: `+ func main() {+ url := "https://api.example.com/v1/resource"++ // Create a new request with the secret as a header+ req, err := http.NewRequest("GET", url, http.NoBody)+ if err != nil {+ fmt.Println("Error creating request:", err)+ return+ }++ brandfetchAPIKey := "0mWrufake4X1dRfake0mxS+E48ofakesTlyl55raNOs="+ req.Header.Set("x-api-key", brandfetchAPIKey) // brandfetch secret++ // Perform the request+ client := &http.Client{}+ resp, _ := client.Do(req)+ defer resp.Body.Close()++ // Check response status+ if resp.StatusCode == http.StatusOK {+ fmt.Println("Request successful!")+ } else {+ fmt.Println("Request failed with status:", resp.Status)+ }+ }+ `,+ want: []string{"0mWrufake4X1dRfake0mxS+E48ofakesTlyl55raNOs="},+ },+ {+ name: "valid pattern - xml",+ input: `+ <com.cloudbees.plugins.credentials.impl.StringCredentialsImpl>+ <scope>GLOBAL</scope>+ <id>{uSiXZ-NMpDW-ZJQFSN-5wkT7SqQ8-mDbr9K2pl}</id>+ <secret>{brandfetch AQAAABAAA 0mWrufake4X1dRfake0mxS+E48ofakesTlyl55rfake=}</secret>+ <description>configuration for production</description>+ <creationDate>2023-05-18T14:32:10Z</creationDate>+ <owner>jenkins-admin</owner>+ </com.cloudbees.plugins.credentials.impl.StringCredentialsImpl>+ `,+ want: []string{"0mWrufake4X1dRfake0mxS+E48ofakesTlyl55rfake="},+ },+ {+ name: "invalid pattern - wrong length",+ input: "brandfetch credentials: yUeIqnFwILOIlEPyBt+=JOAdwfQ7sD2uHOAdwf2U",+ want: nil,+ },+ {+ name: "invalid pattern - invalid characters",+ input: "brandfetch credentials: yUeIqnFwILOIlEPyBt+=JOAdwfQ7sD2uHOAdwf2U[qy]UeIqnFwILOIlEPyBtJ^fakes=",+ want: nil,+ },+ {+ name: "invalid pattern",+ input: `+ func main() {+ url := "https://api.example.com/v1/resource"++ // Create a new request with the secret as a header+ req, err := http.NewRequest("GET", url, http.NoBody)+ if err != nil {+ fmt.Println("Error creating request:", err)+ return+ }++ brandfetchAPIKey := "yUeIqnFwILOIlEPyBt+=JOAdwfQ7sD2uHOAdwf2U[qy]UeIqnFwILOIlEPyBtJ^"+ req.Header.Set("x-api-key", brandfetchAPIKey) // brandfetch secret++ // Perform the request+ client := &http.Client{}+ resp, _ := client.Do(req)+ defer resp.Body.Close()+ }+ `,+ want: nil,+ },+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ matchedDetectors := ahoCorasickCore.FindDetectorMatches([]byte(test.input))+ if len(matchedDetectors) == 0 {+ t.Errorf("test %q failed: expected keywords %v to be found in the input", test.name, d.Keywords())+ return+ }++ results, err := d.FromData(context.Background(), false, []byte(test.input))+ require.NoError(t, err)++ if len(results) != len(test.want) {+ t.Errorf("mismatch in result count: expected %d, got %d", len(test.want), len(results))+ return+ }++ actual := make(map[string]struct{}, len(results))+ for _, r := range results {+ if len(r.RawV2) > 0 {+ actual[string(r.RawV2)] = struct{}{}+ } else {+ actual[string(r.Raw)] = struct{}{}+ }+ }++ expected := make(map[string]struct{}, len(test.want))+ for _, v := range test.want {+ expected[v] = struct{}{}+ }++ if diff := cmp.Diff(expected, actual); diff != "" {+ t.Errorf("%s diff: (-want +got)\n%s", test.name, diff)+ }+ })+ }+}diff --git a/pkg/engine/defaults/defaults.go b/pkg/engine/defaults/defaults.goindex 638ebd21a..73c440408 100644--- a/pkg/engine/defaults/defaults.go+++ b/pkg/engine/defaults/defaults.go@@ -108,7 +108,8 @@ import ("github.com/trufflesecurity/trufflehog/v3/pkg/detectors/box""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/boxoauth""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/braintreepayments"- "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/brandfetch"+ brandfetchv1 "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/brandfetch/v1"+ brandfetchv2 "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/brandfetch/v2""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/browserstack""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/browshot""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/bscscan"@@ -966,7 +967,8 @@ func buildDetectorList() []detectors.Detector {&box.Scanner{},&boxoauth.Scanner{},&braintreepayments.Scanner{},- &brandfetch.Scanner{},+ &brandfetchv1.Scanner{},+ &brandfetchv2.Scanner{},&browserstack.Scanner{},&browshot.Scanner{},&bscscan.Scanner{},