Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
[INS-318] Add New Relic License Key Detector (#4760)
Mustansirf2d9ea762e2d
diff --git a/main.go b/main.goindex c6db793f0..903f14bbe 100644--- a/main.go+++ b/main.go@@ -564,6 +564,7 @@ func run(state overseer.State, logSync func() error) {feature.CloudflareApiTokenV2DetectorEnabled.Store(true)feature.CloudflareGlobalApiKeyV2DetectorEnabled.Store(true)feature.DuoDetectorEnabled.Store(true)+ feature.NewRelicLicenseKeyDetectorEnabled.Store(true)conf := &config.Config{}if *configFilename != "" {diff --git a/pkg/detectors/newreliclicensekey/newreliclicensekey.go b/pkg/detectors/newreliclicensekey/newreliclicensekey.gonew file mode 100644index 000000000..9c98bb691--- /dev/null+++ b/pkg/detectors/newreliclicensekey/newreliclicensekey.go@@ -0,0 +1,121 @@+package newreliclicensekey++import (+ "context"+ "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/detector_typepb"+)++type Scanner struct {+ client *http.Client+}++// Ensure the Scanner satisfies the interfaces at compile time.+var _ detectors.Detector = (*Scanner)(nil)++var (+ defaultClient = common.SaneHttpClient()+ // https://docs.newrelic.com/docs/apis/intro-apis/new-relic-api-keys/#license-key+ // US region keys are 40 characters hexadecimal strings ending with "FFFFNRAL"+ // EU region keys have the same format but first 6 characters are "eu01xx"+ keyPat = regexp.MustCompile(`\b(([0-9a-f]{32}|eu01xx[0-9a-f]{26})FFFFNRAL)\b`)+)++func (s Scanner) getClient() *http.Client {+ if s.client != nil {+ return s.client+ }++ return defaultClient+}++// Keywords are used for efficiently pre-filtering chunks.+func (s Scanner) Keywords() []string { return []string{"ffffnral"} }++func (s Scanner) Type() detector_typepb.DetectorType {+ return detector_typepb.DetectorType_NewRelicLicenseKey+}++func (s Scanner) Description() string {+ return "New Relic license keys are unique authentication tokens used to send telemetry data (metrics, logs, and traces) from your applications and infrastructure to New Relic."+}++func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {+ dataStr := string(data)++ matches := keyPat.FindAllStringSubmatch(dataStr, -1)+ for _, match := range matches {+ resMatch := strings.TrimSpace(match[1])++ s1 := detectors.Result{+ DetectorType: s.Type(),+ Raw: []byte(resMatch),+ Redacted: resMatch[:8] + "...",+ SecretParts: map[string]string{"key": resMatch},+ }++ if strings.HasPrefix(resMatch, "eu01xx") {+ s1.SecretParts["region"] = "eu"+ s1.ExtraData = map[string]string{"region": "eu"}+ } else {+ s1.SecretParts["region"] = "us"+ s1.ExtraData = map[string]string{"region": "us"}+ }++ if verify {+ isVerified, verificationErr := s.verify(ctx, resMatch, s1.SecretParts["region"])+ s1.Verified = isVerified+ s1.SetVerificationError(verificationErr)+ }++ results = append(results, s1)+ }++ return results, nil+}++// verify checks if the provided key is valid by making a request to the New Relic Metrics API.+// It sends a POST request to the metrics endpoint. A valid key will result in a 202 Accepted response, while an invalid key will return a 403 Forbidden.+// Even though the response is 202, no data is actually published to New Relic since the request body is empty.+// https://docs.newrelic.com/docs/data-apis/ingest-apis/metric-api/report-metrics-metric-api/+func (s Scanner) verify(ctx context.Context, key, region string) (bool, error) {+ host := "https://metric-api.newrelic.com"+ if region == "eu" {+ // EU region keys have a different host+ host = "https://metric-api.eu.newrelic.com"+ }+ req, err := http.NewRequestWithContext(+ ctx, http.MethodPost, host+"/metric/v1", http.NoBody)+ if err != nil {+ return false, fmt.Errorf("error constructing request: %w", err)+ }+ req.Header.Add("Content-Type", "application/json")+ req.Header.Add("Api-Key", key)++ client := s.getClient()+ res, err := client.Do(req)+ if err != nil {+ return false, fmt.Errorf("error making request: %w", err)+ }+ defer func() {+ _, _ = io.Copy(io.Discard, res.Body)+ _ = res.Body.Close()+ }()++ switch res.StatusCode {+ case http.StatusAccepted:+ return true, nil+ case http.StatusForbidden:+ return false, nil+ default:+ return false, fmt.Errorf("unexpected status code: %d", res.StatusCode)+ }+}diff --git a/pkg/detectors/newreliclicensekey/newreliclicensekey_integration_test.go b/pkg/detectors/newreliclicensekey/newreliclicensekey_integration_test.gonew file mode 100644index 000000000..e5ca7a8de--- /dev/null+++ b/pkg/detectors/newreliclicensekey/newreliclicensekey_integration_test.go@@ -0,0 +1,162 @@+//go:build detectors+// +build detectors++package newreliclicensekey++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/detector_typepb"+)++func TestNewRelicLicenseKey_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)+ }++ key := testSecrets.MustGetField("NEW_RELIC_LICENSE_KEY")+ keyEU := testSecrets.MustGetField("NEW_RELIC_LICENSE_KEY_EU")+ keyInactive := "72322bc2443d330cf29cde9f24fca105FFFFNRAL"++ 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 new relic license key %s within", key)),+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detector_typepb.DetectorType_NewRelicLicenseKey,+ Verified: true,+ ExtraData: map[string]string{+ "region": "us",+ },+ SecretParts: map[string]string{+ "key": key,+ "region": "us",+ },+ },+ },+ wantErr: false,+ },+ {+ name: "found eu, verified",+ s: Scanner{},+ args: args{+ ctx: context.Background(),+ data: []byte(fmt.Sprintf("You can find a new EU relic license key %s within", keyEU)),+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detector_typepb.DetectorType_NewRelicLicenseKey,+ Verified: true,+ ExtraData: map[string]string{+ "region": "eu",+ },+ SecretParts: map[string]string{+ "key": keyEU,+ "region": "eu",+ },+ },+ },+ wantErr: false,+ },+ {+ name: "found, unverified",+ s: Scanner{},+ args: args{+ ctx: context.Background(),+ data: []byte(fmt.Sprintf("You can find a new relic license key %s within", keyInactive)), // the secret would satisfy the regex but not pass validation+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detector_typepb.DetectorType_NewRelicLicenseKey,+ Verified: false,+ ExtraData: map[string]string{+ "region": "us",+ },+ SecretParts: map[string]string{+ "key": keyInactive,+ "region": "us",+ },+ },+ },+ 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("NewRelicLicenseKey.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 len(got[i].Redacted) == 0 {+ t.Fatalf("no redacted secret present: \n %+v", got[i])+ }+ got[i].Redacted = ""+ }+ if diff := pretty.Compare(got, tt.want); diff != "" {+ t.Errorf("NewRelicLicenseKey.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/newreliclicensekey/newreliclicensekey_test.go b/pkg/detectors/newreliclicensekey/newreliclicensekey_test.gonew file mode 100644index 000000000..b62ec78e1--- /dev/null+++ b/pkg/detectors/newreliclicensekey/newreliclicensekey_test.go@@ -0,0 +1,86 @@+package newreliclicensekey++import (+ "context"+ "fmt"+ "testing"++ "github.com/google/go-cmp/cmp"++ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors"+ "github.com/trufflesecurity/trufflehog/v3/pkg/engine/ahocorasick"+)++var (+ validPattern = "72322bc2443d330cf29cde9f24fca105FFFFNRAL"+ validPatternEU = "eu01xxb7e8b0dddc28ac051a64ffd583FFFFNRAL"+ invalidPattern = "72322bc2443d330cf29cde9f24fca5FFFFNRAL"+)++func TestNewRelicLicenseKey_Pattern(t *testing.T) {+ d := Scanner{}+ ahoCorasickCore := ahocorasick.NewAhoCorasickCore([]detectors.Detector{d})+ tests := []struct {+ name string+ input string+ want []string+ }{+ {+ name: "valid pattern",+ input: fmt.Sprintf("new relic license key = '%s'", validPattern),+ want: []string{validPattern},+ },+ {+ name: "valid pattern EU",+ input: fmt.Sprintf("new relic license key EU = '%s'", validPatternEU),+ want: []string{validPatternEU},+ },+ {+ name: "invalid pattern",+ input: fmt.Sprintf("new relic license key = '%s'", invalidPattern),+ 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.goindex 4bda0fc04..dfcb44bae 100644--- a/pkg/engine/defaults/defaults.go+++ b/pkg/engine/defaults/defaults.go@@ -511,6 +511,7 @@ import ("github.com/trufflesecurity/trufflehog/v3/pkg/detectors/netsuite""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/neutrinoapi""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/newrelicinsightsinsertkey"+ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/newreliclicensekey""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/newrelicpersonalapikey""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/newsapi""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/newscatcher"@@ -1424,6 +1425,7 @@ func buildDetectorList() []detectors.Detector {&netsuite.Scanner{},&neutrinoapi.Scanner{},&newrelicinsightsinsertkey.Scanner{},+ &newreliclicensekey.Scanner{},&newrelicpersonalapikey.Scanner{},&newsapi.Scanner{},&newscatcher.Scanner{},@@ -1864,6 +1866,8 @@ func buildDetectorList() []detectors.Detector {return !feature.CloudflareGlobalApiKeyV2DetectorEnabled.Load()case *duo.Scanner:return !feature.DuoDetectorEnabled.Load()+ case *newreliclicensekey.Scanner:+ return !feature.NewRelicLicenseKeyDetectorEnabled.Load()default:return false}diff --git a/pkg/engine/defaults/defaults_test.go b/pkg/engine/defaults/defaults_test.goindex 75fe77feb..16b87ba1f 100644--- a/pkg/engine/defaults/defaults_test.go+++ b/pkg/engine/defaults/defaults_test.go@@ -145,6 +145,7 @@ var excludedFromDefaultList = map[detector_typepb.DetectorType]struct{}{detector_typepb.DetectorType_HashiCorpVaultBatchToken: {},detector_typepb.DetectorType_HashiCorpVaultToken: {},detector_typepb.DetectorType_Duo: {},+ detector_typepb.DetectorType_NewRelicLicenseKey: {},// Reserved / special types.detector_typepb.DetectorType_CustomRegex: {}, // added dynamically via engine config, not via buildDetectorList()diff --git a/pkg/feature/feature.go b/pkg/feature/feature.goindex 56e93dfe0..a274c3a6f 100644--- a/pkg/feature/feature.go+++ b/pkg/feature/feature.go@@ -42,6 +42,7 @@ var (CloudflareApiTokenV2DetectorEnabled atomic.BoolCloudflareGlobalApiKeyV2DetectorEnabled atomic.BoolDuoDetectorEnabled atomic.Bool+ NewRelicLicenseKeyDetectorEnabled atomic.Bool)type AtomicString struct {diff --git a/pkg/pb/detector_typepb/detector_type.pb.go b/pkg/pb/detector_typepb/detector_type.pb.goindex 9c1c7dfb7..44773339b 100644--- a/pkg/pb/detector_typepb/detector_type.pb.go+++ b/pkg/pb/detector_typepb/detector_type.pb.go@@ -1117,6 +1117,7 @@ const (DetectorType_HashiCorpVaultBatchToken DetectorType = 1061DetectorType_HashiCorpVaultToken DetectorType = 1062DetectorType_Duo DetectorType = 1063+ DetectorType_NewRelicLicenseKey DetectorType = 1064)// Enum value maps for DetectorType.@@ -2182,6 +2183,7 @@ var (1061: "HashiCorpVaultBatchToken",1062: "HashiCorpVaultToken",1063: "Duo",+ 1064: "NewRelicLicenseKey",}DetectorType_value = map[string]int32{"Alibaba": 0,@@ -3244,6 +3246,7 @@ var ("HashiCorpVaultBatchToken": 1061,"HashiCorpVaultToken": 1062,"Duo": 1063,+ "NewRelicLicenseKey": 1064,})@@ -3279,7 +3282,7 @@ var File_detector_type_proto protoreflect.FileDescriptorvar file_detector_type_proto_rawDesc = []byte{0x0a, 0x13, 0x64, 0x65, 0x74, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x2e,0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0d, 0x64, 0x65, 0x74, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x5f,- 0x74, 0x79, 0x70, 0x65, 0x2a, 0xc9, 0x8a, 0x01, 0x0a, 0x0c, 0x44, 0x65, 0x74, 0x65, 0x63, 0x74,+ 0x74, 0x79, 0x70, 0x65, 0x2a, 0xe2, 0x8a, 0x01, 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,@@ -4388,11 +4391,13 @@ var file_detector_type_proto_rawDesc = []byte{0x42, 0x61, 0x74, 0x63, 0x68, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x10, 0xa5, 0x08, 0x12, 0x18, 0x0a,0x13, 0x48, 0x61, 0x73, 0x68, 0x69, 0x43, 0x6f, 0x72, 0x70, 0x56, 0x61, 0x75, 0x6c, 0x74, 0x54,0x6f, 0x6b, 0x65, 0x6e, 0x10, 0xa6, 0x08, 0x12, 0x08, 0x0a, 0x03, 0x44, 0x75, 0x6f, 0x10, 0xa7,- 0x08, 0x42, 0x41, 0x5a, 0x3f, 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, 0x5f, 0x74, 0x79,- 0x70, 0x65, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,+ 0x08, 0x12, 0x17, 0x0a, 0x12, 0x4e, 0x65, 0x77, 0x52, 0x65, 0x6c, 0x69, 0x63, 0x4c, 0x69, 0x63,+ 0x65, 0x6e, 0x73, 0x65, 0x4b, 0x65, 0x79, 0x10, 0xa8, 0x08, 0x42, 0x41, 0x5a, 0x3f, 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, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x70, 0x62, 0x62, 0x06, 0x70,+ 0x72, 0x6f, 0x74, 0x6f, 0x33,}var (diff --git a/proto/detector_type.proto b/proto/detector_type.protoindex dc33d9421..e41f78743 100644--- a/proto/detector_type.proto+++ b/proto/detector_type.proto@@ -1065,4 +1065,5 @@ enum DetectorType {HashiCorpVaultBatchToken = 1061;HashiCorpVaultToken = 1062;Duo = 1063;+ NewRelicLicenseKey = 1064;}