trproof 0.1.0__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.
- trproof/__init__.py +1 -0
- trproof/cli.py +342 -0
- trproof/collectors/__init__.py +30 -0
- trproof/collectors/ad.py +873 -0
- trproof/collectors/entra.py +762 -0
- trproof/graph/__init__.py +1 -0
- trproof/graph/edges.py +219 -0
- trproof/keys/default_ed25519_priv.pem +3 -0
- trproof/keys/default_ed25519_pub.pem +3 -0
- trproof/models.py +76 -0
- trproof/report/__init__.py +1 -0
- trproof/report/html.py +222 -0
- trproof/report/signing.py +121 -0
- trproof/scoring/__init__.py +1 -0
- trproof/scoring/engine.py +50 -0
- trproof-0.1.0.dist-info/METADATA +165 -0
- trproof-0.1.0.dist-info/RECORD +21 -0
- trproof-0.1.0.dist-info/WHEEL +5 -0
- trproof-0.1.0.dist-info/entry_points.txt +3 -0
- trproof-0.1.0.dist-info/licenses/LICENSE +21 -0
- trproof-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,762 @@
|
|
|
1
|
+
"""Read-only Microsoft Entra ID collector (Phase 3)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime as _dt
|
|
6
|
+
from typing import Any, Callable, Dict, Iterable, List, Optional, Set
|
|
7
|
+
|
|
8
|
+
import msal
|
|
9
|
+
import requests
|
|
10
|
+
|
|
11
|
+
from trproof.models import (
|
|
12
|
+
CollectionWarning,
|
|
13
|
+
Finding,
|
|
14
|
+
IdentityEdge,
|
|
15
|
+
PrincipalNode,
|
|
16
|
+
ScanBundle,
|
|
17
|
+
Severity,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
DEFAULT_CLIENT_ID = "04b07795-8ddb-461a-bbee-02f9e1bf7b46"
|
|
22
|
+
|
|
23
|
+
GRAPH_SCOPES = [
|
|
24
|
+
"User.Read.All",
|
|
25
|
+
"Directory.Read.All",
|
|
26
|
+
"Policy.Read.All",
|
|
27
|
+
"AuditLog.Read.All",
|
|
28
|
+
"Reports.Read.All",
|
|
29
|
+
"Application.Read.All",
|
|
30
|
+
"RoleManagement.Read.Directory",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
GRAPH_BASE = "https://graph.microsoft.com/v1.0"
|
|
34
|
+
GRAPH_BETA = "https://graph.microsoft.com/beta"
|
|
35
|
+
GRAPH_APP_ID = "00000003-0000-0000-c000-000000000000"
|
|
36
|
+
|
|
37
|
+
PRIVILEGED_ROLE_NAMES = [
|
|
38
|
+
"Global Administrator",
|
|
39
|
+
"Privileged Role Administrator",
|
|
40
|
+
"Security Administrator",
|
|
41
|
+
"Exchange Administrator",
|
|
42
|
+
"SharePoint Administrator",
|
|
43
|
+
"User Administrator",
|
|
44
|
+
"Cloud Application Administrator",
|
|
45
|
+
]
|
|
46
|
+
_PRIVILEGED_ROLE_LOOKUP = {name.lower() for name in PRIVILEGED_ROLE_NAMES}
|
|
47
|
+
|
|
48
|
+
PHISHING_RESISTANT_METHODS = {
|
|
49
|
+
"fido2",
|
|
50
|
+
"windowshelloforbusiness",
|
|
51
|
+
"microsoftauthenticatorpasswordless",
|
|
52
|
+
}
|
|
53
|
+
SMS_VOICE_METHODS = {"sms", "voicemobile", "voicealternatemobile"}
|
|
54
|
+
|
|
55
|
+
HIGH_RISK_GRAPH_PERMISSIONS = {
|
|
56
|
+
"mail.read": "Mail.Read",
|
|
57
|
+
"mail.readwrite": "Mail.ReadWrite",
|
|
58
|
+
"files.read.all": "Files.Read.All",
|
|
59
|
+
"files.readwrite.all": "Files.ReadWrite.All",
|
|
60
|
+
"rolemanagement.readwrite.directory": "RoleManagement.ReadWrite.Directory",
|
|
61
|
+
"directory.readwrite.all": "Directory.ReadWrite.All",
|
|
62
|
+
"application.readwrite.all": "Application.ReadWrite.All",
|
|
63
|
+
}
|
|
64
|
+
_CRITICAL_GRAPH_PERMISSIONS = {
|
|
65
|
+
"rolemanagement.readwrite.directory",
|
|
66
|
+
"directory.readwrite.all",
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
MICROSOFT_FIRST_PARTY_APP_IDS = {
|
|
70
|
+
GRAPH_APP_ID,
|
|
71
|
+
"00000002-0000-0000-c000-000000000000", # Azure AD Graph
|
|
72
|
+
"00000006-0000-0000-c000-000000000000", # Microsoft Intune
|
|
73
|
+
"0000000a-0000-0000-c000-000000000000", # Microsoft Intune
|
|
74
|
+
"797f4846-ba00-4fd7-ba43-dac1f8f63013", # Azure Service Management
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class GraphPermissionError(Exception):
|
|
79
|
+
"""Raised when Microsoft Graph returns HTTP 403 (Authorization_RequestDenied)."""
|
|
80
|
+
|
|
81
|
+
def __init__(self, url: str, message: str = "Authorization_RequestDenied") -> None:
|
|
82
|
+
super().__init__(f"{message}: {url}")
|
|
83
|
+
self.url = url
|
|
84
|
+
self.message = message
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _norm(value: Any) -> str:
|
|
88
|
+
return str(value or "").strip().lower()
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _as_list(value: Any) -> List[Any]:
|
|
92
|
+
if value is None:
|
|
93
|
+
return []
|
|
94
|
+
return list(value) if isinstance(value, (list, tuple, set)) else [value]
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _parse_datetime(value: Any) -> Optional[_dt.datetime]:
|
|
98
|
+
if not isinstance(value, str) or not value:
|
|
99
|
+
return None
|
|
100
|
+
text = value.strip()
|
|
101
|
+
if text.endswith("Z"):
|
|
102
|
+
text = text[:-1] + "+00:00"
|
|
103
|
+
try:
|
|
104
|
+
parsed = _dt.datetime.fromisoformat(text)
|
|
105
|
+
except ValueError:
|
|
106
|
+
return None
|
|
107
|
+
if parsed.tzinfo is None:
|
|
108
|
+
parsed = parsed.replace(tzinfo=_dt.timezone.utc)
|
|
109
|
+
return parsed
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class EntraCollector:
|
|
113
|
+
"""Collects read-only Entra ID posture data from Microsoft Graph."""
|
|
114
|
+
|
|
115
|
+
CHECK_LABELS = {
|
|
116
|
+
"_check_privileged_roles_and_mfa": "Privileged roles and MFA (_check_privileged_roles_and_mfa)",
|
|
117
|
+
"_check_legacy_auth_conditional_access": "Legacy authentication conditional access (_check_legacy_auth_conditional_access)",
|
|
118
|
+
"_check_stale_and_overprivileged_apps": "Stale and overprivileged apps (_check_stale_and_overprivileged_apps)",
|
|
119
|
+
"_check_privileged_guests": "Privileged guests (_check_privileged_guests)",
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
def __init__(
|
|
123
|
+
self,
|
|
124
|
+
tenant_id: str,
|
|
125
|
+
client_id: Optional[str] = None,
|
|
126
|
+
access_token: Optional[str] = None,
|
|
127
|
+
timeout: int = 15,
|
|
128
|
+
) -> None:
|
|
129
|
+
self.tenant_id = tenant_id
|
|
130
|
+
self.client_id = client_id or DEFAULT_CLIENT_ID
|
|
131
|
+
self.access_token = access_token
|
|
132
|
+
self.timeout = timeout
|
|
133
|
+
|
|
134
|
+
self.nodes: List[PrincipalNode] = []
|
|
135
|
+
self.edges: List[IdentityEdge] = []
|
|
136
|
+
self.findings: List[Finding] = []
|
|
137
|
+
self.warnings: List[CollectionWarning] = []
|
|
138
|
+
|
|
139
|
+
self._privileged_role_members: List[Dict[str, Any]] = []
|
|
140
|
+
self._privileged_roles_loaded = False
|
|
141
|
+
|
|
142
|
+
# ------------------------------------------------------------------ auth
|
|
143
|
+
|
|
144
|
+
def authenticate(self, message_callback: Callable[[str], None] | None = None) -> str:
|
|
145
|
+
"""Acquire a token with the MSAL device code flow, keeping it in RAM only."""
|
|
146
|
+
if self.access_token:
|
|
147
|
+
return self.access_token
|
|
148
|
+
|
|
149
|
+
app = msal.PublicClientApplication(
|
|
150
|
+
self.client_id,
|
|
151
|
+
authority=f"https://login.microsoftonline.com/{self.tenant_id}",
|
|
152
|
+
)
|
|
153
|
+
flow = app.initiate_device_flow(scopes=GRAPH_SCOPES)
|
|
154
|
+
message = ""
|
|
155
|
+
if isinstance(flow, dict):
|
|
156
|
+
message = flow.get("message") or ""
|
|
157
|
+
if message:
|
|
158
|
+
if message_callback is not None:
|
|
159
|
+
message_callback(message)
|
|
160
|
+
else:
|
|
161
|
+
print(message)
|
|
162
|
+
|
|
163
|
+
result = app.acquire_token_by_device_flow(flow)
|
|
164
|
+
token = result.get("access_token") if isinstance(result, dict) else None
|
|
165
|
+
if not token:
|
|
166
|
+
detail = ""
|
|
167
|
+
if isinstance(result, dict):
|
|
168
|
+
detail = result.get("error_description") or result.get("error") or ""
|
|
169
|
+
raise PermissionError(f"Entra authentication did not return an access token. {detail}".strip())
|
|
170
|
+
|
|
171
|
+
self.access_token = token
|
|
172
|
+
return token
|
|
173
|
+
|
|
174
|
+
# ----------------------------------------------------------------- graph
|
|
175
|
+
|
|
176
|
+
def _url(self, path: str) -> str:
|
|
177
|
+
if path.startswith("http://") or path.startswith("https://"):
|
|
178
|
+
return path
|
|
179
|
+
if not path.startswith("/"):
|
|
180
|
+
path = "/" + path
|
|
181
|
+
return GRAPH_BASE + path
|
|
182
|
+
|
|
183
|
+
def _graph_get_all(self, url: str) -> List[Dict[str, Any]]:
|
|
184
|
+
"""Perform GET-only pagination across a Microsoft Graph collection."""
|
|
185
|
+
token = self.access_token or self.authenticate()
|
|
186
|
+
headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"}
|
|
187
|
+
|
|
188
|
+
items: List[Dict[str, Any]] = []
|
|
189
|
+
next_url: Optional[str] = self._url(url)
|
|
190
|
+
seen: Set[str] = set()
|
|
191
|
+
|
|
192
|
+
while next_url and next_url not in seen:
|
|
193
|
+
seen.add(next_url)
|
|
194
|
+
response = requests.get(next_url, headers=headers, timeout=self.timeout)
|
|
195
|
+
|
|
196
|
+
status = getattr(response, "status_code", 200)
|
|
197
|
+
if isinstance(status, int):
|
|
198
|
+
if status == 403:
|
|
199
|
+
body = ""
|
|
200
|
+
try:
|
|
201
|
+
body = str(response.json())
|
|
202
|
+
except Exception:
|
|
203
|
+
body = ""
|
|
204
|
+
raise GraphPermissionError(
|
|
205
|
+
next_url,
|
|
206
|
+
"Authorization_RequestDenied" + (f" ({body})" if body else ""),
|
|
207
|
+
)
|
|
208
|
+
if status >= 400:
|
|
209
|
+
response.raise_for_status()
|
|
210
|
+
|
|
211
|
+
try:
|
|
212
|
+
payload = response.json()
|
|
213
|
+
except Exception:
|
|
214
|
+
payload = {}
|
|
215
|
+
|
|
216
|
+
page_items: List[Any] = []
|
|
217
|
+
next_link: Any = None
|
|
218
|
+
if isinstance(payload, list):
|
|
219
|
+
page_items = payload
|
|
220
|
+
elif isinstance(payload, dict):
|
|
221
|
+
page_items = _as_list(payload.get("value"))
|
|
222
|
+
next_link = payload.get("@odata.nextLink")
|
|
223
|
+
for item in page_items:
|
|
224
|
+
if isinstance(item, dict):
|
|
225
|
+
items.append(item)
|
|
226
|
+
|
|
227
|
+
next_url = next_link if isinstance(next_link, str) and next_link else None
|
|
228
|
+
|
|
229
|
+
return items
|
|
230
|
+
|
|
231
|
+
# --------------------------------------------------------------- helpers
|
|
232
|
+
|
|
233
|
+
def _add_node(self, node: PrincipalNode) -> None:
|
|
234
|
+
if not any(existing.id == node.id for existing in self.nodes):
|
|
235
|
+
self.nodes.append(node)
|
|
236
|
+
|
|
237
|
+
def _add_edge(self, edge: IdentityEdge) -> None:
|
|
238
|
+
duplicate = any(
|
|
239
|
+
e.source_id == edge.source_id
|
|
240
|
+
and e.target_id == edge.target_id
|
|
241
|
+
and e.relation == edge.relation
|
|
242
|
+
for e in self.edges
|
|
243
|
+
)
|
|
244
|
+
if not duplicate:
|
|
245
|
+
self.edges.append(edge)
|
|
246
|
+
|
|
247
|
+
def _load_privileged_roles(self) -> List[Dict[str, Any]]:
|
|
248
|
+
roles = self._graph_get_all(self._url("/directoryRoles?$expand=members"))
|
|
249
|
+
self._privileged_roles_loaded = True
|
|
250
|
+
for role in roles:
|
|
251
|
+
role_name = role.get("displayName") or role.get("display_name") or ""
|
|
252
|
+
if _norm(role_name) not in _PRIVILEGED_ROLE_LOOKUP:
|
|
253
|
+
continue
|
|
254
|
+
role_id = str(role.get("id") or role_name)
|
|
255
|
+
members = _as_list(role.get("members"))
|
|
256
|
+
for member in members:
|
|
257
|
+
if not isinstance(member, dict):
|
|
258
|
+
continue
|
|
259
|
+
self._privileged_role_members.append(
|
|
260
|
+
{"role_name": role_name, "role_id": role_id, "member": member}
|
|
261
|
+
)
|
|
262
|
+
return roles
|
|
263
|
+
|
|
264
|
+
@staticmethod
|
|
265
|
+
def _is_guest(member: Dict[str, Any]) -> bool:
|
|
266
|
+
upn = str(member.get("userPrincipalName") or "")
|
|
267
|
+
user_type = _norm(member.get("userType"))
|
|
268
|
+
return user_type == "guest" or "#ext#" in upn.lower()
|
|
269
|
+
|
|
270
|
+
@staticmethod
|
|
271
|
+
def _member_id(member: Dict[str, Any]) -> str:
|
|
272
|
+
return str(member.get("id") or member.get("userPrincipalName") or member.get("displayName") or "")
|
|
273
|
+
|
|
274
|
+
@staticmethod
|
|
275
|
+
def _member_name(member: Dict[str, Any]) -> str:
|
|
276
|
+
return str(
|
|
277
|
+
member.get("displayName")
|
|
278
|
+
or member.get("userPrincipalName")
|
|
279
|
+
or member.get("id")
|
|
280
|
+
or "unknown"
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
def _is_third_party(self, service_principal: Dict[str, Any]) -> bool:
|
|
284
|
+
app_id = _norm(service_principal.get("appId"))
|
|
285
|
+
if app_id in MICROSOFT_FIRST_PARTY_APP_IDS:
|
|
286
|
+
return False
|
|
287
|
+
owner = service_principal.get("appOwnerOrganizationId")
|
|
288
|
+
if owner and _norm(owner) == _norm(self.tenant_id):
|
|
289
|
+
return False
|
|
290
|
+
return True
|
|
291
|
+
|
|
292
|
+
@staticmethod
|
|
293
|
+
def _credential_is_expired_or_expiring(service_principal: Dict[str, Any]) -> bool:
|
|
294
|
+
now = _dt.datetime.now(_dt.timezone.utc)
|
|
295
|
+
soon = now + _dt.timedelta(days=30)
|
|
296
|
+
for key in ("passwordCredentials", "keyCredentials"):
|
|
297
|
+
for credential in _as_list(service_principal.get(key)):
|
|
298
|
+
if not isinstance(credential, dict):
|
|
299
|
+
continue
|
|
300
|
+
end = _parse_datetime(credential.get("endDateTime"))
|
|
301
|
+
if end is not None and end <= soon:
|
|
302
|
+
return True
|
|
303
|
+
return False
|
|
304
|
+
|
|
305
|
+
@staticmethod
|
|
306
|
+
def _is_stale(service_principal: Dict[str, Any]) -> bool:
|
|
307
|
+
now = _dt.datetime.now(_dt.timezone.utc)
|
|
308
|
+
cutoff = now - _dt.timedelta(days=90)
|
|
309
|
+
activity = service_principal.get("signInActivity") or {}
|
|
310
|
+
if isinstance(activity, dict):
|
|
311
|
+
last = _parse_datetime(
|
|
312
|
+
activity.get("lastSignInDateTime")
|
|
313
|
+
or activity.get("lastSuccessfulSignInDateTime")
|
|
314
|
+
)
|
|
315
|
+
if last is not None:
|
|
316
|
+
return last < cutoff
|
|
317
|
+
created = _parse_datetime(service_principal.get("createdDateTime"))
|
|
318
|
+
return created is not None and created < cutoff
|
|
319
|
+
|
|
320
|
+
# --------------------------------------------------------------- collect
|
|
321
|
+
|
|
322
|
+
def collect(self, progress_callback: Callable[[str], None] | None = None) -> ScanBundle:
|
|
323
|
+
if not self.access_token:
|
|
324
|
+
self.authenticate()
|
|
325
|
+
|
|
326
|
+
checks = [
|
|
327
|
+
(self.CHECK_LABELS["_check_privileged_roles_and_mfa"], self._check_privileged_roles_and_mfa),
|
|
328
|
+
(self.CHECK_LABELS["_check_legacy_auth_conditional_access"], self._check_legacy_auth_conditional_access),
|
|
329
|
+
(self.CHECK_LABELS["_check_stale_and_overprivileged_apps"], self._check_stale_and_overprivileged_apps),
|
|
330
|
+
(self.CHECK_LABELS["_check_privileged_guests"], self._check_privileged_guests),
|
|
331
|
+
]
|
|
332
|
+
|
|
333
|
+
for label, check in checks:
|
|
334
|
+
if progress_callback is not None:
|
|
335
|
+
progress_callback(label)
|
|
336
|
+
try:
|
|
337
|
+
check()
|
|
338
|
+
except GraphPermissionError as exc:
|
|
339
|
+
self.warnings.append(
|
|
340
|
+
CollectionWarning(check_name=label, source="entra", reason=str(exc))
|
|
341
|
+
)
|
|
342
|
+
except requests.RequestException as exc:
|
|
343
|
+
self.warnings.append(
|
|
344
|
+
CollectionWarning(check_name=label, source="entra", reason=str(exc))
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
return ScanBundle(
|
|
348
|
+
nodes=self.nodes,
|
|
349
|
+
edges=self.edges,
|
|
350
|
+
findings=self.findings,
|
|
351
|
+
warnings=self.warnings,
|
|
352
|
+
metadata={
|
|
353
|
+
"source": "entra",
|
|
354
|
+
"tenant_id": self.tenant_id,
|
|
355
|
+
"client_id": self.client_id,
|
|
356
|
+
},
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
# ---------------------------------------------------------------- checks
|
|
360
|
+
|
|
361
|
+
def _check_privileged_roles_and_mfa(self) -> None:
|
|
362
|
+
roles = self._load_privileged_roles()
|
|
363
|
+
|
|
364
|
+
mfa_details: List[Dict[str, Any]] = []
|
|
365
|
+
try:
|
|
366
|
+
mfa_details = self._graph_get_all(
|
|
367
|
+
self._url("/reports/authenticationMethods/userRegistrationDetails")
|
|
368
|
+
)
|
|
369
|
+
except GraphPermissionError as exc:
|
|
370
|
+
self.warnings.append(
|
|
371
|
+
CollectionWarning(
|
|
372
|
+
check_name=self.CHECK_LABELS["_check_privileged_roles_and_mfa"],
|
|
373
|
+
source="entra",
|
|
374
|
+
reason=str(exc),
|
|
375
|
+
)
|
|
376
|
+
)
|
|
377
|
+
except requests.RequestException as exc:
|
|
378
|
+
self.warnings.append(
|
|
379
|
+
CollectionWarning(
|
|
380
|
+
check_name=self.CHECK_LABELS["_check_privileged_roles_and_mfa"],
|
|
381
|
+
source="entra",
|
|
382
|
+
reason=str(exc),
|
|
383
|
+
)
|
|
384
|
+
)
|
|
385
|
+
|
|
386
|
+
methods_by_id: Dict[str, List[str]] = {}
|
|
387
|
+
methods_by_upn: Dict[str, List[str]] = {}
|
|
388
|
+
for detail in mfa_details:
|
|
389
|
+
methods = [_norm(m) for m in _as_list(detail.get("methodsRegistered"))]
|
|
390
|
+
detail_id = str(detail.get("id") or "")
|
|
391
|
+
upn = _norm(detail.get("userPrincipalName"))
|
|
392
|
+
if detail_id:
|
|
393
|
+
methods_by_id[detail_id] = methods
|
|
394
|
+
if upn:
|
|
395
|
+
methods_by_upn[upn] = methods
|
|
396
|
+
|
|
397
|
+
affected: List[str] = []
|
|
398
|
+
affected_ids: Set[str] = set()
|
|
399
|
+
global_admin_gap = False
|
|
400
|
+
|
|
401
|
+
for role in roles:
|
|
402
|
+
role_name = role.get("displayName") or role.get("display_name") or ""
|
|
403
|
+
if _norm(role_name) not in _PRIVILEGED_ROLE_LOOKUP:
|
|
404
|
+
continue
|
|
405
|
+
role_id = str(role.get("id") or role_name)
|
|
406
|
+
members = _as_list(role.get("members"))
|
|
407
|
+
self._add_node(
|
|
408
|
+
PrincipalNode(
|
|
409
|
+
id=role_id,
|
|
410
|
+
name=role_name,
|
|
411
|
+
principal_type="role",
|
|
412
|
+
source="entra",
|
|
413
|
+
is_privileged=True,
|
|
414
|
+
metadata={"member_count": len(members)},
|
|
415
|
+
)
|
|
416
|
+
)
|
|
417
|
+
|
|
418
|
+
for member in members:
|
|
419
|
+
if not isinstance(member, dict):
|
|
420
|
+
continue
|
|
421
|
+
member_id = self._member_id(member)
|
|
422
|
+
if not member_id:
|
|
423
|
+
continue
|
|
424
|
+
member_name = self._member_name(member)
|
|
425
|
+
upn = _norm(member.get("userPrincipalName"))
|
|
426
|
+
methods = methods_by_id.get(member_id)
|
|
427
|
+
if methods is None and upn:
|
|
428
|
+
methods = methods_by_upn.get(upn)
|
|
429
|
+
if methods is None:
|
|
430
|
+
continue
|
|
431
|
+
|
|
432
|
+
has_phishing_resistant = any(m in PHISHING_RESISTANT_METHODS for m in methods)
|
|
433
|
+
uses_sms_or_voice = any(m in SMS_VOICE_METHODS for m in methods)
|
|
434
|
+
if has_phishing_resistant and not uses_sms_or_voice:
|
|
435
|
+
continue
|
|
436
|
+
|
|
437
|
+
if member_id not in affected_ids:
|
|
438
|
+
affected_ids.add(member_id)
|
|
439
|
+
affected.append(member_name)
|
|
440
|
+
|
|
441
|
+
if _norm(role_name) == "global administrator" and not has_phishing_resistant:
|
|
442
|
+
global_admin_gap = True
|
|
443
|
+
|
|
444
|
+
self._add_node(
|
|
445
|
+
PrincipalNode(
|
|
446
|
+
id=member_id,
|
|
447
|
+
name=member_name,
|
|
448
|
+
principal_type="user",
|
|
449
|
+
source="entra",
|
|
450
|
+
is_privileged=True,
|
|
451
|
+
metadata={
|
|
452
|
+
"role": role_name,
|
|
453
|
+
"methods_registered": methods,
|
|
454
|
+
"phishing_resistant_mfa": has_phishing_resistant,
|
|
455
|
+
"sms_or_voice": uses_sms_or_voice,
|
|
456
|
+
"guest": self._is_guest(member),
|
|
457
|
+
},
|
|
458
|
+
)
|
|
459
|
+
)
|
|
460
|
+
self._add_edge(
|
|
461
|
+
IdentityEdge(
|
|
462
|
+
source_id=member_id,
|
|
463
|
+
target_id=role_id,
|
|
464
|
+
relation="has_MFA_gap",
|
|
465
|
+
description=(
|
|
466
|
+
f"{member_name} holds {role_name} without phishing-resistant MFA"
|
|
467
|
+
+ (" and relies on SMS/voice." if uses_sms_or_voice else ".")
|
|
468
|
+
),
|
|
469
|
+
)
|
|
470
|
+
)
|
|
471
|
+
|
|
472
|
+
if affected:
|
|
473
|
+
self.findings.append(
|
|
474
|
+
Finding(
|
|
475
|
+
id="ENTRA-001",
|
|
476
|
+
title="Privileged Entra roles without phishing-resistant MFA",
|
|
477
|
+
severity=Severity.CRITICAL if global_admin_gap else Severity.HIGH,
|
|
478
|
+
source="entra",
|
|
479
|
+
affected_count=len(affected),
|
|
480
|
+
affected_entities=affected,
|
|
481
|
+
why_it_matters=(
|
|
482
|
+
"Privileged accounts protected only by passwords, SMS, or voice can be "
|
|
483
|
+
"phished or intercepted, giving an attacker full control of the tenant."
|
|
484
|
+
),
|
|
485
|
+
how_to_fix=(
|
|
486
|
+
"Require phishing-resistant MFA (FIDO2, Windows Hello for Business, or "
|
|
487
|
+
"Microsoft Authenticator passwordless) for every privileged role, especially "
|
|
488
|
+
"Global Administrator."
|
|
489
|
+
),
|
|
490
|
+
)
|
|
491
|
+
)
|
|
492
|
+
|
|
493
|
+
def _check_legacy_auth_conditional_access(self) -> None:
|
|
494
|
+
policies = self._graph_get_all(self._url("/identity/conditionalAccess/policies"))
|
|
495
|
+
|
|
496
|
+
has_blocking_policy = False
|
|
497
|
+
enabled_policy_names: List[str] = []
|
|
498
|
+
for policy in policies:
|
|
499
|
+
state = _norm(policy.get("state"))
|
|
500
|
+
if state != "enabled":
|
|
501
|
+
continue
|
|
502
|
+
display_name = str(policy.get("displayName") or policy.get("name") or "Unnamed policy")
|
|
503
|
+
enabled_policy_names.append(display_name)
|
|
504
|
+
|
|
505
|
+
conditions = policy.get("conditions") or {}
|
|
506
|
+
users = conditions.get("users") or {}
|
|
507
|
+
include_users = {_norm(u) for u in _as_list(users.get("includeUsers"))}
|
|
508
|
+
targets_all = bool(include_users & {"all", "all users"})
|
|
509
|
+
|
|
510
|
+
client_apps = {_norm(a) for a in _as_list(conditions.get("clientAppTypes"))}
|
|
511
|
+
targets_legacy = "exchangeactivesync" in client_apps and "other" in client_apps
|
|
512
|
+
|
|
513
|
+
grant = policy.get("grantControls") or {}
|
|
514
|
+
built_in = {_norm(c) for c in _as_list(grant.get("builtInControls"))}
|
|
515
|
+
blocks = "block" in built_in
|
|
516
|
+
|
|
517
|
+
if targets_all and targets_legacy and blocks:
|
|
518
|
+
has_blocking_policy = True
|
|
519
|
+
break
|
|
520
|
+
|
|
521
|
+
if not has_blocking_policy:
|
|
522
|
+
self.findings.append(
|
|
523
|
+
Finding(
|
|
524
|
+
id="ENTRA-002",
|
|
525
|
+
title="Legacy authentication is not blocked by conditional access",
|
|
526
|
+
severity=Severity.CRITICAL,
|
|
527
|
+
source="entra",
|
|
528
|
+
affected_count=1,
|
|
529
|
+
affected_entities=["No enabled legacy-auth blocking policy"],
|
|
530
|
+
why_it_matters=(
|
|
531
|
+
"Legacy protocols such as IMAP, SMTP, and POP3 can bypass MFA, so a stolen "
|
|
532
|
+
"password alone may be enough for an attacker to read mail or move laterally."
|
|
533
|
+
),
|
|
534
|
+
how_to_fix=(
|
|
535
|
+
"Create an enabled conditional access policy for All users that targets the "
|
|
536
|
+
"Exchange ActiveSync and Other client app types and blocks access."
|
|
537
|
+
),
|
|
538
|
+
)
|
|
539
|
+
)
|
|
540
|
+
|
|
541
|
+
def _check_stale_and_overprivileged_apps(self) -> None:
|
|
542
|
+
service_principals = self._graph_get_all(self._url("/servicePrincipals"))
|
|
543
|
+
grants = self._graph_get_all(self._url("/oauth2PermissionGrants"))
|
|
544
|
+
|
|
545
|
+
sp_by_id: Dict[str, Dict[str, Any]] = {}
|
|
546
|
+
graph_sp: Optional[Dict[str, Any]] = None
|
|
547
|
+
for sp in service_principals:
|
|
548
|
+
sp_id = str(sp.get("id") or "")
|
|
549
|
+
if not sp_id:
|
|
550
|
+
continue
|
|
551
|
+
sp_by_id[sp_id] = sp
|
|
552
|
+
if _norm(sp.get("appId")) == GRAPH_APP_ID:
|
|
553
|
+
graph_sp = sp
|
|
554
|
+
|
|
555
|
+
graph_role_names: Dict[str, str] = {}
|
|
556
|
+
if graph_sp is not None:
|
|
557
|
+
for app_role in _as_list(graph_sp.get("appRoles")):
|
|
558
|
+
if not isinstance(app_role, dict):
|
|
559
|
+
continue
|
|
560
|
+
role_id = str(app_role.get("id") or "")
|
|
561
|
+
role_name = str(app_role.get("value") or app_role.get("displayName") or "")
|
|
562
|
+
if role_id and role_name:
|
|
563
|
+
graph_role_names[role_id] = role_name
|
|
564
|
+
|
|
565
|
+
risky: Dict[str, Dict[str, Any]] = {}
|
|
566
|
+
|
|
567
|
+
def mark(sp: Dict[str, Any], perm: str) -> None:
|
|
568
|
+
sp_id = str(sp.get("id") or sp.get("appId") or sp.get("displayName") or "")
|
|
569
|
+
if not sp_id:
|
|
570
|
+
return
|
|
571
|
+
entry = risky.setdefault(
|
|
572
|
+
sp_id,
|
|
573
|
+
{"sp": sp, "permissions": set(), "stale": False, "credential": False},
|
|
574
|
+
)
|
|
575
|
+
entry["permissions"].add(HIGH_RISK_GRAPH_PERMISSIONS.get(_norm(perm), perm))
|
|
576
|
+
|
|
577
|
+
for grant in grants:
|
|
578
|
+
sp_id = str(grant.get("clientId") or "")
|
|
579
|
+
sp = sp_by_id.get(sp_id)
|
|
580
|
+
if sp is None or not self._is_third_party(sp):
|
|
581
|
+
continue
|
|
582
|
+
for scope in _as_list(grant.get("scope")):
|
|
583
|
+
for token in str(scope).split():
|
|
584
|
+
if _norm(token) in HIGH_RISK_GRAPH_PERMISSIONS:
|
|
585
|
+
mark(sp, HIGH_RISK_GRAPH_PERMISSIONS[_norm(token)])
|
|
586
|
+
|
|
587
|
+
# App role assignments are the application-permission equivalent of OAuth grants.
|
|
588
|
+
for sp_id, sp in sp_by_id.items():
|
|
589
|
+
if not self._is_third_party(sp):
|
|
590
|
+
continue
|
|
591
|
+
try:
|
|
592
|
+
assignments = self._graph_get_all(
|
|
593
|
+
self._url(f"/servicePrincipals/{sp_id}/appRoleAssignments")
|
|
594
|
+
)
|
|
595
|
+
except (GraphPermissionError, requests.RequestException):
|
|
596
|
+
assignments = []
|
|
597
|
+
for assignment in assignments:
|
|
598
|
+
if not isinstance(assignment, dict):
|
|
599
|
+
continue
|
|
600
|
+
if _norm(assignment.get("resourceId")) != _norm(graph_sp.get("id") if graph_sp else ""):
|
|
601
|
+
continue
|
|
602
|
+
perm = graph_role_names.get(str(assignment.get("appRoleId") or ""))
|
|
603
|
+
if perm and _norm(perm) in HIGH_RISK_GRAPH_PERMISSIONS:
|
|
604
|
+
mark(sp, perm)
|
|
605
|
+
|
|
606
|
+
# Service principals that are members of privileged directory roles.
|
|
607
|
+
privileged_sp_ids: Set[str] = set()
|
|
608
|
+
for item in self._privileged_role_members:
|
|
609
|
+
member = item.get("member") or {}
|
|
610
|
+
member_id = self._member_id(member)
|
|
611
|
+
if member_id and member_id in sp_by_id:
|
|
612
|
+
privileged_sp_ids.add(member_id)
|
|
613
|
+
|
|
614
|
+
for sp_id, sp in sp_by_id.items():
|
|
615
|
+
if sp_id not in risky and sp_id not in privileged_sp_ids:
|
|
616
|
+
continue
|
|
617
|
+
entry = risky.setdefault(
|
|
618
|
+
sp_id,
|
|
619
|
+
{"sp": sp, "permissions": set(), "stale": False, "credential": False},
|
|
620
|
+
)
|
|
621
|
+
entry["stale"] = self._is_stale(sp)
|
|
622
|
+
entry["credential"] = self._credential_is_expired_or_expiring(sp)
|
|
623
|
+
|
|
624
|
+
if not risky:
|
|
625
|
+
return
|
|
626
|
+
|
|
627
|
+
affected_names: List[str] = []
|
|
628
|
+
critical = False
|
|
629
|
+
for entry in risky.values():
|
|
630
|
+
sp = entry["sp"]
|
|
631
|
+
sp_id = str(sp.get("id") or sp.get("appId") or "")
|
|
632
|
+
display_name = str(sp.get("displayName") or sp.get("appId") or sp_id or "unknown app")
|
|
633
|
+
permissions = sorted(entry["permissions"])
|
|
634
|
+
risky_third_party = self._is_third_party(sp)
|
|
635
|
+
if risky_third_party and any(
|
|
636
|
+
_norm(perm) in _CRITICAL_GRAPH_PERMISSIONS for perm in permissions
|
|
637
|
+
):
|
|
638
|
+
critical = True
|
|
639
|
+
|
|
640
|
+
affected_names.append(display_name)
|
|
641
|
+
self._add_node(
|
|
642
|
+
PrincipalNode(
|
|
643
|
+
id=sp_id or display_name,
|
|
644
|
+
name=display_name,
|
|
645
|
+
principal_type="service_principal",
|
|
646
|
+
source="entra",
|
|
647
|
+
is_privileged=True,
|
|
648
|
+
metadata={
|
|
649
|
+
"app_id": sp.get("appId"),
|
|
650
|
+
"permissions": permissions,
|
|
651
|
+
"stale": entry["stale"],
|
|
652
|
+
"expired_or_expiring_credentials": entry["credential"],
|
|
653
|
+
"third_party": risky_third_party,
|
|
654
|
+
},
|
|
655
|
+
)
|
|
656
|
+
)
|
|
657
|
+
for perm in permissions:
|
|
658
|
+
self._add_edge(
|
|
659
|
+
IdentityEdge(
|
|
660
|
+
source_id=sp_id or display_name,
|
|
661
|
+
target_id=perm,
|
|
662
|
+
relation="has_high_risk_permission",
|
|
663
|
+
description=f"{display_name} is consented to the high-risk Graph permission {perm}.",
|
|
664
|
+
)
|
|
665
|
+
)
|
|
666
|
+
if entry["stale"] or entry["credential"]:
|
|
667
|
+
self._add_edge(
|
|
668
|
+
IdentityEdge(
|
|
669
|
+
source_id=sp_id or display_name,
|
|
670
|
+
target_id="Microsoft Graph",
|
|
671
|
+
relation="is_stale_or_expiring_app",
|
|
672
|
+
description=(
|
|
673
|
+
f"{display_name} holds privileged access with stale sign-in/creation "
|
|
674
|
+
"metadata or expired/expiring credentials."
|
|
675
|
+
),
|
|
676
|
+
)
|
|
677
|
+
)
|
|
678
|
+
|
|
679
|
+
self.findings.append(
|
|
680
|
+
Finding(
|
|
681
|
+
id="ENTRA-003",
|
|
682
|
+
title="Overprivileged or stale third-party applications",
|
|
683
|
+
severity=Severity.CRITICAL if critical else Severity.HIGH,
|
|
684
|
+
source="entra",
|
|
685
|
+
affected_count=len(affected_names),
|
|
686
|
+
affected_entities=affected_names,
|
|
687
|
+
why_it_matters=(
|
|
688
|
+
"A third-party app with broad Graph permissions or stale credentials can read "
|
|
689
|
+
"mail, files, or directory data and may be hijacked without a user password."
|
|
690
|
+
),
|
|
691
|
+
how_to_fix=(
|
|
692
|
+
"Remove unnecessary Graph permissions, prefer least-privilege scopes, and "
|
|
693
|
+
"rotate or delete expired app credentials."
|
|
694
|
+
),
|
|
695
|
+
)
|
|
696
|
+
)
|
|
697
|
+
|
|
698
|
+
def _check_privileged_guests(self) -> None:
|
|
699
|
+
if not self._privileged_roles_loaded:
|
|
700
|
+
self._load_privileged_roles()
|
|
701
|
+
|
|
702
|
+
guests: List[str] = []
|
|
703
|
+
guest_ids: Set[str] = set()
|
|
704
|
+
global_admin_guest = False
|
|
705
|
+
|
|
706
|
+
for item in self._privileged_role_members:
|
|
707
|
+
member = item.get("member") or {}
|
|
708
|
+
if not self._is_guest(member):
|
|
709
|
+
continue
|
|
710
|
+
member_id = self._member_id(member)
|
|
711
|
+
if not member_id or member_id in guest_ids:
|
|
712
|
+
continue
|
|
713
|
+
guest_ids.add(member_id)
|
|
714
|
+
guest_name = self._member_name(member)
|
|
715
|
+
guests.append(guest_name)
|
|
716
|
+
role_name = str(item.get("role_name") or "")
|
|
717
|
+
role_id = str(item.get("role_id") or role_name)
|
|
718
|
+
if _norm(role_name) == "global administrator":
|
|
719
|
+
global_admin_guest = True
|
|
720
|
+
|
|
721
|
+
self._add_node(
|
|
722
|
+
PrincipalNode(
|
|
723
|
+
id=member_id,
|
|
724
|
+
name=guest_name,
|
|
725
|
+
principal_type="user",
|
|
726
|
+
source="entra",
|
|
727
|
+
is_privileged=True,
|
|
728
|
+
metadata={
|
|
729
|
+
"guest": True,
|
|
730
|
+
"role": role_name,
|
|
731
|
+
"user_principal_name": member.get("userPrincipalName"),
|
|
732
|
+
},
|
|
733
|
+
)
|
|
734
|
+
)
|
|
735
|
+
self._add_edge(
|
|
736
|
+
IdentityEdge(
|
|
737
|
+
source_id=member_id,
|
|
738
|
+
target_id=role_id,
|
|
739
|
+
relation="guest_holds_privileged_role",
|
|
740
|
+
description=f"External guest {guest_name} holds the privileged role {role_name}.",
|
|
741
|
+
)
|
|
742
|
+
)
|
|
743
|
+
|
|
744
|
+
if guests:
|
|
745
|
+
self.findings.append(
|
|
746
|
+
Finding(
|
|
747
|
+
id="ENTRA-004",
|
|
748
|
+
title="External guests holding privileged Entra roles",
|
|
749
|
+
severity=Severity.CRITICAL if global_admin_guest else Severity.HIGH,
|
|
750
|
+
source="entra",
|
|
751
|
+
affected_count=len(guests),
|
|
752
|
+
affected_entities=guests,
|
|
753
|
+
why_it_matters=(
|
|
754
|
+
"Guest accounts are controlled outside your organization, so a compromised "
|
|
755
|
+
"guest identity with a privileged role can take over your tenant."
|
|
756
|
+
),
|
|
757
|
+
how_to_fix=(
|
|
758
|
+
"Remove privileged directory roles from external guest accounts and use "
|
|
759
|
+
"time-bound, least-privilege access instead."
|
|
760
|
+
),
|
|
761
|
+
)
|
|
762
|
+
)
|