Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
[Feat] Detector implementation for Azure Configuration Connection String Key (#3939)
Abdul Basitce126fab8585
diff --git a/pkg/detectors/azureappconfigconnectionstring/azureappconfigconnectionstring.go b/pkg/detectors/azureappconfigconnectionstring/azureappconfigconnectionstring.gonew file mode 100644index 000000000..a218ba694--- /dev/null+++ b/pkg/detectors/azureappconfigconnectionstring/azureappconfigconnectionstring.go@@ -0,0 +1,162 @@+package azureappconfigconnectionstring++import (+ "context"+ "crypto/hmac"+ "crypto/sha256"+ "encoding/base64"+ "fmt"+ "net/http"+ "strings"+ "time"++ 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()+ connectionStringPat = regexp.MustCompile(`Endpoint=(https:\/\/[a-zA-Z0-9-]+\.azconfig\.io);Id=([a-zA-Z0-9+\/=]+);Secret=([a-zA-Z0-9+\/=]+)`)+)++// 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{".azconfig.io"}+}++// FromData will find and optionally verify Azure Management API keys 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)++ keyMatchesUnique := make(map[string][]string)+ for _, keyMatch := range connectionStringPat.FindAllStringSubmatch(dataStr, -1) {+ keyMatchesUnique[strings.TrimSpace(keyMatch[0])] = keyMatch // keep all the matched groups for verification+ }++ for connectionString, connectionInfo := range keyMatchesUnique {+ endpoint := connectionInfo[1] // Endpoint+ id := connectionInfo[2] // Id+ secret := connectionInfo[3] // Secret+ s1 := detectors.Result{+ DetectorType: detectorspb.DetectorType_AzureAppConfigConnectionString,+ Raw: []byte(id),+ RawV2: []byte(connectionString),+ }++ if verify {+ client := s.client+ if client == nil {+ client = defaultClient+ }++ isVerified, verificationErr := s.verifyMatch(ctx, client, endpoint, id, secret)+ s1.Verified = isVerified++ if verificationErr != nil && !strings.Contains(verificationErr.Error(), "no such host") { // ignore no such host errors+ s1.SetVerificationError(verificationErr, connectionString)+ }+ }++ results = append(results, s1)+ }++ return results, nil+}++func (s Scanner) Type() detectorspb.DetectorType {+ return detectorspb.DetectorType_AzureAppConfigConnectionString+}++func (s Scanner) Description() string {+ return "Azure App Configuration is a managed service that centralizes application settings and feature flags, enabling dynamic updates without redeploying applications. Its connection string, which includes the endpoint URL and an access key, securely connects applications to the configuration store."+}++// generateHMACSignature creates the HMAC-SHA256 signature+func generateHMACSignature(secret, stringToSign string) (string, error) {+ decodedSecret, err := base64.StdEncoding.DecodeString(secret)+ if err != nil {+ return "", fmt.Errorf("failed to decode secret: %w", err)+ }++ h := hmac.New(sha256.New, decodedSecret)+ h.Write([]byte(stringToSign))+ signature := base64.StdEncoding.EncodeToString(h.Sum(nil))+ return signature, nil+}++// verifyMatch sends a request to the Azure App Configuration REST API to verify the provided credentials+// https://learn.microsoft.com/en-us/azure/azure-app-configuration/rest-api-authentication-hmac+func (s Scanner) verifyMatch(ctx context.Context, client *http.Client, endpoint, id, secret string) (bool, error) {+ apiVersion := "1.0"+ requestPath := "/kv"+ query := fmt.Sprintf("?api-version=%s", apiVersion)+ url := fmt.Sprintf("%s%s%s", endpoint, requestPath, query)++ // Prepare request+ req, err := http.NewRequest(http.MethodGet, url, nil)+ if err != nil {+ return false, fmt.Errorf("failed to create request: %w", err)+ }++ // Set required headers+ host := strings.TrimPrefix(strings.TrimPrefix(endpoint, "https://"), "http://")+ date := time.Now().UTC().Format(http.TimeFormat)+ contentHash := base64.StdEncoding.EncodeToString(sha256.New().Sum(nil)) // SHA256 hash of an empty body++ req.Header.Set("Host", host)+ req.Header.Set("Date", date)+ req.Header.Set("x-ms-content-sha256", contentHash)++ // Create the string to sign+ stringToSign := fmt.Sprintf("%s\n%s%s\n%s;%s;%s",+ http.MethodGet,+ requestPath,+ query,+ date,+ host,+ contentHash,+ )++ // Generate the HMAC signature+ signature, err := generateHMACSignature(secret, stringToSign)+ if err != nil {+ return false, fmt.Errorf("failed to generate HMAC signature: %w", err)+ }++ // Set the Authorization header+ authorizationHeader := fmt.Sprintf(+ "HMAC-SHA256 Credential=%s&SignedHeaders=date;host;x-ms-content-sha256&Signature=%s",+ id,+ signature,+ )+ req.Header.Set("Authorization", authorizationHeader)++ // Send the request+ resp, err := client.Do(req)+ if err != nil {+ return false, fmt.Errorf("request failed: %w", err)+ }+ defer resp.Body.Close()++ // Check the response status+ switch resp.StatusCode {+ case http.StatusOK:+ return true, nil+ case http.StatusUnauthorized:+ return false, nil+ default:+ return false, fmt.Errorf("got unexpected status code: %d", resp.StatusCode)+ }+}diff --git a/pkg/detectors/azureappconfigconnectionstring/azureappconfigconnectionstring_integration_test.go b/pkg/detectors/azureappconfigconnectionstring/azureappconfigconnectionstring_integration_test.gonew file mode 100644index 000000000..796718525--- /dev/null+++ b/pkg/detectors/azureappconfigconnectionstring/azureappconfigconnectionstring_integration_test.go@@ -0,0 +1,129 @@+//go:build detectors+// +build detectors++package azureappconfigconnectionstring++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 TestAzureAppConfigConnectionString_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)+ }+ secret := testSecrets.MustGetField("AZURE_APP_CONFIGURATION_CONNECTION_STRING")+ inactiveSecret := testSecrets.MustGetField("AZURE_APP_CONFIGURATION_CONNECTION_STRING_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: ctx,+ data: []byte(fmt.Sprintf("You can find a azureappconfigconnectionstring secret %s within", secret)),+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detectorspb.DetectorType_AzureAppConfigConnectionString,+ Verified: true,+ },+ },+ wantErr: false,+ wantVerificationErr: false,+ },+ {+ name: "found, unverified",+ s: Scanner{},+ args: args{+ ctx: ctx,+ data: []byte(fmt.Sprintf("You can find a azureappconfigconnectionstring secret %s but not valid", inactiveSecret)), // the secret would satisfy the regex but not pass validation+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detectorspb.DetectorType_AzureAppConfigConnectionString,+ Verified: false,+ },+ },+ wantErr: false,+ wantVerificationErr: false,+ },+ {+ name: "not found",+ s: Scanner{},+ args: args{+ ctx: ctx,+ data: []byte("You cannot find the secret within"),+ verify: true,+ },+ want: nil,+ wantErr: false,+ wantVerificationErr: false,+ },+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got, err := tt.s.FromData(tt.args.ctx, tt.args.verify, tt.args.data)+ if (err != nil) != tt.wantErr {+ t.Errorf("AzureAppConfigConnectionString.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 (got[i].VerificationError() != nil) != tt.wantVerificationErr {+ t.Fatalf("wantVerificationError = %v, verification error = %v", tt.wantVerificationErr, got[i].VerificationError())+ }+ }+ ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "RawV2", "Raw", "Redacted", "verificationError")++ if diff := cmp.Diff(got, tt.want, ignoreOpts); diff != "" {+ t.Errorf("AzureAppConfigConnectionString.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/azureappconfigconnectionstring/azureappconfigconnectionstring_test.go b/pkg/detectors/azureappconfigconnectionstring/azureappconfigconnectionstring_test.gonew file mode 100644index 000000000..2222abec2--- /dev/null+++ b/pkg/detectors/azureappconfigconnectionstring/azureappconfigconnectionstring_test.go@@ -0,0 +1,80 @@+package azureappconfigconnectionstring++import (+ "context"+ "testing"++ "github.com/google/go-cmp/cmp"++ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors"+ "github.com/trufflesecurity/trufflehog/v3/pkg/engine/ahocorasick"+)++var (+ validPattern = `Endpoint=https://trufflesecurity.azconfig.io;Id=u+De;Secret=80DtxZkndXpM2mV2J1JjX2vL1x4gm1hHn8Y3JeFJ4N0PPLSO5D70JQQJ99BBAC1i4FpQkb5wAAACAAZC26dr`+ invalidPattern = `Endpoint=https://trufflesecurity.azconfig.io;Secret=80DtxZkndXpMTmV2J3JjX2vL1x4gm1hHn8Y3KeFV4N0PPLSO5D70JQQJ79BBAC1i4FpRkb5wAAACAAZC26dr`+)++func TestAzureAppConfigConnectionString_Pattern(t *testing.T) {+ d := Scanner{}+ ahoCorasickCore := ahocorasick.NewAhoCorasickCore([]detectors.Detector{d})++ tests := []struct {+ name string+ input string+ want []string+ }{+ {+ name: "valid pattern",+ input: validPattern,+ want: []string{"Endpoint=https://trufflesecurity.azconfig.io;Id=u+De;Secret=80DtxZkndXpM2mV2J1JjX2vL1x4gm1hHn8Y3JeFJ4N0PPLSO5D70JQQJ99BBAC1i4FpQkb5wAAACAAZC26dr"},+ },+ {+ name: "invalid pattern",+ input: invalidPattern,+ want: nil,+ },+ }++ 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 b15e52c31..8dc34ddb0 100644--- a/pkg/engine/defaults/defaults.go+++ b/pkg/engine/defaults/defaults.go@@ -75,6 +75,7 @@ import ("github.com/trufflesecurity/trufflehog/v3/pkg/detectors/azure_storage"azurerepositorykey "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/azureapimanagement/repositorykey""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/azureapimanagementsubscriptionkey"+ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/azureappconfigconnectionstring""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/azurecontainerregistry""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/azuredevopspersonalaccesstoken""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/azuredirectmanagementkey"@@ -914,6 +915,7 @@ func buildDetectorList() []detectors.Detector {&azure_entra_serviceprincipal_v1.Scanner{},&azure_entra_serviceprincipal_v2.Scanner{},&azure_batch.Scanner{},+ &azureappconfigconnectionstring.Scanner{},&azure_cosmosdb.Scanner{},&azurecontainerregistry.Scanner{},&azuredevopspersonalaccesstoken.Scanner{},diff --git a/pkg/pb/detectorspb/detectors.pb.go b/pkg/pb/detectorspb/detectors.pb.goindex cb6d1f46b..ac2bf4b54 100644--- a/pkg/pb/detectorspb/detectors.pb.go+++ b/pkg/pb/detectorspb/detectors.pb.go@@ -1129,6 +1129,7 @@ const (DetectorType_BingSubscriptionKey DetectorType = 1022DetectorType_XAI DetectorType = 1023DetectorType_AzureDirectManagementKey DetectorType = 1024+ DetectorType_AzureAppConfigConnectionString DetectorType = 1025)// Enum value maps for DetectorType.@@ -2155,6 +2156,7 @@ var (1022: "BingSubscriptionKey",1023: "XAI",1024: "AzureDirectManagementKey",+ 1025: "AzureAppConfigConnectionString",}DetectorType_value = map[string]int32{"Alibaba": 0,@@ -3178,6 +3180,7 @@ var ("BingSubscriptionKey": 1022,"XAI": 1023,"AzureDirectManagementKey": 1024,+ "AzureAppConfigConnectionString": 1025,})@@ -3631,7 +3634,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, 0xfb, 0x83, 0x01, 0x0a, 0x0c, 0x44, 0x65, 0x74, 0x65, 0x63, 0x74, 0x6f, 0x72,+ 0x10, 0x04, 0x2a, 0xa0, 0x84, 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, 0x03, 0x12,@@ -4687,11 +4690,13 @@ var file_detectors_proto_rawDesc = []byte{0x6f, 0x6e, 0x4b, 0x65, 0x79, 0x10, 0xfe, 0x07, 0x12, 0x08, 0x0a, 0x03, 0x58, 0x41, 0x49, 0x10,0xff, 0x07, 0x12, 0x1d, 0x0a, 0x18, 0x41, 0x7a, 0x75, 0x72, 0x65, 0x44, 0x69, 0x72, 0x65, 0x63,0x74, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x4b, 0x65, 0x79, 0x10, 0x80,- 0x08, 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,+ 0x08, 0x12, 0x23, 0x0a, 0x1e, 0x41, 0x7a, 0x75, 0x72, 0x65, 0x41, 0x70, 0x70, 0x43, 0x6f, 0x6e,+ 0x66, 0x69, 0x67, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x74, 0x72,+ 0x69, 0x6e, 0x67, 0x10, 0x81, 0x08, 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 ecf815a61..a6aa24210 100644--- a/proto/detectors.proto+++ b/proto/detectors.proto@@ -1034,6 +1034,7 @@ enum DetectorType {BingSubscriptionKey = 1022;XAI = 1023;AzureDirectManagementKey = 1024;+ AzureAppConfigConnectionString = 1025;}message Result {