attackmap-analyzer-cpp 0.1.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.
Potentially problematic release.
This version of attackmap-analyzer-cpp might be problematic. Click here for more details.
- attackmap_analyzer_cpp-0.1.0/LICENSE +21 -0
- attackmap_analyzer_cpp-0.1.0/PKG-INFO +91 -0
- attackmap_analyzer_cpp-0.1.0/README.md +51 -0
- attackmap_analyzer_cpp-0.1.0/pyproject.toml +74 -0
- attackmap_analyzer_cpp-0.1.0/setup.cfg +4 -0
- attackmap_analyzer_cpp-0.1.0/src/attackmap_analyzer_cpp/__init__.py +3 -0
- attackmap_analyzer_cpp-0.1.0/src/attackmap_analyzer_cpp/analyzer.py +449 -0
- attackmap_analyzer_cpp-0.1.0/src/attackmap_analyzer_cpp/contracts.py +30 -0
- attackmap_analyzer_cpp-0.1.0/src/attackmap_analyzer_cpp.egg-info/PKG-INFO +91 -0
- attackmap_analyzer_cpp-0.1.0/src/attackmap_analyzer_cpp.egg-info/SOURCES.txt +13 -0
- attackmap_analyzer_cpp-0.1.0/src/attackmap_analyzer_cpp.egg-info/dependency_links.txt +1 -0
- attackmap_analyzer_cpp-0.1.0/src/attackmap_analyzer_cpp.egg-info/entry_points.txt +2 -0
- attackmap_analyzer_cpp-0.1.0/src/attackmap_analyzer_cpp.egg-info/requires.txt +9 -0
- attackmap_analyzer_cpp-0.1.0/src/attackmap_analyzer_cpp.egg-info/top_level.txt +1 -0
- attackmap_analyzer_cpp-0.1.0/tests/test_cpp_analyzer.py +447 -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,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,51 @@
|
|
|
1
|
+
# attackmap-analyzer-cpp
|
|
2
|
+
|
|
3
|
+
C++ ecosystem analyzer for [AttackMap](https://github.com/mlaify/AttackMap).
|
|
4
|
+
|
|
5
|
+
This analyzer extracts structured signals from C++ source trees (`.cpp`, `.cc`, `.cxx`, `.hpp`, `.hxx`, `.ipp`, `.tpp`):
|
|
6
|
+
|
|
7
|
+
- **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)
|
|
8
|
+
- **HTTP clients (external calls)** — libcurl (`CURLOPT_URL` literals), cpr (`cpr::Get(cpr::Url{"..."})`, `cpr::Post(...)`), cpprestsdk (`web::http::client::http_client(URL)`)
|
|
9
|
+
- **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`)
|
|
10
|
+
- **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`)
|
|
11
|
+
- **Secrets** — `std::getenv`, `getenv` with secret-shaped names
|
|
12
|
+
- **Service hints** — project name from `CMakeLists.txt` `project(NAME ...)` declaration
|
|
13
|
+
|
|
14
|
+
All emissions populate AttackMap's Signal v2 fields (line numbers + evidence snippets + confidence) so downstream insights can cite `path/to/file.cpp:NN`.
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pip install git+https://github.com/mlaify/attackmap-analyzer-cpp.git
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The analyzer is auto-discovered by AttackMap via the `attackmap.analyzers` entry-point group.
|
|
23
|
+
|
|
24
|
+
## Usage with AttackMap
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
# Auto-discovered when installed:
|
|
28
|
+
attackmap analyze /path/to/cpp/repo
|
|
29
|
+
|
|
30
|
+
# Or invoke explicitly:
|
|
31
|
+
attackmap analyze /path/to/cpp/repo --module cpp
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Detection
|
|
35
|
+
|
|
36
|
+
`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/`.
|
|
37
|
+
|
|
38
|
+
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.
|
|
39
|
+
|
|
40
|
+
## Coverage notes
|
|
41
|
+
|
|
42
|
+
- **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).
|
|
43
|
+
- **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`.
|
|
44
|
+
- **Drogon `registerHandler` and `ADD_METHOD_TO`**: both shapes are extracted, including the `{Drogon::Get, Drogon::Post}` initializer-list form which produces multiple Routes.
|
|
45
|
+
- **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.
|
|
46
|
+
- **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.
|
|
47
|
+
- **Pure-template / header-only ORM** (sqlite_orm, sqlpp11): only basic detection via headers and `make_storage`; column-level extraction is out of scope.
|
|
48
|
+
|
|
49
|
+
## License
|
|
50
|
+
|
|
51
|
+
MIT
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "attackmap-analyzer-cpp"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "C++ ecosystem analyzer plugin for AttackMap (Crow, Pistache, Drogon, cpprestsdk; libcurl/cpr; OpenSSL/Botan/libsodium/Crypto++; libpqxx/mongocxx/redis-plus-plus)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = {text = "MIT"}
|
|
12
|
+
authors = [
|
|
13
|
+
{name = "Matthew Davis", email = "matthewd@matthewd.xyz"},
|
|
14
|
+
{name = "AttackMap Contributors"},
|
|
15
|
+
]
|
|
16
|
+
maintainers = [
|
|
17
|
+
{name = "Matthew Davis", email = "matthewd@matthewd.xyz"},
|
|
18
|
+
]
|
|
19
|
+
keywords = [
|
|
20
|
+
"security",
|
|
21
|
+
"static-analysis",
|
|
22
|
+
"appsec",
|
|
23
|
+
"defensive-security",
|
|
24
|
+
"attackmap",
|
|
25
|
+
"attackmap-plugin",
|
|
26
|
+
]
|
|
27
|
+
classifiers = [
|
|
28
|
+
"Development Status :: 4 - Beta",
|
|
29
|
+
"Intended Audience :: Developers",
|
|
30
|
+
"Intended Audience :: Information Technology",
|
|
31
|
+
"Intended Audience :: System Administrators",
|
|
32
|
+
"License :: OSI Approved :: MIT License",
|
|
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.1.0",
|
|
50
|
+
]
|
|
51
|
+
dev = [
|
|
52
|
+
"pytest>=8.0.0",
|
|
53
|
+
"build>=1.2.0",
|
|
54
|
+
"attackmap>=0.1.0",
|
|
55
|
+
]
|
|
56
|
+
|
|
57
|
+
[project.urls]
|
|
58
|
+
Homepage = "https://github.com/mlaify/attackmap-analyzer-cpp"
|
|
59
|
+
Repository = "https://github.com/mlaify/attackmap-analyzer-cpp"
|
|
60
|
+
Issues = "https://github.com/mlaify/attackmap-analyzer-cpp/issues"
|
|
61
|
+
Changelog = "https://github.com/mlaify/attackmap-analyzer-cpp/blob/main/CHANGELOG.md"
|
|
62
|
+
"AttackMap core" = "https://github.com/mlaify/AttackMap"
|
|
63
|
+
|
|
64
|
+
[project.entry-points."attackmap.analyzers"]
|
|
65
|
+
cpp = "attackmap_analyzer_cpp:CppAnalyzer"
|
|
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,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,13 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/attackmap_analyzer_cpp/__init__.py
|
|
5
|
+
src/attackmap_analyzer_cpp/analyzer.py
|
|
6
|
+
src/attackmap_analyzer_cpp/contracts.py
|
|
7
|
+
src/attackmap_analyzer_cpp.egg-info/PKG-INFO
|
|
8
|
+
src/attackmap_analyzer_cpp.egg-info/SOURCES.txt
|
|
9
|
+
src/attackmap_analyzer_cpp.egg-info/dependency_links.txt
|
|
10
|
+
src/attackmap_analyzer_cpp.egg-info/entry_points.txt
|
|
11
|
+
src/attackmap_analyzer_cpp.egg-info/requires.txt
|
|
12
|
+
src/attackmap_analyzer_cpp.egg-info/top_level.txt
|
|
13
|
+
tests/test_cpp_analyzer.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
attackmap_analyzer_cpp
|
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
"""Tests for the CppAnalyzer plugin."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
from attackmap_analyzer_cpp import CppAnalyzer
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
# ---------- detect() ----------
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_detect_picks_up_cpp(tmp_path: Path) -> None:
|
|
16
|
+
(tmp_path / "main.cpp").write_text("int main() { return 0; }\n", encoding="utf-8")
|
|
17
|
+
assert CppAnalyzer().detect(tmp_path) is True
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_detect_picks_up_hpp(tmp_path: Path) -> None:
|
|
21
|
+
(tmp_path / "api.hpp").write_text("#pragma once\nclass Foo {};\n", encoding="utf-8")
|
|
22
|
+
assert CppAnalyzer().detect(tmp_path) is True
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def test_detect_skips_build_dir(tmp_path: Path) -> None:
|
|
26
|
+
(tmp_path / "build").mkdir()
|
|
27
|
+
(tmp_path / "build" / "stale.cpp").write_text("int main() { return 0; }\n", encoding="utf-8")
|
|
28
|
+
assert CppAnalyzer().detect(tmp_path) is False
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_detect_does_not_claim_pure_c_repo(tmp_path: Path) -> None:
|
|
32
|
+
"""A repo with only `.c` and `.h` files belongs to the C analyzer."""
|
|
33
|
+
(tmp_path / "main.c").write_text("int main(void) { return 0; }\n", encoding="utf-8")
|
|
34
|
+
assert CppAnalyzer().detect(tmp_path) is False
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# ---------- Crow ----------
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def test_crow_route_default_method(tmp_path: Path) -> None:
|
|
41
|
+
(tmp_path / "main.cpp").write_text(
|
|
42
|
+
'#include <crow.h>\n'
|
|
43
|
+
'\n'
|
|
44
|
+
'int main() {\n'
|
|
45
|
+
' crow::SimpleApp app;\n'
|
|
46
|
+
' CROW_ROUTE(app, "/health")([](){ return "ok"; });\n'
|
|
47
|
+
' app.port(8080).run();\n'
|
|
48
|
+
' return 0;\n'
|
|
49
|
+
'}\n',
|
|
50
|
+
encoding="utf-8",
|
|
51
|
+
)
|
|
52
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
53
|
+
pairs = {(r.path, r.method) for r in result.routes}
|
|
54
|
+
assert ("/health", "ANY") in pairs
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_crow_route_with_methods_chain(tmp_path: Path) -> None:
|
|
58
|
+
(tmp_path / "main.cpp").write_text(
|
|
59
|
+
'#include <crow.h>\n'
|
|
60
|
+
'crow::SimpleApp app;\n'
|
|
61
|
+
'CROW_ROUTE(app, "/users").methods("GET"_method, "POST"_method)\n'
|
|
62
|
+
' ([](const crow::request& r){ return "ok"; });\n'
|
|
63
|
+
'CROW_ROUTE(app, "/admin").methods("DELETE"_method)\n'
|
|
64
|
+
' ([](){ return "deleted"; });\n',
|
|
65
|
+
encoding="utf-8",
|
|
66
|
+
)
|
|
67
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
68
|
+
pairs = sorted({(r.path, r.method) for r in result.routes})
|
|
69
|
+
assert ("/users", "GET") in pairs
|
|
70
|
+
assert ("/users", "POST") in pairs
|
|
71
|
+
assert ("/admin", "DELETE") in pairs
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# ---------- Pistache ----------
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def test_pistache_routes(tmp_path: Path) -> None:
|
|
78
|
+
(tmp_path / "main.cpp").write_text(
|
|
79
|
+
'#include <pistache/router.h>\n'
|
|
80
|
+
'\n'
|
|
81
|
+
'using namespace Pistache;\n'
|
|
82
|
+
'\n'
|
|
83
|
+
'void setup(Rest::Router& router) {\n'
|
|
84
|
+
' Rest::Routes::Get(router, "/api/users", Rest::Routes::bind(&handle_users));\n'
|
|
85
|
+
' Rest::Routes::Post(router, "/api/login", Rest::Routes::bind(&handle_login));\n'
|
|
86
|
+
' Rest::Routes::Delete(router, "/api/users/:id", Rest::Routes::bind(&handle_delete));\n'
|
|
87
|
+
'}\n',
|
|
88
|
+
encoding="utf-8",
|
|
89
|
+
)
|
|
90
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
91
|
+
pairs = {(r.path, r.method) for r in result.routes}
|
|
92
|
+
assert ("/api/users", "GET") in pairs
|
|
93
|
+
assert ("/api/login", "POST") in pairs
|
|
94
|
+
assert ("/api/users/:id", "DELETE") in pairs
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
# ---------- Drogon ----------
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def test_drogon_register_handler_with_methods(tmp_path: Path) -> None:
|
|
101
|
+
(tmp_path / "main.cpp").write_text(
|
|
102
|
+
'#include <drogon/drogon.h>\n'
|
|
103
|
+
'\n'
|
|
104
|
+
'int main() {\n'
|
|
105
|
+
' drogon::app().registerHandler(\n'
|
|
106
|
+
' "/api/orders",\n'
|
|
107
|
+
' [](const drogon::HttpRequestPtr& req, std::function<void(...)>&& cb) {},\n'
|
|
108
|
+
' {Drogon::Get, Drogon::Post});\n'
|
|
109
|
+
' drogon::app().run();\n'
|
|
110
|
+
'}\n',
|
|
111
|
+
encoding="utf-8",
|
|
112
|
+
)
|
|
113
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
114
|
+
pairs = {(r.path, r.method) for r in result.routes}
|
|
115
|
+
assert ("/api/orders", "GET") in pairs
|
|
116
|
+
assert ("/api/orders", "POST") in pairs
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def test_drogon_add_method_to_macro(tmp_path: Path) -> None:
|
|
120
|
+
(tmp_path / "controller.hpp").write_text(
|
|
121
|
+
'#pragma once\n'
|
|
122
|
+
'#include <drogon/HttpController.h>\n'
|
|
123
|
+
'\n'
|
|
124
|
+
'class Users : public drogon::HttpController<Users> {\n'
|
|
125
|
+
'public:\n'
|
|
126
|
+
' METHOD_LIST_BEGIN\n'
|
|
127
|
+
' ADD_METHOD_TO(Users::list, "/users", Get);\n'
|
|
128
|
+
' ADD_METHOD_TO(Users::create, "/users", Post);\n'
|
|
129
|
+
' METHOD_LIST_END\n'
|
|
130
|
+
'\n'
|
|
131
|
+
' void list(...);\n'
|
|
132
|
+
' void create(...);\n'
|
|
133
|
+
'};\n',
|
|
134
|
+
encoding="utf-8",
|
|
135
|
+
)
|
|
136
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
137
|
+
pairs = {(r.path, r.method) for r in result.routes}
|
|
138
|
+
assert ("/users", "GET") in pairs
|
|
139
|
+
assert ("/users", "POST") in pairs
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# ---------- cpprestsdk ----------
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def test_cpprestsdk_listener_extracts_url_path(tmp_path: Path) -> None:
|
|
146
|
+
(tmp_path / "main.cpp").write_text(
|
|
147
|
+
'#include <cpprest/http_listener.h>\n'
|
|
148
|
+
'\n'
|
|
149
|
+
'using namespace web::http::experimental::listener;\n'
|
|
150
|
+
'\n'
|
|
151
|
+
'int main() {\n'
|
|
152
|
+
' http_listener listener("https://0.0.0.0:443/api/v1");\n'
|
|
153
|
+
' listener.support(web::http::methods::GET, [](auto req){});\n'
|
|
154
|
+
' listener.open().wait();\n'
|
|
155
|
+
'}\n',
|
|
156
|
+
encoding="utf-8",
|
|
157
|
+
)
|
|
158
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
159
|
+
paths = {r.path for r in result.routes}
|
|
160
|
+
assert "/api/v1" in paths
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
# ---------- HTTP clients ----------
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def test_libcurl_url_extracted(tmp_path: Path) -> None:
|
|
167
|
+
(tmp_path / "client.cpp").write_text(
|
|
168
|
+
'#include <curl/curl.h>\n'
|
|
169
|
+
'void fetch() {\n'
|
|
170
|
+
' CURL *curl = curl_easy_init();\n'
|
|
171
|
+
' curl_easy_setopt(curl, CURLOPT_URL, "https://api.stripe.com/v1/charges");\n'
|
|
172
|
+
' curl_easy_perform(curl);\n'
|
|
173
|
+
'}\n',
|
|
174
|
+
encoding="utf-8",
|
|
175
|
+
)
|
|
176
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
177
|
+
targets = {e.target for e in result.external_calls}
|
|
178
|
+
assert "https://api.stripe.com/v1/charges" in targets
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def test_cpr_url_extracted(tmp_path: Path) -> None:
|
|
182
|
+
(tmp_path / "client.cpp").write_text(
|
|
183
|
+
'#include <cpr/cpr.h>\n'
|
|
184
|
+
'void fetch() {\n'
|
|
185
|
+
' auto resp = cpr::Get(cpr::Url{"https://api.example.com/data"});\n'
|
|
186
|
+
' auto post = cpr::Post(cpr::Url{"https://api.example.com/submit"}, cpr::Body{"x"});\n'
|
|
187
|
+
'}\n',
|
|
188
|
+
encoding="utf-8",
|
|
189
|
+
)
|
|
190
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
191
|
+
targets = {e.target for e in result.external_calls}
|
|
192
|
+
assert "https://api.example.com/data" in targets
|
|
193
|
+
assert "https://api.example.com/submit" in targets
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def test_cpprestsdk_http_client_url(tmp_path: Path) -> None:
|
|
197
|
+
(tmp_path / "client.cpp").write_text(
|
|
198
|
+
'#include <cpprest/http_client.h>\n'
|
|
199
|
+
'using web::http::client::http_client;\n'
|
|
200
|
+
'void fetch() {\n'
|
|
201
|
+
' http_client client(U("https://api.example.com/v2"));\n'
|
|
202
|
+
' client.request(web::http::methods::GET);\n'
|
|
203
|
+
'}\n',
|
|
204
|
+
encoding="utf-8",
|
|
205
|
+
)
|
|
206
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
207
|
+
targets = {e.target for e in result.external_calls}
|
|
208
|
+
assert "https://api.example.com/v2" in targets
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
# ---------- Databases ----------
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def test_libpqxx_connection_emits_postgresql(tmp_path: Path) -> None:
|
|
215
|
+
(tmp_path / "db.cpp").write_text(
|
|
216
|
+
'#include <pqxx/pqxx>\n'
|
|
217
|
+
'void connect() {\n'
|
|
218
|
+
' pqxx::connection c{"postgresql://localhost/app"};\n'
|
|
219
|
+
' pqxx::work tx{c};\n'
|
|
220
|
+
'}\n',
|
|
221
|
+
encoding="utf-8",
|
|
222
|
+
)
|
|
223
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
224
|
+
assert any(d.kind == "postgresql" for d in result.databases)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def test_mongocxx_redispp_each_emit_distinct_kinds(tmp_path: Path) -> None:
|
|
228
|
+
(tmp_path / "mongo.cpp").write_text(
|
|
229
|
+
'#include <mongocxx/client.hpp>\n'
|
|
230
|
+
'void x() {\n'
|
|
231
|
+
' mongocxx::client client{mongocxx::uri{"mongodb://x"}};\n'
|
|
232
|
+
'}\n',
|
|
233
|
+
encoding="utf-8",
|
|
234
|
+
)
|
|
235
|
+
(tmp_path / "redis.cpp").write_text(
|
|
236
|
+
'#include <sw/redis++/redis++.h>\n'
|
|
237
|
+
'void x() {\n'
|
|
238
|
+
' sw::redis::Redis redis("tcp://127.0.0.1:6379");\n'
|
|
239
|
+
'}\n',
|
|
240
|
+
encoding="utf-8",
|
|
241
|
+
)
|
|
242
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
243
|
+
kinds = {d.kind for d in result.databases}
|
|
244
|
+
assert "mongodb" in kinds
|
|
245
|
+
assert "redis" in kinds
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def test_mysqlx_session_emits_mysql(tmp_path: Path) -> None:
|
|
249
|
+
(tmp_path / "db.cpp").write_text(
|
|
250
|
+
'#include <mysqlx/xdevapi.h>\n'
|
|
251
|
+
'void connect() {\n'
|
|
252
|
+
' mysqlx::Session s{mysqlx::SessionSettings("mysqlx://localhost")};\n'
|
|
253
|
+
'}\n',
|
|
254
|
+
encoding="utf-8",
|
|
255
|
+
)
|
|
256
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
257
|
+
assert any(d.kind == "mysql" for d in result.databases)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
# ---------- Auth ----------
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def test_jwt_cpp_emits_jwt_hint(tmp_path: Path) -> None:
|
|
264
|
+
(tmp_path / "auth.cpp").write_text(
|
|
265
|
+
'#include <jwt-cpp/jwt.h>\n'
|
|
266
|
+
'std::string sign(const std::string& secret) {\n'
|
|
267
|
+
' return jwt::create()\n'
|
|
268
|
+
' .set_issuer("svc")\n'
|
|
269
|
+
' .sign(jwt::algorithm::hs256{secret});\n'
|
|
270
|
+
'}\n',
|
|
271
|
+
encoding="utf-8",
|
|
272
|
+
)
|
|
273
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
274
|
+
assert any(h.hint == "jwt" for h in result.auth_hints)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def test_libsodium_argon2_high_confidence(tmp_path: Path) -> None:
|
|
278
|
+
(tmp_path / "auth.cpp").write_text(
|
|
279
|
+
'#include <sodium.h>\n'
|
|
280
|
+
'int hash(const char *pw, char *out) {\n'
|
|
281
|
+
' return crypto_pwhash_str(out, pw, strlen(pw),\n'
|
|
282
|
+
' crypto_pwhash_OPSLIMIT_INTERACTIVE,\n'
|
|
283
|
+
' crypto_pwhash_MEMLIMIT_INTERACTIVE);\n'
|
|
284
|
+
'}\n',
|
|
285
|
+
encoding="utf-8",
|
|
286
|
+
)
|
|
287
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
288
|
+
by_hint = {h.hint: h for h in result.auth_hints}
|
|
289
|
+
assert "argon2" in by_hint
|
|
290
|
+
assert by_hint["argon2"].confidence == 0.9
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def test_botan_tls_server(tmp_path: Path) -> None:
|
|
294
|
+
(tmp_path / "tls.cpp").write_text(
|
|
295
|
+
'#include <botan/tls_server.h>\n'
|
|
296
|
+
'class MyServer : public Botan::TLS::Server {};\n',
|
|
297
|
+
encoding="utf-8",
|
|
298
|
+
)
|
|
299
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
300
|
+
assert any(h.hint == "botan" for h in result.auth_hints)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def test_cryptopp_aes_emits_hint(tmp_path: Path) -> None:
|
|
304
|
+
(tmp_path / "crypto.cpp").write_text(
|
|
305
|
+
'#include <cryptopp/aes.h>\n'
|
|
306
|
+
'CryptoPP::AES::Encryption enc;\n',
|
|
307
|
+
encoding="utf-8",
|
|
308
|
+
)
|
|
309
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
310
|
+
assert any(h.hint == "cryptopp" for h in result.auth_hints)
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
# ---------- Secrets ----------
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def test_std_getenv_secrets(tmp_path: Path) -> None:
|
|
317
|
+
(tmp_path / "config.cpp").write_text(
|
|
318
|
+
'#include <cstdlib>\n'
|
|
319
|
+
'#include <string>\n'
|
|
320
|
+
'\n'
|
|
321
|
+
'std::string load() {\n'
|
|
322
|
+
' const char *jwt = std::getenv("JWT_SECRET");\n'
|
|
323
|
+
' const char *db = std::getenv("DATABASE_PASSWORD");\n'
|
|
324
|
+
' return jwt ? jwt : "";\n'
|
|
325
|
+
'}\n',
|
|
326
|
+
encoding="utf-8",
|
|
327
|
+
)
|
|
328
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
329
|
+
names = {s.name for s in result.secret_hints}
|
|
330
|
+
assert "JWT_SECRET" in names
|
|
331
|
+
assert "DATABASE_PASSWORD" in names
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def test_getenv_with_non_secret_name_skipped(tmp_path: Path) -> None:
|
|
335
|
+
(tmp_path / "config.cpp").write_text(
|
|
336
|
+
'const char *home = std::getenv("HOME");\n'
|
|
337
|
+
'const char *path = getenv("PATH");\n',
|
|
338
|
+
encoding="utf-8",
|
|
339
|
+
)
|
|
340
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
341
|
+
assert result.secret_hints == []
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
# ---------- Frameworks + entrypoints ----------
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def test_crow_app_run_entrypoint(tmp_path: Path) -> None:
|
|
348
|
+
(tmp_path / "main.cpp").write_text(
|
|
349
|
+
'#include <crow.h>\n'
|
|
350
|
+
'int main() {\n'
|
|
351
|
+
' crow::SimpleApp app;\n'
|
|
352
|
+
' CROW_ROUTE(app, "/")([](){ return "hi"; });\n'
|
|
353
|
+
' app.port(8080).multithreaded().run();\n'
|
|
354
|
+
'}\n',
|
|
355
|
+
encoding="utf-8",
|
|
356
|
+
)
|
|
357
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
358
|
+
fw = {f.hint for f in result.framework_hints}
|
|
359
|
+
assert "crow" in fw
|
|
360
|
+
ep = {e.hint for e in result.entrypoint_hints}
|
|
361
|
+
assert "crow_app_run" in ep
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def test_drogon_app_run_entrypoint(tmp_path: Path) -> None:
|
|
365
|
+
(tmp_path / "main.cpp").write_text(
|
|
366
|
+
'#include <drogon/drogon.h>\n'
|
|
367
|
+
'int main() { drogon::app().run(); }\n',
|
|
368
|
+
encoding="utf-8",
|
|
369
|
+
)
|
|
370
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
371
|
+
fw = {f.hint for f in result.framework_hints}
|
|
372
|
+
assert "drogon" in fw
|
|
373
|
+
ep = {e.hint for e in result.entrypoint_hints}
|
|
374
|
+
assert "drogon_run" in ep
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def test_cpprestsdk_listener_open_entrypoint(tmp_path: Path) -> None:
|
|
378
|
+
(tmp_path / "main.cpp").write_text(
|
|
379
|
+
'#include <cpprest/http_listener.h>\n'
|
|
380
|
+
'using namespace web::http::experimental::listener;\n'
|
|
381
|
+
'int main() {\n'
|
|
382
|
+
' http_listener listener("http://0.0.0.0:80/api");\n'
|
|
383
|
+
' listener.open().wait();\n'
|
|
384
|
+
'}\n',
|
|
385
|
+
encoding="utf-8",
|
|
386
|
+
)
|
|
387
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
388
|
+
ep = {e.hint for e in result.entrypoint_hints}
|
|
389
|
+
assert "cpprestsdk_listener_open" in ep
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
# ---------- CMake → service hint ----------
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def test_cmake_project_picked_up(tmp_path: Path) -> None:
|
|
396
|
+
(tmp_path / "CMakeLists.txt").write_text(
|
|
397
|
+
'project(billing-cpp LANGUAGES CXX)\n', encoding="utf-8"
|
|
398
|
+
)
|
|
399
|
+
(tmp_path / "main.cpp").write_text("int main() { return 0; }\n", encoding="utf-8")
|
|
400
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
401
|
+
assert any(h.hint == "project:billing-cpp" for h in result.service_hints)
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
# ---------- End-to-end ----------
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def test_full_drogon_service_signal_set(tmp_path: Path) -> None:
|
|
408
|
+
(tmp_path / "CMakeLists.txt").write_text(
|
|
409
|
+
'project(orders-cpp LANGUAGES CXX)\nadd_executable(orders main.cpp)\n',
|
|
410
|
+
encoding="utf-8",
|
|
411
|
+
)
|
|
412
|
+
(tmp_path / "main.cpp").write_text(
|
|
413
|
+
'#include <drogon/drogon.h>\n'
|
|
414
|
+
'#include <pqxx/pqxx>\n'
|
|
415
|
+
'#include <jwt-cpp/jwt.h>\n'
|
|
416
|
+
'#include <openssl/ssl.h>\n'
|
|
417
|
+
'#include <cpr/cpr.h>\n'
|
|
418
|
+
'#include <cstdlib>\n'
|
|
419
|
+
'\n'
|
|
420
|
+
'int main() {\n'
|
|
421
|
+
' const char *secret = std::getenv("JWT_SECRET");\n'
|
|
422
|
+
' pqxx::connection conn{"postgresql://localhost/orders"};\n'
|
|
423
|
+
' SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());\n'
|
|
424
|
+
' auto resp = cpr::Get(cpr::Url{"https://api.stripe.com/v1/charges"});\n'
|
|
425
|
+
'\n'
|
|
426
|
+
' drogon::app().registerHandler("/api/orders", handler, {Drogon::Get, Drogon::Post});\n'
|
|
427
|
+
' drogon::app().registerHandler("/admin/refund", refund, {Drogon::Post});\n'
|
|
428
|
+
' drogon::app().run();\n'
|
|
429
|
+
'}\n',
|
|
430
|
+
encoding="utf-8",
|
|
431
|
+
)
|
|
432
|
+
|
|
433
|
+
result = CppAnalyzer().analyze(tmp_path)
|
|
434
|
+
|
|
435
|
+
pairs = {(r.path, r.method) for r in result.routes}
|
|
436
|
+
assert ("/api/orders", "GET") in pairs
|
|
437
|
+
assert ("/api/orders", "POST") in pairs
|
|
438
|
+
assert ("/admin/refund", "POST") in pairs
|
|
439
|
+
|
|
440
|
+
assert any(d.kind == "postgresql" for d in result.databases)
|
|
441
|
+
assert any(h.hint == "jwt" for h in result.auth_hints)
|
|
442
|
+
assert any(h.hint == "openssl_tls" for h in result.auth_hints)
|
|
443
|
+
assert any(s.name == "JWT_SECRET" for s in result.secret_hints)
|
|
444
|
+
assert any(e.target == "https://api.stripe.com/v1/charges" for e in result.external_calls)
|
|
445
|
+
assert any(f.hint == "drogon" for f in result.framework_hints)
|
|
446
|
+
assert any(e.hint == "drogon_run" for e in result.entrypoint_hints)
|
|
447
|
+
assert any(h.hint == "project:orders-cpp" for h in result.service_hints)
|