Skip to content

Find, verify, and analyze leaked credentials

fixed and updated satismeterwritekey detector (#3693)

Kashif Khanf17ad818b386
diff --git a/pkg/detectors/satismeterwritekey/satismeterwritekey.go b/pkg/detectors/satismeterwritekey/satismeterwritekey.go
index 65a97ccfd..55142b47d 100644
--- a/pkg/detectors/satismeterwritekey/satismeterwritekey.go
+++ b/pkg/detectors/satismeterwritekey/satismeterwritekey.go
@@ -1,11 +1,16 @@
package satismeterwritekey
import (
+ "bytes"
"context"
- regexp "github.com/wasilibs/go-re2"
+ "encoding/json"
+ "fmt"
+ "io"
"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"
@@ -20,7 +25,9 @@ var (
client = 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{"satismeter"}) + `\b([a-z0-9A-Z]{16})\b`)
+ writeKeyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"satismeter"}) + `\b([a-z0-9A-Z]{32})\b`)
+ tokenPat = regexp.MustCompile(detectors.PrefixRegex([]string{"satismeter"}) + `\b([A-Za-z0-9]{32})\b`)
+ projectPat = regexp.MustCompile(detectors.PrefixRegex([]string{"satismeter"}) + `\b([a-zA-Z0-9]{24})\b`)
)
// Keywords are used for efficiently pre-filtering chunks.
@@ -33,41 +40,43 @@ func (s Scanner) Keywords() []string {
func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {
dataStr := string(data)
- matches := keyPat.FindAllStringSubmatch(dataStr, -1)
+ uniqueProjectMatches, uniqueWriteKeyMatches, uniqueTokenMatches := make(map[string]struct{}), make(map[string]struct{}), make(map[string]struct{})
- for _, match := range matches {
- if len(match) != 2 {
- continue
- }
- resMatch := strings.TrimSpace(match[1])
+ for _, match := range projectPat.FindAllStringSubmatch(dataStr, -1) {
+ uniqueProjectMatches[strings.TrimSpace(match[1])] = struct{}{}
+ }
- s1 := detectors.Result{
- DetectorType: detectorspb.DetectorType_SatismeterWritekey,
- Raw: []byte(resMatch),
- }
+ for _, match := range writeKeyPat.FindAllStringSubmatch(dataStr, -1) {
+ uniqueWriteKeyMatches[strings.TrimSpace(match[1])] = struct{}{}
+ }
- if verify {
- payload := strings.NewReader(`{
- "type": "track",
- "userId": "007",
- "event": "This is the event name",
- "writeKey": "` + resMatch + `"
- }`)
- req, err := http.NewRequestWithContext(ctx, "POST", "https://app.satismeter.com/api/users?type=track", payload)
- if err != nil {
- continue
- }
- req.Header.Add("Content-Type", "application/json")
- res, err := client.Do(req)
- if err == nil {
- defer res.Body.Close()
- if res.StatusCode >= 200 && res.StatusCode < 300 {
- s1.Verified = true
+ for _, match := range tokenPat.FindAllStringSubmatch(dataStr, -1) {
+ uniqueTokenMatches[strings.TrimSpace(match[1])] = struct{}{}
+ }
+
+ for projectID := range uniqueProjectMatches {
+ for token := range uniqueTokenMatches {
+ for writeKey := range uniqueWriteKeyMatches {
+ // writekey and token has same pattern, so skip the process when both values are same
+ if token == writeKey {
+ continue
+ }
+
+ s1 := detectors.Result{
+ DetectorType: detectorspb.DetectorType_SatismeterWritekey,
+ Raw: []byte(projectID),
+ RawV2: []byte(projectID + writeKey),
+ }
+
+ if verify {
+ isVerified, verificationErr := verifySatisMeterWriteKey(ctx, client, projectID, writeKey, token)
+ s1.Verified = isVerified
+ s1.SetVerificationError(verificationErr, writeKey)
}
+
+ results = append(results, s1)
}
}
-
- results = append(results, s1)
}
return results, nil
@@ -80,3 +89,49 @@ func (s Scanner) Type() detectorspb.DetectorType {
func (s Scanner) Description() string {
return "Satismeter is a customer feedback platform. Satismeter Writekeys can be used to send event data to Satismeter's API."
}
+
+// API Docs with payload details: https://support.satismeter.com/hc/en-us/articles/6980481518227-Track-event-API
+func verifySatisMeterWriteKey(ctx context.Context, client *http.Client, projectID, writeKey, token string) (bool, error) {
+ payload := createPayload(writeKey, projectID)
+ req, err := http.NewRequestWithContext(ctx, "POST", "https://app.satismeter.com/api/users?type=track", bytes.NewBuffer(payload))
+ if err != nil {
+ return false, err
+ }
+
+ req.Header.Add("Content-Type", "application/json")
+ req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
+ resp, err := client.Do(req)
+ if err != nil {
+ return false, nil
+ }
+ defer func() {
+ _, _ = io.Copy(io.Discard, resp.Body)
+ _ = resp.Body.Close()
+ }()
+
+ switch resp.StatusCode {
+ case http.StatusNoContent:
+ return true, nil
+ case http.StatusUnauthorized, http.StatusForbidden:
+ return false, nil
+ default:
+ return false, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
+ }
+}
+
+// createPayload creates a payload for POST api with writekey and projectID
+func createPayload(writeKey, projectID string) []byte {
+ // create the payload as a map
+ payload := map[string]interface{}{
+ "type": "track",
+ "userId": "007",
+ "event": "This is the event name",
+ "writeKey": writeKey,
+ "project": projectID,
+ }
+
+ // convert payload to JSON
+ payloadBytes, _ := json.Marshal(payload)
+
+ return payloadBytes
+}
diff --git a/pkg/detectors/satismeterwritekey/satismeterwritekey_integration_test.go b/pkg/detectors/satismeterwritekey/satismeterwritekey_integration_test.go
new file mode 100644
index 000000000..6ee584ce8
--- /dev/null
+++ b/pkg/detectors/satismeterwritekey/satismeterwritekey_integration_test.go
@@ -0,0 +1,136 @@
+//go:build detectors
+// +build detectors
+
+package satismeterwritekey
+
+import (
+ "context"
+ "fmt"
+ "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 TestSatismeterWritekey_FromChunk(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
+ defer cancel()
+ testSecrets, err := common.GetSecret(ctx, "trufflehog-testing", "detectors3")
+ if err != nil {
+ t.Fatalf("could not get test secrets from GCP: %s", err)
+ }
+ projectID := testSecrets.MustGetField("SATISMETERPROJECTKEY")
+ inactiveProjectID := testSecrets.MustGetField("SATISMETERPROJECTKEY_INACTIVE")
+ token := testSecrets.MustGetField("SATISMETER_TOKEN")
+ inactiveToken := testSecrets.MustGetField("SATISMETER_TOKEN_INACTIVE")
+ writeKey := testSecrets.MustGetField("SATISMETER_WRITEKEY")
+ inactiveWriteKey := testSecrets.MustGetField("SATISMETER_WRITEKEY_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 satismeterwritekey project %s satismeter writekey %s and satismeter token %s in here", projectID, writeKey, token)),
+ verify: true,
+ },
+ want: []detectors.Result{
+ {
+ DetectorType: detectorspb.DetectorType_SatismeterWritekey,
+ Verified: false,
+ RawV2: []byte(projectID + token),
+ },
+ {
+ DetectorType: detectorspb.DetectorType_SatismeterWritekey,
+ Verified: true,
+ RawV2: []byte(projectID + writeKey),
+ },
+ },
+ wantErr: false,
+ },
+ {
+ name: "found, unverified",
+ s: Scanner{},
+ args: args{
+ ctx: context.Background(),
+ data: []byte(fmt.Sprintf("You can find a satismeterwritekey project %s satismeter writekey %s and satismeter token %s in here but not vaild", inactiveProjectID, inactiveWriteKey, inactiveToken)), // the secret would satisfy the regex but not pass validation,
+ verify: true,
+ },
+ want: []detectors.Result{
+ {
+ DetectorType: detectorspb.DetectorType_SatismeterWritekey,
+ Verified: false,
+ RawV2: []byte(inactiveProjectID + inactiveToken),
+ },
+ {
+ DetectorType: detectorspb.DetectorType_SatismeterWritekey,
+ Verified: false,
+ RawV2: []byte(inactiveProjectID + inactiveWriteKey),
+ },
+ },
+ 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("SatismeterWritekey.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
+ }
+ if diff := pretty.Compare(got, tt.want); diff != "" {
+ t.Errorf("SatismeterWritekey.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/satismeterwritekey/satismeterwritekey_test.go b/pkg/detectors/satismeterwritekey/satismeterwritekey_test.go
index 26f3d00fe..6ab32f061 100644
--- a/pkg/detectors/satismeterwritekey/satismeterwritekey_test.go
+++ b/pkg/detectors/satismeterwritekey/satismeterwritekey_test.go
@@ -1,120 +1,105 @@
-//go:build detectors
-// +build detectors
-
package satismeterwritekey
import (
"context"
- "fmt"
"testing"
- "time"
- "github.com/kylelemons/godebug/pretty"
- "github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
+ "github.com/google/go-cmp/cmp"
- "github.com/trufflesecurity/trufflehog/v3/pkg/common"
- "github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/engine/ahocorasick"
)
-func TestSatismeterWritekey_FromChunk(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
- defer cancel()
- testSecrets, err := common.GetSecret(ctx, "trufflehog-testing", "detectors3")
- if err != nil {
- t.Fatalf("could not get test secrets from GCP: %s", err)
- }
- secret := testSecrets.MustGetField("SATISMETERWRITEKEY_TOKEN")
- inactiveSecret := testSecrets.MustGetField("SATISMETERWRITEKEY_INACTIVE")
+var (
+ complexPattern = `
+ func main() {
+ url := "https://api.example.com/v1/resource"
- type args struct {
- ctx context.Context
- data []byte
- verify bool
+ // 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
+ }
+
+ satismeterToken := os.GetEnv("SATISMETER_TOKEN")
+ if satismeterToken == ""{
+ satismeterToken = "VVVCVDXuoVwRFAKEiCseXmDiaC32jq7x"
+ }
+ satismeter_projectID := "satismeter12345678901234"
+ satismeter_writekey := "0TlknArPMr30WgJtL7SuM9V8LWGuqsxr"
+ req.Header.Set("Authorization", "Basic " + satismeterToken)
+
+ // Perform the request
+ client := &http.Client{}
+ resp, _ := client.Do(req)
+ defer resp.Body.Close()
+
+ // Check response status
+ if resp.StatusCode == http.StatusNoContent {
+ fmt.Println("Request successful!")
+ } else {
+ fmt.Println("Request failed with status:", resp.Status)
+ }
+ }
+ `
+ secrets = []string{
+ "satismeter123456789012340TlknArPMr30WgJtL7SuM9V8LWGuqsxr",
+ "satismeter12345678901234VVVCVDXuoVwRFAKEiCseXmDiaC32jq7x",
}
+)
+
+func TestSatisMeterWriteKey_Pattern(t *testing.T) {
+ d := Scanner{}
+ ahoCorasickCore := ahocorasick.NewAhoCorasickCore([]detectors.Detector{d})
+
tests := []struct {
- name string
- s Scanner
- args args
- want []detectors.Result
- wantErr bool
+ name string
+ input string
+ want []string
}{
{
- name: "found, verified",
- s: Scanner{},
- args: args{
- ctx: context.Background(),
- data: []byte(fmt.Sprintf("You can find a satismeterwritekey secret %s within", secret)),
- verify: true,
- },
- want: []detectors.Result{
- {
- DetectorType: detectorspb.DetectorType_SatismeterWritekey,
- Verified: true,
- },
- },
- wantErr: false,
- },
- {
- name: "found, unverified",
- s: Scanner{},
- args: args{
- ctx: context.Background(),
- data: []byte(fmt.Sprintf("You can find a satismeterwritekey 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_SatismeterWritekey,
- 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,
+ name: "valid pattern",
+ input: complexPattern,
+ want: secrets,
},
}
- 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("SatismeterWritekey.FromData() error = %v, wantErr %v", err, tt.wantErr)
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ matchedDetectors := ahoCorasickCore.FindDetectorMatches([]byte(test.input))
+ if len(matchedDetectors) == 0 && test.want != nil {
+ t.Errorf("keywords '%v' not matched by: %s", d.Keywords(), test.input)
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
+
+ results, err := d.FromData(context.Background(), false, []byte(test.input))
+ if err != nil {
+ t.Errorf("error = %v", err)
+ return
}
- if diff := pretty.Compare(got, tt.want); diff != "" {
- t.Errorf("SatismeterWritekey.FromData() %s diff: (-got +want)\n%s", tt.name, diff)
+
+ if len(results) != len(test.want) {
+ t.Errorf("expected %d results, got %d", len(test.want), len(results))
+ return
}
- })
- }
-}
-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)
+ 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)
+ }
})
}
}