attackmap-analyzer-python 0.2.0__tar.gz
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.
- attackmap_analyzer_python-0.2.0/LICENSE +21 -0
- attackmap_analyzer_python-0.2.0/PKG-INFO +134 -0
- attackmap_analyzer_python-0.2.0/README.md +95 -0
- attackmap_analyzer_python-0.2.0/pyproject.toml +74 -0
- attackmap_analyzer_python-0.2.0/setup.cfg +4 -0
- attackmap_analyzer_python-0.2.0/src/attackmap_analyzer_python/__init__.py +3 -0
- attackmap_analyzer_python-0.2.0/src/attackmap_analyzer_python/_pyast.py +90 -0
- attackmap_analyzer_python-0.2.0/src/attackmap_analyzer_python/analyzer.py +783 -0
- attackmap_analyzer_python-0.2.0/src/attackmap_analyzer_python/django_urls.py +667 -0
- attackmap_analyzer_python-0.2.0/src/attackmap_analyzer_python/litestar_routes.py +358 -0
- attackmap_analyzer_python-0.2.0/src/attackmap_analyzer_python/sanic_routes.py +77 -0
- attackmap_analyzer_python-0.2.0/src/attackmap_analyzer_python/tornado_routes.py +182 -0
- attackmap_analyzer_python-0.2.0/src/attackmap_analyzer_python.egg-info/PKG-INFO +134 -0
- attackmap_analyzer_python-0.2.0/src/attackmap_analyzer_python.egg-info/SOURCES.txt +18 -0
- attackmap_analyzer_python-0.2.0/src/attackmap_analyzer_python.egg-info/dependency_links.txt +1 -0
- attackmap_analyzer_python-0.2.0/src/attackmap_analyzer_python.egg-info/entry_points.txt +2 -0
- attackmap_analyzer_python-0.2.0/src/attackmap_analyzer_python.egg-info/requires.txt +9 -0
- attackmap_analyzer_python-0.2.0/src/attackmap_analyzer_python.egg-info/top_level.txt +1 -0
- attackmap_analyzer_python-0.2.0/tests/test_python_analyzer.py +773 -0
- attackmap_analyzer_python-0.2.0/tests/test_routing_frameworks.py +923 -0
|
@@ -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,134 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: attackmap-analyzer-python
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Comprehensive Python ecosystem analyzer plugin for AttackMap (Django, Starlette, AIOHTTP, Sanic, Litestar, DRF; SQLAlchemy/asyncpg/motor; passlib/PyJWT/authlib; httpx/aiohttp).
|
|
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-python
|
|
10
|
+
Project-URL: Repository, https://github.com/mlaify/attackmap-analyzer-python
|
|
11
|
+
Project-URL: Issues, https://github.com/mlaify/attackmap-analyzer-python/issues
|
|
12
|
+
Project-URL: Changelog, https://github.com/mlaify/attackmap-analyzer-python/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-python
|
|
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
|
+
Comprehensive Python ecosystem analyzer for [AttackMap](https://github.com/mlaify/AttackMap).
|
|
51
|
+
|
|
52
|
+
This plugin is **additive** over AttackMap's built-in `python-web` analyzer. The built-in handles FastAPI / Flask routes via the core scanner; this plugin adds everything else.
|
|
53
|
+
|
|
54
|
+
- **Web frameworks** —
|
|
55
|
+
- **Django** routing (`path("users/", ...)`, `path("", ...)` → `/`, `re_path(r"^api/...$", ...)`, legacy `url(...)` / `patterns(...)`) gated by `urlpatterns =` in the file, with the **`include()` graph** resolved repo-wide: `include("app.urls")`, `include(module)`, `include((patterns, "app"))`, `include([...])` and local pattern lists join their prefix onto every child route (`path("api/", include("shop.api_urls"))` + `orders/<int:pk>/` → `/api/orders/<int:pk>/`)
|
|
56
|
+
- **Django REST Framework** routers (`router.register(r'users', UserViewSet)`, any `*Router()`), mounted under their `include(router.urls)` / `urlpatterns = router.urls` prefix, and `@api_view(['GET', 'POST'])` decorators
|
|
57
|
+
- **Starlette** `Route("/x", endpoint=h, methods=["GET", "POST"])` and `WebSocketRoute("/ws/...")`
|
|
58
|
+
- **AIOHTTP** `app.router.add_get/post/...`, `add_route("POST", ...)`, `add_view`, `web.get/post/view(...)` helpers and `web.RouteTableDef()` decorators (`@routes.get("/x")`, `@routes.view`, `@routes.route("PATCH", ...)`) (gated by aiohttp import)
|
|
59
|
+
- **Sanic** `@app.get("/x")`, `@app.post("/x")`, `@app.route("/x", methods=[...])`, `@app.websocket("/ws")` (gated by sanic import)
|
|
60
|
+
- **Litestar** (and legacy Starlite) handlers at any indentation (`@get()`, `@post(path="/x")`, `@route(http_method=[...])`, `@websocket`), `Controller` classes (`path = "/users"` joined onto each handler) and `Router(path=..., route_handlers=[...])` prefixes, including nested routers across files (decorators must be imported from litestar/starlite). `guards=[...]` on the handler/controller/router sets the route's auth to `required`; `exclude_from_auth=True` sets it to `anonymous`
|
|
61
|
+
- **Tornado** `Application([(r"/x", Handler), url(r"/y", H)])` URL specs paired with the handler class's `get`/`post`/... methods (a `WebSocketHandler` is `WS`); `@tornado.web.authenticated` on a method sets its auth to `required`
|
|
62
|
+
- **Flask** `app.add_url_rule("/x", view_func=...)` (additive — built-in covers `@app.route`)
|
|
63
|
+
- **Databases** —
|
|
64
|
+
- **SQLAlchemy** `create_engine("postgresql://...")` with dialect-aware kind inference (postgresql / mysql / mariadb / sqlite / oracle / sqlserver)
|
|
65
|
+
- **asyncpg** / **psycopg2-3** / **pymysql** / **motor.motor_asyncio** / **pymongo** / **redis.asyncio** / **aioredis** / **sqlmodel** / **tortoise**
|
|
66
|
+
- **boto3 resources/clients** for `dynamodb` and `s3`
|
|
67
|
+
- **Django** `DATABASES` dict in `settings.py` — `ENGINE` value parsed for the kind
|
|
68
|
+
- **Auth packages** —
|
|
69
|
+
- **passlib** `CryptContext`, `passlib.hash.argon2/bcrypt/scrypt`
|
|
70
|
+
- **bcrypt** standalone (`bcrypt.hashpw`, `bcrypt.checkpw`)
|
|
71
|
+
- **argon2-cffi** (`from argon2 import PasswordHasher`)
|
|
72
|
+
- **PyJWT** / **python-jose** (`jwt.encode`, `jwt.decode`, `jose.jwt`)
|
|
73
|
+
- **authlib** (`OAuth(...)`, `OAuth2Session(...)`)
|
|
74
|
+
- **fastapi-users** (`BearerTransport`, `JWTStrategy`)
|
|
75
|
+
- **flask-jwt-extended** (`@jwt_required`, `create_access_token`)
|
|
76
|
+
- **django.contrib.auth** (`authenticate`, `make_password`)
|
|
77
|
+
- **casbin** (`Enforcer`)
|
|
78
|
+
- **HTTP clients (external calls)** — **httpx** sync + async, **aiohttp.ClientSession**, **urllib.request.urlopen**
|
|
79
|
+
- **Secrets** —
|
|
80
|
+
- `os.environ.get("X")` and `os.environ["X"]` with secret-shaped names (built-in only covers `os.getenv`)
|
|
81
|
+
- **pydantic-settings** `BaseSettings` field-name extraction (`jwt_secret: str = ...`)
|
|
82
|
+
- `dotenv_values(...)` accessors with secret-shaped keys
|
|
83
|
+
- **Service hints** — `[project] name` from `pyproject.toml`, `[tool.poetry] name`, `name="..."` from `setup.py`, `[metadata] name` from `setup.cfg`, presence of `manage.py` → `framework:django`, Django `INSTALLED_APPS` third-party / local apps
|
|
84
|
+
|
|
85
|
+
All emissions populate AttackMap's Signal v2 fields (line numbers, evidence snippets, confidence) so downstream insights can cite `path/to/module.py:NN`.
|
|
86
|
+
|
|
87
|
+
## Install
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
uv tool install attackmap --with attackmap-analyzer-python \
|
|
91
|
+
--index mlaify=https://pkg.mlaify.io/pypi/simple/ --index-strategy first-index
|
|
92
|
+
# or from source:
|
|
93
|
+
pip install git+https://github.com/mlaify/attackmap-analyzer-python.git
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
The analyzer is auto-discovered by AttackMap via the `attackmap.analyzers` entry-point group.
|
|
97
|
+
|
|
98
|
+
## Usage with AttackMap
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
# Auto-discovered when installed:
|
|
102
|
+
attackmap analyze /path/to/python/repo
|
|
103
|
+
|
|
104
|
+
# Or invoke explicitly:
|
|
105
|
+
attackmap analyze /path/to/python/repo --module python
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Detection
|
|
109
|
+
|
|
110
|
+
`detect()` returns true when any of the following are present, ignoring `.venv/`, `venv/`, `env/`, `.tox/`, `__pycache__/`, `.pytest_cache/`, `dist/`, `build/`, `node_modules/`, `.git/`, `.mypy_cache/`, `.ruff_cache/`, and `site-packages/`:
|
|
111
|
+
|
|
112
|
+
- A `pyproject.toml`, `setup.py`, `setup.cfg`, `manage.py`, or `Pipfile` at the root
|
|
113
|
+
- Any `.py` file in the tree
|
|
114
|
+
|
|
115
|
+
## Coverage notes
|
|
116
|
+
|
|
117
|
+
- **Framework-gated extraction**: route extractors for AIOHTTP, Sanic, Litestar, and Starlette only fire when the file imports the corresponding framework. This prevents mis-attributing generic `@get(...)` / `web.get(...)` / `app.get(...)` calls to a framework when they're really custom decorators or method calls.
|
|
118
|
+
- **Django routing requires `urlpatterns =`** to be in the file. A bare `path("/x", ...)` in any other context (e.g., `pathlib.Path("/x")` is well-behaved, but a project that also has `from django.urls import path; path("/x", view)` outside a urls.py won't fire — by design).
|
|
119
|
+
- **Django settings extraction**: gated by presence of one of `INSTALLED_APPS`, `DATABASES`, `MIDDLEWARE`, or `ROOT_URLCONF`. Built-in Django apps (`django.*`) are filtered out of the INSTALLED_APPS service hints to keep signal high.
|
|
120
|
+
- **DRF `@api_view(['GET', 'POST'])`**: emits framework hints (`drf_api_view:GET`, `drf_api_view:POST`) rather than routes — the actual path is in `urls.py`, which is extracted separately.
|
|
121
|
+
- **Django `include()` resolution**: a module reference resolves only to a URLconf inside the repo (tried from each `manage.py` directory, the repo root, then the including file's ancestors). A resolved `include()` line is a prefix, not an endpoint, so it isn't a route. An include that can't be resolved (a third-party app, `include(get_model_urls(...))`) is still emitted as its prefix (`/accounts/`). A pattern list or router nothing mounts keeps the unprefixed emission. A non-literal route (`path(settings.BASE_PATH, include(...))`) joins as an empty prefix. Regex anchors are stripped when joining, so `re_path(r"^users/$")` is `/users/`. A pattern list is the union of everything assigned to it (reassignments, if/else and try/except branches, `urlpatterns = wrap(urlpatterns)`), so no branch's routes are dropped. The resolver is bounded (5k entries per list, 20k per file, 5k registrations per router, 12 include levels, 64 mounts per list, 200k steps including router registrations, 50k routes) and cycles stop.
|
|
122
|
+
- **Parsing**: URLconfs, Litestar, Tornado and Sanic files are read with `ast` (never executed). A file `ast` can't parse (Python 2, over 1 MB) falls back to the per-file regex extractors.
|
|
123
|
+
- **Not yet**: DRF nested routers' parent prefix, zulip-style custom `rest_path(...)` wrappers, Sanic `Blueprint(url_prefix=...)` joins (core doesn't join them either, so joining here would duplicate routes), and Django route auth decided at the view (`@login_required` on the view function, `LoginRequiredMixin`, DRF `permission_classes`) — see the issue tracker. Auth wrappers applied in the URLconf itself (`login_required(views.x)`, `permission_required("p")(View.as_view())`, `staff_member_required`, `user_passes_test`) do set the route's auth to `required`, and Django 5.1's `login_not_required(...)` sets it to `anonymous`.
|
|
124
|
+
- **pydantic-settings** field extraction matches any class field whose name contains `secret`, `token`, `key`, `password`, `pass`, or `pwd`. False positives are possible (e.g., a non-secret `signing_key` config). Confidence is the standard 0.85.
|
|
125
|
+
|
|
126
|
+
## Coexistence with the built-in `python-web` analyzer
|
|
127
|
+
|
|
128
|
+
AttackMap ships with a `python-web` built-in that handles FastAPI / Flask via the core scanner. When this plugin is installed, both analyzers run on every Python repo. AttackMap's overlay deduplication merges their output so users see a single unified set of findings — no double-counting.
|
|
129
|
+
|
|
130
|
+
This plugin runs at `priority=10`. AttackMap runs analyzers in `(priority, name)` order across built-ins and plugins and merges first-seen-wins, so this plugin runs before the built-in (`priority=20`) and its richer output wins where they overlap.
|
|
131
|
+
|
|
132
|
+
## License
|
|
133
|
+
|
|
134
|
+
MIT
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# attackmap-analyzer-python
|
|
2
|
+
|
|
3
|
+
> [!IMPORTANT]
|
|
4
|
+
> **Active development, slow pace.** AttackMap is under active development, but
|
|
5
|
+
> progress may be slow until more contributors or co-maintainers join. Help is
|
|
6
|
+
> very welcome with the core engine, an analyzer, the macOS app, or the docs —
|
|
7
|
+
> see [CONTRIBUTING.md](CONTRIBUTING.md) or open an issue on
|
|
8
|
+
> [mlaify/AttackMap](https://github.com/mlaify/AttackMap/issues) to say hello.
|
|
9
|
+
> Security reports are still welcome at [security@mlaify.io](mailto:security@mlaify.io).
|
|
10
|
+
|
|
11
|
+
Comprehensive Python ecosystem analyzer for [AttackMap](https://github.com/mlaify/AttackMap).
|
|
12
|
+
|
|
13
|
+
This plugin is **additive** over AttackMap's built-in `python-web` analyzer. The built-in handles FastAPI / Flask routes via the core scanner; this plugin adds everything else.
|
|
14
|
+
|
|
15
|
+
- **Web frameworks** —
|
|
16
|
+
- **Django** routing (`path("users/", ...)`, `path("", ...)` → `/`, `re_path(r"^api/...$", ...)`, legacy `url(...)` / `patterns(...)`) gated by `urlpatterns =` in the file, with the **`include()` graph** resolved repo-wide: `include("app.urls")`, `include(module)`, `include((patterns, "app"))`, `include([...])` and local pattern lists join their prefix onto every child route (`path("api/", include("shop.api_urls"))` + `orders/<int:pk>/` → `/api/orders/<int:pk>/`)
|
|
17
|
+
- **Django REST Framework** routers (`router.register(r'users', UserViewSet)`, any `*Router()`), mounted under their `include(router.urls)` / `urlpatterns = router.urls` prefix, and `@api_view(['GET', 'POST'])` decorators
|
|
18
|
+
- **Starlette** `Route("/x", endpoint=h, methods=["GET", "POST"])` and `WebSocketRoute("/ws/...")`
|
|
19
|
+
- **AIOHTTP** `app.router.add_get/post/...`, `add_route("POST", ...)`, `add_view`, `web.get/post/view(...)` helpers and `web.RouteTableDef()` decorators (`@routes.get("/x")`, `@routes.view`, `@routes.route("PATCH", ...)`) (gated by aiohttp import)
|
|
20
|
+
- **Sanic** `@app.get("/x")`, `@app.post("/x")`, `@app.route("/x", methods=[...])`, `@app.websocket("/ws")` (gated by sanic import)
|
|
21
|
+
- **Litestar** (and legacy Starlite) handlers at any indentation (`@get()`, `@post(path="/x")`, `@route(http_method=[...])`, `@websocket`), `Controller` classes (`path = "/users"` joined onto each handler) and `Router(path=..., route_handlers=[...])` prefixes, including nested routers across files (decorators must be imported from litestar/starlite). `guards=[...]` on the handler/controller/router sets the route's auth to `required`; `exclude_from_auth=True` sets it to `anonymous`
|
|
22
|
+
- **Tornado** `Application([(r"/x", Handler), url(r"/y", H)])` URL specs paired with the handler class's `get`/`post`/... methods (a `WebSocketHandler` is `WS`); `@tornado.web.authenticated` on a method sets its auth to `required`
|
|
23
|
+
- **Flask** `app.add_url_rule("/x", view_func=...)` (additive — built-in covers `@app.route`)
|
|
24
|
+
- **Databases** —
|
|
25
|
+
- **SQLAlchemy** `create_engine("postgresql://...")` with dialect-aware kind inference (postgresql / mysql / mariadb / sqlite / oracle / sqlserver)
|
|
26
|
+
- **asyncpg** / **psycopg2-3** / **pymysql** / **motor.motor_asyncio** / **pymongo** / **redis.asyncio** / **aioredis** / **sqlmodel** / **tortoise**
|
|
27
|
+
- **boto3 resources/clients** for `dynamodb` and `s3`
|
|
28
|
+
- **Django** `DATABASES` dict in `settings.py` — `ENGINE` value parsed for the kind
|
|
29
|
+
- **Auth packages** —
|
|
30
|
+
- **passlib** `CryptContext`, `passlib.hash.argon2/bcrypt/scrypt`
|
|
31
|
+
- **bcrypt** standalone (`bcrypt.hashpw`, `bcrypt.checkpw`)
|
|
32
|
+
- **argon2-cffi** (`from argon2 import PasswordHasher`)
|
|
33
|
+
- **PyJWT** / **python-jose** (`jwt.encode`, `jwt.decode`, `jose.jwt`)
|
|
34
|
+
- **authlib** (`OAuth(...)`, `OAuth2Session(...)`)
|
|
35
|
+
- **fastapi-users** (`BearerTransport`, `JWTStrategy`)
|
|
36
|
+
- **flask-jwt-extended** (`@jwt_required`, `create_access_token`)
|
|
37
|
+
- **django.contrib.auth** (`authenticate`, `make_password`)
|
|
38
|
+
- **casbin** (`Enforcer`)
|
|
39
|
+
- **HTTP clients (external calls)** — **httpx** sync + async, **aiohttp.ClientSession**, **urllib.request.urlopen**
|
|
40
|
+
- **Secrets** —
|
|
41
|
+
- `os.environ.get("X")` and `os.environ["X"]` with secret-shaped names (built-in only covers `os.getenv`)
|
|
42
|
+
- **pydantic-settings** `BaseSettings` field-name extraction (`jwt_secret: str = ...`)
|
|
43
|
+
- `dotenv_values(...)` accessors with secret-shaped keys
|
|
44
|
+
- **Service hints** — `[project] name` from `pyproject.toml`, `[tool.poetry] name`, `name="..."` from `setup.py`, `[metadata] name` from `setup.cfg`, presence of `manage.py` → `framework:django`, Django `INSTALLED_APPS` third-party / local apps
|
|
45
|
+
|
|
46
|
+
All emissions populate AttackMap's Signal v2 fields (line numbers, evidence snippets, confidence) so downstream insights can cite `path/to/module.py:NN`.
|
|
47
|
+
|
|
48
|
+
## Install
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
uv tool install attackmap --with attackmap-analyzer-python \
|
|
52
|
+
--index mlaify=https://pkg.mlaify.io/pypi/simple/ --index-strategy first-index
|
|
53
|
+
# or from source:
|
|
54
|
+
pip install git+https://github.com/mlaify/attackmap-analyzer-python.git
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
The analyzer is auto-discovered by AttackMap via the `attackmap.analyzers` entry-point group.
|
|
58
|
+
|
|
59
|
+
## Usage with AttackMap
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
# Auto-discovered when installed:
|
|
63
|
+
attackmap analyze /path/to/python/repo
|
|
64
|
+
|
|
65
|
+
# Or invoke explicitly:
|
|
66
|
+
attackmap analyze /path/to/python/repo --module python
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Detection
|
|
70
|
+
|
|
71
|
+
`detect()` returns true when any of the following are present, ignoring `.venv/`, `venv/`, `env/`, `.tox/`, `__pycache__/`, `.pytest_cache/`, `dist/`, `build/`, `node_modules/`, `.git/`, `.mypy_cache/`, `.ruff_cache/`, and `site-packages/`:
|
|
72
|
+
|
|
73
|
+
- A `pyproject.toml`, `setup.py`, `setup.cfg`, `manage.py`, or `Pipfile` at the root
|
|
74
|
+
- Any `.py` file in the tree
|
|
75
|
+
|
|
76
|
+
## Coverage notes
|
|
77
|
+
|
|
78
|
+
- **Framework-gated extraction**: route extractors for AIOHTTP, Sanic, Litestar, and Starlette only fire when the file imports the corresponding framework. This prevents mis-attributing generic `@get(...)` / `web.get(...)` / `app.get(...)` calls to a framework when they're really custom decorators or method calls.
|
|
79
|
+
- **Django routing requires `urlpatterns =`** to be in the file. A bare `path("/x", ...)` in any other context (e.g., `pathlib.Path("/x")` is well-behaved, but a project that also has `from django.urls import path; path("/x", view)` outside a urls.py won't fire — by design).
|
|
80
|
+
- **Django settings extraction**: gated by presence of one of `INSTALLED_APPS`, `DATABASES`, `MIDDLEWARE`, or `ROOT_URLCONF`. Built-in Django apps (`django.*`) are filtered out of the INSTALLED_APPS service hints to keep signal high.
|
|
81
|
+
- **DRF `@api_view(['GET', 'POST'])`**: emits framework hints (`drf_api_view:GET`, `drf_api_view:POST`) rather than routes — the actual path is in `urls.py`, which is extracted separately.
|
|
82
|
+
- **Django `include()` resolution**: a module reference resolves only to a URLconf inside the repo (tried from each `manage.py` directory, the repo root, then the including file's ancestors). A resolved `include()` line is a prefix, not an endpoint, so it isn't a route. An include that can't be resolved (a third-party app, `include(get_model_urls(...))`) is still emitted as its prefix (`/accounts/`). A pattern list or router nothing mounts keeps the unprefixed emission. A non-literal route (`path(settings.BASE_PATH, include(...))`) joins as an empty prefix. Regex anchors are stripped when joining, so `re_path(r"^users/$")` is `/users/`. A pattern list is the union of everything assigned to it (reassignments, if/else and try/except branches, `urlpatterns = wrap(urlpatterns)`), so no branch's routes are dropped. The resolver is bounded (5k entries per list, 20k per file, 5k registrations per router, 12 include levels, 64 mounts per list, 200k steps including router registrations, 50k routes) and cycles stop.
|
|
83
|
+
- **Parsing**: URLconfs, Litestar, Tornado and Sanic files are read with `ast` (never executed). A file `ast` can't parse (Python 2, over 1 MB) falls back to the per-file regex extractors.
|
|
84
|
+
- **Not yet**: DRF nested routers' parent prefix, zulip-style custom `rest_path(...)` wrappers, Sanic `Blueprint(url_prefix=...)` joins (core doesn't join them either, so joining here would duplicate routes), and Django route auth decided at the view (`@login_required` on the view function, `LoginRequiredMixin`, DRF `permission_classes`) — see the issue tracker. Auth wrappers applied in the URLconf itself (`login_required(views.x)`, `permission_required("p")(View.as_view())`, `staff_member_required`, `user_passes_test`) do set the route's auth to `required`, and Django 5.1's `login_not_required(...)` sets it to `anonymous`.
|
|
85
|
+
- **pydantic-settings** field extraction matches any class field whose name contains `secret`, `token`, `key`, `password`, `pass`, or `pwd`. False positives are possible (e.g., a non-secret `signing_key` config). Confidence is the standard 0.85.
|
|
86
|
+
|
|
87
|
+
## Coexistence with the built-in `python-web` analyzer
|
|
88
|
+
|
|
89
|
+
AttackMap ships with a `python-web` built-in that handles FastAPI / Flask via the core scanner. When this plugin is installed, both analyzers run on every Python repo. AttackMap's overlay deduplication merges their output so users see a single unified set of findings — no double-counting.
|
|
90
|
+
|
|
91
|
+
This plugin runs at `priority=10`. AttackMap runs analyzers in `(priority, name)` order across built-ins and plugins and merges first-seen-wins, so this plugin runs before the built-in (`priority=20`) and its richer output wins where they overlap.
|
|
92
|
+
|
|
93
|
+
## License
|
|
94
|
+
|
|
95
|
+
MIT
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "attackmap-analyzer-python"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Comprehensive Python ecosystem analyzer plugin for AttackMap (Django, Starlette, AIOHTTP, Sanic, Litestar, DRF; SQLAlchemy/asyncpg/motor; passlib/PyJWT/authlib; httpx/aiohttp)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [
|
|
14
|
+
{name = "Matthew Davis", email = "mlaify@mlaify.io"},
|
|
15
|
+
{name = "AttackMap Contributors"},
|
|
16
|
+
]
|
|
17
|
+
maintainers = [
|
|
18
|
+
{name = "Matthew Davis", email = "mlaify@mlaify.io"},
|
|
19
|
+
]
|
|
20
|
+
keywords = [
|
|
21
|
+
"security",
|
|
22
|
+
"static-analysis",
|
|
23
|
+
"appsec",
|
|
24
|
+
"defensive-security",
|
|
25
|
+
"attackmap",
|
|
26
|
+
"attackmap-plugin",
|
|
27
|
+
]
|
|
28
|
+
classifiers = [
|
|
29
|
+
"Development Status :: 4 - Beta",
|
|
30
|
+
"Intended Audience :: Developers",
|
|
31
|
+
"Intended Audience :: Information Technology",
|
|
32
|
+
"Intended Audience :: System Administrators",
|
|
33
|
+
"Operating System :: OS Independent",
|
|
34
|
+
"Programming Language :: Python :: 3",
|
|
35
|
+
"Programming Language :: Python :: 3.11",
|
|
36
|
+
"Programming Language :: Python :: 3.12",
|
|
37
|
+
"Programming Language :: Python :: 3.13",
|
|
38
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
39
|
+
"Topic :: Security",
|
|
40
|
+
"Topic :: Software Development :: Quality Assurance",
|
|
41
|
+
"Typing :: Typed",
|
|
42
|
+
]
|
|
43
|
+
dependencies = [
|
|
44
|
+
"pydantic>=2.7.0",
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
[project.optional-dependencies]
|
|
48
|
+
core = [
|
|
49
|
+
"attackmap>=0.6.0",
|
|
50
|
+
]
|
|
51
|
+
dev = [
|
|
52
|
+
"pytest>=8.0.0",
|
|
53
|
+
"build>=1.2.0",
|
|
54
|
+
"attackmap>=0.6.0",
|
|
55
|
+
]
|
|
56
|
+
|
|
57
|
+
[project.urls]
|
|
58
|
+
Homepage = "https://github.com/mlaify/attackmap-analyzer-python"
|
|
59
|
+
Repository = "https://github.com/mlaify/attackmap-analyzer-python"
|
|
60
|
+
Issues = "https://github.com/mlaify/attackmap-analyzer-python/issues"
|
|
61
|
+
Changelog = "https://github.com/mlaify/attackmap-analyzer-python/blob/main/CHANGELOG.md"
|
|
62
|
+
"AttackMap core" = "https://github.com/mlaify/AttackMap"
|
|
63
|
+
|
|
64
|
+
[project.entry-points."attackmap.analyzers"]
|
|
65
|
+
python = "attackmap_analyzer_python:PythonAnalyzer"
|
|
66
|
+
|
|
67
|
+
[tool.setuptools]
|
|
68
|
+
package-dir = {"" = "src"}
|
|
69
|
+
|
|
70
|
+
[tool.setuptools.packages.find]
|
|
71
|
+
where = ["src"]
|
|
72
|
+
|
|
73
|
+
[tool.pytest.ini_options]
|
|
74
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Small, defensive helpers around :mod:`ast` for the route extractors.
|
|
2
|
+
|
|
3
|
+
The analyzed repository is untrusted: files can be huge, truncated, Python 2,
|
|
4
|
+
or deliberately pathological. Nothing here executes code — ``ast.parse`` only
|
|
5
|
+
builds a syntax tree — but parsing still has to be bounded and must never
|
|
6
|
+
raise out of ``analyze()``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import ast
|
|
12
|
+
|
|
13
|
+
# Files above this size are left to the regex extractors. Real URLconfs,
|
|
14
|
+
# controllers and handler modules are far smaller; this only bounds the cost of
|
|
15
|
+
# a hostile or generated file.
|
|
16
|
+
MAX_PARSE_CHARS = 1_000_000
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def safe_parse(content: str) -> ast.Module | None:
|
|
20
|
+
"""Parse ``content`` or return ``None`` (too big, not Python 3, hostile)."""
|
|
21
|
+
if len(content) > MAX_PARSE_CHARS:
|
|
22
|
+
return None
|
|
23
|
+
try:
|
|
24
|
+
return ast.parse(content)
|
|
25
|
+
except (SyntaxError, ValueError, RecursionError, MemoryError, OverflowError):
|
|
26
|
+
return None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def call_name(node: ast.AST) -> str | None:
|
|
30
|
+
"""The trailing name of a call target: ``path`` for ``path(...)`` and
|
|
31
|
+
``urls.path(...)``, ``DefaultRouter`` for ``routers.DefaultRouter()``."""
|
|
32
|
+
if isinstance(node, ast.Call):
|
|
33
|
+
node = node.func
|
|
34
|
+
if isinstance(node, ast.Name):
|
|
35
|
+
return node.id
|
|
36
|
+
if isinstance(node, ast.Attribute):
|
|
37
|
+
return node.attr
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def dotted(node: ast.AST, *, max_parts: int = 8) -> str | None:
|
|
42
|
+
"""``a.b.c`` for a Name/Attribute chain, else ``None``."""
|
|
43
|
+
parts: list[str] = []
|
|
44
|
+
while isinstance(node, ast.Attribute) and len(parts) < max_parts:
|
|
45
|
+
parts.append(node.attr)
|
|
46
|
+
node = node.value
|
|
47
|
+
if not isinstance(node, ast.Name) or len(parts) >= max_parts:
|
|
48
|
+
return None
|
|
49
|
+
parts.append(node.id)
|
|
50
|
+
return ".".join(reversed(parts))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def str_const(node: ast.AST | None) -> str | None:
|
|
54
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
|
55
|
+
return node.value
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def keyword(call: ast.Call, name: str) -> ast.expr | None:
|
|
60
|
+
for kw in call.keywords:
|
|
61
|
+
if kw.arg == name:
|
|
62
|
+
return kw.value
|
|
63
|
+
return None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def str_list(node: ast.AST | None, *, limit: int = 64) -> list[str] | None:
|
|
67
|
+
"""String elements of a list/tuple/set literal (non-strings skipped), or
|
|
68
|
+
``None`` when ``node`` isn't such a literal."""
|
|
69
|
+
if not isinstance(node, (ast.List, ast.Tuple, ast.Set)):
|
|
70
|
+
return None
|
|
71
|
+
out: list[str] = []
|
|
72
|
+
for elt in node.elts[:limit]:
|
|
73
|
+
value = str_const(elt)
|
|
74
|
+
if value is not None:
|
|
75
|
+
out.append(value)
|
|
76
|
+
return out
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def expr_names(node: ast.AST | None, *, limit: int = 16) -> list[str]:
|
|
80
|
+
"""Readable names of the elements of a list/tuple literal (``[a, b.c]`` →
|
|
81
|
+
``["a", "b.c"]``; calls give their callee)."""
|
|
82
|
+
if not isinstance(node, (ast.List, ast.Tuple, ast.Set)):
|
|
83
|
+
return []
|
|
84
|
+
out: list[str] = []
|
|
85
|
+
for elt in node.elts[:limit]:
|
|
86
|
+
target = elt.func if isinstance(elt, ast.Call) else elt
|
|
87
|
+
name = dotted(target)
|
|
88
|
+
if name:
|
|
89
|
+
out.append(name)
|
|
90
|
+
return out
|