Skip to content
Changes

Reference

azure_entra · Oct 23, 2026

What this change means

How responses are judged changed, Verification error handling changed. Changes how the detector verifies or what it treats as the credential.

Field changes
FieldBeforeAfter
Expected statusesBefore: 200 (StatusOK) → verified; 400 (StatusBadRequest) → not verified; other (default) → not verifiedAfter: 200 (StatusOK) → verified; 400 (StatusBadRequest) → not verified; other (default) → error or unknown
pkg/detectors/azure_entra/common.go+99−43View file
@@ -4,6 +4,7 @@ import (
44 "fmt"
55 "io"
66 "net/http"
7added: "sort"
78 "strings"
89
910 regexp "github.com/wasilibs/go-re2"
@@ -38,45 +39,93 @@ var (
3839
3940// FindTenantIdMatches returns a list of potential tenant IDs in the provided |data|.
4041func FindTenantIdMatches(data string) map[string]struct{} {
41removed: uniqueMatches := make(map[string]struct{})
42removed:
43removed: for _, match := range tenantIdPat.FindAllStringSubmatch(data, -1) {
44removed: var m string
45removed: if match[1] != "" {
46removed: m = strings.ToLower(match[1])
47removed: } else if match[2] != "" {
48removed: m = strings.ToLower(match[2])
49removed: } else if match[3] != "" {
50removed: m = strings.ToLower(match[3])
51removed: } else if match[4] != "" {
52removed: m = strings.ToLower(match[4])
53removed: }
54removed: if _, ok := detectors.UuidFalsePositives[detectors.FalsePositive(m)]; ok {
55removed: continue
56removed: } else if detectors.StringShannonEntropy(m) < 3 {
57removed: continue
42added: return offsetsToSet(FindTenantIdOffsets(data))
43added: }
44added:
45added: // FindTenantIdOffsets returns potential tenant IDs in |data|, mapped to the byte offsets where each was found.
46added: func FindTenantIdOffsets(data string) map[string][]int {
47added: matches := make(map[string][]int)
48added:
49added: for _, idx := range tenantIdPat.FindAllStringSubmatchIndex(data, -1) {
50added: // The pattern has four alternative capture groups; use the one that matched.
51added: for group := 1; group <= 4; group++ {
52added: start, end := idx[2*group], idx[2*group+1]
53added: if start < 0 {
54added: continue
55added: }
56added: m := strings.ToLower(data[start:end])
57added: if isLikelyId(m) {
58added: matches[m] = append(matches[m], start)
59added: }
60added: break
5861 }
59removed: uniqueMatches[m] = struct{}{}
6062 }
61removed: for _, match := range tenantOnMicrosoftPat.FindAllStringSubmatch(data, -1) {
62removed: uniqueMatches[match[1]] = struct{}{}
63added: for _, idx := range tenantOnMicrosoftPat.FindAllStringSubmatchIndex(data, -1) {
64added: m := data[idx[2]:idx[3]]
65added: matches[m] = append(matches[m], idx[2])
6366 }
64removed: return uniqueMatches
67added: return matches
6568}
6669
6770// FindClientIdMatches returns a list of potential client UUIDs in the provided |data|.
6871func FindClientIdMatches(data string) map[string]struct{} {
69removed: uniqueMatches := make(map[string]struct{})
70removed: for _, match := range clientIdPat.FindAllStringSubmatch(data, -1) {
71removed: m := strings.ToLower(match[1])
72removed: if _, ok := detectors.UuidFalsePositives[detectors.FalsePositive(m)]; ok {
73removed: continue
74removed: } else if detectors.StringShannonEntropy(m) < 3 {
75removed: continue
72added: return offsetsToSet(FindClientIdOffsets(data))
73added: }
74added:
75added: // FindClientIdOffsets returns potential client UUIDs in |data|, mapped to the byte offsets where each was found.
76added: func FindClientIdOffsets(data string) map[string][]int {
77added: matches := make(map[string][]int)
78added: for _, idx := range clientIdPat.FindAllStringSubmatchIndex(data, -1) {
79added: m := strings.ToLower(data[idx[2]:idx[3]])
80added: if isLikelyId(m) {
81added: matches[m] = append(matches[m], idx[2])
7682 }
77removed: uniqueMatches[m] = struct{}{}
7883 }
79removed: return uniqueMatches
84added: return matches
85added: }
86added:
87added: // NearestFirst returns the keys of |candidates| ordered by their distance to |pos|.
88added: // A candidate's distance is that of its closest occurrence. Ties are broken by value so the order is stable.
89added: func NearestFirst(candidates map[string][]int, pos int) []string {
90added: distances := make(map[string]int, len(candidates))
91added: ordered := make([]string, 0, len(candidates))
92added: for value, offsets := range candidates {
93added: closest := -1
94added: for _, offset := range offsets {
95added: d := offset - pos
96added: if d < 0 {
97added: d = -d
98added: }
99added: if closest < 0 || d < closest {
100added: closest = d
101added: }
102added: }
103added: distances[value] = closest
104added: ordered = append(ordered, value)
105added: }
106added: sort.Slice(ordered, func(i, j int) bool {
107added: if distances[ordered[i]] != distances[ordered[j]] {
108added: return distances[ordered[i]] < distances[ordered[j]]
109added: }
110added: return ordered[i] < ordered[j]
111added: })
112added: return ordered
113added: }
114added:
115added: // isLikelyId filters out well-known placeholder UUIDs and low-entropy values.
116added: func isLikelyId(m string) bool {
117added: if _, ok := detectors.UuidFalsePositives[detectors.FalsePositive(m)]; ok {
118added: return false
119added: }
120added: return detectors.StringShannonEntropy(m) >= 3
121added: }
122added:
123added: func offsetsToSet(offsets map[string][]int) map[string]struct{} {
124added: set := make(map[string]struct{}, len(offsets))
125added: for value := range offsets {
126added: set[value] = struct{}{}
127added: }
128added: return set
80129}
81130
82131var (
@@ -85,35 +134,42 @@ var (
85134)
86135
87136// TenantExists returns whether the tenant exists according to Microsoft's well-known OpenID endpoint.
88removed: func TenantExists(ctx context.Context, client *http.Client, tenant string) bool {
137added: // A non-nil error means the answer is unknown (e.g., a network failure); it is not cached.
138added: func TenantExists(ctx context.Context, client *http.Client, tenant string) (bool, error) {
89139 // Use cached value where possible.
90140 if tenantExists, isCached := tenantCache.Get(tenant); isCached {
91removed: return tenantExists
141added: return tenantExists, nil
92142 }
93143
94144 // https://www.codingexplorations.com/blog/understanding-singleflight-in-golang-a-solution-for-eliminating-redundant-work
95removed: tenantExists, _, _ := tenantGroup.Do(tenant, func() (interface{}, error) {
96removed: result := queryTenant(ctx, client, tenant)
97removed: tenantCache.Set(tenant, result)
98removed: return result, nil
145added: tenantExists, err, _ := tenantGroup.Do(tenant, func() (interface{}, error) {
146added: result, err := queryTenant(ctx, client, tenant)
147added: // Only remember definite answers, so a transient failure doesn't stick.
148added: if err == nil {
149added: tenantCache.Set(tenant, result)
150added: }
151added: return result, err
99152 })
153added: if err != nil {
154added: return false, err
155added: }
100156
101removed: return tenantExists.(bool)
157added: return tenantExists.(bool), nil
102158}
103159
104removed: func queryTenant(ctx context.Context, client *http.Client, tenant string) bool {
160added: func queryTenant(ctx context.Context, client *http.Client, tenant string) (bool, error) {
105161 logger := ctx.Logger().WithName("azure").WithValues("tenant", tenant)
106162
107163 tenantUrl := fmt.Sprintf("https://login.microsoftonline.com/%s/.well-known/openid-configuration", tenant)
108164 req, err := http.NewRequestWithContext(ctx, http.MethodGet, tenantUrl, nil)
109165 if err != nil {
110removed: return false
166added: return false, err
111167 }
112168
113169 res, err := client.Do(req)
114170 if err != nil {
115171 logger.Error(err, "Failed to check if tenant exists")
116removed: return false
172added: return false, err
117173 }
118174 defer func() {
119175 _, _ = io.Copy(io.Discard, res.Body)
@@ -122,13 +178,13 @@ func queryTenant(ctx context.Context, client *http.Client, tenant string) bool {
122178
123179 switch res.StatusCode {
124180 case http.StatusOK:
125removed: return true
181added: return true, nil
126182 case http.StatusBadRequest:
127183 logger.V(4).Info("Tenant does not exist.")
128removed: return false
184added: return false, nil
129185 default:
130186 bodyBytes, _ := io.ReadAll(res.Body)
131187 logger.Error(nil, "WARNING: Unexpected response when checking if tenant exists", "status_code", res.StatusCode, "body", string(bodyBytes))
132removed: return false
188added: return false, fmt.Errorf("unexpected status %d checking tenant", res.StatusCode)
133189 }
134190}
pkg/detectors/azure_entra/refreshtoken/refreshtoken.go+1−1View file
@@ -112,7 +112,7 @@ func (s Scanner) processMatches(ctx context.Context, refreshTokens, clientIds, t
112112 }
113113
114114 if _, ok := validTenants[tenantId]; !ok {
115removed: if azure_entra.TenantExists(logCtx, client, tenantId) {
115added: if exists, err := azure_entra.TenantExists(logCtx, client, tenantId); err == nil && exists {
116116 validTenants[tenantId] = struct{}{}
117117 } else {
118118 delete(tenantIds, tenantId)
pkg/detectors/azure_entra/serviceprincipal/v1/spv1.go+3−3View file
@@ -53,18 +53,18 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
5353 if len(clientSecrets) == 0 {
5454 return
5555 }
56removed: clientIds := azure_entra.FindClientIdMatches(dataStr)
56added: clientIds := azure_entra.FindClientIdOffsets(dataStr)
5757 if len(clientIds) == 0 {
5858 return
5959 }
60removed: tenantIds := azure_entra.FindTenantIdMatches(dataStr)
60added: tenantIds := azure_entra.FindTenantIdOffsets(dataStr)
6161
6262 client := s.client
6363 if client == nil {
6464 client = defaultClient
6565 }
6666 // The handling logic is identical for both versions.
67removed: results = append(results, v2.ProcessData(ctx, clientSecrets, clientIds, tenantIds, verify, client)...)
67added: results = append(results, v2.ProcessData(ctx, dataStr, clientSecrets, clientIds, tenantIds, verify, client)...)
6868 return results, nil
6969}
pkg/detectors/azure_entra/serviceprincipal/v2/spv2.go+65−18View file
@@ -58,34 +58,54 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
5858 if len(clientSecrets) == 0 {
5959 return results, nil
6060 }
61removed: clientIds := azure_entra.FindClientIdMatches(dataStr)
62removed: tenantIds := azure_entra.FindTenantIdMatches(dataStr)
61added: clientIds := azure_entra.FindClientIdOffsets(dataStr)
62added: tenantIds := azure_entra.FindTenantIdOffsets(dataStr)
6363
6464 client := s.client
6565 if client == nil {
6666 client = defaultClient
6767 }
6868
69removed: results = append(results, ProcessData(ctx, clientSecrets, clientIds, tenantIds, verify, client)...)
69added: results = append(results, ProcessData(ctx, dataStr, clientSecrets, clientIds, tenantIds, verify, client)...)
7070 return results, nil
7171}
7272
73removed: func ProcessData(ctx context.Context, clientSecrets, clientIds, tenantIds map[string]struct{}, verify bool, client *http.Client) (results []detectors.Result) {
73added: // ProcessData verifies each secret against the client and tenant IDs found in |data|.
74added: // |clientIds| and |tenantIds| map each candidate to the offsets it was found at, so the
75added: // candidates closest to a secret are tried (and reported) first.
76added: func ProcessData(ctx context.Context, data string, clientSecrets map[string]struct{}, clientIds, tenantIds map[string][]int, verify bool, client *http.Client) (results []detectors.Result) {
7477 logCtx := logContext.AddLogger(ctx)
7578 invalidClientsForTenant := make(map[string]map[string]struct{})
79added: // Tenants whose lookup failed. Not retried again in this call, so one flaky tenant
80added: // costs one request instead of one per secret and client.
81added: unknownTenants := make(map[string]struct{})
7682
7783 for clientSecret := range clientSecrets {
7884 var (
79removed: r *detectors.Result
80removed: clientId string
81removed: tenantId string
85added: r *detectors.Result
86added: // The first client/tenant pair that recognised the app but rejected the secret.
87added: knownClientId, knownTenantId string
8288 )
8389
90added: // Candidates nearest to the secret are the most likely to belong to it.
91added: secretPos := strings.Index(data, clientSecret)
92added: clientOrder := azure_entra.NearestFirst(clientIds, secretPos)
93added: tenantOrder := azure_entra.NearestFirst(tenantIds, secretPos)
94added:
8495 ClientLoop:
85removed: for cId := range clientIds {
86removed: clientId = cId
87removed: for tId := range tenantIds {
88removed: tenantId = tId
96added: for _, clientId := range clientOrder {
97added: // Skip candidates removed earlier (e.g., a tenant that was also read as a client).
98added: if _, ok := clientIds[clientId]; !ok {
99added: continue
100added: }
101added: for _, tenantId := range tenantOrder {
102added: if _, ok := tenantIds[tenantId]; !ok {
103added: continue
104added: }
105added:
106added: if _, unknown := unknownTenants[tenantId]; unknown {
107added: continue
108added: }
89109
90110 // Skip known invalid tenants.
91111 invalidClients := invalidClientsForTenant[tenantId]
@@ -98,7 +118,14 @@ func ProcessData(ctx context.Context, clientSecrets, clientIds, tenantIds map[st
98118 }
99119
100120 if verify {
101removed: if !azure_entra.TenantExists(logCtx, client, tenantId) {
121added: exists, err := azure_entra.TenantExists(logCtx, client, tenantId)
122added: if err != nil {
123added: // Unknown, not "missing". Skip it for now but keep it as a candidate.
124added: // If no pair is recognised, the fallback still picks the nearest tenant.
125added: unknownTenants[tenantId] = struct{}{}
126added: continue
127added: }
128added: if !exists {
102129 // Tenant doesn't exist
103130 delete(tenantIds, tenantId)
104131 continue
@@ -113,6 +140,11 @@ func ProcessData(ctx context.Context, clientSecrets, clientIds, tenantIds map[st
113140 case errors.Is(verificationErr, serviceprincipal.ErrConditionalAccessPolicy):
114141 // Do nothing.
115142 case errors.Is(verificationErr, serviceprincipal.ErrSecretInvalid):
143added: // The app exists in this tenant, only the secret is wrong (e.g.,
144added: // rotated). Remember the pair so the fallback matches the live result.
145added: if knownClientId == "" {
146added: knownClientId, knownTenantId = clientId, tenantId
147added: }
116148 continue ClientLoop
117149 case errors.Is(verificationErr, serviceprincipal.ErrSecretExpired):
118150 r = createResult(tenantId, clientId, clientSecret, false, nil, nil)
@@ -138,12 +170,12 @@ func ProcessData(ctx context.Context, clientSecrets, clientIds, tenantIds map[st
138170 }
139171
140172 if r == nil {
141removed: // Only include the clientId and tenantId if we're confident which one it is.
142removed: if len(clientIds) != 1 {
143removed: clientId = ""
144removed: }
145removed: if len(tenantIds) != 1 {
146removed: tenantId = ""
173added: // Nothing verified. Use the pair Azure recognised, if any. Otherwise report
174added: // the nearest tenant, then the nearest client that isn't ruled out for it.
175added: // This keeps the result the same whether the secret is live or rotated.
176added: clientId, tenantId := knownClientId, knownTenantId
177added: if clientId == "" {
178added: clientId, tenantId = nearestPair(clientIds, tenantIds, invalidClientsForTenant, secretPos)
147179 }
148180 r = createResult(tenantId, clientId, clientSecret, false, nil, nil)
149181 }
@@ -153,6 +185,21 @@ func ProcessData(ctx context.Context, clientSecrets, clientIds, tenantIds map[st
153185 return results
154186}
155187
188added: // nearestPair picks the tenant nearest to |pos|, then the nearest client that isn't
189added: // ruled out for that tenant and isn't the tenant itself.
190added: func nearestPair(clientIds, tenantIds map[string][]int, invalidClientsForTenant map[string]map[string]struct{}, pos int) (clientId, tenantId string) {
191added: if remaining := azure_entra.NearestFirst(tenantIds, pos); len(remaining) > 0 {
192added: tenantId = remaining[0]
193added: }
194added: for _, candidate := range azure_entra.NearestFirst(clientIds, pos) {
195added: if _, ruledOut := invalidClientsForTenant[tenantId][candidate]; ruledOut || candidate == tenantId {
196added: continue
197added: }
198added: return candidate, tenantId
199added: }
200added: return "", tenantId
201added: }
202added:
156203func createResult(tenantId string, clientId string, clientSecret string, verified bool, extraData map[string]string, err error) *detectors.Result {
157204 r := &detectors.Result{
158205 DetectorType: detector_typepb.DetectorType_Azure,