From 95afdd682a506a2efaa22e9ebfb815056695ae35 Mon Sep 17 00:00:00 2001 From: Shahzad Haider <76992801+shahzadhaider1@users.noreply.github.com> Date: Tue, 1 Jul 2025 11:49:59 +0500 Subject: [PATCH] Salesforce OAuth2 Detector (#4252) * salesforce oauth2 secret detector added * salesforce oauth2 detector added * addressed feedback: The secret PAT value can be those 64 characters or it can be a string of 19 numbers. The consumer PAT can include the characters '+/=' in addition to what is here and it can actually have a character length up to 256. * enhanced consumer secret regex pattern by adding prefixes * feedback addressed; handled invalid domains * optimized the domain and credentials verification logic --- .../salesforceoauth2/salesforceoauth2.go | 185 +++++++++++++++++ .../salesforceoauth2_integration_test.go | 189 ++++++++++++++++++ .../salesforceoauth2/salesforceoauth2_test.go | 121 +++++++++++ pkg/engine/defaults/defaults.go | 2 + 4 files changed, 497 insertions(+) create mode 100644 pkg/detectors/salesforceoauth2/salesforceoauth2.go create mode 100644 pkg/detectors/salesforceoauth2/salesforceoauth2_integration_test.go create mode 100644 pkg/detectors/salesforceoauth2/salesforceoauth2_test.go diff --git a/pkg/detectors/salesforceoauth2/salesforceoauth2.go b/pkg/detectors/salesforceoauth2/salesforceoauth2.go new file mode 100644 index 000000000..e55bc6738 --- /dev/null +++ b/pkg/detectors/salesforceoauth2/salesforceoauth2.go @@ -0,0 +1,185 @@ +package salesforceoauth2 + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + + regexp "github.com/wasilibs/go-re2" + + "github.com/trufflesecurity/trufflehog/v3/pkg/cache/simple" + "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 ( + defaultClient = common.SaneHttpClient() + // Make sure that your group is surrounded in boundary characters such as below to reduce false positives. + instancePat = regexp.MustCompile(`\b(?:https?://)?([0-9a-zA-Z\-\.]{1,100}\.my\.salesforce\.com)\b`) + consumerKeyPat = regexp.MustCompile(`\b(3MVG9[0-9a-zA-Z._+/=]{80,251})`) + consumerSecretPat = regexp.MustCompile(detectors.PrefixRegex([]string{"salesforce", "consumer", "secret"}) + `\b([A-Za-z0-9+/=.]{64}|[0-9]{19})\b`) + + invalidHosts = simple.NewCache[struct{}]() + errNoHost = errors.New("no such host") +) + +// 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{"salesforce", "3MVG9"} +} + +func (s Scanner) getClient() *http.Client { + if s.client != nil { + return s.client + } + + return defaultClient +} + +func (s Scanner) Type() detectorspb.DetectorType { + return detectorspb.DetectorType_SalesforceOauth2 +} + +func (s Scanner) Description() string { + return "Salesforce is a customer relationship management (CRM) platform that provides a suite of applications and a platform for custom development. Its APIs use OAuth 2.0, and credentials like the Consumer Key and Secret are used to grant applications access to an organization's data." +} + +// FromData will find and optionally verify Salesforceoauth2 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) + + uniqueInstanceMatches, uniqueKeyMatches, uniqueSecretMatches := make(map[string]struct{}), make(map[string]struct{}), make(map[string]struct{}) + for _, match := range instancePat.FindAllStringSubmatch(dataStr, -1) { + uniqueInstanceMatches[match[1]] = struct{}{} + } + + for _, match := range consumerKeyPat.FindAllStringSubmatch(dataStr, -1) { + uniqueKeyMatches[match[1]] = struct{}{} + } + + for _, match := range consumerSecretPat.FindAllStringSubmatch(dataStr, -1) { + uniqueSecretMatches[match[1]] = struct{}{} + } + + // If we are missing any of the three components, we cannot form a valid credential. + if len(uniqueInstanceMatches) == 0 || len(uniqueKeyMatches) == 0 || len(uniqueSecretMatches) == 0 { + return nil, nil + } + +domainLoop: + for domain := range uniqueInstanceMatches { + if invalidHosts.Exists(domain) { + continue domainLoop + } + + for key := range uniqueKeyMatches { + for secret := range uniqueSecretMatches { + s1 := detectors.Result{ + DetectorType: detectorspb.DetectorType_SalesforceOauth2, + Raw: []byte(secret), + RawV2: fmt.Appendf([]byte{}, "%s:%s:%s", domain, key, secret), + } + + if verify { + isVerified, verificationErr := s.verifyMatch(ctx, s.getClient(), domain, key, secret) + s1.Verified = isVerified + if verificationErr != nil { + if errors.Is(verificationErr, errNoHost) { + invalidHosts.Set(domain, struct{}{}) + continue domainLoop + } + + s1.SetVerificationError(verificationErr, secret) + } + } + + results = append(results, s1) + } + } + } + + return +} + +// verifyMatch attempts to validate a Salesforce Client Credentials pair. +func (s Scanner) verifyMatch(ctx context.Context, client *http.Client, domain, key, secret string) (bool, error) { + form := url.Values{} + form.Set("grant_type", "client_credentials") + form.Set("client_id", key) + form.Set("client_secret", secret) + + authURL := fmt.Sprintf("https://%s/services/oauth2/token", domain) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, authURL, strings.NewReader(form.Encode())) + if err != nil { + return false, fmt.Errorf("failed to create request: %w", err) + } + + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + resp, err := client.Do(req) + if err != nil { + if strings.Contains(err.Error(), "no such host") { + return false, errNoHost + } + + return false, fmt.Errorf("failed to perform request: %w", err) + } + defer func() { + _, _ = io.Copy(io.Discard, resp.Body) + _ = resp.Body.Close() + }() + + switch resp.StatusCode { + case http.StatusOK: + return true, nil + case http.StatusBadRequest: + return s.handleBadRequest(resp) + default: + return false, fmt.Errorf("unexpected status code: %d", resp.StatusCode) + } +} + +// Reusable error response struct +type oauthErrorResponse struct { + Error string `json:"error"` + ErrorDescription string `json:"error_description"` +} + +// handleBadRequest processes 400 responses to determine if credentials are invalid or misconfigured +func (s Scanner) handleBadRequest(resp *http.Response) (bool, error) { + bodyBytes, err := io.ReadAll(resp.Body) + if err != nil { + return false, fmt.Errorf("failed to read error response body: %w", err) + } + + var errorResponse oauthErrorResponse + if err := json.Unmarshal(bodyBytes, &errorResponse); err != nil { + return false, fmt.Errorf("failed to unmarshal error response: %w (body: %s)", err, string(bodyBytes)) + } + + switch errorResponse.Error { + case "invalid_client_id", "invalid_client": + // This definitively means the key is invalid + // Or the key is valid but the secret is wrong. + return false, nil + case "invalid_grant": + // This can mean the secret is wrong OR the user isn't configured with the app secret. + // We'll treat it as a VerificationError because the key might be valid but misconfigured. + return false, fmt.Errorf("verification failed: %s", errorResponse.ErrorDescription) + default: + return false, fmt.Errorf("unexpected OAuth error: %s - %s", errorResponse.Error, errorResponse.ErrorDescription) + } +} diff --git a/pkg/detectors/salesforceoauth2/salesforceoauth2_integration_test.go b/pkg/detectors/salesforceoauth2/salesforceoauth2_integration_test.go new file mode 100644 index 000000000..9b05fc864 --- /dev/null +++ b/pkg/detectors/salesforceoauth2/salesforceoauth2_integration_test.go @@ -0,0 +1,189 @@ +//go:build detectors +// +build detectors + +package salesforceoauth2 + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + + "github.com/trufflesecurity/trufflehog/v3/pkg/common" + "github.com/trufflesecurity/trufflehog/v3/pkg/detectors" + "github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb" +) + +func TestSalesforceOauth2_FromData(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + // Fetch the correct secrets needed for the OAuth2 Client Credentials flow. + testSecrets, err := common.GetSecret(ctx, "trufflehog-testing", "detectors5") + if err != nil { + t.Fatalf("could not get test secrets from GCP: %s", err) + } + domain := testSecrets.MustGetField("SALESFORCE_OAUTH2_DOMAIN") + consumerKey := testSecrets.MustGetField("SALESFORCE_OAUTH2_CONSUMER_KEY") + consumerSecret := testSecrets.MustGetField("SALESFORCE_OAUTH2_CONSUMER_SECRET") + inactiveSecret := testSecrets.MustGetField("SALESFORCE_OAUTH2_INACTIVE_CONSUMER_SECRET") + + type args struct { + data []byte + verify bool + } + tests := []struct { + name string + s Scanner + args args + want []detectors.Result + wantErr bool + wantVerificationErr bool + }{ + { + name: "found one valid trio, verified", + s: Scanner{}, + args: args{ + data: []byte(fmt.Sprintf("domain: %s, key: %s, secret: %s", domain, consumerKey, consumerSecret)), + verify: true, + }, + want: []detectors.Result{ + { + DetectorType: detectorspb.DetectorType_SalesforceOauth2, + Verified: true, + }, + }, + wantErr: false, + wantVerificationErr: false, + }, + { + name: "found one invalid trio, unverified", + s: Scanner{}, + args: args{ + data: []byte(fmt.Sprintf("domain: %s, key: %s, secret: %s", domain, consumerKey, inactiveSecret)), + verify: true, + }, + want: []detectors.Result{ + { + DetectorType: detectorspb.DetectorType_SalesforceOauth2, + Verified: false, + }, + }, + wantErr: false, + wantVerificationErr: false, // An invalid secret is a clean "no", not an error. + }, + { + name: "multiple findings, one verified", + s: Scanner{}, + args: args{ + data: []byte(fmt.Sprintf("domain: %s, key: %s, valid_secret: %s, invalid_secret: %s", domain, consumerKey, consumerSecret, inactiveSecret)), + verify: true, + }, + want: []detectors.Result{ + { + DetectorType: detectorspb.DetectorType_SalesforceOauth2, + Verified: true, // The valid secret combination + }, + { + DetectorType: detectorspb.DetectorType_SalesforceOauth2, + Verified: false, // The invalid secret combination + }, + }, + wantErr: false, + wantVerificationErr: false, + }, + { + name: "not found (missing a component)", + s: Scanner{}, + args: args{ + data: []byte(fmt.Sprintf("key: %s, secret: %s", consumerKey, consumerSecret)), // No domain + verify: true, + }, + want: nil, + wantErr: false, + wantVerificationErr: false, + }, + { + name: "found, would be verified if not for timeout", + s: Scanner{client: common.SaneHttpClientTimeOut(1 * time.Microsecond)}, + args: args{ + data: []byte(fmt.Sprintf("domain: %s, key: %s, secret: %s", domain, consumerKey, consumerSecret)), + verify: true, + }, + want: []detectors.Result{ + { + DetectorType: detectorspb.DetectorType_SalesforceOauth2, + Verified: false, + }, + }, + wantErr: false, + wantVerificationErr: true, + }, + { + name: "found, unexpected api response", + s: Scanner{client: common.ConstantResponseHttpClient(404, "")}, + args: args{ + data: []byte(fmt.Sprintf("domain: %s, key: %s, secret: %s", domain, consumerKey, consumerSecret)), + verify: true, + }, + want: []detectors.Result{ + { + DetectorType: detectorspb.DetectorType_SalesforceOauth2, + Verified: false, + }, + }, + wantErr: false, + wantVerificationErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := tt.s.FromData(context.Background(), tt.args.verify, tt.args.data) + if (err != nil) != tt.wantErr { + t.Errorf("FromData() error = %v, wantErr %v", err, tt.wantErr) + return + } + + // Since the order of results can vary with maps, we use a more robust comparison. + // This checks that for every `want` result, there is a matching `got` result. + opts := []cmp.Option{ + cmpopts.IgnoreFields(detectors.Result{}, "Raw", "RawV2", "verificationError", "ExtraData", "VerificationFromCache", "primarySecret"), + cmpopts.SortSlices(func(a, b detectors.Result) bool { return a.Verified }), + } + if diff := cmp.Diff(tt.want, got, opts...); diff != "" { + t.Errorf("FromData() results mismatch (-want +got):\n%s", diff) + } + + // Also check that verification errors match expectations across all results. + var gotErr bool + for _, r := range got { + if r.VerificationError() != nil { + gotErr = true + break + } + } + if gotErr != tt.wantVerificationErr { + t.Errorf("wantVerificationErr = %v, but got an error state of %v", tt.wantVerificationErr, gotErr) + } + }) + } +} + +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/salesforceoauth2/salesforceoauth2_test.go b/pkg/detectors/salesforceoauth2/salesforceoauth2_test.go new file mode 100644 index 000000000..1fecefd23 --- /dev/null +++ b/pkg/detectors/salesforceoauth2/salesforceoauth2_test.go @@ -0,0 +1,121 @@ +package salesforceoauth2 + +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 TestSalesforceOauth2_Pattern(t *testing.T) { + d := Scanner{} + ahoCorasickCore := ahocorasick.NewAhoCorasickCore([]detectors.Detector{d}) + + tests := []struct { + name string + input string + want []string + }{ + { + name: "simple case: one of each component", + input: ` + salesforce_domain = "my-test-org-123.my.salesforce.com" + salesforce_key = "3MVG9dBDux2v1sLoreCoilvmnP337XNeiV01JFJ8uAAVVyH5qX0NPaa0d54El.Wkce6JTB1LmsxhzVaaa.VZ7" + salesforce_secret = "A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2" + `, + want: []string{ + "my-test-org-123.my.salesforce.com:3MVG9dBDux2v1sLoreCoilvmnP337XNeiV01JFJ8uAAVVyH5qX0NPaa0d54El.Wkce6JTB1LmsxhzVaaa.VZ7:A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2", + }, + }, + { + name: "combinatorial test: multiple keys, one domain and secret", + input: ` + salesforce_domain = "my-test-org-123.my.salesforce.com" + salesforce_key1 = "3MVG9dBDux2v1sLoreCoilvmnP337XNeiV01JFJ8uAAVVyH5qX0NPaa0d54El.Wkce6JTB1LmsxhzVaaa.VZ7" + salesforce_key2 = "3MVG9dBDux2v1sLoreCoilvmnP337XNeiV01JFJ8uAAVVyH5qX0NPaa0d54ElfWkce6JTB1LmsxhzVaaaaVZ8" + salesforce_secret = "A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2" + `, + want: []string{ + "my-test-org-123.my.salesforce.com:3MVG9dBDux2v1sLoreCoilvmnP337XNeiV01JFJ8uAAVVyH5qX0NPaa0d54El.Wkce6JTB1LmsxhzVaaa.VZ7:A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2", + "my-test-org-123.my.salesforce.com:3MVG9dBDux2v1sLoreCoilvmnP337XNeiV01JFJ8uAAVVyH5qX0NPaa0d54ElfWkce6JTB1LmsxhzVaaaaVZ8:A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2", + }, + }, + { + name: "combinatorial test: two domains, two keys, one secret", + input: ` + salesforce_domain1 = "my-test-org-123.my.salesforce.com" + salesforce_domain2 = "another-dev-org.my.salesforce.com" + salesforce_key1 = "3MVG9dBDux2v1sLoreCoilvmnP337XNeiV01JFJ8uAAVVyH5qX0NPaa0d54El.Wkce6JTB1LmsxhzVaaa.VZ7" + salesforce_key2 = "3MVG9dBDux2v1sLoreCoilvmnP337XNeiV01JFJ8uAAVVyH5qX0NPaa0d54ElfWkce6JTB1LmsxhzVaaaaVZ8" + salesforce_secret = "A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2" + `, + want: []string{ + "my-test-org-123.my.salesforce.com:3MVG9dBDux2v1sLoreCoilvmnP337XNeiV01JFJ8uAAVVyH5qX0NPaa0d54El.Wkce6JTB1LmsxhzVaaa.VZ7:A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2", + "my-test-org-123.my.salesforce.com:3MVG9dBDux2v1sLoreCoilvmnP337XNeiV01JFJ8uAAVVyH5qX0NPaa0d54ElfWkce6JTB1LmsxhzVaaaaVZ8:A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2", + "another-dev-org.my.salesforce.com:3MVG9dBDux2v1sLoreCoilvmnP337XNeiV01JFJ8uAAVVyH5qX0NPaa0d54El.Wkce6JTB1LmsxhzVaaa.VZ7:A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2", + "another-dev-org.my.salesforce.com:3MVG9dBDux2v1sLoreCoilvmnP337XNeiV01JFJ8uAAVVyH5qX0NPaa0d54ElfWkce6JTB1LmsxhzVaaaaVZ8:A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2", + }, + }, + { + name: "negative case: missing secret component", + input: `salesforce_domain = "my-test-org-123.my.salesforce.com", salesforce_key = "3MVG9dBDux2v1sLoreCoilvmnP337XNeiV01JFJ8uAAVVyH5qX0NPaa0d54El.Wkce6JTB1LmsxhzVaaa.VZ7"`, + want: []string{}, + }, + { + name: "negative case: invalid key format", + input: `salesforce_domain = "my-test-org-123.my.salesforce.com", salesforce_key = "invalid-key-format", salesforce_secret = "A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2"`, + want: []string{}, + }, + { + name: "negative case: invalid secret format (too short)", + input: `salesforce_domain = "my-test-org-123.my.salesforce.com", salesforce_key = "3MVG9dBDux2v1sLoreCoilvmnP337XNeiV01JFJ8uAAVVyH5qX0NPaa0d54El.Wkce6JTB1LmsxhzVaaa.VZ7", salesforce_secret = "ABCDEFG"`, + want: []string{}, + }, + } + + 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.go index b2c6d5c39..1409fc304 100644 --- a/pkg/engine/defaults/defaults.go +++ b/pkg/engine/defaults/defaults.go @@ -621,6 +621,7 @@ import ( "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/salescookie" "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/salesflare" "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/salesforce" + "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/salesforceoauth2" "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/salesmate" "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/sanity" "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/satismeterprojectkey" @@ -1487,6 +1488,7 @@ func buildDetectorList() []detectors.Detector { &salescookie.Scanner{}, &salesflare.Scanner{}, &salesforce.Scanner{}, + &salesforceoauth2.Scanner{}, &salesmate.Scanner{}, &sanity.Scanner{}, &satismeterprojectkey.Scanner{},