Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
Bannerbear Detector V2 (#4222)
Shahzad Haiderbb47e8f43248
diff --git a/pkg/detectors/bannerbear/bannerbear.go b/pkg/detectors/bannerbear/v1/bannerbear.gosimilarity index 92%rename from pkg/detectors/bannerbear/bannerbear.gorename to pkg/detectors/bannerbear/v1/bannerbear.goindex 5ca72ce1c..f23c22e27 100644--- a/pkg/detectors/bannerbear/bannerbear.go+++ b/pkg/detectors/bannerbear/v1/bannerbear.go@@ -16,8 +16,11 @@ import (type Scanner struct{}+func (s Scanner) Version() int { return 1 }+// Ensure the Scanner satisfies the interface at compile time.var _ detectors.Detector = (*Scanner)(nil)+var _ detectors.Versioner = (*Scanner)(nil)var (client = common.SaneHttpClient()@@ -44,6 +47,9 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results1 := detectors.Result{DetectorType: detectorspb.DetectorType_Bannerbear,Raw: []byte(resMatch),+ ExtraData: map[string]string{+ "version": fmt.Sprintf("%d", s.Version()),+ },}if verify {@@ -77,7 +83,7 @@ func verifyBannerBear(ctx context.Context, client *http.Client, key string) (booresp, err := client.Do(req)if err != nil {- return false, nil+ return false, err}defer func() {diff --git a/pkg/detectors/bannerbear/bannerbear_integration_test.go b/pkg/detectors/bannerbear/v1/bannerbear_integration_test.gosimilarity index 89%rename from pkg/detectors/bannerbear/bannerbear_integration_test.gorename to pkg/detectors/bannerbear/v1/bannerbear_integration_test.goindex 263daa202..c67e040f5 100644--- a/pkg/detectors/bannerbear/bannerbear_integration_test.go+++ b/pkg/detectors/bannerbear/v1/bannerbear_integration_test.go@@ -9,7 +9,8 @@ import ("testing""time"- "github.com/kylelemons/godebug/pretty"+ "github.com/google/go-cmp/cmp"+ "github.com/google/go-cmp/cmp/cmpopts""github.com/trufflesecurity/trufflehog/v3/pkg/detectors""github.com/trufflesecurity/trufflehog/v3/pkg/common"@@ -96,8 +97,10 @@ func TestBannerbear_FromChunk(t *testing.T) {}got[i].Raw = nil}- if diff := pretty.Compare(got, tt.want); diff != "" {- t.Errorf("Bannerbear.FromData() %s diff: (-got +want)\n%s", tt.name, diff)++ ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "verificationError", "primarySecret", "ExtraData")+ if diff := cmp.Diff(tt.want, got, ignoreOpts); diff != "" {+ t.Errorf("BannerbearV1.FromData() %s - diff: (-got +want)\n%s", tt.name, diff)}})}diff --git a/pkg/detectors/bannerbear/bannerbear_test.go b/pkg/detectors/bannerbear/v1/bannerbear_test.gosimilarity index 100%rename from pkg/detectors/bannerbear/bannerbear_test.gorename to pkg/detectors/bannerbear/v1/bannerbear_test.godiff --git a/pkg/detectors/bannerbear/v2/bannerbear.go b/pkg/detectors/bannerbear/v2/bannerbear.gonew file mode 100644index 000000000..3b0265421--- /dev/null+++ b/pkg/detectors/bannerbear/v2/bannerbear.go@@ -0,0 +1,126 @@+package bannerbear++import (+ "bytes"+ "context"+ "fmt"+ "io"+ "net/http"++ regexp "github.com/wasilibs/go-re2"++ "github.com/trufflesecurity/trufflehog/v3/pkg/common"+ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors"+ "github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"+)++type Scanner struct{}++func (s Scanner) Version() int { return 2 }++// Ensure the Scanner satisfies the interface at compile time.+var _ detectors.Detector = (*Scanner)(nil)+var _ detectors.Versioner = (*Scanner)(nil)++var (+ client = common.SaneHttpClient()++ // Make sure that your group is surrounded in boundary characters such as below to reduce false positives.+ keyPat = regexp.MustCompile(`\b(bb_(?:pr|ma)_[a-f0-9]{30})\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{"bb_pr_", "bb_ma_"}+}++// FromData will find and optionally verify Bannerbear 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)+ uniqueMatches := make(map[string]struct{}, len(matches))++ for _, match := range matches {+ uniqueMatches[match[1]] = struct{}{}+ }++ for match := range uniqueMatches {+ s1 := detectors.Result{+ DetectorType: detectorspb.DetectorType_Bannerbear,+ Raw: []byte(match),+ ExtraData: map[string]string{+ "version": fmt.Sprintf("%d", s.Version()),+ },+ }++ if verify {+ isVerified, extraData, verificationErr := s.verifyBannerBear(ctx, client, match)+ s1.Verified = isVerified+ s1.ExtraData = extraData+ s1.SetVerificationError(verificationErr, match)+ }++ results = append(results, s1)+ }++ return results, nil+}++func (s Scanner) Type() detectorspb.DetectorType {+ return detectorspb.DetectorType_Bannerbear+}++func (s Scanner) Description() string {+ return "Bannerbear is an API for generating dynamic images, videos, and GIFs. Bannerbear API keys can be used to access and manipulate these resources."+}++// docs: https://developers.bannerbear.com/+func (s Scanner) verifyBannerBear(ctx context.Context, client *http.Client, key string) (bool, map[string]string, error) {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.bannerbear.com/v2/auth", http.NoBody)+ if err != nil {+ return false, nil, err+ }++ req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", key))++ resp, err := client.Do(req)+ if err != nil {+ return false, nil, err+ }++ defer func() {+ _, _ = io.Copy(io.Discard, resp.Body)+ _ = resp.Body.Close()+ }()++ extraData := map[string]string{"version": fmt.Sprintf("%d", s.Version())}++ switch resp.StatusCode {+ case http.StatusOK:+ extraData["key_type"] = "Project API Key"+ return true, extraData, nil+ case http.StatusBadRequest:+ bodyBytes, err := io.ReadAll(resp.Body)+ if err != nil {+ return false, extraData, err+ }++ // According to Bannerbear API docs (https://developers.bannerbear.com/#authentication), the /auth endpoint+ // expects us to add a project_id parameter to the payload, when using a Full Access Master API Key.+ // otherwise, it returns a 400 Bad Request with "Error: When using a Master API Key you must set a project_id parameter"+ // Also, when we use a Master API Key with limited access, it returns a 400 Bad Request with "Error: this Master Key is Limited Access only"+ validResponse := bytes.Contains(bodyBytes, []byte("When using a Master API Key")) || bytes.Contains(bodyBytes, []byte("Master Key is Limited Access"))+ if validResponse {+ extraData["key_type"] = "Master API Key"+ return true, extraData, nil+ } else {+ return false, extraData, fmt.Errorf("bad request: %s, body: %s", resp.Status, string(bodyBytes))+ }+ case http.StatusUnauthorized:+ return false, extraData, nil+ default:+ return false, extraData, fmt.Errorf("unexpected status code: %d", resp.StatusCode)+ }+}diff --git a/pkg/detectors/bannerbear/v2/bannerbear_integration_test.go b/pkg/detectors/bannerbear/v2/bannerbear_integration_test.gonew file mode 100644index 000000000..ef8dd9a4c--- /dev/null+++ b/pkg/detectors/bannerbear/v2/bannerbear_integration_test.go@@ -0,0 +1,123 @@+//go:build detectors+// +build detectors++package bannerbear++import (+ "context"+ "fmt"+ "testing"+ "time"++ "github.com/google/go-cmp/cmp"+ "github.com/google/go-cmp/cmp/cmpopts"+ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors"++ "github.com/trufflesecurity/trufflehog/v3/pkg/common"+ "github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"+)++func TestBannerbear_FromChunk(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)+ defer cancel()+ testSecrets, err := common.GetSecret(ctx, "trufflehog-testing", "detectors5")+ if err != nil {+ t.Fatalf("could not get test secrets from GCP: %s", err)+ }+ secret := testSecrets.MustGetField("BANNERBEARV2")+ inactiveSecret := testSecrets.MustGetField("BANNERBEARV2_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 bannerbear secret %s within", secret)),+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detectorspb.DetectorType_Bannerbear,+ Verified: true,+ },+ },+ wantErr: false,+ },+ {+ name: "found, unverified",+ s: Scanner{},+ args: args{+ ctx: context.Background(),+ data: []byte(fmt.Sprintf("You can find a bannerbear 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_Bannerbear,+ 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("Bannerbear.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+ }++ ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "verificationError", "primarySecret", "ExtraData")+ if diff := cmp.Diff(tt.want, got, ignoreOpts); diff != "" {+ t.Errorf("BannerbearV2.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/bannerbear/v2/bannerbear_test.go b/pkg/detectors/bannerbear/v2/bannerbear_test.gonew file mode 100644index 000000000..4ac8506d4--- /dev/null+++ b/pkg/detectors/bannerbear/v2/bannerbear_test.go@@ -0,0 +1,80 @@+package bannerbear++import (+ "context"+ "testing"++ "github.com/google/go-cmp/cmp"++ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors"+ "github.com/trufflesecurity/trufflehog/v3/pkg/engine/ahocorasick"+)++func TestBannerBear_Pattern(t *testing.T) {+ d := Scanner{}+ ahoCorasickCore := ahocorasick.NewAhoCorasickCore([]detectors.Detector{d})++ tests := []struct {+ name string+ input string+ want []string+ }{+ {+ name: "valid pattern",+ input: "bannerbear credentials: bb_pr_abcdc2b40ef44abcd8cbf3739aabcd",+ want: []string{"bb_pr_abcdc2b40ef44abcd8cbf3739aabcd"},+ },+ {+ name: "valid pattern - complex",+ input: "bannerbear credentials: ajahf ajkahfkjah fka bb_pr_abcdc2b40ef44abcd8cbf3739aacba adlkajflaihflahdljajfla",+ want: []string{"bb_pr_abcdc2b40ef44abcd8cbf3739aacba"},+ },+ {+ name: "invalid pattern",+ input: "bannerbear credentials: bb_pr_abcd",+ 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("keywords '%v' not matched by: %s", d.Keywords(), test.input)+ return+ }++ results, err := d.FromData(context.Background(), false, []byte(test.input))+ if err != nil {+ t.Errorf("error = %v", err)+ return+ }++ if len(results) != len(test.want) {+ if len(results) == 0 {+ t.Errorf("did not receive result")+ } else {+ t.Errorf("expected %d results, only received %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 8b9e64b1f..8cc460284 100644--- a/pkg/engine/defaults/defaults.go+++ b/pkg/engine/defaults/defaults.go@@ -83,7 +83,8 @@ import ("github.com/trufflesecurity/trufflehog/v3/pkg/detectors/azuresastoken""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/azuresearchadminkey""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/azuresearchquerykey"- "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/bannerbear"+ bannerbearv1 "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/bannerbear/v1"+ bannerbearv2 "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/bannerbear/v2""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/baremetrics""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/beamer""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/beebole"@@ -933,7 +934,8 @@ func buildDetectorList() []detectors.Detector {&azuresearchquerykey.Scanner{},&azure_storage.Scanner{},&azurerepositorykey.Scanner{},- &bannerbear.Scanner{},+ &bannerbearv1.Scanner{},+ &bannerbearv2.Scanner{},&baremetrics.Scanner{},&beamer.Scanner{},&beebole.Scanner{},