From 4de26b9b84fd1ec839b1cb98f3f5e251d9c480ec Mon Sep 17 00:00:00 2001 From: lotherk Date: Sat, 21 Nov 2026 11:46:10 +0000 Subject: [PATCH] apex-twin 1.4.0: JWT audit, hash identification, ATT&CK mapping, process snapshot Red, offline (tools_red.c): - jwt_audit decodes header and payload, reports alg/typ/kid and the claims iss/aud/sub/exp/iat/nbf, and flags alg=none (critical), a missing exp, an expired token, a path-like kid, a missing audience/issuer and a validity over a year. With secret= it verifies HS256 over header.payload with HMAC-SHA256 and reports valid or invalid; alg=none is never reported as verified. - hash_id identifies MD5/NTLM, SHA-1/256/512, bcrypt, Argon2, crypt(3) formats and JWTs by shape. It cracks nothing. Blue, offline (tools_blue.c): - mitre_map maps recorded findings to ATT&CK techniques through keywords in title, tool, tags and CWE, and lists the finding ids per technique. - process_snapshot reads /proc: name, exe, fd count, and flags executables under /tmp, /dev/shm or /var/tmp, deleted executables, reverse-shell command lines and more than 256 open files. sha256.c gains a raw digest and HMAC-SHA256 for the JWT signature check. Fixed the tool table capacity: g_tools[64] silently dropped tool number 65 (hash_id); it is 96 now. Tests: HS256 valid and invalid tokens, alg=none and expired findings, a path-like kid, malformed token, MD5/bcrypt/JWT identification, ATT&CK mapping against real finding ids, and a spawned process with nc -e in its command line caught by the snapshot. 490 checks, ASan suite green, analyze clean (a false-positive uninitialised-buffer report was removed by decoding into a calloc buffer), release-check green including distcheck 1.4.0. --- CHANGELOG.md | 23 ++- README.md | 19 ++- SECURITY.md | 5 +- docs/apex-twin.1 | 10 +- src/apex-twin.c | 24 +-- src/apex.h | 7 +- src/sha256.c | 59 +++++++- src/tools_blue.c | 302 +++++++++++++++++++++++++++++++++++++ src/tools_red.c | 357 ++++++++++++++++++++++++++++++++++++++++++++ tests/gate_audit.py | 4 +- tests/run.py | 100 ++++++++++++- 11 files changed, 875 insertions(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 40dd231..c086455 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,28 @@ fields, and state from an older version is read by a newer one. There are no git tags. The hash next to a version is the commit that introduced it; the current entry is the commit that adds this section. -## 1.3.0 — 2026-11-21 — this change +## 1.4.0 — 2026-11-21 — this change + +- **Red, offline:** `jwt_audit` decodes header and payload, reports alg/typ/kid + and iss/aud/sub/exp/iat/nbf, and flags alg=none (critical), a missing exp, an + expired token, a path-like kid, a missing audience/issuer and a validity over + a year. With `secret=` it verifies HS256 with HMAC-SHA256 (new raw digest and + HMAC helpers in `sha256.c`) and reports valid/invalid. `hash_id` recognises + MD5/NTLM, SHA-1/256/512, bcrypt, Argon2, crypt(3) formats and JWTs; it does + not crack anything. +- **Blue, offline:** `mitre_map` maps findings to ATT&CK techniques (T1190, + T1059.007, T1078, T1213, T1557, T1185, T1046, T1590) and lists the finding id + per technique. `process_snapshot` reads `/proc`: name, exe, fd count, and + flags executables under /tmp, /dev/shm or /var/tmp, deleted executables, + reverse-shell command lines and >256 open files. +- Fixed the tool table capacity: `g_tools[64]` silently dropped tool number 65; + it is now 96. +- Tests: HS256 valid/invalid, alg=none and expired tokens, path-like kid, + hash shapes, ATT&CK mapping with real finding ids, and a spawned process with + `nc -e` in its command line caught by the snapshot. 490 checks. Coverage + 79.9%. + +## 1.3.0 — 2026-11-21 — 8e6f075 - **Red:** `ssrf_probe` injects one parameter with a URL that points at a loopback listener this process opens (or at a `callback_base` collector) and diff --git a/README.md b/README.md index 81c1517..21ca590 100644 --- a/README.md +++ b/README.md @@ -5,11 +5,11 @@ no Python in the serving path. It gives an agent real reconnaissance and real we testing behind a scope gate that refuses everything until a rules-of-engagement file says otherwise. -**61 tools · 476 end-to-end checks · 340 fuzz cases · 79.4% line coverage · ~313 KiB** +**65 tools · 490 end-to-end checks · 340 fuzz cases · 79.9% line coverage · ~325 KiB** ``` $ ./apex-twin --check -{"version":"1.3.0","tools":61,...,"scope":{"loaded":true,...}} +{"version":"1.4.0","tools":65,...,"scope":{"loaded":true,...}} ``` APEX TWIN was inspired by [ARTEX](https://github.com/Autumn-27/artex) (scope @@ -149,7 +149,7 @@ closes a request whose head or body does not arrive within --- -## Tools (61) +## Tools (65) ### Scope and bookkeeping @@ -252,6 +252,8 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `vhost_discovery` | Host-header fuzzing against one in-scope IP; reports names whose status, byte count or title differs from the baseline, with evidence | | `http_brute` | Built-in, comma or file wordlist for hidden paths; 200/201/204/3xx/401/403 are hits, 100 ms apart, evidence for the first five 200s | | `ssrf_probe` | Injects a URL parameter pointing at its own loopback listener (or your `callback_base`) and confirms a real fetch; never targets metadata endpoints | +| `jwt_audit` | Offline JWT audit: alg/typ/kid, iss/aud/sub/exp/iat/nbf, alg=none, expired, missing exp, path-like kid; HS256 signature verified with `secret=` | +| `hash_id` | Identify a hash shape: MD5/NTLM, SHA-1/256/512, bcrypt, Argon2, crypt(3) formats, JWT | ### Blue team @@ -263,6 +265,8 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `web_log_audit` | nginx/apache access log: status split, top IPs, scanner UAs, SQLi/traversal/XSS patterns (URL-decoded), 4xx/5xx bursts | | `detect_rules` | Sigma, Suricata and YARA skeletons per finding under `$APEX_HOME/detections/`; templates that need tuning | | `integrity_baseline` | SHA-256 manifest of a tree (`create`) and a changed/missing/added report (`verify`), no external tools | +| `mitre_map` | Map findings to ATT&CK techniques by title/tool/tags/CWE, with finding ids per technique | +| `process_snapshot` | Read `/proc`: exe/fd count per process, flags /tmp or deleted executables, reverse-shell command lines, >256 fds | ### ESP32 @@ -456,7 +460,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 476 end-to-end checks +make test # version check + gate audit + 490 end-to-end checks make version-check # the five places that carry a version must agree make gate-audit # static: every target-taking tool calls the gate make asan # apex-twin-asan with ASan + UBSan @@ -561,7 +565,7 @@ src/tools_traffic.c traffic_list / traffic_read src/tools_red.c vuln_check, subdomain_enum, cred_test src/tools_blue.c hardening_audit, log_audit, ioc_scan src/tools_esp.c esp_info, esp_monitor, esp_read_flash, esp_flash -src/sha256.c SHA-256 for integrity_baseline +src/sha256.c SHA-256/HMAC for integrity_baseline and jwt_audit src/tools_guard.c guard_check src/apex-twin.c MCP stdio + HTTP face, --check, --version vendor/libmcp/ header-only MCP transport (JSON-RPC, tools, HTTP body) @@ -590,7 +594,7 @@ examples/ scope.json ## Status -1.3.0. Built and run: 61 tools, 476 checks, 340 fuzz cases and 79.4% line +1.4.0. Built and run: 65 tools, 490 checks, 340 fuzz cases and 79.9% line coverage. The loop closes: a probe captures the exchange as a pair, a finding points at it, `finding_update` gives it a state, an asset records the host it came from, `cors_check`/`cookie_audit`/`http_options` turn a web answer into a @@ -612,7 +616,8 @@ keeps the gaps visible. 1.1 added the red, blue and ESP32 tool groups; 1.2 added vhost discovery, wordlist path brute-forcing and access-log analysis; 1.3 added SSRF verification, detection-rule export, integrity baselines and firmware writing -(confirm-gated), again without changing an existing tool or file format. +(confirm-gated); 1.4 added offline JWT/hash analysis, ATT&CK mapping and a +/proc snapshot, again without changing an existing tool or file format. Not yet wired into a fleet router, and there is no TLS interception. diff --git a/SECURITY.md b/SECURITY.md index c91617f..9724022 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -9,7 +9,7 @@ problem. The supported line is the one printed by `apex-twin --version` for the tree you built; this document ships with that same tree. At the time of writing the line -is **1.3.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.4.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current line. The 1.0 line promises that the on-disk JSON formats for findings, assets and traffic only gain fields, so state stays readable; older builds are still rebuilt rather than patched in place. @@ -66,6 +66,9 @@ only narrow what the proxy does (the scope gate still runs first). - **Firmware writing needs an explicit confirmation.** `esp_flash` refuses without `confirm=true`, validates an absolute image path and audits the attempt; it exists to provision the operator's own board. +- **Offline analysis stays offline.** `jwt_audit` and `hash_id` parse a value + the operator supplies; the JWT signature check is local HMAC-SHA256 and no + hash is cracked. `process_snapshot` only reads `/proc`. - **Local reads.** `hardening_audit` and `ioc_scan` read files the operator can already read; `log_audit` only accepts paths under `/var/log/` or the state directory. None of them change anything. diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index a9a4da3..b17cdd8 100644 --- a/docs/apex-twin.1 +++ b/docs/apex-twin.1 @@ -1,5 +1,5 @@ .\" apex-twin.1 - manual page for APEX TWIN -.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.3.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.4.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS @@ -36,10 +36,10 @@ and the radio is the ESP32 Marauder serial CLI. It is not an exploit framework: there is no shell, no exploit payload, no post\-exploitation, no C2 and no persistence. Besides reconnaissance and web testing it carries offensive verification (vuln_check, subdomain_enum, -cred_test, vhost_discovery, http_brute, ssrf_probe), defensive audits -(hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, -integrity_baseline) and ESP32 board tools (esp_info, esp_monitor, -esp_read_flash, esp_flash). +cred_test, vhost_discovery, http_brute, ssrf_probe, jwt_audit, hash_id), +defensive audits (hardening_audit, log_audit, ioc_scan, web_log_audit, +detect_rules, integrity_baseline, mitre_map, process_snapshot) and ESP32 board +tools (esp_info, esp_monitor, esp_read_flash, esp_flash). .SH MODES .TP .B apex-twin diff --git a/src/apex-twin.c b/src/apex-twin.c index 4ed2518..2161c8b 100644 --- a/src/apex-twin.c +++ b/src/apex-twin.c @@ -35,7 +35,7 @@ #define MAX_BODY (8u << 20) static mcp_server g_srv; -static mcp_tool g_tools[64]; +static mcp_tool g_tools[96]; static volatile sig_atomic_t g_http_stop; static volatile sig_atomic_t g_http_child_exit; static int g_http_children; @@ -102,27 +102,27 @@ static void build_tools(void) size_t n = 0; size_t i; - for (i = 0; i < TOOLS_RECON_N && n < 64; i++) + for (i = 0; i < TOOLS_RECON_N && n < 96; i++) g_tools[n++] = TOOLS_RECON[i]; - for (i = 0; i < TOOLS_WEB_N && n < 64; i++) + for (i = 0; i < TOOLS_WEB_N && n < 96; i++) g_tools[n++] = TOOLS_WEB[i]; - for (i = 0; i < TOOLS_RADIO_N && n < 64; i++) + for (i = 0; i < TOOLS_RADIO_N && n < 96; i++) g_tools[n++] = TOOLS_RADIO[i]; - for (i = 0; i < TOOLS_KB_N && n < 64; i++) + for (i = 0; i < TOOLS_KB_N && n < 96; i++) g_tools[n++] = TOOLS_KB[i]; - for (i = 0; i < TOOLS_REPORT_N && n < 64; i++) + for (i = 0; i < TOOLS_REPORT_N && n < 96; i++) g_tools[n++] = TOOLS_REPORT[i]; - for (i = 0; i < TOOLS_GUARD_N && n < 64; i++) + for (i = 0; i < TOOLS_GUARD_N && n < 96; i++) g_tools[n++] = TOOLS_GUARD[i]; - for (i = 0; i < TOOLS_ASSET_N && n < 64; i++) + for (i = 0; i < TOOLS_ASSET_N && n < 96; i++) g_tools[n++] = TOOLS_ASSET[i]; - for (i = 0; i < TOOLS_TRAFFIC_N && n < 64; i++) + for (i = 0; i < TOOLS_TRAFFIC_N && n < 96; i++) g_tools[n++] = TOOLS_TRAFFIC[i]; - for (i = 0; i < TOOLS_RED_N && n < 64; i++) + for (i = 0; i < TOOLS_RED_N && n < 96; i++) g_tools[n++] = TOOLS_RED[i]; - for (i = 0; i < TOOLS_BLUE_N && n < 64; i++) + for (i = 0; i < TOOLS_BLUE_N && n < 96; i++) g_tools[n++] = TOOLS_BLUE[i]; - for (i = 0; i < TOOLS_ESP_N && n < 64; i++) + for (i = 0; i < TOOLS_ESP_N && n < 96; i++) g_tools[n++] = TOOLS_ESP[i]; g_srv.name = "apex-twin"; diff --git a/src/apex.h b/src/apex.h index 9a73cba..31beda3 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.3.0" +#define APEX_VERSION "1.4.0" #define APEX_MAX_OUT (1u << 20) #define APEX_PATH_MAX 512 #define APEX_PATH_FULL 1024 @@ -115,8 +115,11 @@ int apex_have(const char *prog); char *apex_join_argv(char *const argv[]); char *apex_strdup(const char *s); -/* SHA-256 in lowercase hex (64 characters plus NUL). */ +/* SHA-256 in lowercase hex (64 characters plus NUL), raw, and HMAC-SHA256. */ void apex_sha256(const void *data, size_t len, char hex[65]); +void apex_sha256_raw(const void *data, size_t len, unsigned char out[32]); +void apex_hmac_sha256(const void *key, size_t klen, const void *msg, + size_t mlen, unsigned char out[32]); /* ----------------------------------------------------------------- store */ diff --git a/src/sha256.c b/src/sha256.c index 5347bc2..fc612fc 100644 --- a/src/sha256.c +++ b/src/sha256.c @@ -7,6 +7,7 @@ */ #include #include +#include #include #include "apex.h" @@ -71,7 +72,7 @@ static void block(uint32_t h[8], const unsigned char *p) h[4] += e; h[5] += f; h[6] += g; h[7] += hh; } -void apex_sha256(const void *data, size_t len, char hex[65]) +static void sha256_raw(const void *data, size_t len, unsigned char out[32]) { uint32_t h[8] = { 0x6a09e667u, 0xbb67ae85u, 0x3c6ef372u, 0xa54ff53au, 0x510e527fu, 0x9b05688cu, 0x1f83d9abu, 0x5be0cd19u }; @@ -96,7 +97,59 @@ void apex_sha256(const void *data, size_t len, char hex[65]) block(h, tail); if (tail_len == 128) block(h, tail + 64); - for (i = 0; i < 8; i++) - snprintf(hex + i * 8, 9, "%08x", h[i]); + for (i = 0; i < 8; i++) { + out[i * 4] = (unsigned char)(h[i] >> 24); + out[i * 4 + 1] = (unsigned char)(h[i] >> 16); + out[i * 4 + 2] = (unsigned char)(h[i] >> 8); + out[i * 4 + 3] = (unsigned char)h[i]; + } +} + +void apex_sha256_raw(const void *data, size_t len, unsigned char out[32]) +{ + sha256_raw(data, len, out); +} + +void apex_sha256(const void *data, size_t len, char hex[65]) +{ + unsigned char raw[32]; + int i; + + sha256_raw(data, len, raw); + for (i = 0; i < 32; i++) + snprintf(hex + i * 2, 3, "%02x", raw[i]); hex[64] = '\0'; } + +void apex_hmac_sha256(const void *key, size_t klen, const void *msg, + size_t mlen, unsigned char out[32]) +{ + unsigned char k[64]; + unsigned char ipad[64]; + unsigned char opad[64]; + unsigned char inner[32]; + unsigned char *buf; + size_t i; + + memset(k, 0, sizeof(k)); + if (klen > sizeof(k)) + sha256_raw(key, klen, k); + else + memcpy(k, key, klen); + for (i = 0; i < sizeof(k); i++) { + ipad[i] = (unsigned char)(k[i] ^ 0x36); + opad[i] = (unsigned char)(k[i] ^ 0x5c); + } + buf = malloc(sizeof(ipad) + mlen); + if (buf == NULL) { + memset(out, 0, 32); + return; + } + memcpy(buf, ipad, sizeof(ipad)); + memcpy(buf + sizeof(ipad), msg, mlen); + sha256_raw(buf, sizeof(ipad) + mlen, inner); + memcpy(buf, opad, sizeof(opad)); + memcpy(buf + sizeof(opad), inner, sizeof(inner)); + sha256_raw(buf, sizeof(opad) + sizeof(inner), out); + free(buf); +} diff --git a/src/tools_blue.c b/src/tools_blue.c index e01f9f8..6fea61f 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -1449,6 +1449,291 @@ static void t_integrity_baseline(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&detail); } +/* ---------------------------------------------------------------- mitre_map */ + +typedef struct { + const char *needle; + const char *id; + const char *name; +} mitre_rule; + +static const mitre_rule MITRE[] = { + { "sql", "T1190", "Exploit Public-Facing Application" }, + { "xss", "T1059.007", "JavaScript" }, + { "cross-site", "T1059.007", "JavaScript" }, + { "default credential", "T1078", "Valid Accounts" }, + { "password", "T1078", "Valid Accounts" }, + { "exposed", "T1213", "Data from Information Repositories" }, + { ".git", "T1213", "Data from Information Repositories" }, + { "directory listing", "T1213", "Data from Information Repositories" }, + { "backup", "T1213", "Data from Information Repositories" }, + { "ssrf", "T1190", "Exploit Public-Facing Application" }, + { "hsts", "T1557", "Adversary-in-the-Middle" }, + { "cors", "T1185", "Browser Session Hijacking" }, + { "port", "T1046", "Network Service Discovery" }, + { "subdomain", "T1590", "Gather Victim Network Information" }, + { NULL, NULL, NULL } +}; + +typedef struct { + int rule; + int count; + char ids[512]; +} mitre_hit; + +static void t_mitre_map(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + apex_finding *rows; + int n; + int i; + int r; + int mapped = 0; + mitre_hit hits[32]; + int nhits = 0; + mcp_buf b; + + (void)user; + rows = calloc(1024, sizeof(*rows)); + if (rows == NULL) { + mcp_reply_error(c, "out of memory"); + return; + } + n = apex_finding_scan(rows, 1024); + memset(hits, 0, sizeof(hits)); + for (i = 0; i < n; i++) { + const apex_finding *f = &rows[i]; + char hay[1400]; + int matched = 0; + + if (target != NULL && *target != '\0' && + strcmp(f->target, target) != 0) + continue; + snprintf(hay, sizeof(hay), "%s %s %s %s %s", f->title, f->tool, + f->tags, f->cwe, f->severity); + { + size_t k; + + for (k = 0; hay[k] != '\0'; k++) + hay[k] = (char)tolower((unsigned char)hay[k]); + } + for (r = 0; MITRE[r].needle != NULL; r++) { + int h; + int known = -1; + + if (strstr(hay, MITRE[r].needle) == NULL) + continue; + matched = 1; + for (h = 0; h < nhits; h++) + if (hits[h].rule == r) + known = h; + if (known < 0 && nhits < 32) { + known = nhits++; + hits[known].rule = r; + hits[known].count = 0; + hits[known].ids[0] = '\0'; + } + if (known >= 0) { + hits[known].count++; + if (strlen(hits[known].ids) + strlen(f->id) + 2 < + sizeof(hits[known].ids)) { + if (hits[known].ids[0] != '\0') + strcat(hits[known].ids, ","); + strcat(hits[known].ids, f->id); + } + } + } + if (matched) + mapped++; + } + mcp_buf_init(&b); + mcp_buf_printf(&b, "{\"findings\":%d,\"mapped\":%d,\"unmapped\":%d," + "\"techniques\":[", n, mapped, n - mapped); + for (i = 0; i < nhits; i++) { + const mitre_rule *mr = &MITRE[hits[i].rule]; + char ids[512]; + char *save = NULL; + char *tok; + int first = 1; + + snprintf(ids, sizeof(ids), "%s", hits[i].ids); + if (i > 0) + mcp_buf_puts(&b, ","); + mcp_buf_puts(&b, "{\"id\":"); + apex_json_str(&b, mr->id); + mcp_buf_puts(&b, ",\"name\":"); + apex_json_str(&b, mr->name); + mcp_buf_printf(&b, ",\"count\":%d,\"findings\":[", hits[i].count); + tok = strtok_r(ids, ",", &save); + while (tok != NULL) { + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + apex_json_str(&b, tok); + tok = strtok_r(NULL, ",", &save); + } + mcp_buf_puts(&b, "]}"); + } + mcp_buf_puts(&b, "]}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + free(rows); +} + +/* ----------------------------------------------------------- process_snapshot */ + +static int proc_fd_count(int pid) +{ + char path[64]; + DIR *d; + struct dirent *ent; + int n = 0; + + snprintf(path, sizeof(path), "/proc/%d/fd", pid); + d = opendir(path); + if (d == NULL) + return 0; + while ((ent = readdir(d)) != NULL) + if (ent->d_name[0] != '.') + n++; + closedir(d); + return n; +} + +static void proc_cmdline(int pid, char *out, size_t n) +{ + char path[64]; + FILE *f; + size_t got; + size_t i; + + out[0] = '\0'; + snprintf(path, sizeof(path), "/proc/%d/cmdline", pid); + f = fopen(path, "rb"); + if (f == NULL) + return; + got = fread(out, 1, n - 1, f); + fclose(f); + out[got] = '\0'; + for (i = 0; i < got; i++) + if (out[i] == '\0') + out[i] = ' '; +} + +static void proc_exe(int pid, char *out, size_t n) +{ + char path[64]; + ssize_t r; + + out[0] = '\0'; + snprintf(path, sizeof(path), "/proc/%d/exe", pid); + r = readlink(path, out, n - 1); + if (r > 0) + out[r] = '\0'; + else + out[0] = '\0'; +} + +static void proc_comm(int pid, char *out, size_t n) +{ + char path[64]; + FILE *f; + + out[0] = '\0'; + snprintf(path, sizeof(path), "/proc/%d/comm", pid); + f = fopen(path, "rb"); + if (f == NULL) + return; + if (fgets(out, (int)n, f) == NULL) + out[0] = '\0'; + fclose(f); + trim_eol(out); +} + +static int proc_suspicious(const char *exe, const char *cmd) +{ + static const char *patterns[] = { + "nc -e", "ncat -e", "/dev/tcp/", "base64 -d", "socat", + "bash -i", "sh -i", NULL + }; + int i; + + if (exe[0] != '\0' && + (strncmp(exe, "/tmp/", 5) == 0 || + strncmp(exe, "/dev/shm/", 9) == 0 || + strncmp(exe, "/var/tmp/", 9) == 0)) + return 1; + if (strstr(exe, "(deleted)") != NULL) + return 1; + for (i = 0; patterns[i] != NULL; i++) + if (strstr(cmd, patterns[i]) != NULL) + return 1; + return 0; +} + +static void t_process_snapshot(mcp_conn *c, const mcp_json *args, void *user) +{ + DIR *d; + struct dirent *ent; + int processes = 0; + int suspicious = 0; + int emitted = 0; + mcp_buf b; + + (void)args; + (void)user; + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"findings\":["); + d = opendir("/proc"); + if (d == NULL) { + mcp_buf_free(&b); + mcp_reply_error(c, "cannot read /proc"); + return; + } + while ((ent = readdir(d)) != NULL && processes < 4000) { + int pid; + char comm[64]; + char exe[512]; + char cmd[1024]; + int fds; + + if (ent->d_name[0] < '0' || ent->d_name[0] > '9') + continue; + pid = atoi(ent->d_name); + if (pid <= 0) + continue; + processes++; + proc_comm(pid, comm, sizeof(comm)); + proc_exe(pid, exe, sizeof(exe)); + proc_cmdline(pid, cmd, sizeof(cmd)); + fds = proc_fd_count(pid); + if (proc_suspicious(exe, cmd) || fds > 256) { + suspicious++; + if (emitted < 100) { + const char *why = proc_suspicious(exe, cmd) + ? "suspicious executable or command" + : "more than 256 open files"; + + if (emitted > 0) + mcp_buf_puts(&b, ","); + emitted++; + mcp_buf_printf(&b, "{\"pid\":%d,\"name\":", pid); + apex_json_str(&b, comm); + mcp_buf_puts(&b, ",\"exe\":"); + apex_json_str(&b, exe); + mcp_buf_printf(&b, ",\"fds\":%d,\"reason\":", fds); + apex_json_str(&b, why); + mcp_buf_puts(&b, "}"); + } + } + } + closedir(d); + mcp_buf_printf(&b, "],\"processes\":%d,\"findings_count\":%d}", + processes, suspicious); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + const mcp_tool TOOLS_BLUE[] = { { "hardening_audit", "Read-only posture audit of the local host: sshd_config (root login, " @@ -1521,6 +1806,23 @@ const mcp_tool TOOLS_BLUE[] = { "\"limit\":{\"type\":\"integer\",\"description\":\"max files, " "default 1000\"}}}", t_integrity_baseline }, + { "mitre_map", + "Map recorded findings to MITRE ATT&CK techniques by keywords in the " + "title, tool, tags and CWE (SQLi/SSRF -> T1190, XSS -> T1059.007, default " + "credentials -> T1078, exposed repositories/backups -> T1213, missing " + "HSTS -> T1557, CORS -> T1185, port scanning -> T1046). Reports the " + "mapped count, unmapped count and the finding ids per technique.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\",\"description\":\"only findings for " + "this target\"}}}", + t_mitre_map }, + { "process_snapshot", + "Read-only snapshot of /proc: for every process report name, exe and open " + "fd count, and flag executables under /tmp, /dev/shm or /var/tmp, deleted " + "executables, reverse-shell style command lines (nc -e, /dev/tcp, " + "base64 -d, socat, bash -i) and more than 256 open files.", + "{\"type\":\"object\",\"properties\":{}}", + t_process_snapshot }, }; const size_t TOOLS_BLUE_N = sizeof(TOOLS_BLUE) / sizeof(TOOLS_BLUE[0]); diff --git a/src/tools_red.c b/src/tools_red.c index ee0ed70..11a6254 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -1188,6 +1188,343 @@ static void t_ssrf_probe(mcp_conn *c, const mcp_json *args, void *user) close(ls); } +/* ---------------------------------------------------------------- jwt_audit */ + +static int b64url_val(int c) +{ + if (c >= 'A' && c <= 'Z') + return c - 'A'; + if (c >= 'a' && c <= 'z') + return c - 'a' + 26; + if (c >= '0' && c <= '9') + return c - '0' + 52; + if (c == '-') + return 62; + if (c == '_') + return 63; + return -1; +} + +static int b64url_decode(const char *s, unsigned char *out, size_t max) +{ + unsigned long acc = 0; + int bits = 0; + size_t w = 0; + + for (; *s != '\0'; s++) { + int v; + + if (*s == '=') + break; + v = b64url_val((unsigned char)*s); + if (v < 0) + return -1; + acc = (acc << 6) | (unsigned long)v; + bits += 6; + if (bits >= 8) { + bits -= 8; + if (w >= max) + return -1; + out[w++] = (unsigned char)((acc >> bits) & 0xff); + } + } + return (int)w; +} + +static char *b64url_json(const char *seg) +{ + char *text = calloc(1, 65537); + int n; + + if (text == NULL) + return NULL; + n = b64url_decode(seg, (unsigned char *)text, 65536); + if (n < 0) { + free(text); + return NULL; + } + text[n] = '\0'; + return text; +} + +static int jstr(const char *json, const char *key, char *out, size_t n) +{ + char pattern[64]; + const char *p; + size_t i = 0; + + snprintf(pattern, sizeof(pattern), "\"%s\":\"", key); + p = strstr(json, pattern); + if (p == NULL) { + out[0] = '\0'; + return 0; + } + p += strlen(pattern); + while (*p != '\0' && *p != '"' && i + 1 < n) + out[i++] = *p++; + out[i] = '\0'; + return 1; +} + +static long jnum(const char *json, const char *key, int *found) +{ + char pattern[64]; + const char *p; + + if (found != NULL) + *found = 0; + snprintf(pattern, sizeof(pattern), "\"%s\":", key); + p = strstr(json, pattern); + if (p == NULL) + return 0; + p += strlen(pattern); + while (*p == ' ') + p++; + if (found != NULL) + *found = 1; + return atol(p); +} + +static void jwt_finding(mcp_buf *b, int *first, const char *id, + const char *severity, const char *detail) +{ + if (!*first) + mcp_buf_puts(b, ","); + *first = 0; + mcp_buf_puts(b, "{\"id\":"); + apex_json_str(b, id); + mcp_buf_puts(b, ",\"severity\":"); + apex_json_str(b, severity); + mcp_buf_puts(b, ",\"detail\":"); + apex_json_str(b, detail); + mcp_buf_puts(b, "}"); +} + +static void t_jwt_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *token = mcp_arg_string(args, "token"); + const char *secret = mcp_arg_string(args, "secret"); + char *copy; + char *save = NULL; + char *h; + char *p; + char *sig; + char alg[32]; + char typ[32]; + char kid[128]; + char iss[128]; + char aud[128]; + char sub[128]; + char *hjson; + char *pjson; + mcp_buf b; + int first = 1; + int found; + long exp; + long nbf; + long iat; + time_t now = time(NULL); + const char *signature = "not-checked"; + + (void)user; + if (token == NULL || *token == '\0') { + mcp_reply_error(c, "token is required"); + return; + } + if (strlen(token) > 60000) { + mcp_reply_error(c, "token too long"); + return; + } + copy = strdup(token); + if (copy == NULL) { + mcp_reply_error(c, "out of memory"); + return; + } + { + char *dot1 = strchr(copy, '.'); + char *dot2 = dot1 != NULL ? strchr(dot1 + 1, '.') : NULL; + + if (dot1 == NULL || dot2 == NULL) { + mcp_reply_error(c, "not a JWT: expected header.payload.signature"); + free(copy); + return; + } + *dot1 = '\0'; + *dot2 = '\0'; + h = copy; + p = dot1 + 1; + sig = dot2 + 1; /* may be empty for alg=none */ + } + (void)save; + hjson = b64url_json(h); + pjson = b64url_json(p); + if (hjson == NULL || pjson == NULL || + hjson[0] != '{' || pjson[0] != '{') { + mcp_reply_error(c, "cannot decode the JWT segments"); + free(hjson); + free(pjson); + free(copy); + return; + } + jstr(hjson, "alg", alg, sizeof(alg)); + jstr(hjson, "typ", typ, sizeof(typ)); + jstr(hjson, "kid", kid, sizeof(kid)); + jstr(pjson, "iss", iss, sizeof(iss)); + jstr(pjson, "aud", aud, sizeof(aud)); + jstr(pjson, "sub", sub, sizeof(sub)); + exp = jnum(pjson, "exp", &found); + if (!found) + exp = -1; + nbf = jnum(pjson, "nbf", NULL); + iat = jnum(pjson, "iat", NULL); + + if (secret != NULL && *secret != '\0' && strcmp(alg, "HS256") == 0) { + unsigned char mac[32]; + unsigned char given[512]; + char signing[80000]; + int glen; + int ok = 1; + int i; + + snprintf(signing, sizeof(signing), "%s.%s", h, p); + apex_hmac_sha256(secret, strlen(secret), signing, strlen(signing), + mac); + glen = b64url_decode(sig, given, sizeof(given)); + if (glen != 32) { + signature = "invalid"; + } else { + for (i = 0; i < 32; i++) + if (mac[i] != given[i]) + ok = 0; + signature = ok ? "valid" : "invalid"; + } + } + + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"header\":{\"alg\":"); + apex_json_str(&b, alg); + mcp_buf_puts(&b, ",\"typ\":"); + apex_json_str(&b, typ); + mcp_buf_puts(&b, ",\"kid\":"); + apex_json_str(&b, kid); + mcp_buf_puts(&b, "},\"claims\":{\"iss\":"); + apex_json_str(&b, iss); + mcp_buf_puts(&b, ",\"aud\":"); + apex_json_str(&b, aud); + mcp_buf_puts(&b, ",\"sub\":"); + apex_json_str(&b, sub); + if (found) + mcp_buf_printf(&b, ",\"exp\":%ld", exp); + else + mcp_buf_puts(&b, ",\"exp\":null"); + mcp_buf_printf(&b, ",\"iat\":%ld,\"nbf\":%ld},\"findings\":[", iat, + nbf); + if (alg[0] == '\0') + jwt_finding(&b, &first, "alg-missing", "high", + "header has no alg"); + else if (strcasecmp(alg, "none") == 0) + jwt_finding(&b, &first, "alg-none", "critical", + "alg=none: the token is unsigned"); + if (kid[0] != '\0' && (strstr(kid, "/") != NULL || + strstr(kid, "..") != NULL)) + jwt_finding(&b, &first, "kid-path", "high", + "kid contains a path separator"); + if (!found) + jwt_finding(&b, &first, "exp-missing", "medium", + "no exp claim: the token never expires"); + else if (exp < (long)now) + jwt_finding(&b, &first, "expired", "high", + "the token is expired"); + else if (exp > (long)now + 365L * 86400L) + jwt_finding(&b, &first, "long-lived", "low", + "the token lives longer than a year"); + if (aud[0] == '\0') + jwt_finding(&b, &first, "aud-missing", "low", + "no audience claim"); + if (iss[0] == '\0') + jwt_finding(&b, &first, "iss-missing", "low", + "no issuer claim"); + mcp_buf_printf(&b, "],\"signature\":\"%s\"}", signature); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + free(hjson); + free(pjson); + free(copy); +} + +/* ------------------------------------------------------------------ hash_id */ + +static int all_hex(const char *s, size_t n) +{ + size_t i; + + for (i = 0; i < n; i++) + if (!((s[i] >= '0' && s[i] <= '9') || + (s[i] >= 'a' && s[i] <= 'f') || + (s[i] >= 'A' && s[i] <= 'F'))) + return 0; + return 1; +} + +static void t_hash_id(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *value = mcp_arg_string(args, "value"); + size_t n; + mcp_buf b; + int first = 1; + + (void)user; + if (value == NULL || *value == '\0') { + mcp_reply_error(c, "value is required"); + return; + } + n = strlen(value); + mcp_buf_init(&b); + mcp_buf_printf(&b, "{\"length\":%lu,\"candidates\":[", + (unsigned long)n); +#define CAND(fmt, note) do { \ + if (!first) mcp_buf_puts(&b, ","); \ + first = 0; \ + mcp_buf_puts(&b, "{\"format\":"); \ + apex_json_str(&b, fmt); \ + mcp_buf_puts(&b, ",\"note\":"); \ + apex_json_str(&b, note); \ + mcp_buf_puts(&b, "}"); \ +} while (0) + if (n == 32 && all_hex(value, n)) { + CAND("md5", "32 hex digits; also looks like NTLM"); + CAND("ntlm", "same length as MD5"); + } else if (n == 40 && all_hex(value, n)) { + CAND("sha1", "40 hex digits"); + } else if (n == 64 && all_hex(value, n)) { + CAND("sha256", "64 hex digits"); + } else if (n == 128 && all_hex(value, n)) { + CAND("sha512", "128 hex digits"); + } else if (strncmp(value, "$2a$", 4) == 0 || + strncmp(value, "$2b$", 4) == 0 || + strncmp(value, "$2y$", 4) == 0) { + CAND("bcrypt", "bcrypt modular crypt format"); + } else if (strncmp(value, "$argon2id$", 10) == 0) { + CAND("argon2id", "Argon2id PHC string"); + } else if (strncmp(value, "$argon2i$", 9) == 0) { + CAND("argon2i", "Argon2i PHC string"); + } else if (strncmp(value, "$1$", 3) == 0) { + CAND("md5crypt", "md5crypt modular crypt format"); + } else if (strncmp(value, "$5$", 3) == 0) { + CAND("sha256crypt", "sha256crypt modular crypt format"); + } else if (strncmp(value, "$6$", 3) == 0) { + CAND("sha512crypt", "sha512crypt modular crypt format"); + } else if (strncmp(value, "eyJ", 3) == 0 && strchr(value, '.') != NULL) { + CAND("jwt", "looks like a JWT; use jwt_audit"); + } else { + CAND("unknown", "no known hash format; may be plaintext"); + } +#undef CAND + mcp_buf_puts(&b, "]}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + const mcp_tool TOOLS_RED[] = { { "vuln_check", "Non-destructive verification of exposed artifacts on one web target: " @@ -1301,6 +1638,26 @@ const mcp_tool TOOLS_RED[] = { "\"tls\":{\"type\":\"boolean\"}}," "\"required\":[\"target\",\"param\"]}", t_ssrf_probe }, + { "jwt_audit", + "Audit a JWT offline: decode header and payload, report alg/typ/kid and " + "the claims iss/aud/sub/exp/iat/nbf, and flag alg=none, a missing exp, an " + "expired token, a path-like kid, a missing audience/issuer and a validity " + "longer than a year. With secret= it verifies an HS256 signature " + "(HMAC-SHA256) and says valid or invalid; nothing is sent anywhere.", + "{\"type\":\"object\",\"properties\":{" + "\"token\":{\"type\":\"string\"}," + "\"secret\":{\"type\":\"string\",\"description\":\"optional HS256 " + "secret for signature verification\"}}," + "\"required\":[\"token\"]}", + t_jwt_audit }, + { "hash_id", + "Identify a hash string by shape: MD5/NTLM, SHA-1, SHA-256, SHA-512, " + "bcrypt, Argon2id/Argon2i, md5crypt/sha256crypt/sha512crypt, or a JWT. " + "Reports candidates and a note; it does not crack anything.", + "{\"type\":\"object\",\"properties\":{" + "\"value\":{\"type\":\"string\"}}," + "\"required\":[\"value\"]}", + t_hash_id }, }; const size_t TOOLS_RED_N = sizeof(TOOLS_RED) / sizeof(TOOLS_RED[0]); diff --git a/tests/gate_audit.py b/tests/gate_audit.py index def508b..e29be3e 100755 --- a/tests/gate_audit.py +++ b/tests/gate_audit.py @@ -21,12 +21,12 @@ import re import sys HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -EXPECTED_TOOLS = 61 +EXPECTED_TOOLS = 65 GATE = ("gated(", "gated_cmd(", "apex_scope_check(") NET = ("http_once(", "tcp_connect_host(", "tcp_probe(", "apex_run(") # Tools whose "target" argument filters local records; they never touch it. RECORD_FILTERS = {"asset_list", "finding_list", "report_markdown", - "traffic_list", "detect_rules"} + "traffic_list", "detect_rules", "mitre_map"} # Tools that spawn a local program for hardware, not a network target. They take # no target and cannot reach one through the argv they build. LOCAL_EXEC = {"esp_info", "esp_read_flash", "esp_flash"} diff --git a/tests/run.py b/tests/run.py index 391868a..99fab6f 100755 --- a/tests/run.py +++ b/tests/run.py @@ -7,6 +7,8 @@ point of the suite is the gate: everything else is a tool, the gate is the product. """ import base64 +import hashlib +import hmac import http.server import json import os @@ -130,7 +132,7 @@ res, _ = run([ ], home=empty) check("tools/list answers", any(r.get("id") == 1 for r in res)) tools = [r for r in res if r.get("id") == 1][0]["result"]["tools"] -check("61 tools registered", len(tools) == 61, len(tools)) +check("65 tools registered", len(tools) == 65, len(tools)) names = {t["name"] for t in tools} for need in ("portscan", "nmap", "http_request", "marauder_scan", "method_playbook", "finding_add", "finding_update", "scope_check", @@ -1556,7 +1558,7 @@ try: check("http initialize", init["result"]["serverInfo"]["name"] == "apex-twin", init) listing = post({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}) - check("http tools/list", len(listing["result"]["tools"]) == 61) + check("http tools/list", len(listing["result"]["tools"]) == 65) shown = post(call(3, "scope_show")) check("http scope_show", '"loaded":true' in shown["result"]["content"][0]["text"]) # the id must be the request's id, not one found inside the arguments @@ -2876,6 +2878,72 @@ check("web_log_audit flags the 4xx burst source", wl["burst_ips"]) check("web_log_audit refuses a path outside the allowed roots", err(by_id[2]), text(by_id[2])) +print("\n== jwt and hash identification ==") + + +def b64u(raw): + return base64.urlsafe_b64encode(raw).decode().rstrip("=") + + +def make_jwt(header, payload, secret=None): + h = b64u(json.dumps(header, separators=(",", ":")).encode()) + p = b64u(json.dumps(payload, separators=(",", ":")).encode()) + signing = (h + "." + p).encode() + if secret is None: + sig = "" + else: + sig = b64u(hmac.new(secret, signing, hashlib.sha256).digest()) + return h + "." + p + "." + sig + + +good_token = make_jwt({"alg": "HS256", "typ": "JWT", "kid": "k1"}, + {"sub": "42", "iss": "apex", "aud": "api", + "exp": int(time.time()) + 3600}, b"secret") +none_token = make_jwt({"alg": "none", "typ": "JWT"}, + {"sub": "42", "exp": 1000}) +kid_token = make_jwt({"alg": "HS256", "kid": "../../etc/passwd"}, + {"sub": "42", "exp": int(time.time()) + 60}, b"secret") +jwt_home = tempfile.mkdtemp(prefix="apex-jwt-") +write_scope(jwt_home, {"label": "jwt", "expires": "2099-12-31T23:59:59Z"}) +res, _ = run([ + call(1, "jwt_audit", token=good_token, secret="secret"), + call(2, "jwt_audit", token=none_token), + call(3, "jwt_audit", token=kid_token, secret="secret"), + call(4, "hash_id", value="5d41402abc4b2a76b9719d911017c592"), + call(5, "hash_id", value="$2b$12$abcdefghijklmnopqrstuv"), + call(6, "hash_id", value=good_token), + call(7, "jwt_audit", token="not.a.jwt"), +], home=jwt_home) +by_id = {r.get("id"): r for r in res} +good = json.loads(text(by_id[1])) +check("jwt_audit verifies a valid HS256 signature", + good["signature"] == "valid" and good["findings"] == [], good) +check("jwt_audit reports the header and claims", + good["header"]["alg"] == "HS256" and good["claims"]["iss"] == "apex" and + good["claims"]["aud"] == "api", good) +none = json.loads(text(by_id[2])) +none_ids = {f["id"] for f in none["findings"]} +check("jwt_audit flags alg=none as critical", + "alg-none" in none_ids and + any(f["severity"] == "critical" for f in none["findings"]), none) +check("jwt_audit flags an expired token", "expired" in none_ids, none) +check("jwt_audit does not claim to verify alg=none", + none["signature"] == "not-checked", none) +kid = json.loads(text(by_id[3])) +check("jwt_audit flags a path-like kid", + "kid-path" in {f["id"] for f in kid["findings"]}, kid) +md5 = json.loads(text(by_id[4])) +check("hash_id recognises an MD5-shaped value", + {c["format"] for c in md5["candidates"]} >= {"md5", "ntlm"}, md5) +bc = json.loads(text(by_id[5])) +check("hash_id recognises bcrypt", + bc["candidates"][0]["format"] == "bcrypt", bc) +jwt_id = json.loads(text(by_id[6])) +check("hash_id points a JWT at jwt_audit", + jwt_id["candidates"][0]["format"] == "jwt", jwt_id) +check("jwt_audit rejects a malformed token", err(by_id[7]), text(by_id[7])) +shutil.rmtree(jwt_home, ignore_errors=True) + print("\n== detections and integrity ==") det_home = tempfile.mkdtemp(prefix="apex-det-") write_scope(det_home, {"label": "det", "expires": "2099-12-31T23:59:59Z", @@ -2949,6 +3017,34 @@ check("integrity_baseline sees the new file", ver["added"] == 1, ver) check("integrity_baseline reports what changed", {d["what"] for d in ver["details"]} == {"changed", "missing", "added"}, ver["details"]) +res, _ = run([ + call(1, "finding_add", target="10.10.0.5", title="Reflected XSS in search", + severity="high", tool="xss_probe"), + call(2, "finding_add", target="10.10.0.5", title="Exposed .git directory", + severity="medium", tool="vuln_check"), + call(3, "mitre_map"), +], home=det_home) +by_id = {r.get("id"): r for r in res} +mm = json.loads(text(by_id[3])) +techs = {t["id"]: t for t in mm["techniques"]} +check("mitre_map maps XSS and exposed repositories", + "T1059.007" in techs and "T1213" in techs and mm["mapped"] >= 2, mm) +xss_id = json.loads(text(by_id[1]))["id"] +check("mitre_map lists the finding ids per technique", + xss_id in techs["T1059.007"]["findings"], techs["T1059.007"]) + +child = subprocess.Popen(["/bin/sh", "-c", "sleep 15; : nc -e"]) +time.sleep(0.3) +try: + res, _ = run([call(1, "process_snapshot")], home=det_home) + snap = json.loads(text(res[0])) + flagged = [f for f in snap["findings"] if f["pid"] == child.pid] + check("process_snapshot walks /proc", snap["processes"] > 5, snap) + check("process_snapshot flags a reverse-shell command line", + bool(flagged) and "suspicious" in flagged[0]["reason"], flagged) +finally: + child.kill() + child.wait(timeout=5) shutil.rmtree(det_home, ignore_errors=True) print("\n== esp32 tools ==")