Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
Added v2 for CircleCI Detector (#4300)
Kashif Khan8d5986d13039
diff --git a/pkg/detectors/circleci/v1/circleci.go b/pkg/detectors/circleci/v1/circleci.gonew file mode 100644index 000000000..d98d3bf6f--- /dev/null+++ b/pkg/detectors/circleci/v1/circleci.go@@ -0,0 +1,114 @@+package circleci++import (+ "context"+ "fmt"+ "io"+ "net/http"+ "strconv"++ 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 {+ client *http.Client+}++// Ensure the Scanner satisfies the interface at compile time.+var _ detectors.Detector = (*Scanner)(nil)+var _ detectors.Versioner = (*Scanner)(nil)++var (+ defaultClient = common.SaneHttpClient()++ keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"circle"}) + `([a-fA-F0-9]{40})`)+)++func (s Scanner) getClient() *http.Client {+ if s.client != nil {+ return s.client+ }++ return defaultClient+}++func (Scanner) Version() int { return 1 }++// 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{"circle"}+}++func (s Scanner) Type() detectorspb.DetectorType {+ return detectorspb.DetectorType_Circle+}++func (s Scanner) Description() string {+ return "CircleCI is a continuous integration and delivery platform used to build, test, and deploy software. CircleCI tokens can be used to interact with the CircleCI API and access various resources and functionalities."+}++// FromData will find and optionally verify Circle 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)++ var uniqueTokens = make(map[string]struct{})++ for _, match := range keyPat.FindAllStringSubmatch(dataStr, -1) {+ uniqueTokens[match[1]] = struct{}{}+ }++ for token := range uniqueTokens {+ result := detectors.Result{+ DetectorType: detectorspb.DetectorType_Circle,+ Raw: []byte(token),+ ExtraData: map[string]string{+ "Version": strconv.Itoa(s.Version()),+ },+ }++ if verify {+ // https://circleci.com/docs/api/#authentication+ isVerified, verificationErr := VerifyCircleCIToken(ctx, s.getClient(), token)+ result.Verified = isVerified+ result.SetVerificationError(verificationErr, token)+ }++ results = append(results, result)+ }++ return+}++func VerifyCircleCIToken(ctx context.Context, client *http.Client, token string) (bool, error) {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://circleci.com/api/v2/me", http.NoBody)+ if err != nil {+ return false, err+ }++ req.Header.Add("Accept", "application/json;")+ req.Header.Add("Circle-Token", token)++ resp, err := client.Do(req)+ if err != nil {+ return false, err+ }++ defer func() {+ _, _ = io.Copy(io.Discard, resp.Body)+ _ = resp.Body.Close()+ }()++ switch resp.StatusCode {+ case http.StatusOK:+ return true, nil+ case http.StatusUnauthorized:+ return false, nil+ default:+ return false, fmt.Errorf("unexpected status code: %d", resp.StatusCode)+ }+}diff --git a/pkg/detectors/circleci/circleci_integration_test.go b/pkg/detectors/circleci/v1/circleci_integration_test.gosimilarity index 100%rename from pkg/detectors/circleci/circleci_integration_test.gorename to pkg/detectors/circleci/v1/circleci_integration_test.godiff --git a/pkg/detectors/circleci/circleci_test.go b/pkg/detectors/circleci/v1/circleci_test.gosimilarity index 100%rename from pkg/detectors/circleci/circleci_test.gorename to pkg/detectors/circleci/v1/circleci_test.godiff --git a/pkg/detectors/circleci/circleci.go b/pkg/detectors/circleci/v2/circleci.gosimilarity index 59%rename from pkg/detectors/circleci/circleci.gorename to pkg/detectors/circleci/v2/circleci.goindex b81745bdf..6cf34ef54 100644--- a/pkg/detectors/circleci/circleci.go+++ b/pkg/detectors/circleci/v2/circleci.go@@ -3,61 +3,77 @@ package circleciimport ("context""net/http"+ "strconv"regexp "github.com/wasilibs/go-re2"+ "github.com/trufflesecurity/trufflehog/v3/pkg/common""github.com/trufflesecurity/trufflehog/v3/pkg/detectors"+ v1 "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/circleci/v1""github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"-- "github.com/trufflesecurity/trufflehog/v3/pkg/common")-type Scanner struct{}+type Scanner struct {+ client *http.Client+}// Ensure the Scanner satisfies the interface at compile time.var _ detectors.Detector = (*Scanner)(nil)+var _ detectors.Versioner = (*Scanner)(nil)var (- keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"circle"}) + `([a-fA-F0-9]{40})`)+ defaultClient = common.SaneHttpClient()++ keyPat = regexp.MustCompile(`(CCIPAT_[a-zA-Z0-9]{22}_[a-fA-F0-9]{40})`))+func (s Scanner) getClient() *http.Client {+ if s.client != nil {+ return s.client+ }++ return defaultClient+}++func (Scanner) Version() int { return 2 }+// 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{"circle"}+ return []string{"CCIPAT_"}+}++func (s Scanner) Type() detectorspb.DetectorType {+ return detectorspb.DetectorType_Circle+}++func (s Scanner) Description() string {+ return "CircleCI is a continuous integration and delivery platform used to build, test, and deploy software. CircleCI tokens can be used to interact with the CircleCI API and access various resources and functionalities."}// FromData will find and optionally verify Circle 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)+ var uniqueTokens = make(map[string]struct{})- for _, match := range matches {-- token := match[1]+ for _, match := range keyPat.FindAllStringSubmatch(dataStr, -1) {+ uniqueTokens[match[1]] = struct{}{}+ }+ for token := range uniqueTokens {result := detectors.Result{DetectorType: detectorspb.DetectorType_Circle,Raw: []byte(token),+ ExtraData: map[string]string{+ "Version": strconv.Itoa(s.Version()),+ },}if verify {- client := common.SaneHttpClient()- // https://circleci.com/docs/api/#authentication- req, err := http.NewRequestWithContext(ctx, "GET", "https://circleci.com/api/v2/me", nil)- if err != nil {- continue- }- req.Header.Add("Accept", "application/json;")- req.Header.Add("Circle-Token", token)- res, err := client.Do(req)- if err == nil {- defer res.Body.Close()- }- if res != nil && res.StatusCode >= 200 && res.StatusCode < 300 {- result.Verified = true- }+ isVerified, verificationErr := v1.VerifyCircleCIToken(ctx, s.getClient(), token)+ result.Verified = isVerified+ result.SetVerificationError(verificationErr, token)}results = append(results, result)@@ -65,11 +81,3 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (resultreturn}--func (s Scanner) Type() detectorspb.DetectorType {- return detectorspb.DetectorType_Circle-}--func (s Scanner) Description() string {- return "CircleCI is a continuous integration and delivery platform used to build, test, and deploy software. CircleCI tokens can be used to interact with the CircleCI API and access various resources and functionalities."-}diff --git a/pkg/detectors/circleci/v2/circleci_integration_test.go b/pkg/detectors/circleci/v2/circleci_integration_test.gonew file mode 100644index 000000000..e514bc23f--- /dev/null+++ b/pkg/detectors/circleci/v2/circleci_integration_test.go@@ -0,0 +1,123 @@+//go:build detectors+// +build detectors++package circleci++import (+ "context"+ "fmt"+ "os"+ "testing"+ "time"++ "github.com/kylelemons/godebug/pretty"+ "github.com/trufflesecurity/trufflehog/v3/pkg/common"+ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors"+ "github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"+)++func TestCircleCI_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("CIRCLECI")+ secretInactive := testSecrets.MustGetField("CIRCLECI_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 circle secret %s within", secret)),+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detectorspb.DetectorType_Circle,+ Verified: true,+ },+ },+ wantErr: false,+ },+ {+ name: "found, unverified",+ s: Scanner{},+ args: args{+ ctx: context.Background(),+ data: []byte(fmt.Sprintf("You can find a circle secret %s within", secretInactive)),+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detectorspb.DetectorType_Circle,+ 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("CircleCI.FromData() error = %v, wantErr %v", err, tt.wantErr)+ return+ }+ if os.Getenv("FORCE_PASS_DIFF") == "true" {+ return+ }+ for i := range got {+ if len(got[i].Raw) == 0 {+ t.Fatal("no raw secret present")+ }+ got[i].Raw = nil+ got[i].ExtraData = nil+ }+ if diff := pretty.Compare(got, tt.want); diff != "" {+ t.Errorf("CircleCI.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/circleci/v2/circleci_test.go b/pkg/detectors/circleci/v2/circleci_test.gonew file mode 100644index 000000000..d67f067a4--- /dev/null+++ b/pkg/detectors/circleci/v2/circleci_test.go@@ -0,0 +1,86 @@+package circleci++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 TestCircleCI_Pattern(t *testing.T) {+ d := Scanner{}+ ahoCorasickCore := ahocorasick.NewAhoCorasickCore([]detectors.Detector{d})++ tests := []struct {+ name string+ input string+ want []string+ }{+ {+ name: "valid pattern",+ input: `+ # Configuration File: config.yaml+ database:+ host: $DB_HOST+ port: $DB_PORT+ username: $DB_USERNAME+ password: $DB_PASS # IMPORTANT: Do not share this password publicly++ api:+ auth_type: API-Key+ base_url: "https://api.example.com/v1/user"+ api_key: "CCIPAT_FAKEd5qPreGFAKEaQxBi6i_914bf0042f4f2d34e1d2ef6615c051a5caf70172"++ # Notes:+ # - Remember to rotate the secret every 90 days.+ # - The above credentials should only be used in a secure environment.+ `,+ want: []string{"CCIPAT_FAKEd5qPreGFAKEaQxBi6i_914bf0042f4f2d34e1d2ef6615c051a5caf70172"},+ },+ }++ 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 e34dd7cdd..e32c7555b 100644--- a/pkg/engine/defaults/defaults.go+++ b/pkg/engine/defaults/defaults.go@@ -144,7 +144,8 @@ import ("github.com/trufflesecurity/trufflehog/v3/pkg/detectors/checkout""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/checkvist""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/cicero"- "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/circleci"+ circleciV1 "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/circleci/v1"+ circleciV2 "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/circleci/v2""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/clarifai""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/clearbit""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/clickhelp"@@ -996,7 +997,8 @@ func buildDetectorList() []detectors.Detector {&checkout.Scanner{},&checkvist.Scanner{},&cicero.Scanner{},- &circleci.Scanner{},+ &circleciV1.Scanner{},+ &circleciV2.Scanner{},&clarifai.Scanner{},&clearbit.Scanner{},&clickhelp.Scanner{},