attackmap-analyzer-cpp 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-cpp might be problematic. Click here for more details.

@@ -0,0 +1,3 @@
1
+ from .analyzer import CppAnalyzer
2
+
3
+ __all__ = ["CppAnalyzer"]
@@ -0,0 +1,449 @@
1
+ """C++ ecosystem analyzer for AttackMap.
2
+
3
+ Coverage (v0.1):
4
+ - Web frameworks: Crow (CROW_ROUTE macro routes), Pistache (Routes::Get/Post/...),
5
+ Drogon (registerHandler + ADD_METHOD_TO macro), cpprestsdk (http_listener URL +
6
+ listener.support method handlers)
7
+ - HTTP clients (external calls): libcurl (CURLOPT_URL), cpprestsdk
8
+ http_client(URL), cpr (cpr::Get/Post/Put/Delete with cpr::Url{...})
9
+ - Databases: libpqxx (pqxx::connection), MySQL X DevAPI (mysqlx::Session),
10
+ mongocxx (mongocxx::client + mongocxx::uri), redis-plus-plus
11
+ (sw::redis::Redis), SOCI (soci::session), sqlite_orm (header-only sqlite)
12
+ - Auth/crypto: OpenSSL (TLS / EVP / RAND), Botan (TLS / KDF / cipher),
13
+ libsodium (crypto_pwhash, crypto_secretbox, AEAD), Crypto++
14
+ (CryptoPP::AES/SHA256/Argon2), JWT C++ libraries (jwt::create, jwt::decode,
15
+ jwt::verify)
16
+ - Secrets: getenv / std::getenv with secret-shaped names
17
+ - Service hints: project name from CMakeLists.txt project() declaration
18
+
19
+ C++ shares much of its data-plane vocabulary with C (libcurl, OpenSSL,
20
+ libsodium) — those patterns are duplicated here so a pure-C++ project
21
+ without the C analyzer installed still gets full coverage. AttackMap's
22
+ overlay deduplication handles cases where both analyzers fire on the
23
+ same evidence.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import re
29
+ from pathlib import Path
30
+
31
+ from .contracts import (
32
+ AnalyzerMetadata,
33
+ AuthHint,
34
+ DatabaseHint,
35
+ EntrypointHint,
36
+ ExternalCall,
37
+ FrameworkHint,
38
+ Route,
39
+ ScanResult,
40
+ SecretHint,
41
+ ServiceHint,
42
+ )
43
+
44
+ CODE_SUFFIXES = {".cpp", ".cc", ".cxx", ".hpp", ".hxx", ".ipp", ".tpp"}
45
+ SKIP_DIRS = {
46
+ "build",
47
+ ".git",
48
+ "_deps",
49
+ "third_party",
50
+ "vendor",
51
+ "external",
52
+ ".cache",
53
+ "out",
54
+ "node_modules",
55
+ "Debug",
56
+ "Release",
57
+ }
58
+ _SNIPPET_MAX_CHARS = 160
59
+
60
+
61
+ # ---------- Patterns ----------
62
+
63
+ # Crow: CROW_ROUTE(app, "/path") or CROW_ROUTE(app, "/path").methods("POST"_method)
64
+ CROW_ROUTE_PATTERN = re.compile(
65
+ r'\bCROW_ROUTE\s*\(\s*\w+\s*,\s*"([^"]+)"\s*\)(?P<chain>(?:\s*\.\s*\w+\([^)]*\))*)',
66
+ )
67
+ # Crow .methods("POST"_method, "PUT"_method)
68
+ CROW_METHODS_PATTERN = re.compile(
69
+ r'\.methods\s*\(\s*((?:"[A-Z]+"_method(?:\s*,\s*)?)+)\s*\)',
70
+ )
71
+
72
+ # Pistache: Routes::Get(router, "/path", handler), Routes::Post(...)
73
+ PISTACHE_ROUTE_PATTERN = re.compile(
74
+ r'\b(?:Pistache::)?(?:Rest::)?Routes::(Get|Post|Put|Delete|Patch|Head|Options)\s*\(\s*\w+\s*,\s*"([^"]+)"',
75
+ )
76
+
77
+ # Drogon: app().registerHandler("/path", handler, {Drogon::Get, Drogon::Post})
78
+ # Handler arg may be a lambda containing commas, so match non-greedy across the
79
+ # middle and anchor on the trailing `{ Drogon::* }` brace.
80
+ DROGON_REGISTER_PATTERN = re.compile(
81
+ r'\bregisterHandler\s*\(\s*"([^"]+)"\s*,.+?,\s*\{([^}]*)\}\s*\)',
82
+ re.DOTALL,
83
+ )
84
+
85
+ # Drogon annotation-style: METHOD_LIST_BEGIN ADD_METHOD_TO(controller::handler, "/path", Get) METHOD_LIST_END
86
+ DROGON_ADD_METHOD_PATTERN = re.compile(
87
+ r'\bADD_METHOD_TO\s*\(\s*[^,]+,\s*"([^"]+)"\s*,\s*([A-Za-z]+)',
88
+ )
89
+
90
+ # cpprestsdk: web::http::experimental::listener::http_listener listener("https://example.com/api");
91
+ CPPRESTSDK_LISTENER_PATTERN = re.compile(
92
+ r'\bhttp_listener\s+\w+\s*\(\s*(?:U\s*\(\s*)?"(https?://[^")]+)"',
93
+ )
94
+
95
+ # External HTTP calls
96
+ OUTBOUND_PATTERNS: list[re.Pattern[str]] = [
97
+ re.compile(r'\bcurl_easy_setopt\s*\(\s*\w+\s*,\s*CURLOPT_URL\s*,\s*"(https?://[^"]+)"'),
98
+ re.compile(r'\bcpr::(?:Get|Post|Put|Delete|Patch|Head)\s*\(\s*cpr::Url\s*\{\s*"(https?://[^"]+)"'),
99
+ # Permissive http_client(URL) — namespace prefix may be `using`-elided.
100
+ re.compile(r'\bhttp_client\s+\w+\s*\(\s*(?:U\s*\(\s*)?"(https?://[^")]+)"'),
101
+ re.compile(r'\bRequest\s+\w+\s*\(\s*"(https?://[^"]+)"'),
102
+ ]
103
+
104
+ # DBs
105
+ DB_PATTERNS: list[tuple[re.Pattern[str], str]] = [
106
+ (re.compile(r'\bpqxx::connection\b|\bpqxx::work\b|#\s*include\s+["<]pqxx/'), "postgresql"),
107
+ (re.compile(r'\bmysqlx::Session\b|\bmysqlx::SessionSettings\b|#\s*include\s+["<]mysqlx/'), "mysql"),
108
+ (re.compile(r'\bmongocxx::client\b|\bmongocxx::uri\b|#\s*include\s+["<]mongocxx/'), "mongodb"),
109
+ (re.compile(r'\bsw::redis::Redis\b|\bsw::redis::RedisCluster\b|#\s*include\s+["<]sw/redis\+\+'), "redis"),
110
+ (re.compile(r'\bsoci::session\b|\bsoci::statement\b'), "sql"),
111
+ (re.compile(r'\bsqlite_orm::make_storage\b|\bsqlite3_open(?:_v2)?\s*\('), "sqlite"),
112
+ (re.compile(r'\bsql::mysql::MySQL_Driver\b|\bMySQL_Connection\b'), "mysql"),
113
+ ]
114
+
115
+ # Auth / crypto
116
+ AUTH_PATTERNS: list[tuple[re.Pattern[str], str, float]] = [
117
+ (re.compile(r'\bcrypto_pwhash(?:_argon2(?:i|id))?\s*\(|\bcrypto_pwhash_str\s*\('), "argon2", 0.9),
118
+ (re.compile(r'\bargon2(?:i|d|id)?_hash\w*\s*\(|\bCryptoPP::Argon2\b'), "argon2", 0.9),
119
+ (re.compile(r'\bbcrypt(?:_hashpw|_checkpw|_gensalt)?\s*\(|\bCryptoPP::BCrypt\b'), "bcrypt", 0.9),
120
+ (re.compile(r'\bscrypt(?:_kdf)?\s*\(|\bBotan::Scrypt\b|\bCryptoPP::Scrypt\b'), "scrypt", 0.9),
121
+ (re.compile(r'\bcrypto_secretbox\w*\s*\(|\bcrypto_aead_(?:chacha20poly1305|aes256gcm)\w*\s*\('), "libsodium_aead", 0.85),
122
+ (re.compile(r'\bSSL_CTX_new\s*\(|\bSSL_new\s*\(|\bTLS_method\s*\(|\bTLS_(?:client|server)_method\s*\('), "openssl_tls", 0.85),
123
+ (re.compile(r'\bEVP_PKEY_new\s*\(|\bEVP_(?:Encrypt|Decrypt)Init\w*\s*\('), "openssl_evp", 0.8),
124
+ (re.compile(r'\bBotan::TLS::(?:Server|Client)\b|\bBotan::Cipher_Mode\b|\bBotan::PKCS5_PBKDF2\b'), "botan", 0.85),
125
+ (re.compile(r'\bjwt::create\s*\(|\bjwt::decode\s*\(|\bjwt::verify\s*\(|#\s*include\s+["<]jwt-cpp/'), "jwt", 0.85),
126
+ (re.compile(r'\bCryptoPP::AES\b|\bCryptoPP::SHA(?:256|384|512|3)\b|\bCryptoPP::HMAC\b'), "cryptopp", 0.85),
127
+ (re.compile(r'\bAuthorization\b'), "authorization_header", 0.6),
128
+ (re.compile(r'\bBearer\b'), "bearer_token", 0.6),
129
+ (re.compile(r'\bapi[_-]?key\b', re.IGNORECASE), "api_key", 0.6),
130
+ ]
131
+
132
+ FRAMEWORK_PATTERNS: list[tuple[re.Pattern[str], str]] = [
133
+ (re.compile(r'\bcrow::SimpleApp\b|#\s*include\s+["<]crow\.h|\bCROW_ROUTE\s*\('), "crow"),
134
+ (re.compile(r'\bPistache::(?:Http|Rest)\b|#\s*include\s+["<]pistache/'), "pistache"),
135
+ (re.compile(r'\bdrogon::HttpAppFramework\b|\bapp\(\)\.registerHandler\b|#\s*include\s+["<]drogon/'), "drogon"),
136
+ (re.compile(r'\bweb::http::experimental::listener\b|#\s*include\s+["<]cpprest/'), "cpprestsdk"),
137
+ (re.compile(r'\bboost::beast\b|#\s*include\s+["<]boost/beast'), "boost-beast"),
138
+ (re.compile(r'\bPoco::Net::HTTPServer\b|#\s*include\s+["<]Poco/Net/'), "poco-net"),
139
+ (re.compile(r'\boatpp::web::server\b|#\s*include\s+["<]oatpp/'), "oatpp"),
140
+ (re.compile(r'#\s*include\s+["<]openssl/'), "openssl"),
141
+ (re.compile(r'#\s*include\s+["<]botan/'), "botan"),
142
+ (re.compile(r'#\s*include\s+["<]sodium\.h'), "libsodium"),
143
+ (re.compile(r'#\s*include\s+["<]cryptopp/'), "cryptopp"),
144
+ (re.compile(r'#\s*include\s+["<]curl/curl\.h|#\s*include\s+["<]cpr/'), "libcurl"),
145
+ (re.compile(r'#\s*include\s+["<]pqxx/'), "libpqxx"),
146
+ (re.compile(r'#\s*include\s+["<]mongocxx/'), "mongocxx"),
147
+ (re.compile(r'#\s*include\s+["<]sw/redis\+\+'), "redis-plus-plus"),
148
+ ]
149
+
150
+ ENTRYPOINT_PATTERNS: list[tuple[re.Pattern[str], str]] = [
151
+ (re.compile(r'\bapp\.(?:port|bindaddr|run|multithreaded)\(.*?\)\.run\s*\(\s*\)', re.DOTALL), "crow_app_run"),
152
+ (re.compile(r'\bcrow::SimpleApp\b'), "crow_app"),
153
+ (re.compile(r'\b\w+\.serve\s*\(\s*\)', re.IGNORECASE), "pistache_serve"),
154
+ (re.compile(r'\bapp\(\)\.run\s*\(\s*\)|\bdrogon::app\(\)\.run\b'), "drogon_run"),
155
+ (re.compile(r'\blistener\.open\s*\(\s*\)\.wait\s*\(\s*\)|\blistener\.open\s*\(\s*\)\.then\b'), "cpprestsdk_listener_open"),
156
+ (re.compile(r'\bPoco::Net::HTTPServer\s+\w+'), "poco_http_server"),
157
+ ]
158
+
159
+ # Secrets via getenv / std::getenv
160
+ SECRET_PATTERNS: list[re.Pattern[str]] = [
161
+ re.compile(
162
+ r'\b(?:std::)?(?:secure_)?getenv\s*\(\s*"([A-Z0-9_]*(?:SECRET|TOKEN|KEY|PASSWORD|PASS|PWD)[A-Z0-9_]*)"',
163
+ ),
164
+ ]
165
+
166
+
167
+ def _line_of(content: str, offset: int) -> int:
168
+ if offset <= 0:
169
+ return 1
170
+ return content.count("\n", 0, offset) + 1
171
+
172
+
173
+ def _line_snippet(content: str, offset: int, *, max_chars: int = _SNIPPET_MAX_CHARS) -> str:
174
+ line_start = content.rfind("\n", 0, offset) + 1
175
+ line_end = content.find("\n", offset)
176
+ if line_end == -1:
177
+ line_end = len(content)
178
+ line = content[line_start:line_end].strip()
179
+ if len(line) > max_chars:
180
+ line = line[: max_chars - 1] + "…"
181
+ return line
182
+
183
+
184
+ def _project_name_from_cmake(cmake_path: Path) -> str | None:
185
+ if not cmake_path.exists():
186
+ return None
187
+ try:
188
+ text = cmake_path.read_text(encoding="utf-8")
189
+ except UnicodeDecodeError:
190
+ return None
191
+ match = re.search(r"\bproject\s*\(\s*([A-Za-z0-9_\-]+)", text)
192
+ if match:
193
+ return match.group(1)
194
+ return None
195
+
196
+
197
+ class CppAnalyzer:
198
+ metadata = AnalyzerMetadata(
199
+ name="cpp",
200
+ display_name="C++ Analyzer",
201
+ version="0.1.0",
202
+ description="C++ analyzer covering Crow, Pistache, Drogon, cpprestsdk, libcurl/cpr, OpenSSL/Botan/libsodium/Crypto++, libpqxx/mongocxx/redis-plus-plus.",
203
+ scope="C++ source trees and CMake projects. Detects modern HTTP frameworks and common DB / crypto libraries.",
204
+ targets=["cpp", "c++", "crow", "pistache", "drogon", "cpprestsdk"],
205
+ languages=["cpp"],
206
+ priority=20,
207
+ experimental=True, # Like the C analyzer; regex coverage of C++ is more leaky than of stricter ecosystems.
208
+ enabled_by_default=True,
209
+ )
210
+
211
+ @property
212
+ def name(self) -> str:
213
+ return self.metadata.name
214
+
215
+ # ---------- Public entry points ----------
216
+
217
+ def detect(self, repo_path: str | Path) -> bool:
218
+ root = Path(repo_path).resolve()
219
+ if not root.exists() or not root.is_dir():
220
+ return False
221
+ for path in root.rglob("*"):
222
+ if any(part in SKIP_DIRS for part in path.parts):
223
+ continue
224
+ if not path.is_file():
225
+ continue
226
+ if path.suffix in CODE_SUFFIXES:
227
+ return True
228
+ return False
229
+
230
+ def analyze(self, repo_path: str | Path) -> ScanResult:
231
+ root = Path(repo_path).resolve()
232
+ result = ScanResult(root=str(root))
233
+ if not root.exists() or not root.is_dir():
234
+ return result
235
+
236
+ for cmake in root.rglob("CMakeLists.txt"):
237
+ if any(part in SKIP_DIRS for part in cmake.parts):
238
+ continue
239
+ project = _project_name_from_cmake(cmake)
240
+ if project:
241
+ self._append_unique_service(result, f"project:{project}", str(cmake.relative_to(root)))
242
+
243
+ for file_path in root.rglob("*"):
244
+ if not file_path.is_file():
245
+ continue
246
+ if any(part in SKIP_DIRS for part in file_path.parts):
247
+ continue
248
+ if file_path.suffix not in CODE_SUFFIXES:
249
+ continue
250
+
251
+ result.files_scanned += 1
252
+ if "cpp" not in result.languages:
253
+ result.languages.append("cpp")
254
+
255
+ try:
256
+ content = file_path.read_text(encoding="utf-8")
257
+ except UnicodeDecodeError:
258
+ continue
259
+
260
+ relative = str(file_path.relative_to(root))
261
+ self._extract_routes(content, relative, result)
262
+ self._extract_databases(content, relative, result)
263
+ self._extract_auth(content, relative, result)
264
+ self._extract_secrets(content, relative, result)
265
+ self._extract_external_calls(content, relative, result)
266
+ self._extract_frameworks(content, relative, result)
267
+ self._extract_entrypoints(content, relative, result)
268
+
269
+ result.languages.sort()
270
+ return result
271
+
272
+ # ---------- Extractors ----------
273
+
274
+ def _extract_routes(self, content: str, relative: str, result: ScanResult) -> None:
275
+ # Crow: CROW_ROUTE(app, "/x").methods("POST"_method, "PUT"_method)
276
+ for match in CROW_ROUTE_PATTERN.finditer(content):
277
+ path = match.group(1)
278
+ chain = match.group("chain") or ""
279
+ line = _line_of(content, match.start())
280
+ methods: set[str] = set()
281
+ methods_match = CROW_METHODS_PATTERN.search(chain)
282
+ if methods_match:
283
+ methods = {m.upper() for m in re.findall(r'"([A-Z]+)"_method', methods_match.group(1))}
284
+ if not methods:
285
+ methods = {"ANY"}
286
+ for method in sorted(methods):
287
+ self._append_unique_route(result, path, method, relative, line)
288
+
289
+ # Pistache: Routes::Get(router, "/x", handler)
290
+ for match in PISTACHE_ROUTE_PATTERN.finditer(content):
291
+ method, path = match.group(1).upper(), match.group(2)
292
+ self._append_unique_route(result, path, method, relative, _line_of(content, match.start()))
293
+
294
+ # Drogon registerHandler with explicit method list: {Drogon::Get, Drogon::Post}
295
+ for match in DROGON_REGISTER_PATTERN.finditer(content):
296
+ path = match.group(1)
297
+ methods_blob = match.group(2)
298
+ methods = {
299
+ m.upper()
300
+ for m in re.findall(r'\b(?:Drogon::)?(Get|Post|Put|Delete|Patch|Head|Options)\b', methods_blob)
301
+ }
302
+ line = _line_of(content, match.start())
303
+ if not methods:
304
+ methods = {"ANY"}
305
+ for method in sorted(methods):
306
+ self._append_unique_route(result, path, method, relative, line)
307
+
308
+ # Drogon ADD_METHOD_TO macro: ADD_METHOD_TO(ctrl::handler, "/path", Get)
309
+ for match in DROGON_ADD_METHOD_PATTERN.finditer(content):
310
+ path, method = match.group(1), match.group(2).upper()
311
+ self._append_unique_route(result, path, method, relative, _line_of(content, match.start()))
312
+
313
+ # cpprestsdk listener URL — the listener is constructed with the full URL
314
+ # which we treat as both an entrypoint and a route (path part).
315
+ for match in CPPRESTSDK_LISTENER_PATTERN.finditer(content):
316
+ url = match.group(1)
317
+ # Best-effort: extract the path component of the URL.
318
+ path_match = re.search(r"https?://[^/]+(/[^?]*)", url)
319
+ if path_match:
320
+ path = path_match.group(1) or "/"
321
+ self._append_unique_route(result, path, "ANY", relative, _line_of(content, match.start()))
322
+
323
+ def _extract_databases(self, content: str, relative: str, result: ScanResult) -> None:
324
+ for pattern, kind in DB_PATTERNS:
325
+ match = pattern.search(content)
326
+ if match is None:
327
+ continue
328
+ self._append_unique_database(
329
+ result, kind, relative,
330
+ _line_of(content, match.start()),
331
+ _line_snippet(content, match.start()),
332
+ )
333
+
334
+ def _extract_auth(self, content: str, relative: str, result: ScanResult) -> None:
335
+ for pattern, hint, confidence in AUTH_PATTERNS:
336
+ match = pattern.search(content)
337
+ if match is None:
338
+ continue
339
+ self._append_unique_auth(
340
+ result, hint, relative,
341
+ _line_of(content, match.start()),
342
+ _line_snippet(content, match.start()),
343
+ confidence,
344
+ )
345
+
346
+ def _extract_secrets(self, content: str, relative: str, result: ScanResult) -> None:
347
+ for pattern in SECRET_PATTERNS:
348
+ for match in pattern.finditer(content):
349
+ name = match.group(1)
350
+ self._append_unique_secret(
351
+ result, name, relative,
352
+ _line_of(content, match.start()),
353
+ _line_snippet(content, match.start()),
354
+ )
355
+
356
+ def _extract_external_calls(self, content: str, relative: str, result: ScanResult) -> None:
357
+ for pattern in OUTBOUND_PATTERNS:
358
+ for match in pattern.finditer(content):
359
+ target = match.group(1)
360
+ if not (target.startswith("http://") or target.startswith("https://")):
361
+ continue
362
+ self._append_unique_external(
363
+ result, target, relative,
364
+ _line_of(content, match.start()),
365
+ _line_snippet(content, match.start()),
366
+ )
367
+
368
+ def _extract_frameworks(self, content: str, relative: str, result: ScanResult) -> None:
369
+ for pattern, name in FRAMEWORK_PATTERNS:
370
+ match = pattern.search(content)
371
+ if match is None:
372
+ continue
373
+ self._append_unique_framework(
374
+ result, name, relative,
375
+ _line_of(content, match.start()),
376
+ _line_snippet(content, match.start()),
377
+ )
378
+
379
+ def _extract_entrypoints(self, content: str, relative: str, result: ScanResult) -> None:
380
+ for pattern, hint in ENTRYPOINT_PATTERNS:
381
+ match = pattern.search(content)
382
+ if match is None:
383
+ continue
384
+ self._append_unique_entrypoint(
385
+ result, hint, relative,
386
+ _line_of(content, match.start()),
387
+ _line_snippet(content, match.start()),
388
+ )
389
+
390
+ # ---------- Append helpers ----------
391
+
392
+ @staticmethod
393
+ def _append_unique_route(result: ScanResult, path: str, method: str, file: str, line: int | None) -> None:
394
+ key = (path, method, file)
395
+ if any((item.path, item.method, item.file) == key for item in result.routes):
396
+ return
397
+ result.routes.append(Route(path=path, method=method, file=file, line=line))
398
+
399
+ @staticmethod
400
+ def _append_unique_database(result: ScanResult, kind: str, file: str, line: int | None, evidence: str | None) -> None:
401
+ key = (kind, file)
402
+ if any((item.kind, item.file) == key for item in result.databases):
403
+ return
404
+ result.databases.append(DatabaseHint(kind=kind, file=file, line=line, evidence_text=evidence))
405
+
406
+ @staticmethod
407
+ def _append_unique_auth(result: ScanResult, hint: str, file: str, line: int | None, evidence: str | None, confidence: float) -> None:
408
+ key = (hint, file)
409
+ if any((item.hint, item.file) == key for item in result.auth_hints):
410
+ return
411
+ result.auth_hints.append(AuthHint(hint=hint, file=file, line=line, evidence_text=evidence, confidence=confidence))
412
+
413
+ @staticmethod
414
+ def _append_unique_secret(result: ScanResult, name: str, file: str, line: int | None, evidence: str | None) -> None:
415
+ key = (name, file)
416
+ if any((item.name, item.file) == key for item in result.secret_hints):
417
+ return
418
+ result.secret_hints.append(SecretHint(name=name, file=file, line=line, evidence_text=evidence, confidence=0.85))
419
+
420
+ @staticmethod
421
+ def _append_unique_external(result: ScanResult, target: str, file: str, line: int | None, evidence: str | None) -> None:
422
+ key = (target, file)
423
+ if any((item.target, item.file) == key for item in result.external_calls):
424
+ return
425
+ result.external_calls.append(ExternalCall(target=target, file=file, line=line, evidence_text=evidence))
426
+
427
+ @staticmethod
428
+ def _append_unique_framework(result: ScanResult, hint: str, file: str, line: int | None, evidence: str | None) -> None:
429
+ key = (hint, file)
430
+ if any((item.hint, item.file) == key for item in result.framework_hints):
431
+ return
432
+ result.framework_hints.append(FrameworkHint(hint=hint, file=file, line=line, evidence_text=evidence))
433
+
434
+ @staticmethod
435
+ def _append_unique_entrypoint(result: ScanResult, hint: str, file: str, line: int | None, evidence: str | None) -> None:
436
+ key = (hint, file)
437
+ if any((item.hint, item.file) == key for item in result.entrypoint_hints):
438
+ return
439
+ result.entrypoint_hints.append(EntrypointHint(hint=hint, file=file, line=line, evidence_text=evidence))
440
+
441
+ @staticmethod
442
+ def _append_unique_service(result: ScanResult, hint: str, file: str) -> None:
443
+ key = (hint, file)
444
+ if any((item.hint, item.file) == key for item in result.service_hints):
445
+ return
446
+ result.service_hints.append(ServiceHint(hint=hint, file=file))
447
+
448
+
449
+ __all__ = ["CppAnalyzer"]
@@ -0,0 +1,30 @@
1
+ from __future__ import annotations
2
+
3
+ from attackmap.sdk.contracts import AnalyzerMetadata, AnalyzerProtocol
4
+ from attackmap.sdk.models import (
5
+ AuthHint,
6
+ DatabaseHint,
7
+ EntrypointHint,
8
+ ExternalCall,
9
+ FrameworkHint,
10
+ Route,
11
+ ScanResult,
12
+ SecretHint,
13
+ ServiceHint,
14
+ )
15
+
16
+ AttackMapAnalyzerProtocol = AnalyzerProtocol
17
+
18
+ __all__ = [
19
+ "AnalyzerMetadata",
20
+ "AttackMapAnalyzerProtocol",
21
+ "Route",
22
+ "ExternalCall",
23
+ "DatabaseHint",
24
+ "AuthHint",
25
+ "EntrypointHint",
26
+ "FrameworkHint",
27
+ "ServiceHint",
28
+ "SecretHint",
29
+ "ScanResult",
30
+ ]
@@ -0,0 +1,91 @@
1
+ Metadata-Version: 2.4
2
+ Name: attackmap-analyzer-cpp
3
+ Version: 0.1.0
4
+ Summary: C++ ecosystem analyzer plugin for AttackMap (Crow, Pistache, Drogon, cpprestsdk; libcurl/cpr; OpenSSL/Botan/libsodium/Crypto++; libpqxx/mongocxx/redis-plus-plus).
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-cpp
10
+ Project-URL: Repository, https://github.com/mlaify/attackmap-analyzer-cpp
11
+ Project-URL: Issues, https://github.com/mlaify/attackmap-analyzer-cpp/issues
12
+ Project-URL: Changelog, https://github.com/mlaify/attackmap-analyzer-cpp/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-cpp
42
+
43
+ C++ ecosystem analyzer for [AttackMap](https://github.com/mlaify/AttackMap).
44
+
45
+ This analyzer extracts structured signals from C++ source trees (`.cpp`, `.cc`, `.cxx`, `.hpp`, `.hxx`, `.ipp`, `.tpp`):
46
+
47
+ - **Web frameworks** — Crow (`CROW_ROUTE` macro with `.methods("POST"_method, ...)` chain), Pistache (`Routes::Get/Post/...`), Drogon (`registerHandler` with explicit method list AND `ADD_METHOD_TO` macro), cpprestsdk / Casablanca (`http_listener("https://...")` URL extraction)
48
+ - **HTTP clients (external calls)** — libcurl (`CURLOPT_URL` literals), cpr (`cpr::Get(cpr::Url{"..."})`, `cpr::Post(...)`), cpprestsdk (`web::http::client::http_client(URL)`)
49
+ - **Databases** — libpqxx (`pqxx::connection`, `pqxx::work`), MySQL X DevAPI (`mysqlx::Session`), mongocxx (`mongocxx::client` + `mongocxx::uri`), redis-plus-plus (`sw::redis::Redis`), SOCI (`soci::session`), sqlite_orm (`sqlite_orm::make_storage`)
50
+ - **Auth/crypto** — OpenSSL (TLS / EVP / RAND), Botan (`TLS::Server`, `Cipher_Mode`, `PKCS5_PBKDF2`, `Scrypt`), libsodium (`crypto_pwhash` → argon2, `crypto_secretbox`, AEAD primitives), Crypto++ (`CryptoPP::AES`, `CryptoPP::SHA256`, `CryptoPP::Argon2`, `CryptoPP::HMAC`), JWT C++ libraries (`jwt::create`, `jwt::decode`, `jwt::verify`)
51
+ - **Secrets** — `std::getenv`, `getenv` with secret-shaped names
52
+ - **Service hints** — project name from `CMakeLists.txt` `project(NAME ...)` declaration
53
+
54
+ All emissions populate AttackMap's Signal v2 fields (line numbers + evidence snippets + confidence) so downstream insights can cite `path/to/file.cpp:NN`.
55
+
56
+ ## Install
57
+
58
+ ```bash
59
+ pip install git+https://github.com/mlaify/attackmap-analyzer-cpp.git
60
+ ```
61
+
62
+ The analyzer is auto-discovered by AttackMap via the `attackmap.analyzers` entry-point group.
63
+
64
+ ## Usage with AttackMap
65
+
66
+ ```bash
67
+ # Auto-discovered when installed:
68
+ attackmap analyze /path/to/cpp/repo
69
+
70
+ # Or invoke explicitly:
71
+ attackmap analyze /path/to/cpp/repo --module cpp
72
+ ```
73
+
74
+ ## Detection
75
+
76
+ `detect()` returns true when any `.cpp`, `.cc`, `.cxx`, `.hpp`, `.hxx`, `.ipp`, or `.tpp` file is present, ignoring `build/`, `.git/`, `_deps/`, `third_party/`, `vendor/`, `external/`, `.cache/`, `out/`, `Debug/`, `Release/`, and `node_modules/`.
77
+
78
+ This analyzer **does not** claim `.h` files — those are handled by the C analyzer (`attackmap-analyzer-c`). A repo with only `.c` and `.h` files is not picked up here.
79
+
80
+ ## Coverage notes
81
+
82
+ - **Marked experimental**: like the C analyzer, regex coverage of C++ has more false-positive risk than language-specific analyzers with strict imports. Confidence tiering is the primary defense (0.9 for hash-class auth primitives, 0.85 for canonical TLS / cipher / JWT API hits, 0.6 for keyword sweeps).
83
+ - **Crow `.methods("X"_method)` chains**: when present, the route emits one Route per method in the chain. When absent, the route emits with method `ANY`.
84
+ - **Drogon `registerHandler` and `ADD_METHOD_TO`**: both shapes are extracted, including the `{Drogon::Get, Drogon::Post}` initializer-list form which produces multiple Routes.
85
+ - **cpprestsdk listener routes**: only the path component of the listener's URL is extracted as a Route. Per-method handlers (`listener.support(methods::GET, ...)`) are not separately emitted — that would require tracking the listener's lifetime.
86
+ - **C++ shares vocabulary with C** (libcurl, OpenSSL, libsodium). Those patterns are duplicated here so a pure-C++ project without the C analyzer installed still gets full coverage. AttackMap's overlay deduplication handles double-firing.
87
+ - **Pure-template / header-only ORM** (sqlite_orm, sqlpp11): only basic detection via headers and `make_storage`; column-level extraction is out of scope.
88
+
89
+ ## License
90
+
91
+ MIT
@@ -0,0 +1,9 @@
1
+ attackmap_analyzer_cpp/__init__.py,sha256=lWdIq_sE3dcwrKHvJJxOtX3gaxQDYNZDfL_Ab8ubu3Q,61
2
+ attackmap_analyzer_cpp/analyzer.py,sha256=oN6JYH-sqx7sB7TZ8Zsj20it52RWGBUxs9r-ekOWbn8,20088
3
+ attackmap_analyzer_cpp/contracts.py,sha256=dsveFe7szz7xceev0PIfyc5jQlNiES0whsdxwu9D7YI,578
4
+ attackmap_analyzer_cpp-0.1.0.dist-info/licenses/LICENSE,sha256=vtPQVGUyxq359j0JmD3_eJaXyHmaHyjzaMOtaLwJc88,1097
5
+ attackmap_analyzer_cpp-0.1.0.dist-info/METADATA,sha256=0xGMF_MYSvgeHSsg-TYGJCGtwsfgNzwrKzD5R9N1sBA,5615
6
+ attackmap_analyzer_cpp-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
7
+ attackmap_analyzer_cpp-0.1.0.dist-info/entry_points.txt,sha256=Hov7DLdDs9qjDh1RjIXw4uveEu_GKhOERHSk2gTo0Wk,63
8
+ attackmap_analyzer_cpp-0.1.0.dist-info/top_level.txt,sha256=rIqk7py9tOCVX265ZVN-2mDCl7Y7Te2WcONxLm29ak0,23
9
+ attackmap_analyzer_cpp-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
+ cpp = attackmap_analyzer_cpp:CppAnalyzer
@@ -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_cpp