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

@@ -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,89 @@
1
+ Metadata-Version: 2.4
2
+ Name: attackmap-analyzer-c
3
+ Version: 0.1.0
4
+ Summary: C ecosystem analyzer plugin for AttackMap (libmicrohttpd, civetweb, mongoose; libcurl; OpenSSL/mbedTLS/libsodium; sqlite3/libpq/mysql/hiredis/mongoc).
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-c
10
+ Project-URL: Repository, https://github.com/mlaify/attackmap-analyzer-c
11
+ Project-URL: Issues, https://github.com/mlaify/attackmap-analyzer-c/issues
12
+ Project-URL: Changelog, https://github.com/mlaify/attackmap-analyzer-c/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-c
42
+
43
+ C ecosystem analyzer for [AttackMap](https://github.com/mlaify/AttackMap).
44
+
45
+ C is more fragmented than language-specific ecosystems — there's no dominant web framework, and routing patterns vary widely. This analyzer captures what regex can reach reliably from common third-party libraries.
46
+
47
+ - **Web frameworks** — civetweb (`mg_set_request_handler` extracts routes), libmicrohttpd (`MHD_start_daemon` entrypoint), mongoose (`mg_http_listen` entrypoint + `mg_http_match_uri` pseudo-routes), libonion (`onion_url_add` routes)
48
+ - **HTTP clients (external calls)** — libcurl (`curl_easy_setopt(handle, CURLOPT_URL, "...")` URL string literals)
49
+ - **Databases** — sqlite3 (`sqlite3_open*`), libpq (`PQconnectdb*`, `PQsetdbLogin`), MySQL/MariaDB C client (`mysql_real_connect`, `mariadb_real_connect`), hiredis (`redisConnect*`), MongoDB C driver (`mongoc_client_new`)
50
+ - **Auth/crypto** — OpenSSL (TLS context, EVP cipher, RAND), mbedTLS (SSL/X.509), libsodium (`crypto_pwhash`, `crypto_secretbox`, `crypto_aead_*`), Argon2 reference impl (`argon2id_hash_*`), bcrypt-c, scrypt, JWT C libraries (`jwt_encode`, `jwt_decode`)
51
+ - **Secrets** — `getenv`, `secure_getenv`, `getenv_s` with secret-shaped names (`*SECRET*`, `*TOKEN*`, `*KEY*`, `*PASSWORD*`, `*PASS*`, `*PWD*`)
52
+ - **Service hints** — project name from `CMakeLists.txt` (`project(NAME ...)`)
53
+
54
+ All emissions populate AttackMap's Signal v2 fields (line numbers + evidence snippets + confidence) so downstream insights can cite `path/to/file.c:NN`.
55
+
56
+ ## Install
57
+
58
+ ```bash
59
+ pip install git+https://github.com/mlaify/attackmap-analyzer-c.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/c/repo
69
+
70
+ # Or invoke explicitly:
71
+ attackmap analyze /path/to/c/repo --module c
72
+ ```
73
+
74
+ ## Detection
75
+
76
+ `detect()` returns true when any `.c` or `.h` file is present in the tree, ignoring `build/`, `.git/`, `_deps/`, `third_party/`, `vendor/`, `external/`, `.cache/`, `out/`, and `node_modules/`. A `CMakeLists.txt` alongside `.cpp` files (and no `.c` files) is **not** claimed by this analyzer — that's the C++ analyzer's territory.
77
+
78
+ ## Coverage notes
79
+
80
+ - **Marked experimental**: regex-based extraction in C has more false positives than language-with-strict-imports analyzers. Keep the confidence-tier model in mind when consuming output (0.6 keyword sweeps vs. 0.85+ canonical function-name hits).
81
+ - **Routes**: civetweb / mongoose / libonion all expose path strings explicitly in their routing API; libmicrohttpd does not (single-callback dispatch on `url`). For libmicrohttpd, only the entrypoint is captured — per-route URLs would need to be regexed out of `if (strcmp(url, "/x") == 0)` patterns inside the answer-callback.
82
+ - **HTTP method on routes**: the C web frameworks covered here don't statically declare HTTP methods at registration time (handlers branch on method internally), so all routes are emitted with method `ANY`.
83
+ - **OpenSSL EVP / RAND** signals are confidence 0.8 — they're broad indicators of crypto usage but not strong defensive signals on their own.
84
+ - **Authorization / Bearer / api_key keyword matches** are tier-0.6 (low confidence). They're useful as supporting evidence for an auth posture, not as load-bearing.
85
+ - **Hardcoded `#define JWT_SECRET "abc..."` macros** are not extracted — too noisy. `getenv("JWT_SECRET")` is the canonical pattern we rely on.
86
+
87
+ ## License
88
+
89
+ MIT
@@ -0,0 +1,49 @@
1
+ # attackmap-analyzer-c
2
+
3
+ C ecosystem analyzer for [AttackMap](https://github.com/mlaify/AttackMap).
4
+
5
+ C is more fragmented than language-specific ecosystems — there's no dominant web framework, and routing patterns vary widely. This analyzer captures what regex can reach reliably from common third-party libraries.
6
+
7
+ - **Web frameworks** — civetweb (`mg_set_request_handler` extracts routes), libmicrohttpd (`MHD_start_daemon` entrypoint), mongoose (`mg_http_listen` entrypoint + `mg_http_match_uri` pseudo-routes), libonion (`onion_url_add` routes)
8
+ - **HTTP clients (external calls)** — libcurl (`curl_easy_setopt(handle, CURLOPT_URL, "...")` URL string literals)
9
+ - **Databases** — sqlite3 (`sqlite3_open*`), libpq (`PQconnectdb*`, `PQsetdbLogin`), MySQL/MariaDB C client (`mysql_real_connect`, `mariadb_real_connect`), hiredis (`redisConnect*`), MongoDB C driver (`mongoc_client_new`)
10
+ - **Auth/crypto** — OpenSSL (TLS context, EVP cipher, RAND), mbedTLS (SSL/X.509), libsodium (`crypto_pwhash`, `crypto_secretbox`, `crypto_aead_*`), Argon2 reference impl (`argon2id_hash_*`), bcrypt-c, scrypt, JWT C libraries (`jwt_encode`, `jwt_decode`)
11
+ - **Secrets** — `getenv`, `secure_getenv`, `getenv_s` with secret-shaped names (`*SECRET*`, `*TOKEN*`, `*KEY*`, `*PASSWORD*`, `*PASS*`, `*PWD*`)
12
+ - **Service hints** — project name from `CMakeLists.txt` (`project(NAME ...)`)
13
+
14
+ All emissions populate AttackMap's Signal v2 fields (line numbers + evidence snippets + confidence) so downstream insights can cite `path/to/file.c:NN`.
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ pip install git+https://github.com/mlaify/attackmap-analyzer-c.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/c/repo
29
+
30
+ # Or invoke explicitly:
31
+ attackmap analyze /path/to/c/repo --module c
32
+ ```
33
+
34
+ ## Detection
35
+
36
+ `detect()` returns true when any `.c` or `.h` file is present in the tree, ignoring `build/`, `.git/`, `_deps/`, `third_party/`, `vendor/`, `external/`, `.cache/`, `out/`, and `node_modules/`. A `CMakeLists.txt` alongside `.cpp` files (and no `.c` files) is **not** claimed by this analyzer — that's the C++ analyzer's territory.
37
+
38
+ ## Coverage notes
39
+
40
+ - **Marked experimental**: regex-based extraction in C has more false positives than language-with-strict-imports analyzers. Keep the confidence-tier model in mind when consuming output (0.6 keyword sweeps vs. 0.85+ canonical function-name hits).
41
+ - **Routes**: civetweb / mongoose / libonion all expose path strings explicitly in their routing API; libmicrohttpd does not (single-callback dispatch on `url`). For libmicrohttpd, only the entrypoint is captured — per-route URLs would need to be regexed out of `if (strcmp(url, "/x") == 0)` patterns inside the answer-callback.
42
+ - **HTTP method on routes**: the C web frameworks covered here don't statically declare HTTP methods at registration time (handlers branch on method internally), so all routes are emitted with method `ANY`.
43
+ - **OpenSSL EVP / RAND** signals are confidence 0.8 — they're broad indicators of crypto usage but not strong defensive signals on their own.
44
+ - **Authorization / Bearer / api_key keyword matches** are tier-0.6 (low confidence). They're useful as supporting evidence for an auth posture, not as load-bearing.
45
+ - **Hardcoded `#define JWT_SECRET "abc..."` macros** are not extracted — too noisy. `getenv("JWT_SECRET")` is the canonical pattern we rely on.
46
+
47
+ ## License
48
+
49
+ 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-c"
7
+ version = "0.1.0"
8
+ description = "C ecosystem analyzer plugin for AttackMap (libmicrohttpd, civetweb, mongoose; libcurl; OpenSSL/mbedTLS/libsodium; sqlite3/libpq/mysql/hiredis/mongoc)."
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-c"
59
+ Repository = "https://github.com/mlaify/attackmap-analyzer-c"
60
+ Issues = "https://github.com/mlaify/attackmap-analyzer-c/issues"
61
+ Changelog = "https://github.com/mlaify/attackmap-analyzer-c/blob/main/CHANGELOG.md"
62
+ "AttackMap core" = "https://github.com/mlaify/AttackMap"
63
+
64
+ [project.entry-points."attackmap.analyzers"]
65
+ c = "attackmap_analyzer_c:CAnalyzer"
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,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ from .analyzer import CAnalyzer
2
+
3
+ __all__ = ["CAnalyzer"]
@@ -0,0 +1,386 @@
1
+ """C ecosystem analyzer for AttackMap.
2
+
3
+ Coverage (v0.1):
4
+ - Web frameworks: civetweb (mg_set_request_handler routes), libmicrohttpd
5
+ (MHD_start_daemon entrypoint), mongoose (mg_http_listen entrypoint +
6
+ mg_http_match_uri pseudo-routes), libonion (onion_url_add routes)
7
+ - HTTP clients (external calls): libcurl (CURLOPT_URL string literals)
8
+ - Databases: sqlite3 (sqlite3_open*), libpq (PQconnectdb*), MySQL/MariaDB C
9
+ client (mysql_real_connect), hiredis (redisConnect*), MongoDB C driver
10
+ (mongoc_client_new)
11
+ - Auth/crypto: OpenSSL (broad framework hint via EVP_/SSL_/RSA_), mbedTLS,
12
+ libsodium (crypto_pwhash, crypto_secretbox), Argon2 reference impl,
13
+ bcrypt-c, scrypt
14
+ - Secrets: getenv / secure_getenv / getenv_s with secret-shaped names
15
+ - Service hints: project name from CMakeLists.txt
16
+
17
+ C is more fragmented than other ecosystems — there's no single dominant
18
+ HTTP framework, and routing patterns vary widely. We capture what regex
19
+ can reach reliably and conservatively confidence-tag pattern hits.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import re
25
+ from pathlib import Path
26
+
27
+ from .contracts import (
28
+ AnalyzerMetadata,
29
+ AuthHint,
30
+ DatabaseHint,
31
+ EntrypointHint,
32
+ ExternalCall,
33
+ FrameworkHint,
34
+ Route,
35
+ ScanResult,
36
+ SecretHint,
37
+ ServiceHint,
38
+ )
39
+
40
+ CODE_SUFFIXES = {".c", ".h"}
41
+ SKIP_DIRS = {
42
+ "build",
43
+ ".git",
44
+ "_deps",
45
+ "third_party",
46
+ "vendor",
47
+ "external",
48
+ ".cache",
49
+ "out",
50
+ "node_modules",
51
+ }
52
+ _SNIPPET_MAX_CHARS = 160
53
+
54
+
55
+ # ---------- Patterns ----------
56
+
57
+ # civetweb: mg_set_request_handler(ctx, "/path", handler, NULL)
58
+ CIVETWEB_ROUTE_PATTERN = re.compile(
59
+ r'\bmg_set_request_handler\s*\(\s*\w+\s*,\s*"([^"]+)"',
60
+ )
61
+
62
+ # mongoose: mg_http_match_uri(hm, "/path") inside an event handler — pseudo-routes
63
+ MONGOOSE_MATCH_URI_PATTERN = re.compile(
64
+ r'\bmg_http_match_uri\s*\(\s*\w+\s*,\s*"([^"]+)"',
65
+ )
66
+
67
+ # libonion: onion_url_add(url, "^/path/?$", handler, ...)
68
+ ONION_ROUTE_PATTERN = re.compile(
69
+ r'\bonion_url_add(?:_static|_with_data)?\s*\(\s*\w+\s*,\s*"([^"]+)"',
70
+ )
71
+
72
+ # libcurl: curl_easy_setopt(handle, CURLOPT_URL, "https://...")
73
+ LIBCURL_URL_PATTERN = re.compile(
74
+ r'\bcurl_easy_setopt\s*\(\s*\w+\s*,\s*CURLOPT_URL\s*,\s*"(https?://[^"]+)"',
75
+ )
76
+
77
+ # DBs
78
+ DB_PATTERNS: list[tuple[re.Pattern[str], str]] = [
79
+ (re.compile(r'\bsqlite3_open(?:_v2)?\s*\('), "sqlite"),
80
+ (re.compile(r'\bPQconnectdb(?:Params)?\s*\(|\bPQsetdbLogin\s*\('), "postgresql"),
81
+ (re.compile(r'\bmysql_real_connect\s*\(|\bmariadb_real_connect\s*\('), "mysql"),
82
+ (re.compile(r'\bredisConnect(?:WithTimeout)?\s*\('), "redis"),
83
+ (re.compile(r'\bmongoc_client_new\s*\(|\bmongoc_uri_new\s*\('), "mongodb"),
84
+ ]
85
+
86
+ # Auth / crypto
87
+ AUTH_PATTERNS: list[tuple[re.Pattern[str], str, float]] = [
88
+ (re.compile(r'\bcrypto_pwhash(?:_argon2(?:i|id))?\s*\(|\bcrypto_pwhash_str\s*\('), "argon2", 0.9),
89
+ (re.compile(r'\bargon2(?:i|d|id)?_hash\w*\s*\('), "argon2", 0.9),
90
+ (re.compile(r'\bbcrypt(?:_hashpw|_checkpw|_gensalt)?\s*\('), "bcrypt", 0.9),
91
+ (re.compile(r'\bscrypt(?:_kdf)?\s*\('), "scrypt", 0.9),
92
+ (re.compile(r'\bcrypto_secretbox\w*\s*\(|\bcrypto_aead_(?:chacha20poly1305|aes256gcm)\w*\s*\('), "libsodium_aead", 0.85),
93
+ (re.compile(r'\bSSL_CTX_new\s*\(|\bSSL_new\s*\(|\bTLS_method\s*\(|\bTLS_(?:client|server)_method\s*\('), "openssl_tls", 0.85),
94
+ (re.compile(r'\bEVP_PKEY_new\s*\(|\bEVP_(?:Encrypt|Decrypt)Init\w*\s*\('), "openssl_evp", 0.8),
95
+ (re.compile(r'\bRAND_bytes\s*\(|\bRAND_priv_bytes\s*\('), "openssl_rand", 0.8),
96
+ (re.compile(r'\bmbedtls_(?:ssl|x509)_\w+\s*\('), "mbedtls", 0.85),
97
+ (re.compile(r'\bjwt_(?:encode|decode|new|verify)\s*\('), "jwt", 0.85),
98
+ (re.compile(r'\bAuthorization\b'), "authorization_header", 0.6),
99
+ (re.compile(r'\bBearer\b'), "bearer_token", 0.6),
100
+ (re.compile(r'\bapi[_-]?key\b', re.IGNORECASE), "api_key", 0.6),
101
+ ]
102
+
103
+ FRAMEWORK_PATTERNS: list[tuple[re.Pattern[str], str]] = [
104
+ (re.compile(r'\bMHD_start_daemon\s*\(|\bMHD_create_response\w*\s*\(|#\s*include\s+["<]microhttpd\.h'), "libmicrohttpd"),
105
+ (re.compile(r'\bmg_start\s*\(|\bmg_set_request_handler\s*\(|#\s*include\s+["<]civetweb\.h'), "civetweb"),
106
+ (re.compile(r'\bmg_mgr_init\s*\(|\bmg_http_listen\s*\(|#\s*include\s+["<]mongoose\.h'), "mongoose"),
107
+ (re.compile(r'\bonion_new\s*\(|\bonion_listen\s*\(|#\s*include\s+["<]onion/onion\.h'), "libonion"),
108
+ (re.compile(r'#\s*include\s+["<]openssl/'), "openssl"),
109
+ (re.compile(r'#\s*include\s+["<]mbedtls/'), "mbedtls"),
110
+ (re.compile(r'#\s*include\s+["<]sodium\.h'), "libsodium"),
111
+ (re.compile(r'#\s*include\s+["<]curl/curl\.h'), "libcurl"),
112
+ (re.compile(r'#\s*include\s+["<]sqlite3\.h'), "sqlite3"),
113
+ (re.compile(r'#\s*include\s+["<]libpq-fe\.h'), "libpq"),
114
+ (re.compile(r'#\s*include\s+["<]hiredis/hiredis\.h'), "hiredis"),
115
+ (re.compile(r'#\s*include\s+["<]mongoc/mongoc\.h|#\s*include\s+["<]mongoc\.h'), "mongoc"),
116
+ ]
117
+
118
+ ENTRYPOINT_PATTERNS: list[tuple[re.Pattern[str], str]] = [
119
+ (re.compile(r'\bMHD_start_daemon\s*\('), "mhd_start_daemon"),
120
+ (re.compile(r'\bmg_start\s*\('), "civetweb_start"),
121
+ (re.compile(r'\bmg_http_listen\s*\('), "mongoose_http_listen"),
122
+ (re.compile(r'\bonion_listen\s*\('), "onion_listen"),
123
+ (re.compile(r'\baccept\s*\(\s*\w+\s*,\s*\(struct\s+sockaddr\s*\*\)'), "raw_socket_accept"),
124
+ ]
125
+
126
+ # Secrets via getenv / secure_getenv / getenv_s
127
+ SECRET_PATTERNS: list[re.Pattern[str]] = [
128
+ re.compile(
129
+ r'\b(?:secure_)?getenv\s*\(\s*"([A-Z0-9_]*(?:SECRET|TOKEN|KEY|PASSWORD|PASS|PWD)[A-Z0-9_]*)"',
130
+ ),
131
+ re.compile(
132
+ r'\bgetenv_s\s*\([^,]*,\s*[^,]*,\s*"([A-Z0-9_]*(?:SECRET|TOKEN|KEY|PASSWORD|PASS|PWD)[A-Z0-9_]*)"',
133
+ ),
134
+ ]
135
+
136
+
137
+ def _line_of(content: str, offset: int) -> int:
138
+ if offset <= 0:
139
+ return 1
140
+ return content.count("\n", 0, offset) + 1
141
+
142
+
143
+ def _line_snippet(content: str, offset: int, *, max_chars: int = _SNIPPET_MAX_CHARS) -> str:
144
+ line_start = content.rfind("\n", 0, offset) + 1
145
+ line_end = content.find("\n", offset)
146
+ if line_end == -1:
147
+ line_end = len(content)
148
+ line = content[line_start:line_end].strip()
149
+ if len(line) > max_chars:
150
+ line = line[: max_chars - 1] + "…"
151
+ return line
152
+
153
+
154
+ def _project_name_from_cmake(cmake_path: Path) -> str | None:
155
+ if not cmake_path.exists():
156
+ return None
157
+ try:
158
+ text = cmake_path.read_text(encoding="utf-8")
159
+ except UnicodeDecodeError:
160
+ return None
161
+ match = re.search(r"\bproject\s*\(\s*([A-Za-z0-9_\-]+)", text)
162
+ if match:
163
+ return match.group(1)
164
+ return None
165
+
166
+
167
+ class CAnalyzer:
168
+ metadata = AnalyzerMetadata(
169
+ name="c",
170
+ display_name="C Analyzer",
171
+ version="0.1.0",
172
+ description="C ecosystem analyzer covering libmicrohttpd, civetweb, mongoose, libonion, libcurl, OpenSSL, libsodium, sqlite3, libpq, mysql, hiredis, mongoc.",
173
+ scope="C source trees and CMake/Make projects. Detects HTTP server entrypoints, libcurl outbound calls, common DB and crypto libraries.",
174
+ targets=["c", "civetweb", "libmicrohttpd", "mongoose"],
175
+ languages=["c"],
176
+ priority=20,
177
+ experimental=True, # C ecosystem coverage is heuristic and partial; mark experimental.
178
+ enabled_by_default=True,
179
+ )
180
+
181
+ @property
182
+ def name(self) -> str:
183
+ return self.metadata.name
184
+
185
+ # ---------- Public entry points ----------
186
+
187
+ def detect(self, repo_path: str | Path) -> bool:
188
+ root = Path(repo_path).resolve()
189
+ if not root.exists() or not root.is_dir():
190
+ return False
191
+ for path in root.rglob("*"):
192
+ if any(part in SKIP_DIRS for part in path.parts):
193
+ continue
194
+ if not path.is_file():
195
+ continue
196
+ if path.suffix in CODE_SUFFIXES:
197
+ return True
198
+ if path.name in {"CMakeLists.txt", "Makefile"}:
199
+ # Disambiguate: a CMake project may be C++ rather than C. Only return True
200
+ # when there's at least one .c file alongside it; otherwise let the C++
201
+ # analyzer claim the repo.
202
+ for sibling in path.parent.rglob("*.c"):
203
+ if any(part in SKIP_DIRS for part in sibling.parts):
204
+ continue
205
+ return True
206
+ return False
207
+
208
+ def analyze(self, repo_path: str | Path) -> ScanResult:
209
+ root = Path(repo_path).resolve()
210
+ result = ScanResult(root=str(root))
211
+ if not root.exists() or not root.is_dir():
212
+ return result
213
+
214
+ for cmake in root.rglob("CMakeLists.txt"):
215
+ if any(part in SKIP_DIRS for part in cmake.parts):
216
+ continue
217
+ project = _project_name_from_cmake(cmake)
218
+ if project:
219
+ self._append_unique_service(result, f"project:{project}", str(cmake.relative_to(root)))
220
+
221
+ for file_path in root.rglob("*"):
222
+ if not file_path.is_file():
223
+ continue
224
+ if any(part in SKIP_DIRS for part in file_path.parts):
225
+ continue
226
+ if file_path.suffix not in CODE_SUFFIXES:
227
+ continue
228
+
229
+ result.files_scanned += 1
230
+ if "c" not in result.languages:
231
+ result.languages.append("c")
232
+
233
+ try:
234
+ content = file_path.read_text(encoding="utf-8")
235
+ except UnicodeDecodeError:
236
+ continue
237
+
238
+ relative = str(file_path.relative_to(root))
239
+ self._extract_routes(content, relative, result)
240
+ self._extract_databases(content, relative, result)
241
+ self._extract_auth(content, relative, result)
242
+ self._extract_secrets(content, relative, result)
243
+ self._extract_external_calls(content, relative, result)
244
+ self._extract_frameworks(content, relative, result)
245
+ self._extract_entrypoints(content, relative, result)
246
+
247
+ result.languages.sort()
248
+ return result
249
+
250
+ # ---------- Extractors ----------
251
+
252
+ def _extract_routes(self, content: str, relative: str, result: ScanResult) -> None:
253
+ for match in CIVETWEB_ROUTE_PATTERN.finditer(content):
254
+ path = match.group(1)
255
+ self._append_unique_route(result, path, "ANY", relative, _line_of(content, match.start()))
256
+ for match in MONGOOSE_MATCH_URI_PATTERN.finditer(content):
257
+ path = match.group(1)
258
+ self._append_unique_route(result, path, "ANY", relative, _line_of(content, match.start()))
259
+ for match in ONION_ROUTE_PATTERN.finditer(content):
260
+ path = match.group(1)
261
+ self._append_unique_route(result, path, "ANY", relative, _line_of(content, match.start()))
262
+
263
+ def _extract_databases(self, content: str, relative: str, result: ScanResult) -> None:
264
+ for pattern, kind in DB_PATTERNS:
265
+ match = pattern.search(content)
266
+ if match is None:
267
+ continue
268
+ self._append_unique_database(
269
+ result, kind, relative,
270
+ _line_of(content, match.start()),
271
+ _line_snippet(content, match.start()),
272
+ )
273
+
274
+ def _extract_auth(self, content: str, relative: str, result: ScanResult) -> None:
275
+ for pattern, hint, confidence in AUTH_PATTERNS:
276
+ match = pattern.search(content)
277
+ if match is None:
278
+ continue
279
+ self._append_unique_auth(
280
+ result, hint, relative,
281
+ _line_of(content, match.start()),
282
+ _line_snippet(content, match.start()),
283
+ confidence,
284
+ )
285
+
286
+ def _extract_secrets(self, content: str, relative: str, result: ScanResult) -> None:
287
+ for pattern in SECRET_PATTERNS:
288
+ for match in pattern.finditer(content):
289
+ name = match.group(1)
290
+ self._append_unique_secret(
291
+ result, name, relative,
292
+ _line_of(content, match.start()),
293
+ _line_snippet(content, match.start()),
294
+ )
295
+
296
+ def _extract_external_calls(self, content: str, relative: str, result: ScanResult) -> None:
297
+ for match in LIBCURL_URL_PATTERN.finditer(content):
298
+ target = match.group(1)
299
+ self._append_unique_external(
300
+ result, target, relative,
301
+ _line_of(content, match.start()),
302
+ _line_snippet(content, match.start()),
303
+ )
304
+
305
+ def _extract_frameworks(self, content: str, relative: str, result: ScanResult) -> None:
306
+ for pattern, name in FRAMEWORK_PATTERNS:
307
+ match = pattern.search(content)
308
+ if match is None:
309
+ continue
310
+ self._append_unique_framework(
311
+ result, name, relative,
312
+ _line_of(content, match.start()),
313
+ _line_snippet(content, match.start()),
314
+ )
315
+
316
+ def _extract_entrypoints(self, content: str, relative: str, result: ScanResult) -> None:
317
+ for pattern, hint in ENTRYPOINT_PATTERNS:
318
+ match = pattern.search(content)
319
+ if match is None:
320
+ continue
321
+ self._append_unique_entrypoint(
322
+ result, hint, relative,
323
+ _line_of(content, match.start()),
324
+ _line_snippet(content, match.start()),
325
+ )
326
+
327
+ # ---------- Append helpers ----------
328
+
329
+ @staticmethod
330
+ def _append_unique_route(result: ScanResult, path: str, method: str, file: str, line: int | None) -> None:
331
+ key = (path, method, file)
332
+ if any((item.path, item.method, item.file) == key for item in result.routes):
333
+ return
334
+ result.routes.append(Route(path=path, method=method, file=file, line=line))
335
+
336
+ @staticmethod
337
+ def _append_unique_database(result: ScanResult, kind: str, file: str, line: int | None, evidence: str | None) -> None:
338
+ key = (kind, file)
339
+ if any((item.kind, item.file) == key for item in result.databases):
340
+ return
341
+ result.databases.append(DatabaseHint(kind=kind, file=file, line=line, evidence_text=evidence))
342
+
343
+ @staticmethod
344
+ def _append_unique_auth(result: ScanResult, hint: str, file: str, line: int | None, evidence: str | None, confidence: float) -> None:
345
+ key = (hint, file)
346
+ if any((item.hint, item.file) == key for item in result.auth_hints):
347
+ return
348
+ result.auth_hints.append(AuthHint(hint=hint, file=file, line=line, evidence_text=evidence, confidence=confidence))
349
+
350
+ @staticmethod
351
+ def _append_unique_secret(result: ScanResult, name: str, file: str, line: int | None, evidence: str | None) -> None:
352
+ key = (name, file)
353
+ if any((item.name, item.file) == key for item in result.secret_hints):
354
+ return
355
+ result.secret_hints.append(SecretHint(name=name, file=file, line=line, evidence_text=evidence, confidence=0.85))
356
+
357
+ @staticmethod
358
+ def _append_unique_external(result: ScanResult, target: str, file: str, line: int | None, evidence: str | None) -> None:
359
+ key = (target, file)
360
+ if any((item.target, item.file) == key for item in result.external_calls):
361
+ return
362
+ result.external_calls.append(ExternalCall(target=target, file=file, line=line, evidence_text=evidence))
363
+
364
+ @staticmethod
365
+ def _append_unique_framework(result: ScanResult, hint: str, file: str, line: int | None, evidence: str | None) -> None:
366
+ key = (hint, file)
367
+ if any((item.hint, item.file) == key for item in result.framework_hints):
368
+ return
369
+ result.framework_hints.append(FrameworkHint(hint=hint, file=file, line=line, evidence_text=evidence))
370
+
371
+ @staticmethod
372
+ def _append_unique_entrypoint(result: ScanResult, hint: str, file: str, line: int | None, evidence: str | None) -> None:
373
+ key = (hint, file)
374
+ if any((item.hint, item.file) == key for item in result.entrypoint_hints):
375
+ return
376
+ result.entrypoint_hints.append(EntrypointHint(hint=hint, file=file, line=line, evidence_text=evidence))
377
+
378
+ @staticmethod
379
+ def _append_unique_service(result: ScanResult, hint: str, file: str) -> None:
380
+ key = (hint, file)
381
+ if any((item.hint, item.file) == key for item in result.service_hints):
382
+ return
383
+ result.service_hints.append(ServiceHint(hint=hint, file=file))
384
+
385
+
386
+ __all__ = ["CAnalyzer"]
@@ -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,89 @@
1
+ Metadata-Version: 2.4
2
+ Name: attackmap-analyzer-c
3
+ Version: 0.1.0
4
+ Summary: C ecosystem analyzer plugin for AttackMap (libmicrohttpd, civetweb, mongoose; libcurl; OpenSSL/mbedTLS/libsodium; sqlite3/libpq/mysql/hiredis/mongoc).
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-c
10
+ Project-URL: Repository, https://github.com/mlaify/attackmap-analyzer-c
11
+ Project-URL: Issues, https://github.com/mlaify/attackmap-analyzer-c/issues
12
+ Project-URL: Changelog, https://github.com/mlaify/attackmap-analyzer-c/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-c
42
+
43
+ C ecosystem analyzer for [AttackMap](https://github.com/mlaify/AttackMap).
44
+
45
+ C is more fragmented than language-specific ecosystems — there's no dominant web framework, and routing patterns vary widely. This analyzer captures what regex can reach reliably from common third-party libraries.
46
+
47
+ - **Web frameworks** — civetweb (`mg_set_request_handler` extracts routes), libmicrohttpd (`MHD_start_daemon` entrypoint), mongoose (`mg_http_listen` entrypoint + `mg_http_match_uri` pseudo-routes), libonion (`onion_url_add` routes)
48
+ - **HTTP clients (external calls)** — libcurl (`curl_easy_setopt(handle, CURLOPT_URL, "...")` URL string literals)
49
+ - **Databases** — sqlite3 (`sqlite3_open*`), libpq (`PQconnectdb*`, `PQsetdbLogin`), MySQL/MariaDB C client (`mysql_real_connect`, `mariadb_real_connect`), hiredis (`redisConnect*`), MongoDB C driver (`mongoc_client_new`)
50
+ - **Auth/crypto** — OpenSSL (TLS context, EVP cipher, RAND), mbedTLS (SSL/X.509), libsodium (`crypto_pwhash`, `crypto_secretbox`, `crypto_aead_*`), Argon2 reference impl (`argon2id_hash_*`), bcrypt-c, scrypt, JWT C libraries (`jwt_encode`, `jwt_decode`)
51
+ - **Secrets** — `getenv`, `secure_getenv`, `getenv_s` with secret-shaped names (`*SECRET*`, `*TOKEN*`, `*KEY*`, `*PASSWORD*`, `*PASS*`, `*PWD*`)
52
+ - **Service hints** — project name from `CMakeLists.txt` (`project(NAME ...)`)
53
+
54
+ All emissions populate AttackMap's Signal v2 fields (line numbers + evidence snippets + confidence) so downstream insights can cite `path/to/file.c:NN`.
55
+
56
+ ## Install
57
+
58
+ ```bash
59
+ pip install git+https://github.com/mlaify/attackmap-analyzer-c.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/c/repo
69
+
70
+ # Or invoke explicitly:
71
+ attackmap analyze /path/to/c/repo --module c
72
+ ```
73
+
74
+ ## Detection
75
+
76
+ `detect()` returns true when any `.c` or `.h` file is present in the tree, ignoring `build/`, `.git/`, `_deps/`, `third_party/`, `vendor/`, `external/`, `.cache/`, `out/`, and `node_modules/`. A `CMakeLists.txt` alongside `.cpp` files (and no `.c` files) is **not** claimed by this analyzer — that's the C++ analyzer's territory.
77
+
78
+ ## Coverage notes
79
+
80
+ - **Marked experimental**: regex-based extraction in C has more false positives than language-with-strict-imports analyzers. Keep the confidence-tier model in mind when consuming output (0.6 keyword sweeps vs. 0.85+ canonical function-name hits).
81
+ - **Routes**: civetweb / mongoose / libonion all expose path strings explicitly in their routing API; libmicrohttpd does not (single-callback dispatch on `url`). For libmicrohttpd, only the entrypoint is captured — per-route URLs would need to be regexed out of `if (strcmp(url, "/x") == 0)` patterns inside the answer-callback.
82
+ - **HTTP method on routes**: the C web frameworks covered here don't statically declare HTTP methods at registration time (handlers branch on method internally), so all routes are emitted with method `ANY`.
83
+ - **OpenSSL EVP / RAND** signals are confidence 0.8 — they're broad indicators of crypto usage but not strong defensive signals on their own.
84
+ - **Authorization / Bearer / api_key keyword matches** are tier-0.6 (low confidence). They're useful as supporting evidence for an auth posture, not as load-bearing.
85
+ - **Hardcoded `#define JWT_SECRET "abc..."` macros** are not extracted — too noisy. `getenv("JWT_SECRET")` is the canonical pattern we rely on.
86
+
87
+ ## License
88
+
89
+ MIT
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/attackmap_analyzer_c/__init__.py
5
+ src/attackmap_analyzer_c/analyzer.py
6
+ src/attackmap_analyzer_c/contracts.py
7
+ src/attackmap_analyzer_c.egg-info/PKG-INFO
8
+ src/attackmap_analyzer_c.egg-info/SOURCES.txt
9
+ src/attackmap_analyzer_c.egg-info/dependency_links.txt
10
+ src/attackmap_analyzer_c.egg-info/entry_points.txt
11
+ src/attackmap_analyzer_c.egg-info/requires.txt
12
+ src/attackmap_analyzer_c.egg-info/top_level.txt
13
+ tests/test_c_analyzer.py
@@ -0,0 +1,2 @@
1
+ [attackmap.analyzers]
2
+ c = attackmap_analyzer_c:CAnalyzer
@@ -0,0 +1,9 @@
1
+ pydantic>=2.7.0
2
+
3
+ [core]
4
+ attackmap>=0.1.0
5
+
6
+ [dev]
7
+ pytest>=8.0.0
8
+ build>=1.2.0
9
+ attackmap>=0.1.0
@@ -0,0 +1,389 @@
1
+ """Tests for the CAnalyzer plugin."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import pytest
8
+
9
+ from attackmap_analyzer_c import CAnalyzer
10
+
11
+
12
+ # ---------- detect() ----------
13
+
14
+
15
+ def test_detect_picks_up_c_file(tmp_path: Path) -> None:
16
+ (tmp_path / "main.c").write_text("int main(void) { return 0; }\n", encoding="utf-8")
17
+ assert CAnalyzer().detect(tmp_path) is True
18
+
19
+
20
+ def test_detect_picks_up_header_file(tmp_path: Path) -> None:
21
+ (tmp_path / "api.h").write_text("#pragma once\nint foo(void);\n", encoding="utf-8")
22
+ assert CAnalyzer().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.c").write_text("int main() { return 0; }\n", encoding="utf-8")
28
+ assert CAnalyzer().detect(tmp_path) is False
29
+
30
+
31
+ def test_detect_returns_false_for_empty(tmp_path: Path) -> None:
32
+ assert CAnalyzer().detect(tmp_path) is False
33
+
34
+
35
+ def test_detect_cmake_only_without_c_files_does_not_claim(tmp_path: Path) -> None:
36
+ """A CMakeLists.txt next to .cpp files belongs to the C++ analyzer, not C."""
37
+ (tmp_path / "CMakeLists.txt").write_text("project(demo)\n", encoding="utf-8")
38
+ (tmp_path / "main.cpp").write_text("int main() {}\n", encoding="utf-8")
39
+ assert CAnalyzer().detect(tmp_path) is False
40
+
41
+
42
+ # ---------- Routes ----------
43
+
44
+
45
+ def test_civetweb_set_request_handler(tmp_path: Path) -> None:
46
+ (tmp_path / "app.c").write_text(
47
+ '#include <civetweb.h>\n'
48
+ '\n'
49
+ 'int main(void) {\n'
50
+ ' struct mg_context *ctx = mg_start(NULL, NULL, NULL);\n'
51
+ ' mg_set_request_handler(ctx, "/api/users", users_handler, NULL);\n'
52
+ ' mg_set_request_handler(ctx, "/health", health_handler, NULL);\n'
53
+ ' return 0;\n'
54
+ '}\n',
55
+ encoding="utf-8",
56
+ )
57
+ result = CAnalyzer().analyze(tmp_path)
58
+ paths = {r.path for r in result.routes}
59
+ assert "/api/users" in paths
60
+ assert "/health" in paths
61
+
62
+ users = next(r for r in result.routes if r.path == "/api/users")
63
+ assert users.line == 5
64
+
65
+
66
+ def test_mongoose_match_uri_emits_pseudo_routes(tmp_path: Path) -> None:
67
+ (tmp_path / "handler.c").write_text(
68
+ '#include <mongoose.h>\n'
69
+ '\n'
70
+ 'static void handler(struct mg_connection *c, int ev, void *ev_data) {\n'
71
+ ' if (ev == MG_EV_HTTP_MSG) {\n'
72
+ ' struct mg_http_message *hm = (struct mg_http_message *)ev_data;\n'
73
+ ' if (mg_http_match_uri(hm, "/api/login")) {\n'
74
+ ' login(c, hm);\n'
75
+ ' } else if (mg_http_match_uri(hm, "/admin/*")) {\n'
76
+ ' admin(c, hm);\n'
77
+ ' }\n'
78
+ ' }\n'
79
+ '}\n',
80
+ encoding="utf-8",
81
+ )
82
+ result = CAnalyzer().analyze(tmp_path)
83
+ paths = {r.path for r in result.routes}
84
+ assert "/api/login" in paths
85
+ assert "/admin/*" in paths
86
+
87
+
88
+ def test_libonion_url_add(tmp_path: Path) -> None:
89
+ (tmp_path / "app.c").write_text(
90
+ '#include <onion/onion.h>\n'
91
+ '\n'
92
+ 'void setup(onion_url *url) {\n'
93
+ ' onion_url_add(url, "^/users/?$", users_handler);\n'
94
+ ' onion_url_add_static(url, "^/static/", "./public", 0);\n'
95
+ '}\n',
96
+ encoding="utf-8",
97
+ )
98
+ result = CAnalyzer().analyze(tmp_path)
99
+ paths = {r.path for r in result.routes}
100
+ assert "^/users/?$" in paths
101
+ assert "^/static/" in paths
102
+
103
+
104
+ # ---------- HTTP clients ----------
105
+
106
+
107
+ def test_libcurl_url_extracted(tmp_path: Path) -> None:
108
+ (tmp_path / "client.c").write_text(
109
+ '#include <curl/curl.h>\n'
110
+ '\n'
111
+ 'int fetch(void) {\n'
112
+ ' CURL *curl = curl_easy_init();\n'
113
+ ' curl_easy_setopt(curl, CURLOPT_URL, "https://api.stripe.com/v1/charges");\n'
114
+ ' return curl_easy_perform(curl);\n'
115
+ '}\n',
116
+ encoding="utf-8",
117
+ )
118
+ result = CAnalyzer().analyze(tmp_path)
119
+ targets = {e.target for e in result.external_calls}
120
+ assert "https://api.stripe.com/v1/charges" in targets
121
+
122
+
123
+ def test_curlopt_url_with_non_url_string_skipped(tmp_path: Path) -> None:
124
+ (tmp_path / "client.c").write_text(
125
+ 'curl_easy_setopt(curl, CURLOPT_URL, "/local/path");\n',
126
+ encoding="utf-8",
127
+ )
128
+ result = CAnalyzer().analyze(tmp_path)
129
+ assert result.external_calls == []
130
+
131
+
132
+ # ---------- Databases ----------
133
+
134
+
135
+ def test_sqlite_open(tmp_path: Path) -> None:
136
+ (tmp_path / "db.c").write_text(
137
+ '#include <sqlite3.h>\n'
138
+ '\n'
139
+ 'sqlite3 *open_db(void) {\n'
140
+ ' sqlite3 *db;\n'
141
+ ' sqlite3_open("data.db", &db);\n'
142
+ ' return db;\n'
143
+ '}\n',
144
+ encoding="utf-8",
145
+ )
146
+ result = CAnalyzer().analyze(tmp_path)
147
+ assert any(d.kind == "sqlite" for d in result.databases)
148
+
149
+
150
+ def test_libpq_connect(tmp_path: Path) -> None:
151
+ (tmp_path / "pg.c").write_text(
152
+ '#include <libpq-fe.h>\n'
153
+ 'PGconn *connect_db(void) {\n'
154
+ ' return PQconnectdb("host=localhost dbname=app");\n'
155
+ '}\n',
156
+ encoding="utf-8",
157
+ )
158
+ result = CAnalyzer().analyze(tmp_path)
159
+ assert any(d.kind == "postgresql" for d in result.databases)
160
+
161
+
162
+ def test_mysql_and_redis_distinct_kinds(tmp_path: Path) -> None:
163
+ (tmp_path / "mysql.c").write_text(
164
+ 'MYSQL *m = mysql_init(NULL);\n'
165
+ 'mysql_real_connect(m, "host", "user", "pass", "db", 3306, NULL, 0);\n',
166
+ encoding="utf-8",
167
+ )
168
+ (tmp_path / "redis.c").write_text(
169
+ '#include <hiredis/hiredis.h>\n'
170
+ 'redisContext *c = redisConnect("127.0.0.1", 6379);\n',
171
+ encoding="utf-8",
172
+ )
173
+ result = CAnalyzer().analyze(tmp_path)
174
+ kinds = {d.kind for d in result.databases}
175
+ assert "mysql" in kinds
176
+ assert "redis" in kinds
177
+
178
+
179
+ def test_mongoc_emits_mongodb(tmp_path: Path) -> None:
180
+ (tmp_path / "mongo.c").write_text(
181
+ '#include <mongoc/mongoc.h>\n'
182
+ 'int main(void) {\n'
183
+ ' mongoc_client_t *client = mongoc_client_new("mongodb://x");\n'
184
+ ' return 0;\n'
185
+ '}\n',
186
+ encoding="utf-8",
187
+ )
188
+ result = CAnalyzer().analyze(tmp_path)
189
+ assert any(d.kind == "mongodb" for d in result.databases)
190
+
191
+
192
+ # ---------- Auth / crypto ----------
193
+
194
+
195
+ def test_libsodium_pwhash_emits_argon2_hint(tmp_path: Path) -> None:
196
+ (tmp_path / "auth.c").write_text(
197
+ '#include <sodium.h>\n'
198
+ 'int hash(const char *pw, char *out) {\n'
199
+ ' return crypto_pwhash_str(out, pw, strlen(pw),\n'
200
+ ' crypto_pwhash_OPSLIMIT_INTERACTIVE,\n'
201
+ ' crypto_pwhash_MEMLIMIT_INTERACTIVE);\n'
202
+ '}\n',
203
+ encoding="utf-8",
204
+ )
205
+ result = CAnalyzer().analyze(tmp_path)
206
+ by_hint = {h.hint: h for h in result.auth_hints}
207
+ assert "argon2" in by_hint
208
+ assert by_hint["argon2"].confidence == 0.9
209
+
210
+
211
+ def test_argon2_reference_impl_emits_hint(tmp_path: Path) -> None:
212
+ (tmp_path / "auth.c").write_text(
213
+ '#include "argon2.h"\n'
214
+ 'int verify(const char *pw, const char *encoded) {\n'
215
+ ' return argon2id_hash_encoded(2, 1<<16, 1, pw, strlen(pw), salt, 16, 32, encoded, sizeof(encoded));\n'
216
+ '}\n',
217
+ encoding="utf-8",
218
+ )
219
+ result = CAnalyzer().analyze(tmp_path)
220
+ assert any(h.hint == "argon2" for h in result.auth_hints)
221
+
222
+
223
+ def test_openssl_tls_setup_emits_hint(tmp_path: Path) -> None:
224
+ (tmp_path / "tls.c").write_text(
225
+ '#include <openssl/ssl.h>\n'
226
+ 'SSL_CTX *create(void) {\n'
227
+ ' return SSL_CTX_new(TLS_server_method());\n'
228
+ '}\n',
229
+ encoding="utf-8",
230
+ )
231
+ result = CAnalyzer().analyze(tmp_path)
232
+ assert any(h.hint == "openssl_tls" for h in result.auth_hints)
233
+
234
+
235
+ # ---------- Secrets ----------
236
+
237
+
238
+ def test_getenv_secrets(tmp_path: Path) -> None:
239
+ (tmp_path / "config.c").write_text(
240
+ '#include <stdlib.h>\n'
241
+ 'int main(void) {\n'
242
+ ' const char *jwt = getenv("JWT_SECRET");\n'
243
+ ' const char *db = getenv("DATABASE_PASSWORD");\n'
244
+ ' const char *api = secure_getenv("STRIPE_API_KEY");\n'
245
+ ' return 0;\n'
246
+ '}\n',
247
+ encoding="utf-8",
248
+ )
249
+ result = CAnalyzer().analyze(tmp_path)
250
+ names = {s.name for s in result.secret_hints}
251
+ assert "JWT_SECRET" in names
252
+ assert "DATABASE_PASSWORD" in names
253
+ assert "STRIPE_API_KEY" in names
254
+
255
+ jwt = next(s for s in result.secret_hints if s.name == "JWT_SECRET")
256
+ assert jwt.line == 3
257
+
258
+
259
+ def test_getenv_with_non_secret_name_skipped(tmp_path: Path) -> None:
260
+ (tmp_path / "config.c").write_text(
261
+ '#include <stdlib.h>\n'
262
+ 'int main(void) {\n'
263
+ ' const char *home = getenv("HOME");\n'
264
+ ' const char *path = getenv("PATH");\n'
265
+ ' return 0;\n'
266
+ '}\n',
267
+ encoding="utf-8",
268
+ )
269
+ result = CAnalyzer().analyze(tmp_path)
270
+ assert result.secret_hints == []
271
+
272
+
273
+ # ---------- Frameworks + entrypoints ----------
274
+
275
+
276
+ def test_libmicrohttpd_framework_and_entrypoint(tmp_path: Path) -> None:
277
+ (tmp_path / "main.c").write_text(
278
+ '#include <microhttpd.h>\n'
279
+ '\n'
280
+ 'int main(void) {\n'
281
+ ' struct MHD_Daemon *d = MHD_start_daemon(\n'
282
+ ' MHD_USE_THREAD_PER_CONNECTION, 8888, NULL, NULL, &handler, NULL,\n'
283
+ ' MHD_OPTION_END);\n'
284
+ ' return d ? 0 : 1;\n'
285
+ '}\n',
286
+ encoding="utf-8",
287
+ )
288
+ result = CAnalyzer().analyze(tmp_path)
289
+ fw = {f.hint for f in result.framework_hints}
290
+ assert "libmicrohttpd" in fw
291
+ ep = {e.hint for e in result.entrypoint_hints}
292
+ assert "mhd_start_daemon" in ep
293
+
294
+
295
+ def test_civetweb_framework_and_entrypoint(tmp_path: Path) -> None:
296
+ (tmp_path / "main.c").write_text(
297
+ '#include <civetweb.h>\n'
298
+ 'int main(void) {\n'
299
+ ' struct mg_context *ctx = mg_start(NULL, NULL, NULL);\n'
300
+ ' return ctx ? 0 : 1;\n'
301
+ '}\n',
302
+ encoding="utf-8",
303
+ )
304
+ result = CAnalyzer().analyze(tmp_path)
305
+ fw = {f.hint for f in result.framework_hints}
306
+ assert "civetweb" in fw
307
+ ep = {e.hint for e in result.entrypoint_hints}
308
+ assert "civetweb_start" in ep
309
+
310
+
311
+ def test_mongoose_framework_and_listen(tmp_path: Path) -> None:
312
+ (tmp_path / "main.c").write_text(
313
+ '#include <mongoose.h>\n'
314
+ 'int main(void) {\n'
315
+ ' struct mg_mgr mgr;\n'
316
+ ' mg_mgr_init(&mgr);\n'
317
+ ' mg_http_listen(&mgr, "http://0.0.0.0:8080", handler, NULL);\n'
318
+ ' return 0;\n'
319
+ '}\n',
320
+ encoding="utf-8",
321
+ )
322
+ result = CAnalyzer().analyze(tmp_path)
323
+ fw = {f.hint for f in result.framework_hints}
324
+ assert "mongoose" in fw
325
+ ep = {e.hint for e in result.entrypoint_hints}
326
+ assert "mongoose_http_listen" in ep
327
+
328
+
329
+ # ---------- CMake → service hint ----------
330
+
331
+
332
+ def test_cmake_project_name_picked_up(tmp_path: Path) -> None:
333
+ (tmp_path / "CMakeLists.txt").write_text(
334
+ 'cmake_minimum_required(VERSION 3.10)\n'
335
+ 'project(billing-api LANGUAGES C)\n'
336
+ 'add_executable(billing src/main.c)\n',
337
+ encoding="utf-8",
338
+ )
339
+ (tmp_path / "src").mkdir()
340
+ (tmp_path / "src" / "main.c").write_text("int main(void) { return 0; }\n", encoding="utf-8")
341
+ result = CAnalyzer().analyze(tmp_path)
342
+ assert any(h.hint == "project:billing-api" for h in result.service_hints)
343
+
344
+
345
+ # ---------- End-to-end ----------
346
+
347
+
348
+ def test_full_civetweb_service_signal_set(tmp_path: Path) -> None:
349
+ (tmp_path / "CMakeLists.txt").write_text(
350
+ 'project(demo-svc LANGUAGES C)\nadd_executable(demo src/main.c)\n',
351
+ encoding="utf-8",
352
+ )
353
+ src = tmp_path / "src" / "main.c"
354
+ src.parent.mkdir()
355
+ src.write_text(
356
+ '#include <civetweb.h>\n'
357
+ '#include <curl/curl.h>\n'
358
+ '#include <sqlite3.h>\n'
359
+ '#include <openssl/ssl.h>\n'
360
+ '#include <stdlib.h>\n'
361
+ '\n'
362
+ 'int main(void) {\n'
363
+ ' const char *jwt = getenv("JWT_SECRET");\n'
364
+ ' sqlite3 *db; sqlite3_open("data.db", &db);\n'
365
+ ' SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());\n'
366
+ ' CURL *curl = curl_easy_init();\n'
367
+ ' curl_easy_setopt(curl, CURLOPT_URL, "https://api.example.com/data");\n'
368
+ '\n'
369
+ ' struct mg_context *srv = mg_start(NULL, NULL, NULL);\n'
370
+ ' mg_set_request_handler(srv, "/login", login_handler, NULL);\n'
371
+ ' mg_set_request_handler(srv, "/admin", admin_handler, NULL);\n'
372
+ ' return 0;\n'
373
+ '}\n',
374
+ encoding="utf-8",
375
+ )
376
+
377
+ result = CAnalyzer().analyze(tmp_path)
378
+
379
+ paths = {r.path for r in result.routes}
380
+ assert "/login" in paths
381
+ assert "/admin" in paths
382
+
383
+ assert any(d.kind == "sqlite" for d in result.databases)
384
+ assert any(h.hint == "openssl_tls" for h in result.auth_hints)
385
+ assert any(s.name == "JWT_SECRET" for s in result.secret_hints)
386
+ assert any(e.target == "https://api.example.com/data" for e in result.external_calls)
387
+ assert any(f.hint == "civetweb" for f in result.framework_hints)
388
+ assert any(e.hint == "civetweb_start" for e in result.entrypoint_hints)
389
+ assert any(h.hint == "project:demo-svc" for h in result.service_hints)