|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Decide whether an Azure credential found in code is still live. |
| 3 | +
|
| 4 | +Two kinds are handled, because they are the two whose liveness can be read |
| 5 | +or checked without touching anything: |
| 6 | +
|
| 7 | + entra_token a Microsoft Entra (Azure AD) access token, a JWT. Its own |
| 8 | + payload says when it stops working, so most of the answer is |
| 9 | + there to read with no network at all. When the live probe is |
| 10 | + on, a single read only call to the issuing resource (Microsoft |
| 11 | + Graph or Azure Resource Manager) says whether the token is |
| 12 | + still accepted. |
| 13 | + sas an Azure Storage shared access signature. The query string |
| 14 | + carries its own expiry (se=), read offline. When the probe is |
| 15 | + on and a full resource URL is in hand, one HEAD says whether |
| 16 | + the signature is still honored. |
| 17 | +
|
| 18 | +The offline read is always safe: it sends nothing and leaks nothing, and a |
| 19 | +token past its own expiry is dead whatever a server would say. The live probe |
| 20 | +sends the credential to Microsoft, so it is opt in (--probe) and strictly read |
| 21 | +only: GET for a token, HEAD for a SAS, no redirects off Azure, and the |
| 22 | +destination host must be a Microsoft cloud endpoint whose address resolves to |
| 23 | +a public IP. A live result raises the finding to a confirmed credential; a |
| 24 | +definitive dead result (expired, or the provider refused it) is the rare |
| 25 | +positive evidence that a credential is not a live one. |
| 26 | +
|
| 27 | +Reads one secret from stdin, writes one compact JSON object to stdout. Never |
| 28 | +prints the secret, never fails the scan: on any trouble it prints {} and |
| 29 | +exits 0, so the caller merges nothing. |
| 30 | +""" |
| 31 | + |
| 32 | +from __future__ import annotations |
| 33 | + |
| 34 | +import base64 |
| 35 | +import binascii |
| 36 | +import datetime as _dt |
| 37 | +import ipaddress |
| 38 | +import json |
| 39 | +import socket |
| 40 | +import sys |
| 41 | +import urllib.error |
| 42 | +import urllib.request |
| 43 | +from urllib.parse import parse_qs, unquote, urlsplit |
| 44 | + |
| 45 | +# Microsoft cloud endpoints, by role. Suffixes so a storage account name in |
| 46 | +# front of the domain still matches, exact hosts for the fixed service roots. |
| 47 | +_GRAPH_HOSTS = { |
| 48 | + "graph.microsoft.com", "graph.microsoft.us", "dod-graph.microsoft.us", |
| 49 | + "microsoftgraph.chinacloudapi.cn", |
| 50 | +} |
| 51 | +_ARM_HOSTS = { |
| 52 | + "management.azure.com", "management.usgovcloudapi.net", |
| 53 | + "management.chinacloudapi.cn", |
| 54 | +} |
| 55 | +_STORAGE_SUFFIXES = ( |
| 56 | + ".core.windows.net", ".core.usgovcloudapi.net", |
| 57 | + ".core.chinacloudapi.cn", ".core.cloudapi.de", |
| 58 | +) |
| 59 | +# Audience values that name a resource we know how to probe. Microsoft Graph |
| 60 | +# and ARM each have a stable GUID as well as a URL form. |
| 61 | +_GRAPH_AUD = {"https://graph.microsoft.com", "https://graph.microsoft.com/", |
| 62 | + "00000003-0000-0000-c000-000000000000"} |
| 63 | +_ARM_AUD = {"https://management.azure.com", "https://management.azure.com/", |
| 64 | + "https://management.core.windows.net", |
| 65 | + "https://management.core.windows.net/", |
| 66 | + "797f4846-ba00-4fd7-ba43-dac1f8f63013"} |
| 67 | +_ENTRA_ISSUER_HINTS = ("sts.windows.net", "login.microsoftonline.com", |
| 68 | + "login.microsoft.com", "login.microsoftonline.us", |
| 69 | + "login.partner.microsoftonline.cn", "login.windows.net") |
| 70 | + |
| 71 | +_TIMEOUT = 6.0 |
| 72 | +_UA = "gcr-secret-verifier" # generic on purpose: never carries who is scanning |
| 73 | + |
| 74 | + |
| 75 | +def _now() -> int: |
| 76 | + return int(_dt.datetime.now(_dt.timezone.utc).timestamp()) |
| 77 | + |
| 78 | + |
| 79 | +def _b64url_json(part: str): |
| 80 | + """Decode one base64url JWT segment to an object, or None.""" |
| 81 | + pad = "=" * (-len(part) % 4) |
| 82 | + try: |
| 83 | + raw = base64.urlsafe_b64decode(part + pad) |
| 84 | + obj = json.loads(raw) |
| 85 | + except (binascii.Error, ValueError, UnicodeDecodeError): |
| 86 | + return None |
| 87 | + return obj if isinstance(obj, dict) else None |
| 88 | + |
| 89 | + |
| 90 | +def _iso(epoch) -> str | None: |
| 91 | + try: |
| 92 | + return _dt.datetime.fromtimestamp(int(epoch), _dt.timezone.utc).strftime( |
| 93 | + "%Y-%m-%dT%H:%M:%SZ") |
| 94 | + except (TypeError, ValueError, OverflowError, OSError): |
| 95 | + return None |
| 96 | + |
| 97 | + |
| 98 | +# ---------------------------------------------------------------- classify |
| 99 | + |
| 100 | +def classify(secret: str) -> str: |
| 101 | + """entra_token, sas, or '' for anything this tool does not judge.""" |
| 102 | + s = (secret or "").strip() |
| 103 | + if not s: |
| 104 | + return "" |
| 105 | + parts = s.split(".") |
| 106 | + if len(parts) == 3 and all(parts[:2]): |
| 107 | + header = _b64url_json(parts[0]) |
| 108 | + body = _b64url_json(parts[1]) |
| 109 | + if isinstance(header, dict) and isinstance(body, dict) and "alg" in header: |
| 110 | + if _entra_resource(body) is not None or _is_entra_issuer(body): |
| 111 | + return "entra_token" |
| 112 | + return "" # a JWT, but not one we can place as Azure |
| 113 | + if "sig=" in s and ("sv=" in s or "se=" in s or "sr=" in s or "sp=" in s): |
| 114 | + return "sas" |
| 115 | + return "" |
| 116 | + |
| 117 | + |
| 118 | +def _is_entra_issuer(body: dict) -> bool: |
| 119 | + iss = str(body.get("iss") or "").lower() |
| 120 | + return any(h in iss for h in _ENTRA_ISSUER_HINTS) |
| 121 | + |
| 122 | + |
| 123 | +def _entra_resource(body: dict): |
| 124 | + """Which resource a token is for: 'graph', 'arm', or None (do not probe).""" |
| 125 | + auds = body.get("aud") |
| 126 | + values = auds if isinstance(auds, list) else [auds] |
| 127 | + for aud in values: |
| 128 | + a = str(aud or "").strip().rstrip("/") |
| 129 | + if a in {x.rstrip("/") for x in _GRAPH_AUD} or "graph.microsoft" in a: |
| 130 | + return "graph" |
| 131 | + if a in {x.rstrip("/") for x in _ARM_AUD} or "management.azure" in a \ |
| 132 | + or "management.core.windows.net" in a: |
| 133 | + return "arm" |
| 134 | + return None |
| 135 | + |
| 136 | + |
| 137 | +# ---------------------------------------------------------------- offline |
| 138 | + |
| 139 | +def inspect(secret: str) -> dict: |
| 140 | + """What can be known with no network: kind, expiry, and what to probe.""" |
| 141 | + kind = classify(secret) |
| 142 | + out = {"azure_kind": kind, "azure_expired": None, "azure_expires_at": None, |
| 143 | + "azure_resource": "", "_probe_url": "", "_probe_method": "", |
| 144 | + "_bearer": False} |
| 145 | + if kind == "entra_token": |
| 146 | + body = _b64url_json(secret.split(".")[1]) or {} |
| 147 | + exp = body.get("exp") |
| 148 | + if isinstance(exp, (int, float)): |
| 149 | + out["azure_expires_at"] = _iso(exp) |
| 150 | + out["azure_expired"] = exp < _now() |
| 151 | + resource = _entra_resource(body) |
| 152 | + if resource == "graph": |
| 153 | + out["azure_resource"] = "graph.microsoft.com" |
| 154 | + out["_probe_url"] = "https://graph.microsoft.com/v1.0/organization" |
| 155 | + out["_probe_method"], out["_bearer"] = "GET", True |
| 156 | + elif resource == "arm": |
| 157 | + out["azure_resource"] = "management.azure.com" |
| 158 | + out["_probe_url"] = ("https://management.azure.com/subscriptions" |
| 159 | + "?api-version=2022-12-01") |
| 160 | + out["_probe_method"], out["_bearer"] = "GET", True |
| 161 | + elif kind == "sas": |
| 162 | + se, host, url = _sas_facts(secret) |
| 163 | + if se is not None: |
| 164 | + out["azure_expires_at"] = _iso(se) |
| 165 | + out["azure_expired"] = se < _now() |
| 166 | + if host: |
| 167 | + out["azure_resource"] = host |
| 168 | + if url: |
| 169 | + out["_probe_url"], out["_probe_method"] = url, "HEAD" |
| 170 | + return out |
| 171 | + |
| 172 | + |
| 173 | +def _sas_facts(secret: str): |
| 174 | + """(expiry_epoch|None, storage_host|'', full_https_url|'') from a SAS.""" |
| 175 | + s = secret.strip() |
| 176 | + split = urlsplit(s if "://" in s else "//" + s.lstrip("/"), scheme="https") |
| 177 | + host = (split.hostname or "").lower() |
| 178 | + query = split.query or (s.split("?", 1)[1] if "?" in s else s) |
| 179 | + params = parse_qs(query, keep_blank_values=True) |
| 180 | + se = None |
| 181 | + if params.get("se"): |
| 182 | + se = _parse_azure_time(unquote(params["se"][0])) |
| 183 | + is_storage = host.endswith(_STORAGE_SUFFIXES) |
| 184 | + url = "" |
| 185 | + if "://" in s and is_storage and split.path: |
| 186 | + # Only a full, path bearing URL on a storage host is probeable. |
| 187 | + url = "https://%s%s?%s" % (host, split.path, split.query) |
| 188 | + return se, (host if is_storage else ""), url |
| 189 | + |
| 190 | + |
| 191 | +def _parse_azure_time(value: str): |
| 192 | + v = (value or "").strip() |
| 193 | + for fmt in ("%Y-%m-%dT%H:%M:%SZ", "%Y-%m-%dT%H:%M:%S.%fZ", |
| 194 | + "%Y-%m-%dT%H:%MZ", "%Y-%m-%dT%H:%M:%S", |
| 195 | + "%Y-%m-%d"): |
| 196 | + try: |
| 197 | + dt = _dt.datetime.strptime(v, fmt).replace(tzinfo=_dt.timezone.utc) |
| 198 | + return int(dt.timestamp()) |
| 199 | + except ValueError: |
| 200 | + continue |
| 201 | + return None |
| 202 | + |
| 203 | + |
| 204 | +# ---------------------------------------------------------------- live probe |
| 205 | + |
| 206 | +class _NoRedirect(urllib.request.HTTPRedirectHandler): |
| 207 | + """A probe never follows a redirect: the next hop is not where we checked.""" |
| 208 | + |
| 209 | + def redirect_request(self, req, fp, code, msg, headers, newurl): |
| 210 | + return None |
| 211 | + |
| 212 | + |
| 213 | +def _host_is_azure(host: str) -> bool: |
| 214 | + h = (host or "").lower() |
| 215 | + return (h in _GRAPH_HOSTS or h in _ARM_HOSTS or h.endswith(_STORAGE_SUFFIXES)) |
| 216 | + |
| 217 | + |
| 218 | +def _resolves_public(host: str) -> bool: |
| 219 | + """True only if every address the host resolves to is a public one.""" |
| 220 | + try: |
| 221 | + infos = socket.getaddrinfo(host, 443, proto=socket.IPPROTO_TCP) |
| 222 | + except socket.gaierror: |
| 223 | + return False |
| 224 | + seen = False |
| 225 | + for info in infos: |
| 226 | + ip = ipaddress.ip_address(info[4][0]) |
| 227 | + if (ip.is_private or ip.is_loopback or ip.is_link_local |
| 228 | + or ip.is_reserved or ip.is_multicast or ip.is_unspecified): |
| 229 | + return False |
| 230 | + seen = True |
| 231 | + return seen |
| 232 | + |
| 233 | + |
| 234 | +def _http(method: str, url: str, token: str, timeout: float): |
| 235 | + """One read only request to a checked Azure host. (status, headers). |
| 236 | +
|
| 237 | + Isolated so a test can stand in for it without a network. Refuses any |
| 238 | + URL that is not https to a Microsoft cloud host resolving to a public IP. |
| 239 | + """ |
| 240 | + parts = urlsplit(url) |
| 241 | + if parts.scheme != "https" or not _host_is_azure(parts.hostname or ""): |
| 242 | + raise ValueError("not an Azure https endpoint") |
| 243 | + if not _resolves_public(parts.hostname): |
| 244 | + raise ValueError("host does not resolve to a public address") |
| 245 | + headers = {"User-Agent": _UA, "Accept": "application/json"} |
| 246 | + if token: |
| 247 | + headers["Authorization"] = "Bearer " + token |
| 248 | + req = urllib.request.Request(url, method=method, headers=headers) |
| 249 | + opener = urllib.request.build_opener(_NoRedirect) |
| 250 | + try: |
| 251 | + with opener.open(req, timeout=timeout) as resp: |
| 252 | + return resp.status, {k.lower(): v for k, v in resp.headers.items()} |
| 253 | + except urllib.error.HTTPError as err: |
| 254 | + return err.code, {k.lower(): v for k, v in (err.headers or {}).items()} |
| 255 | + |
| 256 | + |
| 257 | +def probe(secret: str, facts: dict, timeout: float = _TIMEOUT) -> dict: |
| 258 | + """Ask the provider whether the credential still works. Read only. |
| 259 | +
|
| 260 | + -> {azure_live: True|False|None, azure_status, azure_detail}. None means |
| 261 | + the check could not decide, which is not the same as dead. |
| 262 | + """ |
| 263 | + out = {"azure_live": None, "azure_status": None, "azure_detail": ""} |
| 264 | + url, method = facts.get("_probe_url") or "", facts.get("_probe_method") or "" |
| 265 | + if not url: |
| 266 | + out["azure_detail"] = "no resource to probe" |
| 267 | + return out |
| 268 | + token = secret if facts.get("_bearer") else "" |
| 269 | + try: |
| 270 | + status, headers = _http(method, url, token, timeout) |
| 271 | + except ValueError as err: |
| 272 | + out["azure_detail"] = str(err) |
| 273 | + return out |
| 274 | + except (urllib.error.URLError, socket.timeout, OSError) as err: |
| 275 | + out["azure_detail"] = "could not reach the provider: %s" % ( |
| 276 | + getattr(err, "reason", err),) |
| 277 | + return out |
| 278 | + out["azure_status"] = status |
| 279 | + if facts.get("azure_kind") == "entra_token": |
| 280 | + if status in (200, 403): |
| 281 | + # 403 is a valid token the tenant accepted but without the scope |
| 282 | + # for this read. Still a live credential. |
| 283 | + out["azure_live"] = True |
| 284 | + out["azure_detail"] = ("accepted by the provider" |
| 285 | + if status == 200 else |
| 286 | + "accepted, lacks scope for this read") |
| 287 | + elif status == 401: |
| 288 | + out["azure_live"] = False |
| 289 | + out["azure_detail"] = "the provider rejected the token" |
| 290 | + else: |
| 291 | + out["azure_detail"] = "inconclusive status %s" % status |
| 292 | + else: # sas |
| 293 | + code = (headers.get("x-ms-error-code") or "").strip() |
| 294 | + if status in (200, 206): |
| 295 | + out["azure_live"] = True |
| 296 | + out["azure_detail"] = "the signature was honored" |
| 297 | + elif status == 403 and code in ("AuthenticationFailed", |
| 298 | + "AuthorizationFailure", |
| 299 | + "AuthenticationFailedSignatureDidNotMatch"): |
| 300 | + out["azure_live"] = False |
| 301 | + out["azure_detail"] = "the signature was refused (%s)" % code |
| 302 | + else: |
| 303 | + out["azure_detail"] = "inconclusive status %s%s" % ( |
| 304 | + status, " %s" % code if code else "") |
| 305 | + return out |
| 306 | + |
| 307 | + |
| 308 | +# ---------------------------------------------------------------- public API |
| 309 | + |
| 310 | +def verify(secret: str, do_probe: bool = False, timeout: float = _TIMEOUT) -> dict: |
| 311 | + """Offline facts, then a live probe when asked, folded into one result. |
| 312 | +
|
| 313 | + Fields the secrets pass merges onto the finding: |
| 314 | + azure_kind, azure_expired, azure_expires_at, azure_resource, azure_live, |
| 315 | + azure_status, azure_detail. |
| 316 | + verification_attempted true when a live probe actually ran. |
| 317 | + verified true only when a provider confirmed it live. |
| 318 | + verification_error the reason it is not a confirmed live credential. |
| 319 | + """ |
| 320 | + facts = inspect(secret) |
| 321 | + kind = facts["azure_kind"] |
| 322 | + result = {k: facts[k] for k in ("azure_kind", "azure_expired", |
| 323 | + "azure_expires_at", "azure_resource")} |
| 324 | + if not kind: |
| 325 | + return {} # nothing to say; caller merges nothing |
| 326 | + result["verification_attempted"] = False |
| 327 | + if do_probe and facts.get("_probe_url") and facts.get("azure_expired") is not True: |
| 328 | + # No point spending a request on a token we can already read as expired. |
| 329 | + probed = probe(secret, facts, timeout) |
| 330 | + result.update(azure_live=probed["azure_live"], |
| 331 | + azure_status=probed["azure_status"], |
| 332 | + azure_detail=probed["azure_detail"]) |
| 333 | + result["verification_attempted"] = True |
| 334 | + if probed["azure_live"] is True: |
| 335 | + result["verified"] = True |
| 336 | + elif probed["azure_live"] is False: |
| 337 | + result["verification_error"] = "Azure verifier: %s" % probed["azure_detail"] |
| 338 | + else: |
| 339 | + result["verification_error"] = "Azure verifier: %s" % ( |
| 340 | + probed["azure_detail"] or "could not confirm") |
| 341 | + elif facts.get("azure_expired") is True: |
| 342 | + result["verification_error"] = ( |
| 343 | + "Azure verifier: token is past its own expiry (%s)" |
| 344 | + % (facts["azure_expires_at"] or "expired")) |
| 345 | + return result |
| 346 | + |
| 347 | + |
| 348 | +def main(argv) -> int: |
| 349 | + do_probe = "--probe" in argv |
| 350 | + timeout = _TIMEOUT |
| 351 | + if "--timeout" in argv: |
| 352 | + try: |
| 353 | + timeout = float(argv[argv.index("--timeout") + 1]) |
| 354 | + except (ValueError, IndexError): |
| 355 | + timeout = _TIMEOUT |
| 356 | + secret = sys.stdin.read().strip() |
| 357 | + try: |
| 358 | + out = verify(secret, do_probe=do_probe, timeout=timeout) |
| 359 | + except Exception: # never fail the scan over a verifier |
| 360 | + out = {} |
| 361 | + sys.stdout.write(json.dumps(out)) |
| 362 | + return 0 |
| 363 | + |
| 364 | + |
| 365 | +if __name__ == "__main__": |
| 366 | + sys.exit(main(sys.argv[1:])) |
0 commit comments