diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b086f2..e60de61 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,24 @@ 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.25.0 — 2026-11-21 — this change +## 1.26.0 — 2026-11-21 — this change + +- **HTTP/2** (`http2_probe`): over TLS, `openssl s_client -alpn h2` and the + negotiated ALPN protocol; over cleartext, the HTTP/2 client preface plus a + SETTINGS frame, reporting the first frame type. One handshake or one preface. +- **SSH host keys** (`ssh_hostkey_fingerprint`): runs ssh-keyscan (rsa, ecdsa, + ed25519) or parses a saved scan output, decodes each base64 blob and reports + key type, bit size and `SHA256:` fingerprint (base64, unpadded). +- **Blue** (`logrotate_audit`): /etc/logrotate.conf and logrotate.d (root + prefix): world-writable configs, rotate counts of two or fewer, missing + compress and postrotate commands from /tmp or downloading code. +- Tests with an ALPN h2 TLS server, an h2c SETTINGS server, constructed SSH key + blobs with independently computed fingerprints and a logrotate tree. 756 + checks. Coverage 80.8%. +- Fixture lesson: the scope must allow port 22 for the offline SSH key parse, + because the gate runs before the output-file branch. + +## 1.25.0 — 2026-11-21 — 492b29d - **OIDC** (`oidc_discovery`): fetches /.well-known/openid-configuration and the OAuth authorization-server metadata, reporting issuer, authorization, token, diff --git a/README.md b/README.md index 21feb37..77bd50d 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. -**143 tools · 747 end-to-end checks · 340 fuzz cases · 80.8% line coverage · ~601 KiB** +**146 tools · 756 end-to-end checks · 340 fuzz cases · 80.8% line coverage · ~609 KiB** ``` $ ./apex-twin --check -{"version":"1.25.0","tools":143,...,"scope":{"loaded":true,...}} +{"version":"1.26.0","tools":146,...,"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 (143) +## Tools (146) ### Scope and bookkeeping @@ -289,6 +289,8 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `ntp_monlist_probe` | Mode-7 MON_GETLIST; monlist enabled, entry estimate, amplification | | `oidc_discovery` | OpenID/OAuth metadata: issuer, auth/token/JWKS/userinfo endpoints, evidence | | `security_txt` | security.txt Contact/Expires/Policy; expired documents flagged | +| `http2_probe` | ALPN h2 over TLS or h2c preface/SETTINGS; reports HTTP/2 support | +| `ssh_hostkey_fingerprint` | ssh-keyscan or saved output: key type, bits, SHA-256 fingerprint | | `imap_probe` | Banner, CAPABILITY list, STARTTLS and LOGINDISABLED; no LOGIN | | `pop3_probe` | Banner, CAPA list, STLS flag; no USER/PASS | | `sip_probe` | One UDP OPTIONS: status line, Server header, Allow methods | @@ -340,6 +342,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `audit_rules` | audit.rules/rules.d: rule count, -e 2, execve, watches on passwd/shadow/sudoers/group | | `usb_audit` | sysfs USB devices: IDs, strings, serial, mass-storage interface flagged | | `ssh_known_hosts_audit` | known_hosts: hashed vs plain, ssh-rsa/ssh-dss, duplicates | +| `logrotate_audit` | logrotate configs: world-writable, low rotate, no compress, unsafe postrotate | ### ESP32 @@ -576,6 +579,9 @@ The full threat model, trust boundaries and a hardening checklist are in | NTP/DNS version | one or two queries, no state | | OIDC/security.txt | two well-known GETs each | | Known hosts | 100 files, read-only | +| HTTP/2 | one handshake (ALPN) or one preface (h2c) | +| SSH keys | ssh-keyscan 20 s, or a saved output | +| Logrotate | 100 files, read-only | | USB audit | 200 devices, sysfs reads only | --- @@ -587,7 +593,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 747 end-to-end checks +make test # version check + gate audit + 756 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 @@ -701,7 +707,7 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, tls_cipher_matrix, smb_null_session, smb_shares, email_security_audit, smtp_open_relay, dns_open_resolver, crlf_probe, dns_version_bind, oidc_discovery, - security_txt + security_txt, http2_probe, ssh_hostkey_fingerprint src/tools_blue.c hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, persistence_audit, net_baseline, @@ -744,7 +750,7 @@ examples/ scope.json ## Status -1.25.0. Built and run: 143 tools, 747 checks, 340 fuzz cases and 80.8% line +1.26.0. Built and run: 146 tools, 756 checks, 340 fuzz cases and 80.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 @@ -786,8 +792,9 @@ audit; 1.21 added SMB share probing, e-mail security checks and a web-root audit; 1.22 added SMTP relay and DNS resolver checks plus AppArmor/SELinux audits; 1.23 added ESP image verification, CRLF injection and audit-rule checks; 1.24 added NTP monlist and DNS version disclosure checks plus a USB -audit; 1.25 added OIDC discovery, security.txt and known-hosts checks, again -without changing an existing file format. +audit; 1.25 added OIDC discovery, security.txt and known-hosts checks; 1.26 added +HTTP/2 probing, SSH host-key fingerprints and a logrotate audit, again without +changing an existing file format. Not yet wired into a fleet router, and there is no TLS interception. diff --git a/SECURITY.md b/SECURITY.md index ec7bde7..4d68a9b 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.25.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.26.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. +- **Protocol and key checks stay read-only.** `http2_probe` performs one ALPN + handshake or one h2c preface; `ssh_hostkey_fingerprint` runs ssh-keyscan or + parses a saved output; `logrotate_audit` reads config files. - **Metadata fetches are plain GETs.** `oidc_discovery` and `security_txt` request their well-known paths without credentials; `ssh_known_hosts_audit` reads local key files. diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index f0c88c3..f97f1ee 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.25.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.26.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS diff --git a/src/apex.h b/src/apex.h index 2b1867d..0984077 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.25.0" +#define APEX_VERSION "1.26.0" #define APEX_MAX_OUT (1u << 20) #define APEX_PATH_MAX 512 #define APEX_PATH_FULL 1024 diff --git a/src/tools_blue.c b/src/tools_blue.c index 6ccfa13..849b950 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -5876,6 +5876,148 @@ static void t_ssh_known_hosts_audit(mcp_conn *c, const mcp_json *args, mcp_buf_free(&findings); } +/* -------------------------------------------------------------- logrotate_audit */ + +typedef struct { + mcp_buf *b; + int first; + int count; + int files; +} lr_ctx; + +static void lr_finding(lr_ctx *ctx, const char *path, int line, + const char *kind, const char *severity, + const char *detail) +{ + if (ctx->count >= 100) + return; + 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,\"kind\":", line); + apex_json_str(ctx->b, kind); + mcp_buf_puts(ctx->b, ",\"severity\":"); + apex_json_str(ctx->b, severity); + mcp_buf_puts(ctx->b, ",\"detail\":"); + apex_json_str(ctx->b, detail); + mcp_buf_puts(ctx->b, "}"); +} + +static void lr_scan_file(lr_ctx *ctx, const char *path) +{ + FILE *f; + struct stat st; + char *line = NULL; + size_t cap = 0; + int lineno = 0; + int compress = 0; + int in_post = 0; + + if (ctx->files >= 100) + return; + f = fopen(path, "rb"); + if (f == NULL) + return; + ctx->files++; + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) + lr_finding(ctx, path, 0, "world-writable", "high", + "logrotate file is writable by anyone"); + while (getline(&line, &cap, f) >= 0) { + char *t = line; + + lineno++; + while (*t == ' ' || *t == '\t') + t++; + if (*t == '\0' || *t == '#') + continue; + if (strncmp(t, "compress", 8) == 0) + compress = 1; + if (strncmp(t, "rotate ", 7) == 0) { + int n = atoi(t + 7); + + if (n <= 2) + lr_finding(ctx, path, lineno, "rotate-low", "low", + "only one or two old logs are kept"); + } + if (strncmp(t, "postrotate", 10) == 0) + in_post = 1; + else if (strncmp(t, "endscript", 9) == 0) + in_post = 0; + else if (in_post && + (strstr(t, "/tmp/") != NULL || + strstr(t, "/dev/shm/") != NULL || + strstr(t, "curl ") != NULL || + strstr(t, "wget ") != NULL)) + lr_finding(ctx, path, lineno, "unsafe-postrotate", "medium", + "postrotate runs from a temp path or downloads code"); + } + free(line); + fclose(f); + if (!compress) + lr_finding(ctx, path, 0, "no-compress", "low", + "configuration does not compress rotated logs"); +} + +static void t_logrotate_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char base[512]; + char path[1024]; + mcp_buf b; + mcp_buf findings; + lr_ctx ctx; + + (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); + mcp_buf_init(&findings); + memset(&ctx, 0, sizeof(ctx)); + ctx.b = &findings; + ctx.first = 1; + snprintf(path, sizeof(path), "%s/etc/logrotate.conf", base); + lr_scan_file(&ctx, path); + snprintf(path, sizeof(path), "%s/etc/logrotate.d", base); + { + DIR *d = opendir(path); + struct dirent *ent; + + if (d != NULL) { + while ((ent = readdir(d)) != NULL) { + char full[1024]; + struct stat st; + + if (ent->d_name[0] == '.') + continue; + snprintf(full, sizeof(full), "%.800s/%.160s", path, + ent->d_name); + if (stat(full, &st) != 0 || !S_ISREG(st.st_mode)) + continue; + lr_scan_file(&ctx, full); + } + closedir(d); + } + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, base); + mcp_buf_printf(&b, ",\"files\":%d,\"findings_count\":%d,\"findings\":[", + ctx.files, ctx.count); + 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, " @@ -6217,6 +6359,13 @@ const mcp_tool TOOLS_BLUE[] = { "{\"type\":\"object\",\"properties\":{" "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", t_ssh_known_hosts_audit }, + { "logrotate_audit", + "Parse /etc/logrotate.conf and /etc/logrotate.d (root prefix): " + "world-writable configs, rotate counts of two or fewer, missing compress " + "and postrotate commands that run from /tmp or download code. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_logrotate_audit }, }; const size_t TOOLS_BLUE_N = sizeof(TOOLS_BLUE) / sizeof(TOOLS_BLUE[0]); diff --git a/src/tools_proto.c b/src/tools_proto.c index 3d45b6f..37dbd3f 100644 --- a/src/tools_proto.c +++ b/src/tools_proto.c @@ -4971,6 +4971,132 @@ static void t_ntp_monlist_probe(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* --------------------------------------------------------------- http2_probe */ + +static int h2c_try(const char *target, int port, int *frame_type) +{ + int fd = tcp_connect_host(target, port, 6000); + static const unsigned char preface[] = + "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"; + static const unsigned char settings[9] = { + 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00 + }; + unsigned char frame[9]; + struct pollfd pfd; + + *frame_type = -1; + if (fd < 0) + return 0; + if (write_bytes(fd, preface, sizeof(preface) - 1) != 0 || + write_bytes(fd, settings, sizeof(settings)) != 0) { + close(fd); + return 0; + } + pfd.fd = fd; + pfd.events = POLLIN; + pfd.revents = 0; + if (poll(&pfd, 1, 2000) <= 0) { + close(fd); + return 0; + } + if (apex_net_exact(fd, frame, 9) != 0) { + close(fd); + return 0; + } + close(fd); + { + unsigned long len = ((unsigned long)frame[0] << 16) | + ((unsigned long)frame[1] << 8) | frame[2]; + int type = frame[3]; + + if (len <= 16384 && type >= 0 && type <= 9) { + *frame_type = type; + return 1; + } + } + return 0; +} + +static void t_http2_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", 443); + int tls = mcp_arg_bool(args, "tls", apex_looks_tls(port)); + char conn[320]; + int alpn = 0; + char protocol[64]; + int frame_type = -1; + int h2c = 0; + mcp_buf b; + + (void)user; + if (target == NULL || *target == '\0') { + mcp_reply_error(c, "target is required"); + return; + } + if (port <= 0 || port > 65535) { + mcp_reply_error(c, "port out of range"); + return; + } + if (!gated(c, "http2_probe", target, port)) + return; + protocol[0] = '\0'; + if (tls) { + char *argv[12]; + int k = 0; + apex_proc p; + + if (!apex_have("openssl")) { + mcp_reply_error(c, "openssl is not installed on this host"); + return; + } + tls_conn_string(target, port, conn, sizeof(conn)); + argv[k++] = "openssl"; + argv[k++] = "s_client"; + argv[k++] = "-connect"; + argv[k++] = conn; + argv[k++] = "-servername"; + argv[k++] = (char *)target; + argv[k++] = "-alpn"; + argv[k++] = "h2"; + argv[k] = NULL; + if (apex_run(argv, 15000, g_cfg.max_output, &p) == 0) { + if (p.out != NULL) { + const char *hit = strstr(p.out, "ALPN protocol: "); + + if (hit != NULL) { + size_t w = 0; + + hit += 15; + while (*hit != '\0' && *hit != '\n' && + *hit != '\r' && w + 1 < sizeof(protocol)) + protocol[w++] = *hit++; + protocol[w] = '\0'; + } + } + apex_proc_free(&p); + } + alpn = strcmp(protocol, "h2") == 0; + } else { + h2c = h2c_try(target, port, &frame_type); + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"tls\":%s,\"alpn\":{\"supported\":%s," + "\"protocol\":", port, tls ? "true" : "false", + alpn ? "true" : "false"); + apex_json_str(&b, protocol); + mcp_buf_printf(&b, "},\"h2c\":{\"supported\":%s,\"frame_type\":%d}," + "\"http2\":%s}", h2c ? "true" : "false", frame_type, + (alpn || h2c) ? "true" : "false"); + apex_audit("http2_probe", target, port, !(alpn || h2c), + (alpn || h2c) ? "HTTP/2 supported" : "no HTTP/2 support", + tls ? "ALPN h2" : "h2c preface"); + 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 " @@ -5268,6 +5394,17 @@ const mcp_tool TOOLS_PROTO[] = { "\"port\":{\"type\":\"integer\",\"description\":\"default 123\"}}," "\"required\":[\"target\"]}", t_ntp_monlist_probe }, + { "http2_probe", + "Check HTTP/2 support: over TLS with openssl s_client -alpn h2 (reports " + "the negotiated ALPN protocol), over cleartext with the HTTP/2 client " + "preface plus a SETTINGS frame (reports the first frame type). One " + "handshake or one request each. Gate: the target must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 443\"}," + "\"tls\":{\"type\":\"boolean\"}}," + "\"required\":[\"target\"]}", + t_http2_probe }, }; const size_t TOOLS_PROTO_N = sizeof(TOOLS_PROTO) / sizeof(TOOLS_PROTO[0]); diff --git a/src/tools_red.c b/src/tools_red.c index a8e6b66..08f4873 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -4419,6 +4419,257 @@ static void t_security_txt(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ---------------------------------------------------- ssh_hostkey_fingerprint */ + +static int b64_value(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 unsigned char *b64_decode_alloc(const char *s, size_t *out_len) +{ + size_t cap = strlen(s) * 3 / 4 + 4; + unsigned char *out = malloc(cap); + unsigned long acc = 0; + int bits = 0; + size_t w = 0; + + if (out == NULL) + return NULL; + while (*s != '\0') { + int v; + + if (*s == '=' || *s == '\n' || *s == '\r' || *s == ' ' || + *s == '\t') { + s++; + continue; + } + v = b64_value((unsigned char)*s++); + if (v < 0) { + free(out); + return NULL; + } + acc = (acc << 6) | (unsigned long)v; + bits += 6; + if (bits >= 8) { + bits -= 8; + out[w++] = (unsigned char)((acc >> bits) & 0xff); + } + } + *out_len = w; + return out; +} + +static unsigned int ssh_rsa_bits(const unsigned char *blob, size_t len) +{ + size_t o = 0; + unsigned long klen; + unsigned long elen; + unsigned long nlen; + const unsigned char *n; + int lead = 0; + + if (len < 4) + return 0; + klen = ((unsigned long)blob[0] << 24) | ((unsigned long)blob[1] << 16) | + ((unsigned long)blob[2] << 8) | blob[3]; + o = 4 + klen; + if (o + 4 > len) + return 0; + elen = ((unsigned long)blob[o] << 24) | ((unsigned long)blob[o + 1] << 16) | + ((unsigned long)blob[o + 2] << 8) | blob[o + 3]; + o += 4 + elen; + if (o + 4 > len) + return 0; + nlen = ((unsigned long)blob[o] << 24) | ((unsigned long)blob[o + 1] << 16) | + ((unsigned long)blob[o + 2] << 8) | blob[o + 3]; + o += 4; + if (nlen == 0 || o + nlen > len) + return 0; + n = blob + o; + while (nlen > 0 && *n == 0) { + n++; + nlen--; + } + if (nlen == 0) + return 0; + { + unsigned char top = *n; + + while ((top & 0x80) == 0) { + top = (unsigned char)(top << 1); + lead++; + } + } + return (unsigned int)(nlen * 8 - (size_t)lead); +} + +static void sshkey_add(mcp_buf *keys, int *first, int *count, + const char *type, const char *b64) +{ + size_t blen = 0; + unsigned char *blob = b64_decode_alloc(b64, &blen); + char fp[128]; + unsigned int bits = 0; + + if (blob == NULL) + return; + { + unsigned char raw[32]; + char *encoded; + size_t k; + + apex_sha256_raw(blob, blen, raw); + encoded = apex_base64_alloc((const char *)raw, sizeof(raw)); + if (encoded != NULL) { + size_t n = strlen(encoded); + + while (n > 0 && encoded[n - 1] == '=') + encoded[--n] = '\0'; + snprintf(fp, sizeof(fp), "SHA256:%s", encoded); + free(encoded); + } else { + snprintf(fp, sizeof(fp), "%s", "SHA256:?"); + } + (void)k; + } + if (strcmp(type, "ssh-rsa") == 0) + bits = ssh_rsa_bits(blob, blen); + else if (strncmp(type, "ecdsa-sha2-nistp", 17) == 0) + bits = (unsigned int)atoi(type + 17); + else if (strcmp(type, "ssh-ed25519") == 0) + bits = 256; + free(blob); + if (!*first) + mcp_buf_puts(keys, ","); + *first = 0; + (*count)++; + mcp_buf_puts(keys, "{\"type\":"); + apex_json_str(keys, type); + mcp_buf_printf(keys, ",\"bits\":%u,\"fingerprint\":", bits); + apex_json_str(keys, fp); + mcp_buf_printf(keys, ",\"blob_bytes\":%lu}", (unsigned long)blen); +} + +static void sshkey_parse(mcp_buf *keys, int *first, int *count, char *text) +{ + char *save = NULL; + char *line = strtok_r(text, "\n", &save); + + while (line != NULL) { + char *tokens[4]; + int ntok = 0; + char *tsave = NULL; + char *tok = strtok_r(line, " \t", &tsave); + + while (tok != NULL && ntok < 4) { + tokens[ntok++] = tok; + tok = strtok_r(NULL, " \t", &tsave); + } + if (ntok >= 3 && tokens[0][0] != '#') + sshkey_add(keys, first, count, tokens[1], tokens[2]); + line = strtok_r(NULL, "\n", &save); + } +} + +static void t_ssh_hostkey_fingerprint(mcp_conn *c, const mcp_json *args, + void *user) +{ + const char *target = mcp_arg_string(args, "target"); + const char *types = mcp_arg_string(args, "types"); + const char *output = mcp_arg_string(args, "output"); + int port = mcp_arg_int(args, "port", 22); + mcp_buf b; + int first = 1; + int count = 0; + int rc = 0; + char *text = NULL; + const char *source = "live"; + + (void)user; + if (target == NULL || *target == '\0') { + mcp_reply_error(c, "target is required"); + return; + } + if (port <= 0 || port > 65535) { + mcp_reply_error(c, "port out of range"); + return; + } + if (types == NULL || *types == '\0') + types = "rsa,ecdsa,ed25519"; + if (!gated(c, "ssh_hostkey_fingerprint", target, port)) + return; + if (output != NULL && *output != '\0') { + FILE *f = fopen(output, "rb"); + char *line = NULL; + size_t cap = 0; + mcp_buf tmp; + + if (f == NULL) { + mcp_reply_error(c, "cannot read the saved scan output"); + return; + } + mcp_buf_init(&tmp); + while (getline(&line, &cap, f) >= 0) + mcp_buf_add(&tmp, line, strlen(line)); + free(line); + fclose(f); + text = tmp.p; + source = "file"; + } else { + char *argv[10]; + char portstr[16]; + int i = 0; + apex_proc p; + + if (!apex_have("ssh-keyscan")) { + mcp_reply_error(c, "ssh-keyscan is not installed on this host"); + return; + } + snprintf(portstr, sizeof(portstr), "%d", port); + argv[i++] = "ssh-keyscan"; + argv[i++] = "-T"; + argv[i++] = "5"; + argv[i++] = "-p"; + argv[i++] = portstr; + argv[i++] = "-t"; + argv[i++] = (char *)types; + argv[i++] = (char *)target; + argv[i] = NULL; + rc = apex_run(argv, 20000, g_cfg.max_output, &p); + if (rc != 0) { + mcp_reply_error(c, "cannot run ssh-keyscan"); + return; + } + text = p.out; + p.out = NULL; + apex_proc_free(&p); + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"source\":\"%s\",\"keys\":[", port, + source); + if (text != NULL) + sshkey_parse(&b, &first, &count, text); + mcp_buf_printf(&b, "],\"count\":%d}", count); + apex_audit("ssh_hostkey_fingerprint", target, port, count > 0, + count > 0 ? "host keys collected" : "no host keys", types); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + free(text); +} + const mcp_tool TOOLS_RED[] = { { "vuln_check", "Non-destructive verification of exposed artifacts on one web target: " @@ -4815,6 +5066,20 @@ const mcp_tool TOOLS_RED[] = { "\"tls\":{\"type\":\"boolean\"}}," "\"required\":[\"target\"]}", t_security_txt }, + { "ssh_hostkey_fingerprint", + "Collect SSH host keys with ssh-keyscan (types rsa,ecdsa,ed25519) or parse " + "a saved scan output, decode each base64 key blob and report its key type, " + "bit size and SHA-256 fingerprint (base64). Gate: the target must be in " + "scope; the output-file mode still requires it.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 22\"}," + "\"types\":{\"type\":\"string\",\"description\":\"default " + "rsa,ecdsa,ed25519\"}," + "\"output\":{\"type\":\"string\",\"description\":\"parse a saved " + "ssh-keyscan output\"}}," + "\"required\":[\"target\"]}", + t_ssh_hostkey_fingerprint }, }; 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 0f6b48b..f85cf71 100755 --- a/tests/gate_audit.py +++ b/tests/gate_audit.py @@ -21,7 +21,7 @@ import re import sys HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -EXPECTED_TOOLS = 143 +EXPECTED_TOOLS = 146 GATE = ("gated(", "gated_cmd(", "gated_run(", "apex_scope_check(") NET = ("http_once(", "tcp_connect_host(", "tcp_probe(", "apex_run(") # Tools whose "target" argument filters local records; they never touch it. diff --git a/tests/run.py b/tests/run.py index d7e2290..07cc83c 100755 --- a/tests/run.py +++ b/tests/run.py @@ -134,7 +134,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("143 tools registered", len(tools) == 143, len(tools)) +check("146 tools registered", len(tools) == 146, 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", @@ -1560,7 +1560,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"]) == 143) + check("http tools/list", len(listing["result"]["tools"]) == 146) 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 @@ -6535,6 +6535,161 @@ old_srv.server_close() shutil.rmtree(kh_root, ignore_errors=True) shutil.rmtree(oidc_home, ignore_errors=True) +print("\n== HTTP/2, SSH host keys and logrotate ==") + +alpn_dir = tempfile.mkdtemp(prefix="apex-alpn-") +alpn_cert = os.path.join(alpn_dir, "cert.pem") +alpn_key = os.path.join(alpn_dir, "key.pem") +subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", + "-keyout", alpn_key, "-out", alpn_cert, "-days", "2", + "-subj", "/CN=localhost"], + check=True, capture_output=True) + + +def alpn_server(cert, key): + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + ctx.load_cert_chain(cert, key) + ctx.set_alpn_protocols(["h2", "http/1.1"]) + 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: + tls = ctx.wrap_socket(conn, server_side=True) + tls.recv(1) + tls.close() + except (ssl.SSLError, OSError): + conn.close() + + threading.Thread(target=loop, daemon=True).start() + return srv, port + + +def h2c_server(): + 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: + need = 24 + 9 + got = b"" + while len(got) < need: + chunk = conn.recv(need - len(got)) + if not chunk: + break + got += chunk + conn.sendall(b"\x00\x00\x00\x04\x00\x00\x00\x00\x00") + finally: + conn.close() + + threading.Thread(target=loop, daemon=True).start() + return srv, port + + +alpn_srv, alpn_port = alpn_server(alpn_cert, alpn_key) +h2c_srv, h2c_port = h2c_server() + + +def ssh_blob(kind): + if kind == "ed25519": + return (struct.pack(">I", 11) + b"ssh-ed25519" + + struct.pack(">I", 32) + bytes(range(32))) + return (struct.pack(">I", 7) + b"ssh-rsa" + + struct.pack(">I", 3) + b"\x01\x00\x01" + + struct.pack(">I", 256) + b"\x80" + b"\x00" * 255) + + +def ssh_fp(blob): + return "SHA256:" + base64.b64encode( + hashlib.sha256(blob).digest()).decode().rstrip("=") + + +ed_blob = ssh_blob("ed25519") +rsa_blob = ssh_blob("rsa") +scan_path = os.path.join(alpn_dir, "keyscan.txt") +with open(scan_path, "w") as f: + f.write("example.test ssh-ed25519 " + + base64.b64encode(ed_blob).decode() + "\n") + f.write("example.test ssh-rsa " + + base64.b64encode(rsa_blob).decode() + "\n") + +lr_root = tempfile.mkdtemp(prefix="apex-lr-") +os.makedirs(os.path.join(lr_root, "etc", "logrotate.d")) +with open(os.path.join(lr_root, "etc", "logrotate.conf"), "w") as f: + f.write("rotate 4\ncompress\n") +lr_app = os.path.join(lr_root, "etc", "logrotate.d", "app") +with open(lr_app, "w") as f: + f.write("rotate 1\npostrotate\n/tmp/hook.sh\nendscript\n") +os.chmod(lr_app, 0o666) + +http2_home = tempfile.mkdtemp(prefix="apex-h2-home-") +write_scope(http2_home, {"label": "h2", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_port": [str(alpn_port), str(h2c_port), "22"]}) +res, _ = run([ + call(1, "http2_probe", target="127.0.0.1", port=alpn_port, tls=True), + call(2, "http2_probe", target="127.0.0.1", port=h2c_port, tls=False), + call(3, "ssh_hostkey_fingerprint", target="127.0.0.1", + output=scan_path), + call(4, "logrotate_audit", root=lr_root), + call(5, "http2_probe", target="198.51.100.9", port=443), + call(6, "ssh_hostkey_fingerprint", target="198.51.100.9", + output=scan_path), + call(7, "logrotate_audit", root="/nonexistent-lr"), +], home=http2_home) +by_id = {r.get("id"): r for r in res} +h2 = json.loads(text(by_id[1])) +check("http2_probe negotiates h2 over ALPN", + h2["alpn"]["supported"] is True and h2["alpn"]["protocol"] == "h2" and + h2["http2"] is True, h2) +h2c = json.loads(text(by_id[2])) +check("http2_probe detects h2c via the preface", + h2c["h2c"]["supported"] is True and h2c["h2c"]["frame_type"] == 4 and + h2c["http2"] is True, h2c) +keys = json.loads(text(by_id[3])) +by_type = {k["type"]: k for k in keys["keys"]} +check("ssh_hostkey_fingerprint decodes both keys", + keys["source"] == "file" and keys["count"] == 2 and + by_type["ssh-ed25519"]["fingerprint"] == ssh_fp(ed_blob) and + by_type["ssh-rsa"]["fingerprint"] == ssh_fp(rsa_blob), keys) +check("ssh_hostkey_fingerprint reports the RSA size", + by_type["ssh-rsa"]["bits"] == 2048 and + by_type["ssh-ed25519"]["bits"] == 256, by_type) +lr = json.loads(text(by_id[4])) +kinds = {f["kind"] for f in lr["findings"]} +check("logrotate_audit reads both files", + lr["files"] == 2, lr) +check("logrotate_audit flags the unsafe rotate block", + {"world-writable", "rotate-low", "unsafe-postrotate", + "no-compress"} <= kinds, kinds) +check("http2_probe refuses an out-of-scope target", err(by_id[5]), + text(by_id[5])) +check("ssh_hostkey_fingerprint refuses an out-of-scope target", + err(by_id[6]), text(by_id[6])) +check("logrotate_audit survives a missing root", + json.loads(text(by_id[7]))["files"] == 0, text(by_id[7])) +alpn_srv.close() +h2c_srv.close() +shutil.rmtree(alpn_dir, ignore_errors=True) +shutil.rmtree(lr_root, ignore_errors=True) +shutil.rmtree(http2_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"})