attackmap-analyzer-dotnet 0.2.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.
@@ -0,0 +1,494 @@
1
+ """ASP.NET Core route and per-route auth extraction (#2).
2
+
3
+ Covers attribute routing on controllers, minimal APIs (including nested
4
+ `MapGroup` prefixes), `MapHub`, `MapControllerRoute` and Razor Pages
5
+ `@page`, with ASP.NET template semantics:
6
+
7
+ - a member template starting with `/` or `~/` is absolute and replaces the
8
+ controller prefix;
9
+ - `[controller]`, `[action]` and `[area]` are replaced case-insensitively
10
+ (`[action]` drops an `Async` suffix, as ASP.NET Core does by default);
11
+ - every path starts with `/`.
12
+
13
+ Each route also gets its *effective* auth state:
14
+
15
+ - attribute routes: `[AllowAnonymous]` on the action or controller wins over
16
+ any `[Authorize]` (ASP.NET ignores `[Authorize]` once `[AllowAnonymous]` is
17
+ present); otherwise `[Authorize]` on either makes it `required`;
18
+ - minimal APIs: `.AllowAnonymous()` / `.RequireAuthorization()` (and lambda
19
+ `[AllowAnonymous]` / `[Authorize]`) on the endpoint or any enclosing group,
20
+ with the same anonymous-wins rule;
21
+ - anything else is `unknown`; the analyzer upgrades unknown routes to
22
+ `required` when the repo sets an authorization fallback policy, or calls
23
+ `MapControllers().RequireAuthorization()` / `MapRazorPages().RequireAuthorization()`.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import re
29
+ from dataclasses import dataclass, field
30
+ from pathlib import PurePosixPath
31
+
32
+ from .csharp import (
33
+ AttributeBlock,
34
+ attribute_blocks,
35
+ class_scopes,
36
+ innermost_scope,
37
+ mask_comments,
38
+ member_name,
39
+ parse_chains,
40
+ string_literal,
41
+ string_literals,
42
+ )
43
+
44
+ REQUIRED = "required"
45
+ ANONYMOUS = "anonymous"
46
+ UNKNOWN = "unknown"
47
+
48
+ HTTP_VERB_ATTRIBUTES = {
49
+ "HttpGet": "GET",
50
+ "HttpPost": "POST",
51
+ "HttpPut": "PUT",
52
+ "HttpDelete": "DELETE",
53
+ "HttpPatch": "PATCH",
54
+ "HttpHead": "HEAD",
55
+ "HttpOptions": "OPTIONS",
56
+ }
57
+ MINIMAL_VERBS = {
58
+ "MapGet": "GET",
59
+ "MapPost": "POST",
60
+ "MapPut": "PUT",
61
+ "MapDelete": "DELETE",
62
+ "MapPatch": "PATCH",
63
+ }
64
+ DEFAULT_CONVENTIONAL_ROUTE = "{controller=Home}/{action=Index}/{id?}"
65
+ _CHAIN_START = re.compile(
66
+ r"Map(?:Get|Post|Put|Delete|Patch|Methods|Group|Hub|GrpcService|Controllers|RazorPages"
67
+ r"|ControllerRoute|DefaultControllerRoute|AreaControllerRoute)"
68
+ r"|RequireAuthorization|AllowAnonymous"
69
+ )
70
+ _TOKEN_RE = re.compile(r"\[(controller|action|area)\]", re.IGNORECASE)
71
+
72
+
73
+ @dataclass
74
+ class RouteSpec:
75
+ path: str
76
+ method: str
77
+ offset: int
78
+ kind: str # "attribute", "minimal", "conventional", "hub", "razor"
79
+ auth: str = UNKNOWN
80
+ auth_evidence: str | None = None
81
+
82
+
83
+ @dataclass
84
+ class FileRoutes:
85
+ routes: list[RouteSpec] = field(default_factory=list)
86
+ # Repo-wide defaults this file declares.
87
+ controllers_require_auth: bool = False
88
+ razor_pages_require_auth: bool = False
89
+ fallback_policy_requires_auth: bool = False
90
+ # Offsets of `[Authorize]` attributes that guard no extracted route.
91
+ unattached_authorize: list[int] = field(default_factory=list)
92
+ # (hint, offset) protocol hints: SignalR hubs, gRPC services.
93
+ protocol_hints: list[tuple[str, int]] = field(default_factory=list)
94
+
95
+
96
+ # ---------- Template semantics ----------
97
+
98
+
99
+ def normalize(path: str) -> str:
100
+ path = path.strip()
101
+ if path.startswith("~/"):
102
+ path = path[1:]
103
+ if not path.startswith("/"):
104
+ path = "/" + path
105
+ if len(path) > 1:
106
+ path = path.rstrip("/") or "/"
107
+ return path
108
+
109
+
110
+ def combine(prefix: str, template: str) -> str:
111
+ """ASP.NET attribute-route combination of a controller and action template."""
112
+ t = template.strip()
113
+ if t.startswith("/") or t.startswith("~/"):
114
+ return normalize(t)
115
+ p = prefix.strip().strip("/")
116
+ t = t.strip("/")
117
+ if p and t:
118
+ return normalize(p + "/" + t)
119
+ return normalize(p or t)
120
+
121
+
122
+ def replace_tokens(template: str, controller: str | None, action: str | None, area: str | None) -> str:
123
+ def sub(m: re.Match[str]) -> str:
124
+ token = m.group(1).lower()
125
+ if token == "controller" and controller:
126
+ return controller[: -len("Controller")] if controller.endswith("Controller") and controller != "Controller" else controller
127
+ if token == "action" and action:
128
+ return action[: -len("Async")] if action.endswith("Async") and action != "Async" else action
129
+ if token == "area" and area:
130
+ return area
131
+ return m.group(0)
132
+
133
+ return _TOKEN_RE.sub(sub, template)
134
+
135
+
136
+ def _effective(flags: set[str]) -> str:
137
+ if ANONYMOUS in flags:
138
+ return ANONYMOUS
139
+ if REQUIRED in flags:
140
+ return REQUIRED
141
+ return UNKNOWN
142
+
143
+
144
+ # ---------- Attribute routing ----------
145
+
146
+
147
+ def _route_templates(block: AttributeBlock) -> list[str] | None:
148
+ """`[Route]` templates on a block; None if one isn't a readable literal."""
149
+ templates: list[str] = []
150
+ for attribute in block.get("Route"):
151
+ value = attribute.args.first_string("template", "Template")
152
+ if value is None:
153
+ return None
154
+ templates.append(value)
155
+ return templates
156
+
157
+
158
+ def _auth_flags(block: AttributeBlock | None) -> set[str]:
159
+ flags: set[str] = set()
160
+ if block is None:
161
+ return flags
162
+ if block.has("AllowAnonymous"):
163
+ flags.add(ANONYMOUS)
164
+ if block.has("Authorize"):
165
+ flags.add(REQUIRED)
166
+ return flags
167
+
168
+
169
+ def _auth_evidence(member: AttributeBlock, klass: AttributeBlock | None, class_name: str | None, state: str) -> str | None:
170
+ owner = f"controller {class_name}" if class_name else "controller"
171
+ if state == ANONYMOUS:
172
+ return "[AllowAnonymous] on action" if member.has("AllowAnonymous") else f"[AllowAnonymous] on {owner}"
173
+ if state == REQUIRED:
174
+ return "[Authorize] on action" if member.has("Authorize") else f"[Authorize] on {owner}"
175
+ return None
176
+
177
+
178
+ def _attribute_routes(masked: str, out: FileRoutes) -> None:
179
+ blocks = attribute_blocks(masked)
180
+ if not blocks:
181
+ return
182
+ scopes = class_scopes(masked)
183
+ class_blocks: dict[int, AttributeBlock] = {
184
+ b.class_keyword_at: b for b in blocks if b.class_keyword_at is not None
185
+ }
186
+ used_authorize: set[int] = set()
187
+
188
+ for block in blocks:
189
+ if block.class_keyword_at is not None:
190
+ continue
191
+ verbs = [(HTTP_VERB_ATTRIBUTES[a.name], a) for a in block.attributes if a.name in HTTP_VERB_ATTRIBUTES]
192
+ accept = block.get("AcceptVerbs")
193
+ member_templates = _route_templates(block)
194
+ if not verbs and not accept and not member_templates:
195
+ continue
196
+ if member_templates is None:
197
+ continue
198
+
199
+ scope = innermost_scope(scopes, block.start)
200
+ klass = class_blocks.get(scope.keyword_at) if scope is not None else None
201
+ class_name = scope.name if scope is not None else None
202
+ class_templates = _route_templates(klass) if klass is not None else []
203
+ if class_templates is None:
204
+ continue # controller template is a constant: unknown prefix
205
+ prefixes = class_templates or [""]
206
+ area = None
207
+ for source in (block, klass):
208
+ if source is not None and source.get("Area"):
209
+ area = source.get("Area")[0].args.first_string("areaName") or area
210
+ break
211
+ action = member_name(masked, block.end)
212
+
213
+ # (method, template, anchor offset)
214
+ pairs: list[tuple[str, str, int]] = []
215
+ for method, attribute in verbs:
216
+ if attribute.args.has_template("template"):
217
+ template = attribute.args.first_string("template")
218
+ if template is None:
219
+ continue # template is a constant: unknown path
220
+ pairs.append((method, template, attribute.start))
221
+ elif member_templates:
222
+ pairs.extend((method, t, attribute.start) for t in member_templates)
223
+ else:
224
+ pairs.append((method, "", attribute.start))
225
+ for attribute in accept:
226
+ accept_verbs = [string_literal(p) for p in attribute.args.positional]
227
+ route = attribute.args.named.get("Route")
228
+ templates = [string_literal(route)] if route is not None else (member_templates or [""])
229
+ for verb in (v for v in accept_verbs if v):
230
+ pairs.extend((verb.upper(), t, attribute.start) for t in templates if t is not None)
231
+ if member_templates and all(a.args.has_template("template") for _, a in verbs) and not accept:
232
+ # [Route] on the action with no template-less verb: any method.
233
+ anchor = block.get("Route")[0].start
234
+ pairs.extend(("ANY", t, anchor) for t in member_templates)
235
+
236
+ flags = _auth_flags(block) | _auth_flags(klass)
237
+ state = _effective(flags)
238
+ evidence = _auth_evidence(block, klass, class_name, state)
239
+ if pairs and state == REQUIRED:
240
+ for source in (block, klass):
241
+ if source is not None:
242
+ used_authorize.update(a.start for a in source.get("Authorize"))
243
+ for method, template, anchor in pairs:
244
+ for prefix in prefixes:
245
+ prefix_t = replace_tokens(prefix, class_name, action, area)
246
+ template_t = replace_tokens(template, class_name, action, area)
247
+ out.routes.append(
248
+ RouteSpec(combine(prefix_t, template_t), method, anchor, "attribute", state, evidence)
249
+ )
250
+
251
+ for block in blocks:
252
+ for attribute in block.get("Authorize"):
253
+ if attribute.start not in used_authorize:
254
+ out.unattached_authorize.append(attribute.start)
255
+
256
+
257
+ # ---------- Minimal APIs ----------
258
+
259
+
260
+ @dataclass
261
+ class _Group:
262
+ prefix: str | None # None when the prefix isn't a literal
263
+ parent: _Group | None
264
+ flags: set[str] = field(default_factory=set)
265
+ evidence: list[str] = field(default_factory=list)
266
+
267
+ def full_prefix(self) -> str | None:
268
+ parts: list[str] = []
269
+ node: _Group | None = self
270
+ while node is not None:
271
+ if node.prefix is None:
272
+ return None
273
+ parts.append(node.prefix)
274
+ node = node.parent
275
+ path = ""
276
+ for part in reversed(parts):
277
+ path = _join(path, part)
278
+ return path
279
+
280
+ def all_flags(self) -> tuple[set[str], list[str]]:
281
+ flags: set[str] = set()
282
+ evidence: list[str] = []
283
+ node: _Group | None = self
284
+ while node is not None:
285
+ flags |= node.flags
286
+ evidence.extend(node.evidence)
287
+ node = node.parent
288
+ return flags, evidence
289
+
290
+
291
+ @dataclass
292
+ class _Endpoint:
293
+ group: _Group
294
+ specs: list[RouteSpec]
295
+ flags: set[str] = field(default_factory=set)
296
+ evidence: list[str] = field(default_factory=list)
297
+ target: str | None = None # "controllers" / "razor" for convention builders
298
+
299
+
300
+ def _join(a: str, b: str) -> str:
301
+ a = a.strip().rstrip("/")
302
+ b = b.strip()
303
+ if not b or b == "/":
304
+ return a or "/"
305
+ return a + "/" + b.lstrip("/")
306
+
307
+
308
+ def _lambda_flags(raw_args: str) -> set[str]:
309
+ flags: set[str] = set()
310
+ head = raw_args.split("=>", 1)[0]
311
+ if re.search(r"\[\s*(?:[\w.]+\.)?AllowAnonymous(?:Attribute)?\b", head):
312
+ flags.add(ANONYMOUS)
313
+ if re.search(r"\[\s*(?:[\w.]+\.)?Authorize(?:Attribute)?\b", head):
314
+ flags.add(REQUIRED)
315
+ return flags
316
+
317
+
318
+ def _minimal_routes(masked: str, out: FileRoutes) -> None:
319
+ chains = parse_chains(masked, _CHAIN_START)
320
+ groups: dict[str, _Group] = {}
321
+ endpoint_vars: dict[str, _Endpoint] = {}
322
+ endpoints: list[_Endpoint] = []
323
+
324
+ for chain in chains:
325
+ current_group: _Group | None = groups.get(chain.base)
326
+ current_endpoint: _Endpoint | None = endpoint_vars.get(chain.base)
327
+ if current_group is None and current_endpoint is None:
328
+ current_group = _Group(prefix="", parent=None)
329
+ for call in chain.calls:
330
+ name = call.name
331
+ if name == "MapGroup":
332
+ if current_group is None:
333
+ break
334
+ prefix = call.args.first_string("prefix")
335
+ current_group = _Group(prefix=prefix, parent=current_group)
336
+ current_endpoint = None
337
+ elif name in MINIMAL_VERBS or name == "MapMethods" or name == "MapHub":
338
+ if current_group is None:
339
+ break
340
+ path = call.args.first_string("pattern")
341
+ if name == "MapMethods":
342
+ methods_arg = call.args.named.get("httpMethods") or (
343
+ call.args.positional[1] if len(call.args.positional) > 1 else ""
344
+ )
345
+ methods = [m.upper() for m in string_literals(methods_arg)]
346
+ elif name == "MapHub":
347
+ methods = ["ANY"]
348
+ if call.generic:
349
+ out.protocol_hints.append((f"signalr_hub:{call.generic}", call.name_at))
350
+ else:
351
+ methods = [MINIMAL_VERBS[name]]
352
+ kind = "hub" if name == "MapHub" else "minimal"
353
+ specs = [] if path is None else [RouteSpec(path, m, call.name_at, kind) for m in methods]
354
+ current_endpoint = _Endpoint(current_group, specs)
355
+ current_endpoint.flags |= _lambda_flags(call.raw_args)
356
+ if current_endpoint.flags:
357
+ current_endpoint.evidence.append("attribute on the route handler")
358
+ endpoints.append(current_endpoint)
359
+ elif name == "MapGrpcService":
360
+ if call.generic:
361
+ out.protocol_hints.append((f"grpc_service:{call.generic}", call.name_at))
362
+ current_endpoint = _Endpoint(current_group or _Group("", None), [])
363
+ elif name in ("MapControllers", "MapRazorPages"):
364
+ current_endpoint = _Endpoint(
365
+ current_group or _Group("", None), [],
366
+ target="controllers" if name == "MapControllers" else "razor",
367
+ )
368
+ endpoints.append(current_endpoint)
369
+ elif name in ("MapControllerRoute", "MapAreaControllerRoute", "MapDefaultControllerRoute"):
370
+ if name == "MapDefaultControllerRoute":
371
+ pattern = DEFAULT_CONVENTIONAL_ROUTE
372
+ else:
373
+ pattern = call.args.named.get("pattern")
374
+ pattern = string_literal(pattern) if pattern is not None else None
375
+ if pattern is None:
376
+ literal_args = [string_literal(p) for p in call.args.positional]
377
+ literal_args = [p for p in literal_args if p is not None]
378
+ # (name, pattern) or (name, areaName, pattern)
379
+ pattern = literal_args[-1] if len(literal_args) >= 2 else None
380
+ specs = [] if pattern is None else [RouteSpec(pattern, "ANY", call.name_at, "conventional")]
381
+ current_endpoint = _Endpoint(current_group or _Group("", None), specs, target="controllers")
382
+ endpoints.append(current_endpoint)
383
+ elif name in ("RequireAuthorization", "AllowAnonymous"):
384
+ flag = REQUIRED if name == "RequireAuthorization" else ANONYMOUS
385
+ note = f".{name}()"
386
+ if current_endpoint is not None:
387
+ current_endpoint.flags.add(flag)
388
+ current_endpoint.evidence.append(f"{note} on the endpoint")
389
+ elif current_group is not None:
390
+ current_group.flags.add(flag)
391
+ current_group.evidence.append(f"{note} on group {current_group.full_prefix() or '?'}")
392
+ # Any other call (WithName, WithTags, Produces, ...) keeps the builder.
393
+ if chain.assigned_to:
394
+ if current_endpoint is not None:
395
+ endpoint_vars[chain.assigned_to] = current_endpoint
396
+ groups.pop(chain.assigned_to, None)
397
+ elif current_group is not None and current_group.parent is not None:
398
+ groups[chain.assigned_to] = current_group
399
+ endpoint_vars.pop(chain.assigned_to, None)
400
+
401
+ # Resolve after the whole file: group conventions apply to every endpoint
402
+ # in the group no matter where in the file they are added.
403
+ for endpoint in endpoints:
404
+ group_flags, group_evidence = endpoint.group.all_flags()
405
+ flags = endpoint.flags | group_flags
406
+ state = _effective(flags)
407
+ if endpoint.target == "controllers" and REQUIRED in endpoint.flags and endpoint.specs == []:
408
+ out.controllers_require_auth = True
409
+ if endpoint.target == "razor" and REQUIRED in endpoint.flags:
410
+ out.razor_pages_require_auth = True
411
+ prefix = endpoint.group.full_prefix()
412
+ if prefix is None:
413
+ continue # a group prefix we can't read: path unknown
414
+ evidence = "; ".join(endpoint.evidence + group_evidence) or None
415
+ for spec in endpoint.specs:
416
+ if spec.kind == "conventional":
417
+ spec.path = normalize(spec.path)
418
+ else:
419
+ spec.path = normalize(_join(prefix, spec.path))
420
+ spec.auth = state
421
+ spec.auth_evidence = evidence if state != UNKNOWN else None
422
+ out.routes.append(spec)
423
+ if endpoint.target == "controllers" and endpoint.specs and REQUIRED in endpoint.flags:
424
+ out.controllers_require_auth = True
425
+
426
+
427
+ _FALLBACK_POLICY_RE = re.compile(
428
+ r"(?:FallbackPolicy\s*=|SetFallbackPolicy\s*\()(?P<rest>[^;]*)", re.DOTALL
429
+ )
430
+
431
+
432
+ def _fallback_requires_auth(masked: str) -> bool:
433
+ for m in _FALLBACK_POLICY_RE.finditer(masked):
434
+ rest = m.group("rest")
435
+ if re.search(r"RequireAuthenticatedUser|RequireRole|RequireClaim|RequireAssertion|DefaultPolicy", rest):
436
+ return True
437
+ return False
438
+
439
+
440
+ # ---------- Entry points ----------
441
+
442
+
443
+ def extract_cs_routes(content: str) -> FileRoutes:
444
+ out = FileRoutes()
445
+ masked = mask_comments(content)
446
+ if "[" in masked:
447
+ _attribute_routes(masked, out)
448
+ if "Map" in masked or "RequireAuthorization" in masked or "AllowAnonymous" in masked:
449
+ _minimal_routes(masked, out)
450
+ out.fallback_policy_requires_auth = _fallback_requires_auth(masked)
451
+ return out
452
+
453
+
454
+ _PAGE_DIRECTIVE_RE = re.compile(r'^[ \t]*@page(?:[ \t]+"([^"]*)")?[ \t]*\r?$', re.MULTILINE)
455
+
456
+
457
+ def extract_razor_page(content: str, relative: str) -> RouteSpec | None:
458
+ """The route of a Razor Page (`@page` directive in a .cshtml file)."""
459
+ m = _PAGE_DIRECTIVE_RE.search(content)
460
+ if m is None:
461
+ return None
462
+ template = m.group(1)
463
+ parts = PurePosixPath(relative).with_suffix("").parts
464
+ if "Pages" in parts:
465
+ index = len(parts) - 1 - parts[::-1].index("Pages")
466
+ base_parts = list(parts[index + 1 :])
467
+ area = parts[index - 1] if index >= 2 and parts[index - 2] == "Areas" else None
468
+ else:
469
+ base_parts = list(parts[-1:])
470
+ area = None
471
+ if base_parts and base_parts[-1] == "Index":
472
+ base_parts = base_parts[:-1]
473
+ base = "/" + "/".join(base_parts)
474
+ if area:
475
+ base = _join("/" + area, base)
476
+ if template:
477
+ path = normalize(template) if template.startswith("/") or template.startswith("~/") else normalize(_join(base, template))
478
+ else:
479
+ path = normalize(base)
480
+ return RouteSpec(path, "ANY", m.start(), "razor")
481
+
482
+
483
+ __all__ = [
484
+ "ANONYMOUS",
485
+ "REQUIRED",
486
+ "UNKNOWN",
487
+ "FileRoutes",
488
+ "RouteSpec",
489
+ "combine",
490
+ "extract_cs_routes",
491
+ "extract_razor_page",
492
+ "normalize",
493
+ "replace_tokens",
494
+ ]
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: attackmap-analyzer-dotnet
3
+ Version: 0.2.0
4
+ Summary: C# / .NET (ASP.NET Core) ecosystem analyzer plugin for AttackMap (minimal APIs, attribute routing, EF Core, Identity, JwtBearer).
5
+ Author: AttackMap Contributors
6
+ Author-email: Matthew Davis <mlaify@mlaify.io>
7
+ Maintainer-email: Matthew Davis <mlaify@mlaify.io>
8
+ License-Expression: MIT
9
+ Project-URL: Homepage, https://github.com/mlaify/attackmap-analyzer-dotnet
10
+ Project-URL: Repository, https://github.com/mlaify/attackmap-analyzer-dotnet
11
+ Project-URL: Issues, https://github.com/mlaify/attackmap-analyzer-dotnet/issues
12
+ Project-URL: Changelog, https://github.com/mlaify/attackmap-analyzer-dotnet/blob/main/CHANGELOG.md
13
+ Project-URL: AttackMap core, https://github.com/mlaify/AttackMap
14
+ Keywords: security,static-analysis,appsec,defensive-security,attackmap,attackmap-plugin
15
+ Classifier: Development Status :: 4 - Beta
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Intended Audience :: Information Technology
18
+ Classifier: Intended Audience :: System Administrators
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Programming Language :: Python :: 3 :: Only
25
+ Classifier: Topic :: Security
26
+ Classifier: Topic :: Software Development :: Quality Assurance
27
+ Classifier: Typing :: Typed
28
+ Requires-Python: >=3.11
29
+ Description-Content-Type: text/markdown
30
+ License-File: LICENSE
31
+ Requires-Dist: pydantic>=2.7.0
32
+ Provides-Extra: core
33
+ Requires-Dist: attackmap>=0.6.0; extra == "core"
34
+ Provides-Extra: dev
35
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
36
+ Requires-Dist: build>=1.2.0; extra == "dev"
37
+ Requires-Dist: attackmap>=0.6.0; extra == "dev"
38
+ Dynamic: license-file
39
+
40
+ # attackmap-analyzer-dotnet
41
+
42
+ > [!IMPORTANT]
43
+ > **Active development, slow pace.** AttackMap is under active development, but
44
+ > progress may be slow until more contributors or co-maintainers join. Help is
45
+ > very welcome with the core engine, an analyzer, the macOS app, or the docs —
46
+ > see [CONTRIBUTING.md](CONTRIBUTING.md) or open an issue on
47
+ > [mlaify/AttackMap](https://github.com/mlaify/AttackMap/issues) to say hello.
48
+ > Security reports are still welcome at [security@mlaify.io](mailto:security@mlaify.io).
49
+
50
+ C# / .NET (ASP.NET Core) ecosystem analyzer for [AttackMap](https://github.com/mlaify/AttackMap).
51
+
52
+ This analyzer extracts structured signals from .NET solutions and projects:
53
+
54
+ - **Web frameworks** — ASP.NET Core minimal APIs (`app.MapGet`, `app.MapPost`, `app.MapMethods`, nested `MapGroup` prefixes), attribute routing on controllers (`[HttpGet]`, `[HttpPost]`, `[Route]`, `[AcceptVerbs]`, with class-level `[Route]` prefix joining and `[controller]`/`[action]`/`[area]` token substitution), `MapHub<T>`, `MapControllerRoute`, Razor Pages `@page`; `MapGrpcService<T>` as a protocol hint
55
+ - **Databases** — Entity Framework Core (`UseSqlServer` / `UseNpgsql` / `UseMySql` / `UseSqlite`), Dapper, System.Data.SqlClient / Microsoft.Data.SqlClient, Npgsql, MySql.Data / MySqlConnector, MongoDB.Driver, StackExchange.Redis, AWS SDK (S3, DynamoDB)
56
+ - **Auth packages** — `AddJwtBearer` (Microsoft.AspNetCore.Authentication.JwtBearer), `AddOpenIdConnect`, ASP.NET Identity (`UserManager`, `SignInManager`, `IdentityUser`, `PasswordHasher`), per-route `[Authorize]` / `[AllowAnonymous]` / `.RequireAuthorization()` / `.AllowAnonymous()`, Duende IdentityServer, BCrypt.Net, Argon2
57
+ - **HTTP clients (external calls)** — `HttpClient.GetAsync` / `PostAsync` / `SendAsync`, `HttpRequestMessage`, `RestClient` (RestSharp), `new Uri(...)`
58
+ - **Secrets** — `Environment.GetEnvironmentVariable("...")`, `IConfiguration["..."]` / `Configuration["..."]` / `builder.Configuration["..."]` with secret-shaped keys, literal `Password=` in `appsettings*.json` `ConnectionStrings`
59
+ - **Service hints** — `<RootNamespace>` and `<AssemblyName>` from `.csproj`
60
+
61
+ All emissions populate AttackMap's Signal v2 fields (line numbers, evidence snippets, confidence scores) so downstream insights can cite `path/to/file.cs:NN`.
62
+
63
+ ## Install
64
+
65
+ ```bash
66
+ uv tool install attackmap --with attackmap-analyzer-dotnet \
67
+ --index mlaify=https://pkg.mlaify.io/pypi/simple/ --index-strategy first-index
68
+ # or from source:
69
+ pip install git+https://github.com/mlaify/attackmap-analyzer-dotnet.git
70
+ ```
71
+
72
+ The analyzer is auto-discovered by AttackMap via the `attackmap.analyzers` entry-point group.
73
+
74
+ ## Usage with AttackMap
75
+
76
+ ```bash
77
+ # Auto-discovered when installed:
78
+ attackmap analyze /path/to/dotnet/repo
79
+
80
+ # Or invoke explicitly:
81
+ attackmap analyze /path/to/dotnet/repo --module dotnet
82
+ ```
83
+
84
+ ## Detection
85
+
86
+ `detect()` returns true when any of the following are present, ignoring `bin/`, `obj/`, `.vs/`, `.idea/`, `.git/`, `node_modules/`, `packages/`, `TestResults/`, and `publish/`:
87
+
88
+ - A `.csproj`, `.fsproj`, or `.sln` file anywhere in the tree
89
+ - A `.cs` file anywhere in the tree
90
+
91
+ ## Coverage notes
92
+
93
+ - **Route templates** follow ASP.NET semantics: a controller annotated with `[Route("api/[controller]")]` causes its `[HttpGet("{id:int}", Name = "GetUser")]` action to emit as `/api/Orders/{id:int}`. An action template starting with `/` or `~/` is absolute and replaces the controller prefix. `[controller]` (class name minus `Controller`), `[action]` (method name minus `Async`) and `[area]` (`[Area("...")]`) are substituted case-insensitively. A class prefix applies only inside that class's body. Every emitted path starts with `/`.
94
+ - **Minimal API groups**: `var api = app.MapGroup("/api"); var v2 = api.MapGroup("/v2"); v2.MapGet("/orders/{id}", ...)` emits `/api/v2/orders/{id}`. Inline chains (`app.MapGroup("/x").MapGet("/y", ...)`) work too. A group built in another file or by a custom extension method isn't followed.
95
+ - **Per-route auth**: each route's effective state is computed. `[AllowAnonymous]` (attribute) or `.AllowAnonymous()` (minimal API, on the endpoint or any enclosing group) wins over `[Authorize]` / `.RequireAuthorization()`, as in ASP.NET. An authorization fallback policy, or `MapControllers().RequireAuthorization()`, makes unmarked routes require auth. A route that requires auth gets an `aspnet_authorize:<METHOD> <path>` auth hint on its own line; an explicitly anonymous route gets an `aspnet_allow_anonymous:<METHOD> <path>` entrypoint hint and no auth hint. Core attributes auth hints to routes by a ±40-line window until `Route` carries an auth field ([mlaify/AttackMap#256](https://github.com/mlaify/AttackMap/issues/256)), so in a compact controller a neighbor's hint can still show up on an anonymous route. `[Authorize]` inherited from a base controller class isn't followed.
96
+ - **Connection strings**: `GetConnectionString("DefaultConnection")` names a connection string, so it isn't reported as a secret. A literal `Password=`/`Pwd=` inside an `appsettings*.json` `ConnectionStrings` entry is reported as `connection_string_password` (`kind="config_literal"`); the evidence names the entry, never the value.
97
+ - **F# (.fs) projects** are detected via `.fsproj` but route extraction is not yet implemented (Giraffe / Saturn).
98
+ - **Razor Pages**: `@page` in a `.cshtml` file emits an `ANY` route from the file's path under `Pages/` (or `Areas/<Area>/Pages/`), with `Index` mapped to its folder and an optional `@page "template"` appended (or used as-is when it starts with `/`). Page auth conventions (`AuthorizeFolder`, `[Authorize]` on the PageModel) aren't read yet. Blazor `.razor` components aren't covered.
99
+
100
+ ## License
101
+
102
+ MIT
@@ -0,0 +1,10 @@
1
+ attackmap_analyzer_dotnet/__init__.py,sha256=f1bi8uNYh64jIVR1RDyYSHffcPEMY0I_4SRV1XKREmE,67
2
+ attackmap_analyzer_dotnet/analyzer.py,sha256=XkGnl1neHTiSvH2aEeMwrnISISmFVw5uOJQRYzRXEKU,24513
3
+ attackmap_analyzer_dotnet/csharp.py,sha256=JO-FC42m8-TbXBd_SM_iSEwk1cGl-9Cs_64FzJReXio,16120
4
+ attackmap_analyzer_dotnet/routes.py,sha256=uEqS2ZTtTIN6pzYG264R2c7ktqpGxihBe94HxmvTkPg,19468
5
+ attackmap_analyzer_dotnet-0.2.0.dist-info/licenses/LICENSE,sha256=vtPQVGUyxq359j0JmD3_eJaXyHmaHyjzaMOtaLwJc88,1097
6
+ attackmap_analyzer_dotnet-0.2.0.dist-info/METADATA,sha256=EgXo2OxEY36uo_Cu8i256V2W40CzpojiKrSXjdkfVOo,7576
7
+ attackmap_analyzer_dotnet-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ attackmap_analyzer_dotnet-0.2.0.dist-info/entry_points.txt,sha256=qBxh2pQOnk8Xf2XkaIf6W6nHS-2g85WAdYjRvN9umek,72
9
+ attackmap_analyzer_dotnet-0.2.0.dist-info/top_level.txt,sha256=aTWCBOzn0gq6IFqHRxi8KM0clBVrKAadizEL0I17KGw,26
10
+ attackmap_analyzer_dotnet-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [attackmap.analyzers]
2
+ dotnet = attackmap_analyzer_dotnet:DotnetAnalyzer
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Matthew Davis and AttackMap Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ attackmap_analyzer_dotnet