|
| 1 | +package azuredirectmanagementkey |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/hmac" |
| 6 | + "crypto/sha512" |
| 7 | + "encoding/base64" |
| 8 | + "errors" |
| 9 | + "fmt" |
| 10 | + "net/http" |
| 11 | + "strings" |
| 12 | + "time" |
| 13 | + |
| 14 | + regexp "github.com/wasilibs/go-re2" |
| 15 | + |
| 16 | + "github.com/trufflesecurity/trufflehog/v3/pkg/cache/simple" |
| 17 | + "github.com/trufflesecurity/trufflehog/v3/pkg/common" |
| 18 | + logContext "github.com/trufflesecurity/trufflehog/v3/pkg/context" |
| 19 | + "github.com/trufflesecurity/trufflehog/v3/pkg/detectors" |
| 20 | + "github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb" |
| 21 | +) |
| 22 | + |
| 23 | +const RFC3339WithoutMicroseconds = "2006-01-02T15:04:05" |
| 24 | + |
| 25 | +type Scanner struct { |
| 26 | + client *http.Client |
| 27 | + detectors.DefaultMultiPartCredentialProvider |
| 28 | +} |
| 29 | + |
| 30 | +// Ensure the Scanner satisfies the interface at compile time. |
| 31 | +var _ detectors.Detector = (*Scanner)(nil) |
| 32 | +var _ detectors.CustomFalsePositiveChecker = (*Scanner)(nil) |
| 33 | + |
| 34 | +var ( |
| 35 | + defaultClient = common.SaneHttpClient() |
| 36 | + urlPat = regexp.MustCompile(`https://([a-z0-9][a-z0-9-]{0,48}[a-z0-9])\.management\.azure-api\.net`) // https://azure.github.io/PSRule.Rules.Azure/en/rules/Azure.APIM.Name/ |
| 37 | + keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"azure", ".management.azure-api.net"}) + `([a-zA-Z0-9+\/]{83,85}[a-zA-Z0-9]==)`) // pattern for both Primary and secondary key |
| 38 | + |
| 39 | + invalidHosts = simple.NewCache[struct{}]() |
| 40 | + noSuchHostErr = errors.New("no such host") |
| 41 | +) |
| 42 | + |
| 43 | +// Keywords are used for efficiently pre-filtering chunks. |
| 44 | +// Use identifiers in the secret preferably, or the provider name. |
| 45 | +func (s Scanner) Keywords() []string { |
| 46 | + return []string{".management.azure-api.net"} |
| 47 | +} |
| 48 | + |
| 49 | +// FromData will find and optionally verify Azure Management API keys in a given set of bytes. |
| 50 | +func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) { |
| 51 | + logger := logContext.AddLogger(ctx).Logger().WithName("azuredirectmanagementkey") |
| 52 | + dataStr := string(data) |
| 53 | + |
| 54 | + urlMatchesUnique := make(map[string]string) |
| 55 | + for _, urlMatch := range urlPat.FindAllStringSubmatch(dataStr, -1) { |
| 56 | + urlMatchesUnique[urlMatch[0]] = urlMatch[1] // urlMatch[0] is the full url, urlMatch[1] is the service name |
| 57 | + } |
| 58 | + keyMatchesUnique := make(map[string]struct{}) |
| 59 | + for _, keyMatch := range keyPat.FindAllStringSubmatch(dataStr, -1) { |
| 60 | + keyMatchesUnique[strings.TrimSpace(keyMatch[1])] = struct{}{} |
| 61 | + } |
| 62 | + |
| 63 | +EndpointLoop: |
| 64 | + for baseUrl, serviceName := range urlMatchesUnique { |
| 65 | + for key := range keyMatchesUnique { |
| 66 | + s1 := detectors.Result{ |
| 67 | + DetectorType: detectorspb.DetectorType_AzureDirectManagementKey, |
| 68 | + Raw: []byte(baseUrl), |
| 69 | + RawV2: []byte(baseUrl + ":" + key), |
| 70 | + } |
| 71 | + |
| 72 | + if verify { |
| 73 | + if invalidHosts.Exists(baseUrl) { |
| 74 | + logger.V(3).Info("Skipping invalid registry", "baseUrl", baseUrl) |
| 75 | + continue EndpointLoop |
| 76 | + } |
| 77 | + |
| 78 | + client := s.client |
| 79 | + if client == nil { |
| 80 | + client = defaultClient |
| 81 | + } |
| 82 | + |
| 83 | + isVerified, verificationErr := s.verifyMatch(ctx, client, baseUrl, serviceName, key) |
| 84 | + s1.Verified = isVerified |
| 85 | + if verificationErr != nil { |
| 86 | + if errors.Is(verificationErr, noSuchHostErr) { |
| 87 | + invalidHosts.Set(baseUrl, struct{}{}) |
| 88 | + continue EndpointLoop |
| 89 | + } |
| 90 | + s1.SetVerificationError(verificationErr, baseUrl) |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + results = append(results, s1) |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + return results, nil |
| 99 | +} |
| 100 | + |
| 101 | +func (s Scanner) Type() detectorspb.DetectorType { |
| 102 | + return detectorspb.DetectorType_AzureDirectManagementKey |
| 103 | +} |
| 104 | + |
| 105 | +func (s Scanner) Description() string { |
| 106 | + return "Azure API Management provides a direct management REST API for performing operations on selected entities, such as users, groups, products, and subscriptions." |
| 107 | +} |
| 108 | + |
| 109 | +func (s Scanner) IsFalsePositive(_ detectors.Result) (bool, string) { |
| 110 | + return false, "" |
| 111 | +} |
| 112 | + |
| 113 | +func (s Scanner) verifyMatch(ctx context.Context, client *http.Client, baseUrl, serviceName, key string) (bool, error) { |
| 114 | + url := fmt.Sprintf( |
| 115 | + "%s/subscriptions/default/resourceGroups/default/providers/Microsoft.ApiManagement/service/%s/apis?api-version=2024-05-01", |
| 116 | + baseUrl, serviceName, |
| 117 | + ) |
| 118 | + accessToken, err := generateAccessToken(key) |
| 119 | + if err != nil { |
| 120 | + return false, err |
| 121 | + } |
| 122 | + req, err := http.NewRequestWithContext(ctx, "GET", url, nil) |
| 123 | + if err != nil { |
| 124 | + return false, err |
| 125 | + } |
| 126 | + req.Header.Set("Content-Type", "application/json") |
| 127 | + req.Header.Set("Authorization", fmt.Sprintf("SharedAccessSignature %s", accessToken)) |
| 128 | + resp, err := client.Do(req) |
| 129 | + if err != nil { |
| 130 | + return false, nil |
| 131 | + } |
| 132 | + defer resp.Body.Close() |
| 133 | + |
| 134 | + switch resp.StatusCode { |
| 135 | + case http.StatusOK: |
| 136 | + return true, nil |
| 137 | + case http.StatusUnauthorized: |
| 138 | + return false, nil |
| 139 | + default: |
| 140 | + return false, fmt.Errorf("unexpected HTTP response status %d", resp.StatusCode) |
| 141 | + } |
| 142 | +} |
| 143 | + |
| 144 | +// https://learn.microsoft.com/en-us/rest/api/apimanagement/apimanagementrest/azure-api-management-rest-api-authentication |
| 145 | +func generateAccessToken(key string) (string, error) { |
| 146 | + expiry := time.Now().UTC().Add(5 * time.Second).Format(RFC3339WithoutMicroseconds) // expire in 5 seconds |
| 147 | + expiry = expiry + ".0000000Z" // 7 decimals microsecond's precision is must for access token |
| 148 | + |
| 149 | + // Construct the string-to-sign |
| 150 | + stringToSign := fmt.Sprintf("integration\n%s", expiry) |
| 151 | + |
| 152 | + // Generate HMAC-SHA512 signature |
| 153 | + h := hmac.New(sha512.New, []byte(key)) |
| 154 | + h.Write([]byte(stringToSign)) |
| 155 | + signature := h.Sum(nil) |
| 156 | + |
| 157 | + // Base64 encode the signature |
| 158 | + encodedSignature := base64.StdEncoding.EncodeToString(signature) |
| 159 | + |
| 160 | + // Create the access token |
| 161 | + accessToken := fmt.Sprintf("uid=integration&ex=%s&sn=%s", expiry, encodedSignature) |
| 162 | + return accessToken, nil |
| 163 | +} |
0 commit comments