Skip to content

Find, verify, and analyze leaked credentials

fix(azuresastoken): match SAS tokens regardless of parameter order (#5043)

genisis0xf38f8f7dd775
diff --git a/pkg/detectors/azuresastoken/azuresastoken.go b/pkg/detectors/azuresastoken/azuresastoken.go
index e5a74327a..661208374 100644
--- a/pkg/detectors/azuresastoken/azuresastoken.go
+++ b/pkg/detectors/azuresastoken/azuresastoken.go
@@ -31,9 +31,29 @@ var (
// microsoft storage resource naming rules: https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/resource-name-rules#microsoftstorage:~:text=format%3A%0AVaultName_KeyName_KeyVersion.-,Microsoft.Storage,-Expand%20table
urlPat = regexp.MustCompile(`https://([a-zA-Z0-9][a-z0-9_-]{1,22}[a-zA-Z0-9])\.blob\.core\.windows\.net/[a-z0-9]([a-z0-9-]{1,61}[a-z0-9])?(?:/[a-zA-Z0-9._-]+)*`)
- keyPat = regexp.MustCompile(
- detectors.PrefixRegex([]string{"azure", "sas", "token", "blob", ".blob.core.windows.net"}) +
- `(sp=[racwdli]+&st=\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z&se=\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z(?:&sip=\d{1,3}(?:\.\d{1,3}){3}(?:-\d{1,3}(?:\.\d{1,3}){3})?)?(&spr=https)?(?:,https)?&sv=\d{4}-\d{2}-\d{2}&sr=[bcfso]&sig=[a-zA-Z0-9%]{10,})`)
+ // A SAS token is a query string of `&`-joined `key=value` pairs. The parameters
+ // can appear in any order, and values may be URL-encoded (e.g. Azure Storage
+ // Explorer encodes the `:` in the timestamps as %3A and the `+`, `/`, `=` in the
+ // signature as %2B, %2F, %3D). Rather than enumerate every permutation in one
+ // regex, match a contiguous run of query parameters and validate the SAS-specific
+ // parameters in keyMatchIsSASToken below. This keeps detection order-independent.
+ // The value class excludes `=` so a SAS token preceded by a short lowercase
+ // `key=` (e.g. `sas=sp=r&...`) is not absorbed from that preceding key, which
+ // would bury the real `sp` parameter inside the first value and fail
+ // validation. Azure URL-encodes any `=` inside a value (the signature padding
+ // becomes %3D), so excluding the literal does not drop a legitimate value.
+ sasQueryPat = regexp.MustCompile(`[a-z]{2,4}=[^&=\s"'<>]+(?:&[a-z]{2,4}=[^&=\s"'<>]+)+`)
+
+ // Validators for the individual SAS parameters. The `sp` permission set and `sr`
+ // resource set match the formats the previous, order-locked regex accepted.
+ spValuePat = regexp.MustCompile(`^[racwdli]+$`)
+ svValuePat = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}$`)
+ srValuePat = regexp.MustCompile(`^[bcfso]$`)
+ // The `:` separators may be URL-encoded; percent-encoding hex digits are
+ // case-insensitive per RFC 3986, so accept both %3A and %3a.
+ timeValuePat = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}T\d{2}(?::|%3[Aa])\d{2}(?::|%3[Aa])\d{2}Z$`)
+ sigValuePat = regexp.MustCompile(`^[a-zA-Z0-9%+/=]{10,}$`)
+ sipValuePat = regexp.MustCompile(`^\d{1,3}(?:\.\d{1,3}){3}(?:-\d{1,3}(?:\.\d{1,3}){3})?$`)
invalidStorageAccounts = simple.NewCache[struct{}]()
@@ -55,6 +75,60 @@ func (s Scanner) Description() string {
return "An Azure Shared Access Signature (SAS) token is a time-limited, permission-based URL query string that grants secure, granular access to Azure Storage resources (e.g., blobs, containers, files) without exposing account keys."
}
+// keyMatchIsSASToken reports whether a matched query-parameter run is a Azure
+// Storage SAS token. The required parameters may appear in any order; values may
+// be URL-encoded. This reproduces the validations the previous order-locked regex
+// enforced (permission set, resource type, timestamp shape, signature, optional IP)
+// without depending on parameter order.
+func keyMatchIsSASToken(query string) bool {
+ params := make(map[string]string)
+ for _, pair := range strings.Split(query, "&") {
+ key, value, ok := strings.Cut(pair, "=")
+ if !ok {
+ continue
+ }
+ params[key] = value
+ }
+
+ sp, ok := params["sp"]
+ if !ok || !spValuePat.MatchString(sp) {
+ return false
+ }
+ sv, ok := params["sv"]
+ if !ok || !svValuePat.MatchString(sv) {
+ return false
+ }
+ sr, ok := params["sr"]
+ if !ok || !srValuePat.MatchString(sr) {
+ return false
+ }
+ sig, ok := params["sig"]
+ if !ok || !sigValuePat.MatchString(sig) {
+ return false
+ }
+
+ // A SAS token carries a start time, an expiry time, or both; any present one
+ // must be well-formed.
+ st, hasStart := params["st"]
+ se, hasExpiry := params["se"]
+ if !hasStart && !hasExpiry {
+ return false
+ }
+ if hasStart && !timeValuePat.MatchString(st) {
+ return false
+ }
+ if hasExpiry && !timeValuePat.MatchString(se) {
+ return false
+ }
+
+ // The IP restriction is optional, but must be a valid address or range if set.
+ if sip, ok := params["sip"]; ok && !sipValuePat.MatchString(sip) {
+ return false
+ }
+
+ return true
+}
+
func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {
logger := logContext.AddLogger(ctx).Logger().WithName("azuresas")
@@ -68,8 +142,10 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
// deduplicate keyMatches
keyMatchesUnique := make(map[string]struct{})
- for _, keyMatch := range keyPat.FindAllStringSubmatch(dataStr, -1) {
- keyMatchesUnique[keyMatch[1]] = struct{}{}
+ for _, keyMatch := range sasQueryPat.FindAllString(dataStr, -1) {
+ if keyMatchIsSASToken(keyMatch) {
+ keyMatchesUnique[keyMatch] = struct{}{}
+ }
}
// Check results.
diff --git a/pkg/detectors/azuresastoken/azuresastoken_test.go b/pkg/detectors/azuresastoken/azuresastoken_test.go
index fec99debd..59de2623d 100644
--- a/pkg/detectors/azuresastoken/azuresastoken_test.go
+++ b/pkg/detectors/azuresastoken/azuresastoken_test.go
@@ -60,6 +60,43 @@ func TestAzureSASToken_Pattern(t *testing.T) {
`,
want: []string{"https://trufflesecurity.blob.core.windows.net/trufflesecurity/test_blob.txtsp=r&st=2025-03-04T07:24:52Z&se=2025-04-04T15:24:52Z&spr=https&sv=2022-11-02&sr=c&sig=WSdF9YeZhvrbs%2B%2B1f8ZdDBzEe7fBJ%2BenuaXQ%2BJ9WOw0%3D"},
},
+ {
+ // Storage Explorer emits the parameters in a different order (sv first,
+ // sp last) and URL-encodes the ':' in the timestamps as %3A. See #4732.
+ name: "valid pattern, alternate order with url-encoded timestamps",
+ input: `
+ https://accountname.blob.core.windows.net/sorted?sv=2023-01-03&st=2025-06-18T08%3A45%3A11Z&se=2025-06-19T08%3A45%3A11Z&sr=c&sp=r&sig=ow2a1XbXmD4%2BEv9LBUkek8R%2FrAjvrQFpenUbzztILn8%3D
+ `,
+ want: []string{"https://accountname.blob.core.windows.net/sortedsv=2023-01-03&st=2025-06-18T08%3A45%3A11Z&se=2025-06-19T08%3A45%3A11Z&sr=c&sp=r&sig=ow2a1XbXmD4%2BEv9LBUkek8R%2FrAjvrQFpenUbzztILn8%3D"},
+ },
+ {
+ // Percent-encoding hex digits are case-insensitive (RFC 3986), so a
+ // timestamp encoded with lowercase %3a must match just like %3A.
+ name: "valid pattern, url-encoded timestamps with lowercase hex",
+ input: `
+ https://accountname.blob.core.windows.net/sorted?sv=2023-01-03&st=2025-06-18T08%3a45%3a11Z&se=2025-06-19T08%3a45%3a11Z&sr=c&sp=r&sig=ow2a1XbXmD4%2BEv9LBUkek8R%2FrAjvrQFpenUbzztILn8%3D
+ `,
+ want: []string{"https://accountname.blob.core.windows.net/sortedsv=2023-01-03&st=2025-06-18T08%3a45%3a11Z&se=2025-06-19T08%3a45%3a11Z&sr=c&sp=r&sig=ow2a1XbXmD4%2BEv9LBUkek8R%2FrAjvrQFpenUbzztILn8%3D"},
+ },
+ {
+ // A SAS token assigned to a short lowercase variable (`sas=sp=r&...`)
+ // must still be captured: the parameter run has to start at `sp`, not
+ // be absorbed from the preceding `sas=` key.
+ name: "valid pattern preceded by lowercase variable assignment",
+ input: `
+ sas=sp=r&st=2025-03-04T07:24:52Z&se=2025-04-04T15:24:52Z&spr=https&sv=2022-11-02&sr=c&sig=WSdF9YeZhvrbs%2B%2B1f8ZdDBzEe7fBJ%2BenuaXQ%2BJ9WOw0%3D
+ AZURE_BLOB_SAS_URL=https://trufflesecurity.blob.core.windows.net/trufflesecurity
+ `,
+ want: []string{"https://trufflesecurity.blob.core.windows.net/trufflesecuritysp=r&st=2025-03-04T07:24:52Z&se=2025-04-04T15:24:52Z&spr=https&sv=2022-11-02&sr=c&sig=WSdF9YeZhvrbs%2B%2B1f8ZdDBzEe7fBJ%2BenuaXQ%2BJ9WOw0%3D"},
+ },
+ {
+ name: "non-sas query string is ignored",
+ input: `
+ AZURE_BLOB_QUERY=comp=list&restype=container&maxresults=100
+ AZURE_BLOB_SAS_URL=https://trufflesecurity.blob.core.windows.net/trufflesecurity
+ `,
+ want: nil,
+ },
{
name: "invalid pattern",
input: `