Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
adding twitter + Consumer key detector (#2963)
Abdul Basitcb4d332cbfab
diff --git a/pkg/detectors/twitter/twitter.go b/pkg/detectors/twitter/twitter.goindex bcf8c8886..cc69bb90a 100644--- a/pkg/detectors/twitter/twitter.go+++ b/pkg/detectors/twitter/twitter.go@@ -3,10 +3,11 @@ package twitterimport ("context""fmt"- regexp "github.com/wasilibs/go-re2""net/http""strings"+ 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"diff --git a/pkg/detectors/twitterconsumerkey/twitterconsumerkey.go b/pkg/detectors/twitterconsumerkey/twitterconsumerkey.gonew file mode 100644index 000000000..5a0fe7ea1--- /dev/null+++ b/pkg/detectors/twitterconsumerkey/twitterconsumerkey.go@@ -0,0 +1,144 @@+package twitterconsumerkey++import (+ "context"+ b64 "encoding/base64"+ "encoding/json"+ "fmt"+ "net/http"+ "strings"++ 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+ detectors.DefaultMultiPartCredentialProvider+}++// Ensure the Scanner satisfies the interface at compile time.+var _ detectors.Detector = (*Scanner)(nil)++var (+ 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{"twitter", "consumer", "key"}) + `\b([a-zA-Z0-9]{25})\b`)+ secretPat = regexp.MustCompile(detectors.PrefixRegex([]string{"twitter", "consumer", "secret"}) + `\b([a-zA-Z0-9]{50})\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{"twitter"}+}++// FromData will find and optionally verify Twitter 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)++ // find for consumer key + secrets+ keyMatches := make(map[string]struct{})+ for _, match := range keyPat.FindAllStringSubmatch(dataStr, -1) {+ keyMatches[match[1]] = struct{}{}+ }+ secretMatches := make(map[string]struct{})+ for _, match := range secretPat.FindAllStringSubmatch(dataStr, -1) {+ secretMatches[match[1]] = struct{}{}+ }++ for key := range keyMatches {+ for secret := range secretMatches {+ key := strings.TrimSpace(key)+ secret := strings.TrimSpace(secret)++ s1 := detectors.Result{+ DetectorType: detectorspb.DetectorType_TwitterConsumerkey,+ Raw: []byte(key),+ RawV2: []byte(key + secret),+ }++ if verify {+ client := s.client+ if client == nil {+ client = defaultClient+ }+ bearerToken, err := fetchBearerToken(ctx, client, key, secret)+ if err == nil {+ isVerified, err := verifyBearerToken(ctx, client, bearerToken)+ s1.Verified = isVerified+ s1.SetVerificationError(err, key)+ } else {+ s1.SetVerificationError(err, key)+ }+ }+ results = append(results, s1)+ }+ }++ return results, nil+}++func (s Scanner) Type() detectorspb.DetectorType {+ return detectorspb.DetectorType_TwitterConsumerkey+}++func verifyBearerToken(ctx context.Context, client *http.Client, token string) (bool, error) {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.twitter.com/2/tweets/20", nil)+ if err != nil {+ return false, err+ }+ req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))+ res, err := client.Do(req)+ if err == nil {+ defer res.Body.Close()+ switch res.StatusCode {+ case http.StatusOK, http.StatusForbidden:+ // 403 indicates lack of permission, but valid token (could be due to twitter free tier)+ return true, nil+ case http.StatusUnauthorized:+ return false, nil+ default:+ return false, fmt.Errorf("unexpected HTTP response status %d", res.StatusCode)+ }+ }++ return false, err+}++func fetchBearerToken(ctx context.Context, client *http.Client, key, secret string) (string, error) {+ payload := strings.NewReader("grant_type=client_credentials")+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.twitter.com/oauth2/token", payload)+ if err != nil {+ return "", err+ }+ sEnc := b64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", key, secret)))++ req.Header.Add("Authorization", fmt.Sprintf("Basic %s", sEnc))+ req.Header.Add("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")+ res, err := client.Do(req)+ if err != nil {+ return "", err+ }+ defer res.Body.Close()++ switch res.StatusCode {+ case http.StatusOK:+ var token tokenResponse+ if err = json.NewDecoder(res.Body).Decode(&token); err != nil {+ return "", err+ }+ return token.AccessToken, nil+ default:+ return "", fmt.Errorf("unexpected HTTP response status %d", res.StatusCode)+ }+}++type tokenResponse struct {+ TokenType string `json:"token_type"`+ AccessToken string `json:"access_token"`+}diff --git a/pkg/detectors/twitterconsumerkey/twitterconsumerkey_test.go b/pkg/detectors/twitterconsumerkey/twitterconsumerkey_test.gonew file mode 100644index 000000000..8ba404b35--- /dev/null+++ b/pkg/detectors/twitterconsumerkey/twitterconsumerkey_test.go@@ -0,0 +1,139 @@+//go:build detectors+// +build detectors++package twitterconsumerkey++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 TestTwitterConsumerKey_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)+ }+ key := testSecrets.MustGetField("TWITTER_CONSUMER_KEY")+ secret := testSecrets.MustGetField("TWITTER_CONSUMER_SECRET")++ inactiveKey := testSecrets.MustGetField("TWITTER_CONSUMER_KEY_INACTIVE")+ inactiveSecret := testSecrets.MustGetField("TWITTER_CONSUMER_SECRET_INACTIVE")++ type args struct {+ ctx context.Context+ data []byte+ verify bool+ }+ tests := []struct {+ name string+ s Scanner+ args args+ want []detectors.Result+ wantErr bool+ wantVerificationErr bool+ }{+ {+ name: "found, verified",+ s: Scanner{},+ args: args{+ ctx: context.Background(),+ data: []byte(fmt.Sprintf("You can find a twitter key %s and secret %s within", key, secret)),+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detectorspb.DetectorType_TwitterConsumerkey,+ Verified: true,+ Raw: []byte(key),+ RawV2: []byte(key + secret),+ },+ },+ wantErr: false,+ wantVerificationErr: false,+ },+ {+ name: "found, unverified",+ s: Scanner{},+ args: args{+ ctx: context.Background(),+ data: []byte(fmt.Sprintf("You can find a twitter key %s and secret %s within", inactiveKey, inactiveSecret)),+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detectorspb.DetectorType_TwitterConsumerkey,+ Verified: false,+ Raw: []byte(inactiveKey),+ RawV2: []byte(inactiveKey + inactiveSecret),+ },+ },+ wantErr: false,+ wantVerificationErr: true,+ },+ {+ name: "not found",+ s: Scanner{},+ args: args{+ ctx: context.Background(),+ data: []byte("You cannot find the key & secret within"),+ verify: true,+ },+ want: nil,+ wantErr: false,+ wantVerificationErr: 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("TwitterConsumerKey.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])+ }+ if len(got[i].RawV2) == 0 {+ t.Fatalf("no rawV2 secret present: \n %+v", got[i])+ }+ if (got[i].VerificationError() != nil) != tt.wantVerificationErr {+ t.Fatalf("wantVerificationError = %v, verification error = %v", tt.wantVerificationErr, got[i].VerificationError())+ }+ }+ ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "verificationError")+ if diff := cmp.Diff(got, tt.want, ignoreOpts); diff != "" {+ t.Errorf("TwitterConsumerKey.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/engine/defaults.go b/pkg/engine/defaults.goindex 8deea1def..4786de9c4 100644--- a/pkg/engine/defaults.go+++ b/pkg/engine/defaults.go@@ -717,6 +717,7 @@ import ("github.com/trufflesecurity/trufflehog/v3/pkg/detectors/twist""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/twitch""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/twitter"+ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/twitterconsumerkey""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/tyntec""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/typeform""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/typetalk"@@ -1606,6 +1607,7 @@ func DefaultDetectors() []detectors.Detector {onfleet.Scanner{},intra42.Scanner{},groq.Scanner{},+ twitterconsumerkey.Scanner{},}}diff --git a/pkg/pb/detectorspb/detectors.pb.go b/pkg/pb/detectorspb/detectors.pb.goindex ea499fc6b..4d3385fdf 100644--- a/pkg/pb/detectorspb/detectors.pb.go+++ b/pkg/pb/detectorspb/detectors.pb.go@@ -1088,6 +1088,7 @@ const (DetectorType_Onfleet DetectorType = 986DetectorType_Intra42 DetectorType = 987DetectorType_Groq DetectorType = 988+ DetectorType_TwitterConsumerkey DetectorType = 989)// Enum value maps for DetectorType.@@ -2078,6 +2079,7 @@ var (986: "Onfleet",987: "Intra42",988: "Groq",+ 989: "TwitterConsumerkey",}DetectorType_value = map[string]int32{"Alibaba": 0,@@ -3065,6 +3067,7 @@ var ("Onfleet": 986,"Intra42": 987,"Groq": 988,+ "TwitterConsumerkey": 989,})@@ -3518,7 +3521,7 @@ var file_detectors_proto_rawDesc = []byte{0x4c, 0x41, 0x49, 0x4e, 0x10, 0x01, 0x12, 0x0a, 0x0a, 0x06, 0x42, 0x41, 0x53, 0x45, 0x36, 0x34,0x10, 0x02, 0x12, 0x09, 0x0a, 0x05, 0x55, 0x54, 0x46, 0x31, 0x36, 0x10, 0x03, 0x12, 0x13, 0x0a,0x0f, 0x45, 0x53, 0x43, 0x41, 0x50, 0x45, 0x44, 0x5f, 0x55, 0x4e, 0x49, 0x43, 0x4f, 0x44, 0x45,- 0x10, 0x04, 0x2a, 0x94, 0x7e, 0x0a, 0x0c, 0x44, 0x65, 0x74, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x54,+ 0x10, 0x04, 0x2a, 0xad, 0x7e, 0x0a, 0x0c, 0x44, 0x65, 0x74, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x54,0x79, 0x70, 0x65, 0x12, 0x0b, 0x0a, 0x07, 0x41, 0x6c, 0x69, 0x62, 0x61, 0x62, 0x61, 0x10, 0x00,0x12, 0x08, 0x0a, 0x04, 0x41, 0x4d, 0x51, 0x50, 0x10, 0x01, 0x12, 0x07, 0x0a, 0x03, 0x41, 0x57,0x53, 0x10, 0x02, 0x12, 0x09, 0x0a, 0x05, 0x41, 0x7a, 0x75, 0x72, 0x65, 0x10, 0x03, 0x12, 0x0a,@@ -4527,11 +4530,13 @@ var file_detectors_proto_rawDesc = []byte{0x7a, 0x10, 0xd8, 0x07, 0x12, 0x0c, 0x0a, 0x07, 0x50, 0x61, 0x67, 0x61, 0x72, 0x6d, 0x65, 0x10,0xd9, 0x07, 0x12, 0x0c, 0x0a, 0x07, 0x4f, 0x6e, 0x66, 0x6c, 0x65, 0x65, 0x74, 0x10, 0xda, 0x07,0x12, 0x0c, 0x0a, 0x07, 0x49, 0x6e, 0x74, 0x72, 0x61, 0x34, 0x32, 0x10, 0xdb, 0x07, 0x12, 0x09,- 0x0a, 0x04, 0x47, 0x72, 0x6f, 0x71, 0x10, 0xdc, 0x07, 0x42, 0x3d, 0x5a, 0x3b, 0x67, 0x69, 0x74,- 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x72, 0x75, 0x66, 0x66, 0x6c, 0x65, 0x73,- 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x2f, 0x74, 0x72, 0x75, 0x66, 0x66, 0x6c, 0x65, 0x68,- 0x6f, 0x67, 0x2f, 0x76, 0x33, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x70, 0x62, 0x2f, 0x64, 0x65, 0x74,- 0x65, 0x63, 0x74, 0x6f, 0x72, 0x73, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,+ 0x0a, 0x04, 0x47, 0x72, 0x6f, 0x71, 0x10, 0xdc, 0x07, 0x12, 0x17, 0x0a, 0x12, 0x54, 0x77, 0x69,+ 0x74, 0x74, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x73, 0x75, 0x6d, 0x65, 0x72, 0x6b, 0x65, 0x79, 0x10,+ 0xdd, 0x07, 0x42, 0x3d, 0x5a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d,+ 0x2f, 0x74, 0x72, 0x75, 0x66, 0x66, 0x6c, 0x65, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79,+ 0x2f, 0x74, 0x72, 0x75, 0x66, 0x66, 0x6c, 0x65, 0x68, 0x6f, 0x67, 0x2f, 0x76, 0x33, 0x2f, 0x70,+ 0x6b, 0x67, 0x2f, 0x70, 0x62, 0x2f, 0x64, 0x65, 0x74, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x73, 0x70,+ 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,}var (diff --git a/proto/detectors.proto b/proto/detectors.protoindex 906f67525..68bd8ebdb 100644--- a/proto/detectors.proto+++ b/proto/detectors.proto@@ -998,6 +998,7 @@ enum DetectorType {Onfleet = 986;Intra42 = 987;Groq = 988;+ TwitterConsumerkey = 989;}message Result {