wiaudit 0.1.7__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- wiaudit/__init__.py +7 -0
- wiaudit/azure_snapshot.py +115 -0
- wiaudit/cli.py +258 -0
- wiaudit/collectors.py +300 -0
- wiaudit/doctor.py +248 -0
- wiaudit/github_workflows.py +175 -0
- wiaudit/mcp_server.py +123 -0
- wiaudit/models.py +200 -0
- wiaudit/report/__init__.py +49 -0
- wiaudit/report/html.py +92 -0
- wiaudit/report/sarif.py +67 -0
- wiaudit/report/text.py +43 -0
- wiaudit/rules/__init__.py +23 -0
- wiaudit/rules/identity_rules.py +307 -0
- wiaudit/rules/workflow_rules.py +92 -0
- wiaudit/subjects.py +213 -0
- wiaudit-0.1.7.dist-info/METADATA +152 -0
- wiaudit-0.1.7.dist-info/RECORD +22 -0
- wiaudit-0.1.7.dist-info/WHEEL +5 -0
- wiaudit-0.1.7.dist-info/entry_points.txt +3 -0
- wiaudit-0.1.7.dist-info/licenses/LICENSE +202 -0
- wiaudit-0.1.7.dist-info/top_level.txt +1 -0
wiaudit/__init__.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Load and save the Azure snapshot (our own JSON format, produced by `wiaudit collect azure`).
|
|
2
|
+
|
|
3
|
+
Format (version 1):
|
|
4
|
+
{
|
|
5
|
+
"version": 1,
|
|
6
|
+
"tenantId": "...",
|
|
7
|
+
"collectedAt": "2026-11-22T10:00:00Z",
|
|
8
|
+
"identities": [
|
|
9
|
+
{
|
|
10
|
+
"kind": "app" | "managedIdentity",
|
|
11
|
+
"displayName": "...",
|
|
12
|
+
"clientId": "...", # appId for apps
|
|
13
|
+
"objectId": "...", # service principal / MI principal id
|
|
14
|
+
"resourceId": "...", # MI only
|
|
15
|
+
"federatedCredentials": [
|
|
16
|
+
{"name": "...", "issuer": "...", "subject": "..." | null,
|
|
17
|
+
"audiences": ["api://AzureADTokenExchange"],
|
|
18
|
+
"claimsMatchingExpression": "..." | null}
|
|
19
|
+
],
|
|
20
|
+
"roleAssignments": [{"role": "Contributor", "scope": "/subscriptions/..."}]
|
|
21
|
+
}
|
|
22
|
+
]
|
|
23
|
+
}
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import json
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import Any
|
|
31
|
+
|
|
32
|
+
from .models import AzureSnapshot, FederatedCredential, Identity, RepoInfo, RoleAssignment
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _expr_value(raw: Any) -> str | None:
|
|
36
|
+
if raw is None:
|
|
37
|
+
return None
|
|
38
|
+
if isinstance(raw, dict): # Graph returns {"value": "...", "languageVersion": 1}
|
|
39
|
+
return raw.get("value")
|
|
40
|
+
return str(raw)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def snapshot_from_dict(data: dict[str, Any]) -> AzureSnapshot:
|
|
44
|
+
identities = []
|
|
45
|
+
for raw in data.get("identities", []):
|
|
46
|
+
identities.append(
|
|
47
|
+
Identity(
|
|
48
|
+
kind=raw.get("kind", "app"),
|
|
49
|
+
display_name=raw.get("displayName") or raw.get("name") or "?",
|
|
50
|
+
client_id=raw.get("clientId") or raw.get("appId") or "?",
|
|
51
|
+
object_id=raw.get("objectId"),
|
|
52
|
+
resource_id=raw.get("resourceId"),
|
|
53
|
+
federated_credentials=[
|
|
54
|
+
FederatedCredential(
|
|
55
|
+
name=f.get("name", "?"),
|
|
56
|
+
issuer=f.get("issuer", ""),
|
|
57
|
+
subject=f.get("subject"),
|
|
58
|
+
audiences=list(f.get("audiences") or []),
|
|
59
|
+
claims_matching_expression=_expr_value(f.get("claimsMatchingExpression")),
|
|
60
|
+
)
|
|
61
|
+
for f in raw.get("federatedCredentials", [])
|
|
62
|
+
],
|
|
63
|
+
role_assignments=[
|
|
64
|
+
RoleAssignment(
|
|
65
|
+
role=r.get("role") or r.get("roleDefinitionName") or "?",
|
|
66
|
+
scope=r.get("scope", ""),
|
|
67
|
+
)
|
|
68
|
+
for r in raw.get("roleAssignments", [])
|
|
69
|
+
],
|
|
70
|
+
)
|
|
71
|
+
)
|
|
72
|
+
return AzureSnapshot(
|
|
73
|
+
tenant_id=data.get("tenantId"),
|
|
74
|
+
identities=identities,
|
|
75
|
+
collected_at=data.get("collectedAt"),
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def load_snapshot(path: str | Path) -> AzureSnapshot:
|
|
80
|
+
with open(path, encoding="utf-8") as fh:
|
|
81
|
+
return snapshot_from_dict(json.load(fh))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def save_json(data: dict[str, Any] | list[Any], path: str | Path) -> None:
|
|
85
|
+
Path(path).write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def load_repo_inventory(path: str | Path) -> dict[str, RepoInfo]:
|
|
89
|
+
"""repos.json produced by `wiaudit collect github` (or written by hand).
|
|
90
|
+
|
|
91
|
+
[{"fullName": "org/repo", "ownerId": "123", "repoId": "456",
|
|
92
|
+
"createdAt": "2026-08-01T..", "usesImmutable": null, "exists": true}]
|
|
93
|
+
"""
|
|
94
|
+
with open(path, encoding="utf-8") as fh:
|
|
95
|
+
raw = json.load(fh)
|
|
96
|
+
out: dict[str, RepoInfo] = {}
|
|
97
|
+
for r in raw:
|
|
98
|
+
if r.get("exists") is False:
|
|
99
|
+
continue
|
|
100
|
+
info = RepoInfo(
|
|
101
|
+
full_name=r["fullName"],
|
|
102
|
+
owner_id=str(r["ownerId"]) if r.get("ownerId") is not None else None,
|
|
103
|
+
repo_id=str(r["repoId"]) if r.get("repoId") is not None else None,
|
|
104
|
+
created_at=r.get("createdAt"),
|
|
105
|
+
uses_immutable=r.get("usesImmutable"),
|
|
106
|
+
owner_type=r.get("ownerType"),
|
|
107
|
+
)
|
|
108
|
+
out[info.full_name.lower()] = info
|
|
109
|
+
return out
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def load_missing_repos(path: str | Path) -> set[str]:
|
|
113
|
+
with open(path, encoding="utf-8") as fh:
|
|
114
|
+
raw = json.load(fh)
|
|
115
|
+
return {r["fullName"].lower() for r in raw if r.get("exists") is False}
|
wiaudit/cli.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""Command line interface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .azure_snapshot import load_missing_repos, load_repo_inventory, load_snapshot, save_json
|
|
12
|
+
from .collectors import CollectorError, collect_azure, collect_github, repos_referenced_by_snapshot
|
|
13
|
+
from .doctor import diagnose
|
|
14
|
+
from .github_workflows import detect_repo_slug, load_workflows
|
|
15
|
+
from .models import AzureSnapshot, RepoInfo, Severity
|
|
16
|
+
from .report import render
|
|
17
|
+
from .rules import RULES
|
|
18
|
+
from .rules.identity_rules import run_identity_rules
|
|
19
|
+
from .rules.workflow_rules import run_workflow_rules
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _inventory(path: str | None):
|
|
23
|
+
if not path:
|
|
24
|
+
return {}, set(), {}
|
|
25
|
+
import json
|
|
26
|
+
|
|
27
|
+
inv = load_repo_inventory(path)
|
|
28
|
+
missing = load_missing_repos(path)
|
|
29
|
+
renamed = {}
|
|
30
|
+
for r in json.loads(Path(path).read_text(encoding="utf-8")):
|
|
31
|
+
if r.get("renamedFrom"):
|
|
32
|
+
renamed[r["renamedFrom"].lower()] = r["fullName"]
|
|
33
|
+
return inv, missing, renamed
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _repo_info(repo_path: str, slug: str | None, inventory: dict[str, RepoInfo]) -> RepoInfo | None:
|
|
37
|
+
slug = slug or detect_repo_slug(repo_path)
|
|
38
|
+
if not slug:
|
|
39
|
+
return None
|
|
40
|
+
return inventory.get(slug.lower()) or RepoInfo(full_name=slug)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def cmd_scan(args: argparse.Namespace) -> int:
|
|
44
|
+
findings = []
|
|
45
|
+
errors: list[str] = []
|
|
46
|
+
snapshot: AzureSnapshot | None = load_snapshot(args.azure) if args.azure else None
|
|
47
|
+
inventory, missing, renamed = _inventory(args.github)
|
|
48
|
+
all_workflows = []
|
|
49
|
+
|
|
50
|
+
if snapshot:
|
|
51
|
+
allowed = {o.strip() for o in args.allowed_owners.split(',') if o.strip()} if args.allowed_owners else None
|
|
52
|
+
findings += run_identity_rules(snapshot, inventory, missing, renamed, allowed)
|
|
53
|
+
|
|
54
|
+
for repo_path in args.repo or []:
|
|
55
|
+
workflows, errs = load_workflows(repo_path)
|
|
56
|
+
errors += errs
|
|
57
|
+
all_workflows += workflows
|
|
58
|
+
findings += run_workflow_rules(workflows)
|
|
59
|
+
if snapshot and workflows:
|
|
60
|
+
repo = _repo_info(repo_path, args.repo_slug if len(args.repo) == 1 else None, inventory)
|
|
61
|
+
if repo:
|
|
62
|
+
_diag, doc_findings = diagnose(workflows, snapshot, repo)
|
|
63
|
+
findings += doc_findings
|
|
64
|
+
else:
|
|
65
|
+
errors.append(f"{repo_path}: could not detect owner/repo; pass --repo-slug to enable the doctor checks")
|
|
66
|
+
|
|
67
|
+
threshold = Severity.parse(args.min_severity)
|
|
68
|
+
findings = [f for f in findings if f.severity >= threshold]
|
|
69
|
+
meta = {
|
|
70
|
+
"version": __version__,
|
|
71
|
+
"tenantId": snapshot.tenant_id if snapshot else None,
|
|
72
|
+
"identities": len(snapshot.identities) if snapshot else 0,
|
|
73
|
+
"workflows": len(all_workflows),
|
|
74
|
+
"generatedAt": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"),
|
|
75
|
+
"firstWorkflow": all_workflows[0].path if all_workflows else None,
|
|
76
|
+
"errors": errors,
|
|
77
|
+
}
|
|
78
|
+
out = render(args.format, findings, meta)
|
|
79
|
+
if args.output:
|
|
80
|
+
Path(args.output).write_text(out, encoding="utf-8")
|
|
81
|
+
print(f"report written to {args.output}", file=sys.stderr)
|
|
82
|
+
else:
|
|
83
|
+
print(out)
|
|
84
|
+
if args.fail_on and any(f.severity >= Severity.parse(args.fail_on) for f in findings):
|
|
85
|
+
return 2
|
|
86
|
+
return 0
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def cmd_doctor(args: argparse.Namespace) -> int:
|
|
90
|
+
snapshot = load_snapshot(args.azure)
|
|
91
|
+
inventory, _missing, _renamed = _inventory(args.github)
|
|
92
|
+
workflows, errs = load_workflows(args.repo)
|
|
93
|
+
repo = _repo_info(args.repo, args.repo_slug, inventory)
|
|
94
|
+
if not repo:
|
|
95
|
+
print("Could not detect owner/repo from git remote. Pass --repo-slug owner/repo.", file=sys.stderr)
|
|
96
|
+
return 1
|
|
97
|
+
diags, _ = diagnose(workflows, snapshot, repo)
|
|
98
|
+
if not diags:
|
|
99
|
+
print("No jobs using azure/login with OIDC were found.")
|
|
100
|
+
icon = {
|
|
101
|
+
"ok": "OK ",
|
|
102
|
+
"ok-unverified": "OK? ",
|
|
103
|
+
"partial": "PART",
|
|
104
|
+
"no-match": "FAIL",
|
|
105
|
+
"no-permission": "FAIL",
|
|
106
|
+
"unknown-identity": "????",
|
|
107
|
+
}
|
|
108
|
+
bad = 0
|
|
109
|
+
for d in diags:
|
|
110
|
+
print(f"[{icon[d.status]}] {d.workflow} -> job '{d.job}'")
|
|
111
|
+
ids = (d.identity or "-").split(", ")
|
|
112
|
+
shown = ", ".join(ids[:2]) + (f" (+{len(ids) - 2} more)" if len(ids) > 2 else "")
|
|
113
|
+
print(f" identity: {shown}")
|
|
114
|
+
for s in d.matched:
|
|
115
|
+
print(f" accepted: {s}")
|
|
116
|
+
for s in d.unmatched:
|
|
117
|
+
print(f" REJECTED: {s}")
|
|
118
|
+
for c in d.closest:
|
|
119
|
+
print(f" closest credential subject: {c}")
|
|
120
|
+
for h in d.hints:
|
|
121
|
+
print(f" hint: {h}")
|
|
122
|
+
print()
|
|
123
|
+
bad += d.status not in ("ok", "ok-unverified")
|
|
124
|
+
for e in errs:
|
|
125
|
+
print(f"warning: {e}", file=sys.stderr)
|
|
126
|
+
return 2 if bad else 0
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def cmd_collect_azure(args: argparse.Namespace) -> int:
|
|
130
|
+
try:
|
|
131
|
+
data = collect_azure(
|
|
132
|
+
subscriptions=args.subscription,
|
|
133
|
+
all_subscriptions=args.all_subscriptions,
|
|
134
|
+
app_name_prefix=args.app_prefix,
|
|
135
|
+
include_apps=not args.no_apps,
|
|
136
|
+
all_issuers=args.all_issuers,
|
|
137
|
+
include_managed_identities=not args.no_managed_identities,
|
|
138
|
+
)
|
|
139
|
+
except CollectorError as exc:
|
|
140
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
141
|
+
return 1
|
|
142
|
+
except KeyboardInterrupt:
|
|
143
|
+
print("\ninterrupted", file=sys.stderr)
|
|
144
|
+
return 130
|
|
145
|
+
save_json(data, args.output)
|
|
146
|
+
print(f"{len(data['identities'])} identities with federated credentials written to {args.output}", file=sys.stderr)
|
|
147
|
+
if data.get("warnings"):
|
|
148
|
+
print(f"{len(data['warnings'])} warning(s): some data is missing (see 'warnings' in the file); rerun later to complete it", file=sys.stderr)
|
|
149
|
+
return 0
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def cmd_collect_github(args: argparse.Namespace) -> int:
|
|
153
|
+
import json
|
|
154
|
+
|
|
155
|
+
repos = list(args.repo or [])
|
|
156
|
+
if args.from_azure:
|
|
157
|
+
repos += repos_referenced_by_snapshot(json.loads(Path(args.from_azure).read_text(encoding="utf-8")))
|
|
158
|
+
repos = sorted(set(repos))
|
|
159
|
+
if not repos:
|
|
160
|
+
print("Nothing to collect: pass --repo owner/repo or --from-azure snapshot.json", file=sys.stderr)
|
|
161
|
+
return 1
|
|
162
|
+
try:
|
|
163
|
+
data = collect_github(repos)
|
|
164
|
+
except CollectorError as exc:
|
|
165
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
166
|
+
return 1
|
|
167
|
+
except KeyboardInterrupt:
|
|
168
|
+
print("\ninterrupted", file=sys.stderr)
|
|
169
|
+
return 130
|
|
170
|
+
save_json(data, args.output)
|
|
171
|
+
gone = sum(1 for r in data if r.get("exists") is False)
|
|
172
|
+
print(f"{len(data)} repos written to {args.output} ({gone} not found)", file=sys.stderr)
|
|
173
|
+
return 0
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def cmd_rules(_args: argparse.Namespace) -> int:
|
|
177
|
+
for rid, title in RULES.items():
|
|
178
|
+
print(f"{rid} {title}")
|
|
179
|
+
return 0
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
183
|
+
p = argparse.ArgumentParser(
|
|
184
|
+
prog="wiaudit",
|
|
185
|
+
description="Workload Identity Auditor - read-only audit of OIDC trust between GitHub Actions and Azure.",
|
|
186
|
+
)
|
|
187
|
+
p.add_argument("--version", action="version", version=f"wiaudit {__version__}")
|
|
188
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
189
|
+
|
|
190
|
+
s = sub.add_parser("scan", help="run all rules and produce a report")
|
|
191
|
+
s.add_argument("--azure", help="Azure snapshot JSON from `wiaudit collect azure`")
|
|
192
|
+
s.add_argument("--repo", action="append", help="path to a local git repo (repeatable)")
|
|
193
|
+
s.add_argument("--repo-slug", help="owner/repo when it cannot be read from the git remote")
|
|
194
|
+
s.add_argument("--github", help="repos.json from `wiaudit collect github` (IDs, renames, deleted repos)")
|
|
195
|
+
s.add_argument("--format", choices=["text", "json", "sarif", "html"], default="text")
|
|
196
|
+
s.add_argument("--output", "-o", help="write the report to a file")
|
|
197
|
+
s.add_argument("--min-severity", default="info", choices=[x.label for x in Severity])
|
|
198
|
+
s.add_argument(
|
|
199
|
+
"--allowed-owners",
|
|
200
|
+
help="comma-separated GitHub orgs/users you trust; credentials for other owners are flagged (WIA010)",
|
|
201
|
+
)
|
|
202
|
+
s.add_argument("--fail-on", choices=[x.label for x in Severity], help="exit 2 if a finding at this level or above exists")
|
|
203
|
+
s.set_defaults(func=cmd_scan)
|
|
204
|
+
|
|
205
|
+
d = sub.add_parser("doctor", help="explain why a workflow does (not) get an Azure token")
|
|
206
|
+
d.add_argument("--azure", required=True)
|
|
207
|
+
d.add_argument("--repo", default=".")
|
|
208
|
+
d.add_argument("--repo-slug")
|
|
209
|
+
d.add_argument("--github")
|
|
210
|
+
d.set_defaults(func=cmd_doctor)
|
|
211
|
+
|
|
212
|
+
c = sub.add_parser("collect", help="read-only collection using your az / gh login")
|
|
213
|
+
csub = c.add_subparsers(dest="source", required=True)
|
|
214
|
+
ca = csub.add_parser("azure", help="apps and managed identities with federated credentials, plus role assignments")
|
|
215
|
+
ca.add_argument("--subscription", action="append", help="subscription id (repeatable; default: current)")
|
|
216
|
+
ca.add_argument("--all-subscriptions", action="store_true")
|
|
217
|
+
ca.add_argument("--app-prefix", help="only app registrations whose name starts with this")
|
|
218
|
+
ca.add_argument("--no-apps", action="store_true")
|
|
219
|
+
ca.add_argument(
|
|
220
|
+
"--all-issuers",
|
|
221
|
+
action="store_true",
|
|
222
|
+
help="inspect every app registration, not only those trusting GitHub (slow in large tenants; enables WIA009)",
|
|
223
|
+
)
|
|
224
|
+
ca.add_argument("--no-managed-identities", action="store_true")
|
|
225
|
+
ca.add_argument("--output", "-o", default="azure-snapshot.json")
|
|
226
|
+
ca.set_defaults(func=cmd_collect_azure)
|
|
227
|
+
cg = csub.add_parser("github", help="repo IDs, renames and deleted repos via `gh api`")
|
|
228
|
+
cg.add_argument("--repo", action="append", help="owner/repo (repeatable)")
|
|
229
|
+
cg.add_argument("--from-azure", help="also collect every repo referenced by credentials in this snapshot")
|
|
230
|
+
cg.add_argument("--output", "-o", default="repos.json")
|
|
231
|
+
cg.set_defaults(func=cmd_collect_github)
|
|
232
|
+
|
|
233
|
+
r = sub.add_parser("rules", help="list rules")
|
|
234
|
+
r.set_defaults(func=cmd_rules)
|
|
235
|
+
return p
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def main(argv: list[str] | None = None) -> int:
|
|
239
|
+
args = build_parser().parse_args(argv)
|
|
240
|
+
try:
|
|
241
|
+
return args.func(args)
|
|
242
|
+
except FileNotFoundError as exc:
|
|
243
|
+
name = exc.filename or str(exc)
|
|
244
|
+
msg = f"error: file or folder not found: {name}"
|
|
245
|
+
if getattr(args, "azure", None) and str(name).endswith(str(args.azure)):
|
|
246
|
+
msg += "\nhint: create it first with `wiaudit collect azure -o " + str(args.azure) + "`"
|
|
247
|
+
print(msg, file=sys.stderr)
|
|
248
|
+
return 1
|
|
249
|
+
except CollectorError as exc:
|
|
250
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
251
|
+
return 1
|
|
252
|
+
except KeyboardInterrupt:
|
|
253
|
+
print("\ninterrupted", file=sys.stderr)
|
|
254
|
+
return 130
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
if __name__ == "__main__":
|
|
258
|
+
sys.exit(main())
|
wiaudit/collectors.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
"""Read-only collectors that shell out to the official CLIs (az, gh).
|
|
2
|
+
|
|
3
|
+
Nothing here writes to Azure or GitHub. Every call is a GET / list.
|
|
4
|
+
The user's own login is used; credentials never pass through wiaudit.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import shutil
|
|
12
|
+
import subprocess
|
|
13
|
+
import sys
|
|
14
|
+
import time
|
|
15
|
+
from datetime import datetime, timezone
|
|
16
|
+
from typing import Any, Callable
|
|
17
|
+
|
|
18
|
+
from .models import GITHUB_ISSUER
|
|
19
|
+
from .subjects import flexible_sub_patterns, parse_subject
|
|
20
|
+
|
|
21
|
+
Runner = Callable[[list[str]], Any]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class CollectorError(RuntimeError):
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _resolve_command(args: list[str]) -> list[str]:
|
|
29
|
+
"""Return the argv to execute.
|
|
30
|
+
|
|
31
|
+
On Windows `az` is a batch file (az.cmd). Running it sends every argument through
|
|
32
|
+
cmd.exe, which treats `&` in Graph URLs (`?$select=...&$top=999`) as a command
|
|
33
|
+
separator. So we call the Python that ships with Azure CLI directly, exactly as
|
|
34
|
+
az.cmd itself does (`python.exe -IBm azure.cli ...`), and no shell is involved.
|
|
35
|
+
"""
|
|
36
|
+
exe = shutil.which(args[0])
|
|
37
|
+
if not exe:
|
|
38
|
+
raise CollectorError(f"'{args[0]}' not found on PATH. Install it and log in first.")
|
|
39
|
+
if os.name == "nt" and exe.lower().endswith((".cmd", ".bat")):
|
|
40
|
+
if args[0] == "az":
|
|
41
|
+
cli_root = os.path.dirname(os.path.dirname(exe)) # ...\CLI2\wbin\az.cmd -> ...\CLI2
|
|
42
|
+
bundled = os.path.join(cli_root, "python.exe")
|
|
43
|
+
if os.path.isfile(bundled):
|
|
44
|
+
return [bundled, "-IBm", "azure.cli", *args[1:]]
|
|
45
|
+
if any(ch in a for a in args[1:] for ch in "&|<>^%"):
|
|
46
|
+
raise CollectorError(
|
|
47
|
+
f"{exe} is a batch file and an argument contains characters cmd.exe would misread. "
|
|
48
|
+
"Please report this at https://github.com/wiaudit/wiaudit/issues"
|
|
49
|
+
)
|
|
50
|
+
return [exe, *args[1:]]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
RETRIES = 3
|
|
54
|
+
RETRY_DELAYS = (3, 10)
|
|
55
|
+
_TRANSIENT = (
|
|
56
|
+
"connection aborted", "connectionreset", "10054", "timed out", "timeout",
|
|
57
|
+
"too many requests", "429", "502", "503", "504", "temporarily unavailable", "remote end closed",
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _is_transient(err: str) -> bool:
|
|
62
|
+
e = err.lower()
|
|
63
|
+
return any(t in e for t in _TRANSIENT)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _default_runner(args: list[str]) -> Any:
|
|
67
|
+
argv = _resolve_command(args)
|
|
68
|
+
label = " ".join(args[:4])
|
|
69
|
+
for attempt in range(1, RETRIES + 1):
|
|
70
|
+
try:
|
|
71
|
+
proc = subprocess.run(argv, capture_output=True, text=True, timeout=300)
|
|
72
|
+
except subprocess.TimeoutExpired:
|
|
73
|
+
err = "timed out after 300 s"
|
|
74
|
+
else:
|
|
75
|
+
if proc.returncode == 0:
|
|
76
|
+
break
|
|
77
|
+
err = proc.stderr.strip()
|
|
78
|
+
if attempt < RETRIES and _is_transient(err):
|
|
79
|
+
_log(f"[retry] {label}... attempt {attempt} failed ({err[:80]}); retrying")
|
|
80
|
+
time.sleep(RETRY_DELAYS[attempt - 1])
|
|
81
|
+
continue
|
|
82
|
+
raise CollectorError(f"{label}... failed: {err[:500]}")
|
|
83
|
+
out = proc.stdout.strip()
|
|
84
|
+
return json.loads(out) if out else None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _log(msg: str) -> None:
|
|
88
|
+
print(msg, file=sys.stderr)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# --------------------------------------------------------------------- Azure
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _graph_get_all(run: Runner, url: str, advanced: bool = False) -> list[dict[str, Any]]:
|
|
95
|
+
"""GET all pages. advanced=True adds ConsistencyLevel: eventual (Graph advanced queries)."""
|
|
96
|
+
items: list[dict[str, Any]] = []
|
|
97
|
+
extra = ["--headers", "ConsistencyLevel=eventual"] if advanced else []
|
|
98
|
+
while url:
|
|
99
|
+
page = run(["az", "rest", "--method", "GET", "--url", url, *extra, "-o", "json"]) or {}
|
|
100
|
+
items.extend(page.get("value", []))
|
|
101
|
+
url = page.get("@odata.nextLink")
|
|
102
|
+
return items
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
GRAPH = "https://graph.microsoft.com/v1.0"
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _list_apps(run: Runner, all_issuers: bool) -> list[dict[str, Any]]:
|
|
109
|
+
"""Apps to inspect. By default only apps that trust the GitHub issuer, filtered server-side,
|
|
110
|
+
so large tenants (thousands of apps) take seconds instead of hours."""
|
|
111
|
+
select = "$select=id,appId,displayName&$top=999"
|
|
112
|
+
if not all_issuers:
|
|
113
|
+
flt = f"federatedIdentityCredentials/any(f:f/issuer eq '{GITHUB_ISSUER}')".replace(" ", "%20")
|
|
114
|
+
_log("[azure] app registrations trusting GitHub Actions (Microsoft Graph)")
|
|
115
|
+
try:
|
|
116
|
+
return _graph_get_all(run, f"{GRAPH}/applications?$filter={flt}&$count=true&{select}", advanced=True)
|
|
117
|
+
except CollectorError as exc:
|
|
118
|
+
_log(f"[azure] filtered query not available ({str(exc)[:120]}); falling back to listing all apps")
|
|
119
|
+
_log("[azure] all app registrations (Microsoft Graph) - this can take long in large tenants")
|
|
120
|
+
return _graph_get_all(run, f"{GRAPH}/applications?{select}")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def collect_azure(
|
|
124
|
+
subscriptions: list[str] | None = None,
|
|
125
|
+
all_subscriptions: bool = False,
|
|
126
|
+
app_name_prefix: str | None = None,
|
|
127
|
+
include_apps: bool = True,
|
|
128
|
+
include_managed_identities: bool = True,
|
|
129
|
+
all_issuers: bool = False,
|
|
130
|
+
run: Runner = _default_runner,
|
|
131
|
+
) -> dict[str, Any]:
|
|
132
|
+
account = run(["az", "account", "show", "-o", "json"]) or {}
|
|
133
|
+
tenant_id = account.get("tenantId")
|
|
134
|
+
if all_subscriptions:
|
|
135
|
+
subs = [s["id"] for s in run(["az", "account", "list", "-o", "json"]) or [] if s.get("tenantId") == tenant_id]
|
|
136
|
+
else:
|
|
137
|
+
subs = subscriptions or [account.get("id")]
|
|
138
|
+
subs = [s for s in subs if s]
|
|
139
|
+
|
|
140
|
+
identities: list[dict[str, Any]] = []
|
|
141
|
+
|
|
142
|
+
if include_managed_identities:
|
|
143
|
+
for sub in subs:
|
|
144
|
+
_log(f"[azure] managed identities in subscription {sub}")
|
|
145
|
+
for mi in run(["az", "identity", "list", "--subscription", sub, "-o", "json"]) or []:
|
|
146
|
+
fics = run(
|
|
147
|
+
[
|
|
148
|
+
"az", "identity", "federated-credential", "list",
|
|
149
|
+
"--identity-name", mi["name"],
|
|
150
|
+
"--resource-group", mi["resourceGroup"],
|
|
151
|
+
"--subscription", sub, "-o", "json",
|
|
152
|
+
]
|
|
153
|
+
) or []
|
|
154
|
+
if not fics:
|
|
155
|
+
continue
|
|
156
|
+
identities.append(
|
|
157
|
+
{
|
|
158
|
+
"kind": "managedIdentity",
|
|
159
|
+
"displayName": mi["name"],
|
|
160
|
+
"clientId": mi.get("clientId"),
|
|
161
|
+
"objectId": mi.get("principalId"),
|
|
162
|
+
"resourceId": mi.get("id"),
|
|
163
|
+
"federatedCredentials": [_fic(f) for f in fics],
|
|
164
|
+
}
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
if include_apps:
|
|
168
|
+
apps = _list_apps(run, all_issuers)
|
|
169
|
+
if app_name_prefix:
|
|
170
|
+
apps = [a for a in apps if (a.get("displayName") or "").startswith(app_name_prefix)]
|
|
171
|
+
_log(f"[azure] {len(apps)} app registrations to inspect")
|
|
172
|
+
for i, app in enumerate(apps, 1):
|
|
173
|
+
if i % 25 == 0 or i == len(apps):
|
|
174
|
+
_log(f"[azure] {i}/{len(apps)}")
|
|
175
|
+
try: # beta exposes claimsMatchingExpression (flexible credentials)
|
|
176
|
+
fics = _graph_get_all(
|
|
177
|
+
run, f"https://graph.microsoft.com/beta/applications/{app['id']}/federatedIdentityCredentials"
|
|
178
|
+
)
|
|
179
|
+
except CollectorError:
|
|
180
|
+
fics = _graph_get_all(
|
|
181
|
+
run, f"https://graph.microsoft.com/v1.0/applications/{app['id']}/federatedIdentityCredentials"
|
|
182
|
+
)
|
|
183
|
+
if not fics:
|
|
184
|
+
continue
|
|
185
|
+
sp = None
|
|
186
|
+
try:
|
|
187
|
+
sp = run(
|
|
188
|
+
[
|
|
189
|
+
"az", "rest", "--method", "GET", "--url",
|
|
190
|
+
f"https://graph.microsoft.com/v1.0/servicePrincipals(appId='{app['appId']}')?$select=id",
|
|
191
|
+
"-o", "json",
|
|
192
|
+
]
|
|
193
|
+
)
|
|
194
|
+
except CollectorError:
|
|
195
|
+
pass
|
|
196
|
+
identities.append(
|
|
197
|
+
{
|
|
198
|
+
"kind": "app",
|
|
199
|
+
"displayName": app.get("displayName"),
|
|
200
|
+
"clientId": app.get("appId"),
|
|
201
|
+
"objectId": (sp or {}).get("id"),
|
|
202
|
+
"federatedCredentials": [_fic(f) for f in fics],
|
|
203
|
+
}
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
# Role assignments: ONE call per subscription (not per identity), matched locally by principalId.
|
|
207
|
+
by_principal = {i["objectId"]: i for i in identities if i.get("objectId")}
|
|
208
|
+
for ident in identities:
|
|
209
|
+
ident["roleAssignments"] = []
|
|
210
|
+
warnings: list[str] = []
|
|
211
|
+
if by_principal:
|
|
212
|
+
for sub in subs:
|
|
213
|
+
_log(f"[azure] role assignments in subscription {sub}")
|
|
214
|
+
try:
|
|
215
|
+
ras = run(
|
|
216
|
+
[
|
|
217
|
+
"az", "role", "assignment", "list",
|
|
218
|
+
"--all", "--include-inherited",
|
|
219
|
+
"--fill-principal-name", "false",
|
|
220
|
+
"--subscription", sub, "-o", "json",
|
|
221
|
+
]
|
|
222
|
+
) or []
|
|
223
|
+
except CollectorError as exc:
|
|
224
|
+
msg = f"role assignments for subscription {sub} skipped: {str(exc)[:200]}"
|
|
225
|
+
_log(f"[azure] warning: {msg}")
|
|
226
|
+
warnings.append(msg)
|
|
227
|
+
continue
|
|
228
|
+
for ra in ras:
|
|
229
|
+
ident = by_principal.get(ra.get("principalId"))
|
|
230
|
+
if not ident:
|
|
231
|
+
continue
|
|
232
|
+
entry = {"role": ra.get("roleDefinitionName"), "scope": ra.get("scope")}
|
|
233
|
+
if entry not in ident["roleAssignments"]:
|
|
234
|
+
ident["roleAssignments"].append(entry)
|
|
235
|
+
|
|
236
|
+
return {
|
|
237
|
+
"version": 1,
|
|
238
|
+
"tenantId": tenant_id,
|
|
239
|
+
"collectedAt": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
240
|
+
"subscriptions": subs,
|
|
241
|
+
"identities": identities,
|
|
242
|
+
"warnings": warnings,
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _fic(raw: dict[str, Any]) -> dict[str, Any]:
|
|
247
|
+
expr = raw.get("claimsMatchingExpression")
|
|
248
|
+
if isinstance(expr, dict):
|
|
249
|
+
expr = expr.get("value")
|
|
250
|
+
return {
|
|
251
|
+
"name": raw.get("name"),
|
|
252
|
+
"issuer": raw.get("issuer"),
|
|
253
|
+
"subject": raw.get("subject"),
|
|
254
|
+
"audiences": raw.get("audiences") or [],
|
|
255
|
+
"claimsMatchingExpression": expr,
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
# -------------------------------------------------------------------- GitHub
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def repos_referenced_by_snapshot(snapshot: dict[str, Any]) -> list[str]:
|
|
263
|
+
names: set[str] = set()
|
|
264
|
+
for ident in snapshot.get("identities", []):
|
|
265
|
+
for f in ident.get("federatedCredentials", []):
|
|
266
|
+
if (f.get("issuer") or "").rstrip("/") != GITHUB_ISSUER:
|
|
267
|
+
continue
|
|
268
|
+
subjects = [f.get("subject")] + [v for _op, v in flexible_sub_patterns(f.get("claimsMatchingExpression") or "")]
|
|
269
|
+
for s in subjects:
|
|
270
|
+
p = parse_subject(s)
|
|
271
|
+
if p and "*" not in p.full_name and "?" not in p.full_name:
|
|
272
|
+
names.add(p.full_name)
|
|
273
|
+
return sorted(names)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def collect_github(repos: list[str], run: Runner = _default_runner) -> list[dict[str, Any]]:
|
|
277
|
+
"""Fetch ids and creation dates; mark repos that no longer exist (dangling trust)."""
|
|
278
|
+
out = []
|
|
279
|
+
for full in repos:
|
|
280
|
+
_log(f"[github] {full}")
|
|
281
|
+
try:
|
|
282
|
+
data = run(["gh", "api", f"repos/{full}"]) or {}
|
|
283
|
+
except CollectorError as exc:
|
|
284
|
+
if "404" in str(exc) or "Not Found" in str(exc):
|
|
285
|
+
out.append({"fullName": full, "exists": False})
|
|
286
|
+
continue
|
|
287
|
+
raise
|
|
288
|
+
out.append(
|
|
289
|
+
{
|
|
290
|
+
"fullName": data.get("full_name", full),
|
|
291
|
+
"ownerId": (data.get("owner") or {}).get("id"),
|
|
292
|
+
"ownerType": (data.get("owner") or {}).get("type"),
|
|
293
|
+
"repoId": data.get("id"),
|
|
294
|
+
"createdAt": data.get("created_at"),
|
|
295
|
+
"usesImmutable": None,
|
|
296
|
+
"exists": True,
|
|
297
|
+
"renamedFrom": full if data.get("full_name", full).lower() != full.lower() else None,
|
|
298
|
+
}
|
|
299
|
+
)
|
|
300
|
+
return out
|