attackmap-analyzer-php-web 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.

Potentially problematic release.


This version of attackmap-analyzer-php-web might be problematic. Click here for more details.

@@ -0,0 +1,4 @@
1
+ from .analyzer import PhpWebAnalyzer
2
+ from .contracts import AnalyzerMetadata
3
+
4
+ __all__ = ["AnalyzerMetadata", "PhpWebAnalyzer"]
@@ -0,0 +1,230 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ from pathlib import Path
6
+
7
+ from .contracts import AnalyzerMetadata, AuthHint, DatabaseHint, ExternalCall, Route, ScanResult, SecretHint
8
+
9
+ HTTP_METHODS = ("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD")
10
+
11
+ LARAVEL_ROUTE_PATTERN = re.compile(
12
+ r"\bRoute::(get|post|put|patch|delete|options|head|any|match)\s*\(\s*['\"]([^'\"]+)['\"]",
13
+ re.IGNORECASE,
14
+ )
15
+ SLIM_ROUTE_PATTERN = re.compile(
16
+ r"\$\w+->(get|post|put|patch|delete|options|head|any|map)\s*\(\s*['\"]([^'\"]+)['\"]",
17
+ re.IGNORECASE,
18
+ )
19
+ ATTRIBUTE_ROUTE_PATTERN = re.compile(
20
+ r"#\[\s*Route\s*\(\s*['\"]([^'\"]+)['\"](?P<args>.*?)\)\s*\]",
21
+ re.IGNORECASE | re.DOTALL,
22
+ )
23
+ ATTRIBUTE_METHOD_PATTERN = re.compile(r"['\"](GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)['\"]", re.IGNORECASE)
24
+ CONFIG_ROUTE_PATH_PATTERN = re.compile(r"['\"]path['\"]\s*=>\s*['\"]([^'\"]+)['\"]", re.IGNORECASE)
25
+
26
+ OUTBOUND_PATTERNS = [
27
+ re.compile(r"curl_init\s*\(\s*['\"](https?://[^'\"]+)['\"]", re.IGNORECASE),
28
+ re.compile(r"file_get_contents\s*\(\s*['\"](https?://[^'\"]+)['\"]", re.IGNORECASE),
29
+ re.compile(r"->request\s*\(\s*['\"](?:GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)['\"]\s*,\s*['\"](https?://[^'\"]+)['\"]", re.IGNORECASE),
30
+ re.compile(r"->(?:get|post|put|patch|delete)\s*\(\s*['\"](https?://[^'\"]+)['\"]", re.IGNORECASE),
31
+ ]
32
+
33
+ DATABASE_PATTERNS = [
34
+ (re.compile(r"\bnew\s+PDO\s*\(", re.IGNORECASE), "sql"),
35
+ (re.compile(r"\bmysqli_connect\s*\(", re.IGNORECASE), "mysql"),
36
+ (re.compile(r"\bnew\s+mysqli\s*\(", re.IGNORECASE), "mysql"),
37
+ (re.compile(r"Doctrine\\DBAL|Doctrine\\ORM|EntityManager", re.IGNORECASE), "sql"),
38
+ (re.compile(r"\bpg_connect\s*\(", re.IGNORECASE), "postgresql"),
39
+ (re.compile(r"\bRedis\s*::|\bnew\s+Redis\s*\(", re.IGNORECASE), "redis"),
40
+ ]
41
+
42
+ AUTH_PATTERNS = [
43
+ (re.compile(r"\bsession_start\s*\(", re.IGNORECASE), "session"),
44
+ (re.compile(r"\$_SESSION\b", re.IGNORECASE), "session"),
45
+ (re.compile(r"\bpassword_hash\s*\(", re.IGNORECASE), "password_hash"),
46
+ (re.compile(r"\bpassword_verify\s*\(", re.IGNORECASE), "password_verify"),
47
+ (re.compile(r"JWT|firebase\\jwt", re.IGNORECASE), "jwt"),
48
+ (re.compile(r"\bmiddleware\s*\(\s*['\"]auth['\"]", re.IGNORECASE), "auth_middleware"),
49
+ (re.compile(r"\bAuth::|\bauth\s*\(", re.IGNORECASE), "auth"),
50
+ ]
51
+
52
+ SECRET_PATTERNS = [
53
+ re.compile(r"getenv\s*\(\s*['\"]([A-Z0-9_]*(SECRET|TOKEN|KEY|PASSWORD|API|DB)[A-Z0-9_]*)['\"]", re.IGNORECASE),
54
+ re.compile(r"\$_ENV\s*\[\s*['\"]([A-Z0-9_]*(SECRET|TOKEN|KEY|PASSWORD|API|DB)[A-Z0-9_]*)['\"]\s*\]", re.IGNORECASE),
55
+ re.compile(r"\$_SERVER\s*\[\s*['\"]([A-Z0-9_]*(SECRET|TOKEN|KEY|PASSWORD|API|DB)[A-Z0-9_]*)['\"]\s*\]", re.IGNORECASE),
56
+ ]
57
+
58
+
59
+ class PhpWebAnalyzer:
60
+ metadata = AnalyzerMetadata(
61
+ name="php-web",
62
+ display_name="PHP Web Analyzer",
63
+ version="0.1.0",
64
+ description="Broad PHP web analyzer that emits structured security-relevant scan signals.",
65
+ scope="Generic PHP web projects using route declarations, web controllers, and common HTTP/database/auth patterns.",
66
+ targets=["php-web"],
67
+ languages=["php"],
68
+ priority=40,
69
+ experimental=True,
70
+ enabled_by_default=False,
71
+ )
72
+
73
+ @property
74
+ def name(self) -> str:
75
+ return self.metadata.name
76
+
77
+ def detect(self, repo_path: str | Path) -> bool:
78
+ root = Path(repo_path).resolve()
79
+ if not root.exists() or not root.is_dir():
80
+ return False
81
+
82
+ if (root / "composer.json").exists():
83
+ return True
84
+
85
+ if any((root / directory).is_dir() for directory in ("src", "app", "module", "public", "config")):
86
+ return True
87
+
88
+ return any(root.rglob("*.php"))
89
+
90
+ def analyze(self, repo_path: str | Path) -> ScanResult:
91
+ root = Path(repo_path).resolve()
92
+ result = ScanResult(root=str(root))
93
+
94
+ if not root.exists() or not root.is_dir():
95
+ return result
96
+
97
+ composer_path = root / "composer.json"
98
+ if composer_path.exists():
99
+ self._extract_composer_signals(composer_path, result)
100
+
101
+ for file_path in root.rglob("*.php"):
102
+ if not file_path.is_file():
103
+ continue
104
+ if any(part in {"vendor", ".git", "node_modules"} for part in file_path.parts):
105
+ continue
106
+
107
+ result.files_scanned += 1
108
+ if "php" not in result.languages:
109
+ result.languages.append("php")
110
+
111
+ content = self._read_text(file_path)
112
+ if content is None:
113
+ continue
114
+
115
+ relative = str(file_path.relative_to(root))
116
+ self._extract_routes(content, relative, result)
117
+ self._extract_external_calls(content, relative, result)
118
+ self._extract_datastores(content, relative, result)
119
+ self._extract_auth_hints(content, relative, result)
120
+ self._extract_secret_hints(content, relative, result)
121
+
122
+ result.languages.sort()
123
+ return result
124
+
125
+ def _extract_composer_signals(self, composer_path: Path, result: ScanResult) -> None:
126
+ try:
127
+ data = json.loads(composer_path.read_text(encoding="utf-8"))
128
+ except (UnicodeDecodeError, json.JSONDecodeError):
129
+ return
130
+
131
+ requirements = {
132
+ **(data.get("require", {}) if isinstance(data.get("require", {}), dict) else {}),
133
+ **(data.get("require-dev", {}) if isinstance(data.get("require-dev", {}), dict) else {}),
134
+ }
135
+
136
+ for package in requirements:
137
+ lower = package.lower()
138
+ if "doctrine" in lower:
139
+ self._append_unique_database(result, "sql", "composer.json")
140
+ if "guzzle" in lower or "symfony/http-client" in lower:
141
+ self._append_unique_auth(result, "http_client", "composer.json")
142
+ if "firebase/php-jwt" in lower:
143
+ self._append_unique_auth(result, "jwt", "composer.json")
144
+
145
+ def _extract_routes(self, content: str, relative: str, result: ScanResult) -> None:
146
+ for match in LARAVEL_ROUTE_PATTERN.finditer(content):
147
+ method, path = match.group(1).upper(), match.group(2)
148
+ if method == "ANY" or method == "MATCH":
149
+ method = "ANY"
150
+ self._append_unique_route(result, path, method, relative)
151
+
152
+ for match in SLIM_ROUTE_PATTERN.finditer(content):
153
+ method, path = match.group(1).upper(), match.group(2)
154
+ if method == "MAP" or method == "ANY":
155
+ method = "ANY"
156
+ self._append_unique_route(result, path, method, relative)
157
+
158
+ for match in ATTRIBUTE_ROUTE_PATTERN.finditer(content):
159
+ path = match.group(1)
160
+ args = match.group("args")
161
+ methods = [m.upper() for m in ATTRIBUTE_METHOD_PATTERN.findall(args)]
162
+ if not methods:
163
+ methods = ["ANY"]
164
+ for method in methods:
165
+ self._append_unique_route(result, path, method, relative)
166
+
167
+ for match in CONFIG_ROUTE_PATH_PATTERN.finditer(content):
168
+ self._append_unique_route(result, match.group(1), "ANY", relative)
169
+
170
+ def _extract_external_calls(self, content: str, relative: str, result: ScanResult) -> None:
171
+ for pattern in OUTBOUND_PATTERNS:
172
+ for match in pattern.finditer(content):
173
+ self._append_unique_external(result, match.group(1), relative)
174
+
175
+ def _extract_datastores(self, content: str, relative: str, result: ScanResult) -> None:
176
+ for pattern, kind in DATABASE_PATTERNS:
177
+ if pattern.search(content):
178
+ self._append_unique_database(result, kind, relative)
179
+
180
+ def _extract_auth_hints(self, content: str, relative: str, result: ScanResult) -> None:
181
+ for pattern, hint in AUTH_PATTERNS:
182
+ if pattern.search(content):
183
+ self._append_unique_auth(result, hint, relative)
184
+
185
+ def _extract_secret_hints(self, content: str, relative: str, result: ScanResult) -> None:
186
+ for pattern in SECRET_PATTERNS:
187
+ for match in pattern.finditer(content):
188
+ self._append_unique_secret(result, match.group(1), relative)
189
+
190
+ @staticmethod
191
+ def _read_text(path: Path) -> str | None:
192
+ try:
193
+ return path.read_text(encoding="utf-8")
194
+ except UnicodeDecodeError:
195
+ return None
196
+
197
+ @staticmethod
198
+ def _append_unique_route(result: ScanResult, path: str, method: str, file: str) -> None:
199
+ key = (path, method, file)
200
+ if any((item.path, item.method, item.file) == key for item in result.routes):
201
+ return
202
+ result.routes.append(Route(path=path, method=method, file=file))
203
+
204
+ @staticmethod
205
+ def _append_unique_external(result: ScanResult, target: str, file: str) -> None:
206
+ key = (target, file)
207
+ if any((item.target, item.file) == key for item in result.external_calls):
208
+ return
209
+ result.external_calls.append(ExternalCall(target=target, file=file))
210
+
211
+ @staticmethod
212
+ def _append_unique_database(result: ScanResult, kind: str, file: str) -> None:
213
+ key = (kind, file)
214
+ if any((item.kind, item.file) == key for item in result.databases):
215
+ return
216
+ result.databases.append(DatabaseHint(kind=kind, file=file))
217
+
218
+ @staticmethod
219
+ def _append_unique_auth(result: ScanResult, hint: str, file: str) -> None:
220
+ key = (hint, file)
221
+ if any((item.hint, item.file) == key for item in result.auth_hints):
222
+ return
223
+ result.auth_hints.append(AuthHint(hint=hint, file=file))
224
+
225
+ @staticmethod
226
+ def _append_unique_secret(result: ScanResult, name: str, file: str) -> None:
227
+ key = (name, file)
228
+ if any((item.name, item.file) == key for item in result.secret_hints):
229
+ return
230
+ result.secret_hints.append(SecretHint(name=name, file=file))
@@ -0,0 +1,18 @@
1
+ from __future__ import annotations
2
+
3
+ from attackmap.sdk.contracts import AnalyzerMetadata, AnalyzerProtocol
4
+ from attackmap.sdk.models import AuthHint, DatabaseHint, ExternalCall, Route, ScanResult, SecretHint
5
+
6
+ # Compatibility alias used by existing analyzer implementations.
7
+ AttackMapAnalyzerProtocol = AnalyzerProtocol
8
+
9
+ __all__ = [
10
+ "AnalyzerMetadata",
11
+ "AttackMapAnalyzerProtocol",
12
+ "Route",
13
+ "ExternalCall",
14
+ "DatabaseHint",
15
+ "AuthHint",
16
+ "SecretHint",
17
+ "ScanResult",
18
+ ]
@@ -0,0 +1,133 @@
1
+ Metadata-Version: 2.4
2
+ Name: attackmap-analyzer-php-web
3
+ Version: 0.1.0
4
+ Summary: Broad PHP web analyzer plugin for AttackMap
5
+ Author: AttackMap Contributors
6
+ Author-email: Matthew Davis <matthewd@matthewd.xyz>
7
+ Maintainer-email: Matthew Davis <matthewd@matthewd.xyz>
8
+ License: MIT
9
+ Project-URL: Homepage, https://github.com/mlaify/attackmap-analyzer-php-web
10
+ Project-URL: Repository, https://github.com/mlaify/attackmap-analyzer-php-web
11
+ Project-URL: Issues, https://github.com/mlaify/attackmap-analyzer-php-web/issues
12
+ Project-URL: Changelog, https://github.com/mlaify/attackmap-analyzer-php-web/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: License :: OSI Approved :: MIT License
20
+ Classifier: Operating System :: OS Independent
21
+ Classifier: Programming Language :: Python :: 3
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Programming Language :: Python :: 3 :: Only
26
+ Classifier: Topic :: Security
27
+ Classifier: Topic :: Software Development :: Quality Assurance
28
+ Classifier: Typing :: Typed
29
+ Requires-Python: >=3.11
30
+ Description-Content-Type: text/markdown
31
+ License-File: LICENSE
32
+ Requires-Dist: pydantic>=2.7.0
33
+ Provides-Extra: core
34
+ Requires-Dist: attackmap>=0.1.0; extra == "core"
35
+ Provides-Extra: dev
36
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
37
+ Requires-Dist: build>=1.2.0; extra == "dev"
38
+ Requires-Dist: attackmap>=0.1.0; extra == "dev"
39
+ Dynamic: license-file
40
+
41
+ # attackmap-analyzer-php-web
42
+
43
+ Broad PHP web analyzer for [AttackMap](https://github.com/mlaify/AttackMap).
44
+
45
+ This repository is intentionally separate from AttackMap core. It focuses only on extracting structured signals from PHP repositories:
46
+
47
+ - routes
48
+ - outbound HTTP calls
49
+ - datastore hints
50
+ - auth hints
51
+ - secret and env usage
52
+
53
+ It does not render reports and does not own global severity policy.
54
+
55
+ ## Analyzer identity
56
+
57
+ - `name`: `php-web`
58
+ - `display_name`: `PHP Web Analyzer`
59
+ - `version`: `0.1.0`
60
+ - `experimental`: `true`
61
+ - `enabled_by_default`: `false`
62
+
63
+ ## Scope
64
+
65
+ This analyzer is broad and heuristic. It is meant to map common PHP web application surfaces before framework-specific analyzers (for example `php-laminas` or `omeka-s`) are added.
66
+
67
+ ## Detection strategy
68
+
69
+ `detect(repo_path)` uses lightweight signals:
70
+
71
+ - `composer.json` present
72
+ - at least one `.php` file
73
+ - common PHP app layout (`src/`, `app/`, `module/`, `public/`)
74
+
75
+ ## Extraction strategy
76
+
77
+ `analyze(repo_path)` scans `.php` files and emits structured signals using regular-expression heuristics.
78
+
79
+ Route extraction currently includes patterns such as:
80
+
81
+ - `Route::get(...)`/`Route::post(...)` style calls
82
+ - `$app->get(...)` style calls
83
+ - PHP attributes like `#[Route("/path", methods: ["GET"]) ]`
84
+ - basic config-style `"path" => "/..."`
85
+
86
+ Outbound calls currently include patterns such as:
87
+
88
+ - `curl_init("https://...")`
89
+ - `file_get_contents("https://...")`
90
+ - common HTTP client calls such as `->request(...)`, `->get(...)`, `->post(...)`
91
+
92
+ Datastore/auth/secret hints are similarly heuristic and intended as first-pass signals.
93
+
94
+ ## Installation
95
+
96
+ ```bash
97
+ pip install attackmap-analyzer-php-web
98
+ ```
99
+
100
+ For local development:
101
+
102
+ ```bash
103
+ pip install -e .[dev]
104
+ ```
105
+
106
+ ## Contract alignment with AttackMap core
107
+
108
+ This package targets the current AttackMap analyzer contract:
109
+
110
+ - analyzer exposes metadata via `metadata`
111
+ - analyzer implements `detect(repo_path)` and `analyze(repo_path)`
112
+ - `analyze` returns AttackMap-style structured scan data (`ScanResult` shape)
113
+
114
+ The package includes a small compatibility layer so tests can run even if AttackMap core is not installed.
115
+
116
+ ## Future core discovery (documented, not implemented here)
117
+
118
+ AttackMap core can discover this analyzer later via one of these options:
119
+
120
+ 1. entry points (preferred long-term)
121
+ 2. explicit configured analyzer list
122
+ 3. namespace/package scanning in `github.com/mlaify`
123
+
124
+ This repository does not implement core-side discovery logic.
125
+
126
+ ## Limitations
127
+
128
+ - regex-based extraction (not AST)
129
+ - limited config route parsing
130
+ - no framework-specific deep parsing yet
131
+ - no dataflow or reachability modeling inside this analyzer
132
+
133
+ These are deliberate to keep this first external analyzer incremental and maintainable.
@@ -0,0 +1,9 @@
1
+ attackmap_analyzer_php_web/__init__.py,sha256=RlETo1Ve9hK2XYpGkHEfLgufhuM5o0nvQzg7-GRxJq4,127
2
+ attackmap_analyzer_php_web/analyzer.py,sha256=VmPntrd90pr1pc86jHimSWNcNrj1Rsluujw5C66KMOg,9846
3
+ attackmap_analyzer_php_web/contracts.py,sha256=uwshWT7fHGD_lTg8LGS-4JxuHlRQJ7ejBS92Ls3p6Vc,496
4
+ attackmap_analyzer_php_web-0.1.0.dist-info/licenses/LICENSE,sha256=vtPQVGUyxq359j0JmD3_eJaXyHmaHyjzaMOtaLwJc88,1097
5
+ attackmap_analyzer_php_web-0.1.0.dist-info/METADATA,sha256=gBz8QbBZ7lAN703R2lTu36jtfEl3FO3SlbG3jGOFWSc,4530
6
+ attackmap_analyzer_php_web-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
7
+ attackmap_analyzer_php_web-0.1.0.dist-info/entry_points.txt,sha256=GCrZaoTapBvwl8DNL0lM7yyvmvLL8qJmqQLGr8ekXMg,74
8
+ attackmap_analyzer_php_web-0.1.0.dist-info/top_level.txt,sha256=2hL5g79YjmLnbFa4mkFsUoMmHqNGlcqLI2rb7d2iUWo,27
9
+ attackmap_analyzer_php_web-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [attackmap.analyzers]
2
+ php_web = attackmap_analyzer_php_web:PhpWebAnalyzer
@@ -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_php_web