diff --git a/CHANGELOG.md b/CHANGELOG.md index 34d6a5a..d32abf8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,30 @@ # Changelog +## 1.96.0 - 2026-11-24 - this change + +- **PAM restrictions** (`pam_restrict_audit`): `/etc/security/group.conf` and + `time.conf` under the root prefix: a rule with an empty service field that + can never fire, a time list that is not `day+HHMM-HHMM`, a `group.conf` rule + for a group `/etc/group` does not list, a `*` group field, and a time rule + with `*` in every field (permits forever). Field counts are checked because + both files drop a malformed line with only a syslog warning. +- **Password history** (`pwhistory_audit`): `pwhistory.conf` and + `sepermit.conf`: `remember` missing, zero or below 5, `enforce_for_root` + off, `use_authtok` missing, and a `sepermit.conf` separator line that names + no group (every login is exempt from the separation). +- **firewalld** (`firewalld_audit`): `firewalld.conf` plus `zones/*.xml`: + `PanicMode` on (permanent once it survives a reboot), `CleanupOnExit=no`, + `DefaultZone=trusted` or a blocking zone, a zone whose `` is + `ACCEPT` or that holds a rich `` rule, and a zone with neither + `` nor `` (in force nowhere). +- **Cassandra** (`cassandra_probe`): CQL native protocol on 9042. `OPTIONS` + answers `SUPPORTED` without authentication, so the port is identified even + on a locked node; a `STARTUP` answered with `READY` means the cluster takes + queries from anyone, and an `ERROR 0x2200` carrying "Required auth" means an + authenticator is set. No query is sent. +- Checks: 1521 (was 1512). Red proof: neutralising the dead-rule branch in + `pam_restrict_audit` turns the new check red; restored afterwards. + ## 1.95.0 - 2026-11-24 - this change - **SpamAssassin** (`spamassassin_audit`): `local.cf`/`local.conf` with diff --git a/README.md b/README.md index 08735b5..ffc8c18 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. -**410 tools · 1512 end-to-end checks · 240 fuzz cases · 85.1% line coverage · ~1041 KiB** +**414 tools · 1521 end-to-end checks · 240 fuzz cases · 85.0% line coverage · ~1349 KiB** ``` $ ./apex-twin --check -{"version":"1.95.0","tools":410,...,"scope":{"loaded":true,...}} +{"version":"1.96.0","tools":414,...,"scope":{"loaded":true,...}} ``` APEX TWIN was inspired by [ARTEX](https://github.com/Autumn-27/artex) (scope @@ -374,6 +374,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `postgres_probe` | SSL offer plus one StartupMessage; reports trust/cleartext/md5/SCRAM/rejected and the server message | | `mongo_probe` | Hand-built OP_QUERY `isMaster` on `admin.$cmd`: ok, maxWireVersion, writable primary | | `memcached_probe` | One `stats`: open access, version, connections, items, memory limit, uptime | +| `cassandra_probe` | CQL native protocol on 9042: OPTIONS/SUPPORTED, then STARTUP; READY means no authentication | ### External scanners (gated wrappers) @@ -619,6 +620,9 @@ does. | `limits_audit` | limits.conf: unlimited nofile/nproc/memlock, core dumps | | `access_conf_audit` | access.conf: `+ : ALL : ALL`, default-allow tail | | `pwquality_audit` | pwquality.conf: minlen < 8, minclass 0, enforcing=0 | +| `pam_restrict_audit` | group.conf/time.conf: dead rule, unknown group, wildcard, bad time list | +| `pwhistory_audit` | pwhistory.conf: remember missing/0, root not enforced, bare sepermit separator | +| `firewalld_audit` | firewalld: PanicMode, CleanupOnExit=no, trusted default, ACCEPT target, unbound zone | ### ESP32 @@ -1094,7 +1098,8 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, zabbix_probe, datasette_probe, vault_probe, nomad_probe, coredns_probe, openbmc_probe, schema_registry_probe, loki_probe, tempo_probe, - jaeger_probe + jaeger_probe, solr_probe, confluence_probe, + bitbucket_probe, cassandra_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, @@ -1126,7 +1131,8 @@ src/tools_blue.c hardening_audit, log_audit, ioc_scan, web_log_audit, suricata_audit, icinga2_audit, falco_audit, promtail_audit, otel_collector_audit, fluentbit_audit, vector_audit, seccomp_audit, - systemd_socket_audit) + systemd_socket_audit, pam_restrict_audit, + pwhistory_audit, firewalld_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 @@ -1165,7 +1171,7 @@ examples/ scope.json ## Status -1.95.0. Built and run: 410 tools, 1512 checks, 240 fuzz cases and 85.1% line +1.96.0. Built and run: 414 tools, 1521 checks, 240 fuzz cases and 85.0% 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 191647c..66cc6ab 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.95.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.96.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. @@ -274,6 +274,12 @@ only narrow what the proxy does (the scope gate still runs first). stored as bytes. The program does not execute target content. - **TLS interception.** `CONNECT` is a blind tunnel; nothing inside TLS is inspected, logged or rewritten. That is deliberate (no TLS stack is linked). +- **PAM restriction and firewalld audits read local files.** + `pam_restrict_audit` parses `/etc/security/group.conf` and `time.conf`, + `pwhistory_audit` parses `pwhistory.conf` and `sepermit.conf`, and + `firewalld_audit` reads `/etc/firewalld` including the zone XML; none of them + changes a rule, reloads a daemon or contacts firewalld's D-Bus. The Cassandra + probe opens one CQL connection, sends OPTIONS and STARTUP and never a query. - **Denial of service from a local client.** The proxy and the HTTP face fork a child per connection and cap them (`APEX_PROXY_MAX_CHILDREN` and `APEX_HTTP_MAX_CHILDREN`, default 64 each, max 1024); beyond that they answer diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index 4c0a828..99356e7 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-24" "apex-twin 1.95.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-24" "apex-twin 1.96.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS @@ -45,7 +45,7 @@ graphql_probe, docker_api_probe, elasticsearch_probe, imap_probe, pop3_probe, 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, 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, zabbix_probe, datasette_probe, airflow_probe, gitlab_probe, jupyter_probe, jira_probe, ollama_probe, cadvisor_probe, teamcity_probe, superset_probe, vault_probe, nomad_probe, coredns_probe, openbmc_probe, schema_registry_probe, loki_probe, tempo_probe, jaeger_probe, solr_probe, confluence_probe, bitbucket_probe, +websocket_origin_check, dns_fcrdns_check, dns_soa_mname_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, zabbix_probe, datasette_probe, airflow_probe, gitlab_probe, jupyter_probe, jira_probe, ollama_probe, cadvisor_probe, teamcity_probe, superset_probe, vault_probe, nomad_probe, coredns_probe, openbmc_probe, schema_registry_probe, loki_probe, tempo_probe, jaeger_probe, solr_probe, confluence_probe, bitbucket_probe, cassandra_probe, nuclei_scan, nikto_scan, ffuf_scan, gobuster_scan, sqlmap_scan), defensive audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, @@ -101,7 +101,8 @@ fapolicyd_audit, systemd_timer_audit, yara_audit, suricata_audit, promtail_audit, otel_collector_audit, fluentbit_audit, vector_audit, seccomp_audit, systemd_socket_audit, icinga2_audit, falco_audit, -php_fpm_audit, uwsgi_audit, lighttpd_audit) +php_fpm_audit, uwsgi_audit, lighttpd_audit, +pam_restrict_audit, pwhistory_audit, firewalld_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 45f601c..241f77c 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.95.0" +#define APEX_VERSION "1.96.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 ef7d7bf..971e3cb 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -32156,6 +32156,908 @@ static void t_amavis_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&findings); } +/* -------------------------------------------------------- pam_restrict_audit */ + +/* group.conf is "services;ttys;users;times;groups": a rule hands the listed + * groups to a matching login, so an empty groups field takes every group away + * instead. time.conf is "services;ttys;users;times": a matching rule permits + * the login and no match denies it, so a rule with an empty service field can + * never fire and one with "*" in every field permits everything forever. Both + * files ignore a malformed line with only a syslog warning, which is why a + * field-count check is part of the audit. */ +struct pamr_state { + int group_lines; + int time_lines; + int dead; + int allow_all; + int wildcard; + int unknown_group; + int malformed; +}; + +static int pam_field_count(const char *s, char sep) +{ + int n = 1; + + while (*s != '\0') { + if (*s == sep) + n++; + s++; + } + return n; +} + +static void pam_split(char *line, char sep, char *field[], int max) +{ + int n = 0; + char *p = line; + + field[n++] = p; + while (*p != '\0' && n < max) { + if (*p == sep) { + *p = '\0'; + field[n++] = p + 1; + } + p++; + } +} + +static int pam_day_pair(const char *s) +{ + static const char *days[] = { "Mo", "Tu", "We", "Th", "Fr", + "Sa", "Su", "Wk", "Wd", "Al", NULL }; + int i; + + for (i = 0; days[i] != NULL; i++) + if (s[0] == days[i][0] && s[1] == days[i][1]) + return 1; + return 0; +} + +/* HHMM with hour < 24 and minute < 60; "2400" is the one allowed end. */ +static int pam_hhmm(const char *s) +{ + int h; + int m; + + if (strlen(s) < 4 || !isdigit((unsigned char)s[0]) || + !isdigit((unsigned char)s[1]) || !isdigit((unsigned char)s[2]) || + !isdigit((unsigned char)s[3])) + return 0; + h = (s[0] - '0') * 10 + (s[1] - '0'); + m = (s[2] - '0') * 10 + (s[3] - '0'); + if (h == 24 && m == 0) + return 1; + return h < 24 && m < 60; +} + +/* A time token is an optional "!" followed by a day pair and HHMM-HHMM. */ +static int pam_time_token(const char *tok) +{ + const char *s = tok; + const char *dash; + + if (*s == '!') + s++; + if (!pam_day_pair(s)) + return 0; + s += 2; + dash = strchr(s, '-'); + if (dash == NULL || dash - s != 4) + return 0; + s = dash + 1; + return strlen(s) == 4 && pam_hhmm(tok + (*tok == '!' ? 3 : 2)) && + pam_hhmm(s); +} + +static int pam_times_ok(const char *field) +{ + char copy[256]; + char *save = NULL; + char *tok; + + if (strcmp(field, "*") == 0) + return 1; + if (strlen(field) >= sizeof(copy)) + return 0; + snprintf(copy, sizeof(copy), "%s", field); + for (tok = strtok_r(copy, "|", &save); tok != NULL; + tok = strtok_r(NULL, "|", &save)) { + char *s = tok; + + while (*s == ' ' || *s == '\t') + s++; + if (!pam_time_token(s)) + return 0; + } + return 1; +} + +static int pam_group_exists(const char *grouptext, const char *name) +{ + char needle[256]; + const char *p; + + if (*name == '\0' || *name == '@' || strchr(name, '*') != NULL) + return 1; + snprintf(needle, sizeof(needle), "\n%.200s:", name); + p = grouptext; + if (grouptext[0] != '\0') { + char at_start[256]; + + snprintf(at_start, sizeof(at_start), "%.200s:", name); + if (strncmp(p, at_start, strlen(at_start)) == 0) + return 1; + } + return strstr(p, needle) != NULL; +} + +static void pam_scan_group_conf(mcp_buf *findings, int *first, int *count, + const char *path, const char *grouptext, + struct pamr_state *st) +{ + static char text[65536]; + struct stat sb; + const char *p; + + if (read_text(path, text, sizeof(text)) < 0) + return; + if (stat(path, &sb) == 0 && (sb.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[1024]; + char *field[8]; + char *hash; + int nf; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + p = eol != NULL ? eol + 1 : NULL; + hash = strchr(line, '#'); + if (hash != NULL) + *hash = '\0'; + trim_eol(line); + if (line[0] == '\0' || line[0] == '\n') + continue; + st->group_lines++; + nf = pam_field_count(line, ';'); + if (nf != 5) { + st->malformed++; + add_finding(findings, first, "malformed-line", "low", + "%s: a line has %d fields instead of 5", + path, nf); + (*count)++; + continue; + } + pam_split(line, ';', field, 5); + if (strcmp(field[4], "*") == 0 || strchr(field[4], '*') != NULL) { + st->wildcard++; + add_finding(findings, first, "wildcard-groups", "medium", + "%s: a rule hands out every group (%s)", + path, field[4]); + (*count)++; + } else if (field[4][0] == '\0') { + add_finding(findings, first, "no-groups", "medium", + "%s: an empty groups field takes every group " + "away", path); + (*count)++; + } else if (!pam_group_exists(grouptext, field[4])) { + st->unknown_group++; + add_finding(findings, first, "unknown-group", "low", + "%s: group \"%s\" does not exist", + path, field[4]); + (*count)++; + } + if (field[0][0] == '\0') { + st->dead++; + add_finding(findings, first, "dead-rule", "low", + "%s: empty service field, the rule never " + "applies", path); + (*count)++; + } + if (!pam_times_ok(field[3])) { + st->malformed++; + add_finding(findings, first, "bad-times", "low", + "%s: \"%s\" is not a valid time list", + path, field[3]); + (*count)++; + } + } +} + +static void pam_scan_time_conf(mcp_buf *findings, int *first, int *count, + const char *path, struct pamr_state *st) +{ + static char text[65536]; + struct stat sb; + const char *p; + + if (read_text(path, text, sizeof(text)) < 0) + return; + if (stat(path, &sb) == 0 && (sb.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[1024]; + char *field[8]; + char *hash; + int nf; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + p = eol != NULL ? eol + 1 : NULL; + hash = strchr(line, '#'); + if (hash != NULL) + *hash = '\0'; + trim_eol(line); + if (line[0] == '\0') + continue; + st->time_lines++; + nf = pam_field_count(line, ';'); + if (nf != 4) { + st->malformed++; + add_finding(findings, first, "malformed-line", "low", + "%s: a line has %d fields instead of 4", + path, nf); + (*count)++; + continue; + } + pam_split(line, ';', field, 4); + if (field[0][0] == '\0') { + st->dead++; + add_finding(findings, first, "dead-rule", "low", + "%s: empty service field, the rule never " + "applies", path); + (*count)++; + } + if (!pam_times_ok(field[3])) { + st->malformed++; + add_finding(findings, first, "bad-times", "low", + "%s: \"%s\" is not a valid time list", + path, field[3]); + (*count)++; + } + if (strcmp(field[0], "*") == 0 && strcmp(field[1], "*") == 0 && + strcmp(field[2], "*") == 0 && + strcmp(field[3], "Al0000-2400") == 0) { + st->allow_all++; + add_finding(findings, first, "allow-all", "medium", + "%s: a rule permits every service for every " + "user at any time", path); + (*count)++; + } + } +} + +static void t_pam_restrict_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char base[512]; + char path[1024]; + static char grouptext[65536]; + mcp_buf b; + mcp_buf findings; + struct pamr_state st; + int count = 0; + int first = 1; + size_t bl; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) >= sizeof(base) - 2) { + mcp_reply_error(c, "root path too long"); + return; + } + snprintf(base, sizeof(base), "%s", root); + bl = strlen(base); + while (bl > 0 && base[bl - 1] == '/') + base[--bl] = '\0'; + memset(&st, 0, sizeof(st)); + mcp_buf_init(&findings); + + snprintf(path, sizeof(path), "%s/etc/group", base); + if (read_text(path, grouptext, sizeof(grouptext)) < 0) + grouptext[0] = '\0'; + + snprintf(path, sizeof(path), "%s/etc/security/group.conf", base); + pam_scan_group_conf(&findings, &first, &count, path, grouptext, &st); + snprintf(path, sizeof(path), "%s/etc/security/time.conf", base); + pam_scan_time_conf(&findings, &first, &count, path, &st); + + if (st.group_lines == 0 && st.time_lines == 0) { + add_finding(&findings, &first, "no-config", "info", + "neither group.conf nor time.conf is present, so " + "pam_group and pam_time restrict nothing"); + count = 1; + } else if (count == 0) { + add_finding(&findings, &first, "no-findings", "info", + "the PAM restriction files carry no weak rule"); + count = 1; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, base); + mcp_buf_printf(&b, ",\"group_lines\":%d,\"time_lines\":%d," + "\"dead_rules\":%d,\"allow_all\":%d,\"wildcard\":%d," + "\"unknown_group\":%d,\"malformed\":%d," + "\"findings_count\":%d,\"findings\":[", + st.group_lines, st.time_lines, st.dead, st.allow_all, + st.wildcard, st.unknown_group, st.malformed, 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); +} + +/* ------------------------------------------------------------ pwhistory_audit */ + +/* /etc/security/pwhistory.conf is "key = value" and every missing key falls + * back to a weak default (remember = 10 counts, no root enforcement). A + * "remember" of 0 disables reuse checking completely. sepermit.conf lists a + * separator and the groups it excludes: a bare separator line with no group + * and enforce_for_root = yes together let the root account lock itself out of + * su, which is the classic reason a rescue boot is needed. */ +struct pwh_state { + int remember; + int remember_seen; + int enforce_root; + int use_authtok; + int sepermit_rules; + int sepermit_unconfined; +}; + +static int pwh_conf_value(const char *text, const char *key, char *out, size_t n) +{ + const char *p = text; + + out[0] = '\0'; + while (p != NULL && *p != '\0') { + const char *eol = strchr(p, '\n'); + size_t len = eol != NULL ? (size_t)(eol - p) : strlen(p); + char line[512]; + char *eq; + char *name; + char *val; + char *hash; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + p = eol != NULL ? eol + 1 : NULL; + hash = strchr(line, '#'); + if (hash != NULL) + *hash = '\0'; + eq = strchr(line, '='); + if (eq == NULL) + continue; + *eq = '\0'; + name = line; + while (*name == ' ' || *name == '\t') + name++; + trim_eol(name); + val = eq + 1; + while (*val == ' ' || *val == '\t') + val++; + trim_eol(val); + if (strcasecmp(name, key) != 0) + continue; + snprintf(out, n, "%s", val); + return 1; + } + return 0; +} + +static void pwh_scan_conf(mcp_buf *findings, int *first, int *count, + const char *path, struct pwh_state *st) +{ + static char text[65536]; + struct stat sb; + char val[128]; + + if (read_text(path, text, sizeof(text)) < 0) + return; + st->remember_seen = 1; + if (stat(path, &sb) == 0 && (sb.st_mode & 0002) != 0) { + add_finding(findings, first, "world-writable", "high", + "%s is writable by anyone", path); + (*count)++; + } + if (pwh_conf_value(text, "remember", val, sizeof(val))) { + st->remember = atoi(val); + if (st->remember <= 0) { + add_finding(findings, first, "no-remember", "high", + "%s: remember = %d keeps no password history", + path, st->remember); + (*count)++; + } else if (st->remember < 5) { + add_finding(findings, first, "weak-remember", "low", + "%s: remember = %d allows an old password " + "back after %d changes", + path, st->remember, st->remember); + (*count)++; + } + } else { + add_finding(findings, first, "no-remember", "medium", + "%s does not set remember, so the module default " + "(10) applies", path); + (*count)++; + } + if (pwh_conf_value(text, "enforce_for_root", val, sizeof(val)) && + (strcasecmp(val, "yes") == 0 || strcmp(val, "1") == 0)) { + st->enforce_root = 1; + } else { + add_finding(findings, first, "no-root-enforce", "low", + "%s lets root recycle old passwords", + path); + (*count)++; + } + if (pwh_conf_value(text, "use_authtok", val, sizeof(val)) && + (strcasecmp(val, "yes") == 0 || strcmp(val, "1") == 0)) { + st->use_authtok = 1; + } +} + +static void pwh_scan_sepermit(mcp_buf *findings, int *first, int *count, + const char *path, struct pwh_state *st) +{ + static char text[65536]; + struct stat sb; + const char *p; + + if (read_text(path, text, sizeof(text)) < 0) + return; + if (stat(path, &sb) == 0 && (sb.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[512]; + char *sep; + char *rest; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + p = eol != NULL ? eol + 1 : NULL; + trim_eol(line); + if (line[0] == '\0' || line[0] == '#') + continue; + st->sepermit_rules++; + sep = strchr(line, ':'); + rest = sep != NULL ? sep + 1 : ""; + trim_eol(rest); + if (rest[0] == '\0') { + st->sepermit_unconfined++; + add_finding(findings, first, "separator-unconfined", + "medium", + "%s: a separator line names no group, so " + "every account may use it", path); + (*count)++; + } + } +} + +static void t_pwhistory_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char base[512]; + char path[1024]; + mcp_buf b; + mcp_buf findings; + struct pwh_state st; + int count = 0; + int first = 1; + int files = 0; + size_t bl; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) >= sizeof(base) - 2) { + mcp_reply_error(c, "root path too long"); + return; + } + snprintf(base, sizeof(base), "%s", root); + bl = strlen(base); + while (bl > 0 && base[bl - 1] == '/') + base[--bl] = '\0'; + memset(&st, 0, sizeof(st)); + st.remember = -1; + mcp_buf_init(&findings); + + snprintf(path, sizeof(path), "%s/etc/security/pwhistory.conf", base); + { + struct stat sb; + + if (stat(path, &sb) == 0) + files++; + } + pwh_scan_conf(&findings, &first, &count, path, &st); + snprintf(path, sizeof(path), "%s/etc/security/sepermit.conf", base); + { + struct stat sb; + + if (stat(path, &sb) == 0) + files++; + } + pwh_scan_sepermit(&findings, &first, &count, path, &st); + + if (files == 0) { + add_finding(&findings, &first, "no-config", "info", + "neither pwhistory.conf nor sepermit.conf is " + "present"); + count = 1; + } else if (count == 0) { + add_finding(&findings, &first, "no-findings", "info", + "the password history and sepermit files are " + "tight"); + count = 1; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, base); + mcp_buf_printf(&b, ",\"files\":%d,\"remember\":%d," + "\"enforce_for_root\":%s,\"use_authtok\":%s," + "\"separator_rules\":%d,\"separator_unconfined\":%d," + "\"findings_count\":%d,\"findings\":[", + files, st.remember, st.enforce_root ? "true" : "false", + st.use_authtok ? "true" : "false", + st.sepermit_rules, st.sepermit_unconfined, 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); +} + +/* ----------------------------------------------------------- firewalld_audit */ + +/* firewalld.conf is INI; the zone XML files carry one with a and any + * number of /// children. A zone whose + * target is ACCEPT or whose file holds permits everything that lands + * in it, and a zone with no source and no interface binding is in force + * nowhere - it looks configured and protects nothing. DefaultZone decides + * which one a new interface lands in. */ +struct fwd_state { + int conf_files; + int zone_files; + int panic; + int cleanup_off; + int accept_target; + int unbound_zones; +}; + +static int fwd_bool(const char *text, const char *key, int *present) +{ + const char *p = text; + + *present = 0; + while (p != NULL && *p != '\0') { + const char *eol = strchr(p, '\n'); + size_t len = eol != NULL ? (size_t)(eol - p) : strlen(p); + char line[512]; + char *eq; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + p = eol != NULL ? eol + 1 : NULL; + if (line[0] == '#' || line[0] == '\n') + continue; + eq = strchr(line, '='); + if (eq == NULL) + continue; + *eq = '\0'; + trim_eol(line); + if (strcasecmp(line, key) != 0) + continue; + *present = 1; + eq++; + while (*eq == ' ' || *eq == '\t') + eq++; + trim_eol(eq); + return strcasecmp(eq, "yes") == 0 || strcmp(eq, "True") == 0 || + strcmp(eq, "true") == 0; + } + return 0; +} + +static int fwd_conf_string(const char *text, const char *key, + char *out, size_t n) +{ + const char *p = text; + + out[0] = '\0'; + while (p != NULL && *p != '\0') { + const char *eol = strchr(p, '\n'); + size_t len = eol != NULL ? (size_t)(eol - p) : strlen(p); + char line[512]; + char *eq; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + p = eol != NULL ? eol + 1 : NULL; + if (line[0] == '#') + continue; + eq = strchr(line, '='); + if (eq == NULL) + continue; + *eq = '\0'; + trim_eol(line); + if (strcasecmp(line, key) != 0) + continue; + eq++; + while (*eq == ' ' || *eq == '\t') + eq++; + trim_eol(eq); + snprintf(out, n, "%s", eq); + return 1; + } + return 0; +} + +static void fwd_scan_conf(mcp_buf *findings, int *first, int *count, + const char *path, struct fwd_state *st) +{ + static char text[65536]; + struct stat sb; + char zone[128]; + int present; + + if (read_text(path, text, sizeof(text)) < 0) + return; + st->conf_files++; + if (stat(path, &sb) == 0 && (sb.st_mode & 0002) != 0) { + add_finding(findings, first, "world-writable", "high", + "%s is writable by anyone", path); + (*count)++; + } + if (fwd_bool(text, "PanicMode", &present) && present) { + st->panic = 1; + add_finding(findings, first, "panic-mode", "medium", + "%s enables PanicMode: every packet is dropped, " + "which is permanent once it survives a reboot", + path); + (*count)++; + } + if (fwd_bool(text, "CleanupOnExit", &present) == 0 && present == 1) { + st->cleanup_off = 1; + add_finding(findings, first, "cleanup-off", "low", + "%s sets CleanupOnExit=no: runtime rules survive a " + "firewalld restart", path); + (*count)++; + } + if (fwd_conf_string(text, "DefaultZone", zone, sizeof(zone))) { + if (strcmp(zone, "trusted") == 0) { + add_finding(findings, first, "default-trusted", "high", + "%s makes every new interface land in the " + "trusted zone", path); + (*count)++; + } else if (strcmp(zone, "block") == 0 || + strcmp(zone, "drop") == 0) { + add_finding(findings, first, "default-blocking", "low", + "%s defaults to the %s zone, which drops " + "traffic before any allow rule", path, zone); + (*count)++; + } + } +} + +/* The zone name is the file name without .xml; the attributes that matter are + * one and whether any source/interface binds the zone. */ +static int fwd_attr(const char *text, const char *tag, char *out, size_t n) +{ + char open_tag[64]; + const char *p; + + out[0] = '\0'; + snprintf(open_tag, sizeof(open_tag), "<%s ", tag); + p = strstr(text, open_tag); + if (p == NULL) { + snprintf(open_tag, sizeof(open_tag), "<%s/>", tag); + if (strstr(text, open_tag) != NULL) { + out[0] = '\0'; + return 1; + } + return 0; + } + p = strchr(p, '>'); + if (p == NULL) + return 0; + p++; + { + const char *end = strstr(p, "<"); + + if (end == NULL) + return 0; + if ((size_t)(end - p) >= n) + return 0; + memcpy(out, p, (size_t)(end - p)); + out[end - p] = '\0'; + trim_eol(out); + } + return 1; +} + +static void fwd_scan_zone(mcp_buf *findings, int *first, int *count, + const char *path, const char *zone, + struct fwd_state *st) +{ + static char text[65536]; + struct stat sb; + char target[64]; + int has_source; + int has_iface; + + if (read_text(path, text, sizeof(text)) < 0) + return; + st->zone_files++; + if (stat(path, &sb) == 0 && (sb.st_mode & 0002) != 0) { + add_finding(findings, first, "world-writable", "high", + "%s is writable by anyone", path); + (*count)++; + } + has_source = strstr(text, "") != NULL; + has_iface = strstr(text, "") != NULL; + /* firewalld writes the target either as ACCEPT or as + * a self-closing attribute element; both forms mean the same. */ + target[0] = '\0'; + { + const char *tp = strstr(text, ""); + + if (tp != NULL) { + const char *te; + + tp += 8; + te = strstr(tp, ""); + if (te != NULL && (size_t)(te - tp) < sizeof(target)) { + memcpy(target, tp, (size_t)(te - tp)); + target[te - tp] = '\0'; + trim_eol(target); + } + } + if (target[0] == '\0') + fwd_attr(text, "target", target, sizeof(target)); + } + if (strcmp(target, "ACCEPT") == 0) { + st->accept_target = 1; + add_finding(findings, first, "accept-target", "high", + "zone %s (%s) has target ACCEPT: every packet in it " + "is accepted", zone, path); + (*count)++; + } + if (strstr(text, "") != NULL) { + st->accept_target = 1; + add_finding(findings, first, "accept-rule", "high", + "zone %s (%s) contains a rich rule", + zone, path); + (*count)++; + } + if (!has_source && !has_iface) { + st->unbound_zones++; + add_finding(findings, first, "unbound-zone", "low", + "zone %s (%s) names no source and no interface, " + "so nothing is ever placed in it", zone, path); + (*count)++; + } +} + +static void fwd_scan_zones(mcp_buf *findings, int *first, int *count, + const char *dir, struct fwd_state *st) +{ + DIR *d = opendir(dir); + struct dirent *ent; + + if (d == NULL) + return; + while ((ent = readdir(d)) != NULL) { + char path[1024]; + size_t n; + char zone[128]; + + n = strlen(ent->d_name); + if (n < 5 || strcmp(ent->d_name + n - 4, ".xml") != 0) + continue; + if ((size_t)snprintf(path, sizeof(path), "%.800s/%.160s", dir, + ent->d_name) >= sizeof(path)) + continue; + snprintf(zone, sizeof(zone), "%.100s", ent->d_name); + zone[n - 4] = '\0'; + fwd_scan_zone(findings, first, count, path, zone, st); + } + closedir(d); +} + +static void t_firewalld_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char base[512]; + char path[1024]; + mcp_buf b; + mcp_buf findings; + struct fwd_state st; + int count = 0; + int first = 1; + size_t bl; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) >= sizeof(base) - 2) { + mcp_reply_error(c, "root path too long"); + return; + } + snprintf(base, sizeof(base), "%s", root); + bl = strlen(base); + while (bl > 0 && base[bl - 1] == '/') + base[--bl] = '\0'; + memset(&st, 0, sizeof(st)); + mcp_buf_init(&findings); + + snprintf(path, sizeof(path), "%s/etc/firewalld/firewalld.conf", base); + fwd_scan_conf(&findings, &first, &count, path, &st); + snprintf(path, sizeof(path), "%s/etc/firewalld/zones", base); + fwd_scan_zones(&findings, &first, &count, path, &st); + + if (st.conf_files == 0 && st.zone_files == 0) { + add_finding(&findings, &first, "no-config", "info", + "no firewalld configuration found"); + count = 1; + } else if (count == 0) { + add_finding(&findings, &first, "no-findings", "info", + "the firewalld configuration carries no weak zone"); + count = 1; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, base); + mcp_buf_printf(&b, ",\"conf_files\":%d,\"zone_files\":%d," + "\"panic_mode\":%s,\"cleanup_off\":%s," + "\"accept_target\":%s,\"unbound_zones\":%d," + "\"findings_count\":%d,\"findings\":[", + st.conf_files, st.zone_files, + st.panic ? "true" : "false", + st.cleanup_off ? "true" : "false", + st.accept_target ? "true" : "false", + st.unbound_zones, 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, " @@ -33899,6 +34801,31 @@ const mcp_tool TOOLS_BLUE[] = { "{\"type\":\"object\",\"properties\":{" "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", t_amavis_audit }, + { "pam_restrict_audit", + "Parse /etc/security/group.conf and time.conf (root prefix): a rule " + "with an empty service field that never applies, a time list that is " + "not day+HHMM-HHMM, a group.conf rule for a group that /etc/group " + "does not list, a wildcard group field and a time rule with \"*\" in " + "every field. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_pam_restrict_audit }, + { "pwhistory_audit", + "Parse /etc/security/pwhistory.conf and sepermit.conf (root prefix): " + "remember missing, zero or below 5, enforce_for_root off, use_authtok " + "missing and a sepermit separator line that names no group. " + "Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_pwhistory_audit }, + { "firewalld_audit", + "Parse /etc/firewalld (root prefix): PanicMode or CleanupOnExit set, " + "DefaultZone trusted or blocking, a zone whose target is ACCEPT or " + "that holds a rich rule, and a zone with neither source nor " + "interface. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_firewalld_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 779d3ae..f821468 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -10631,6 +10631,201 @@ static void t_bitbucket_probe(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ------------------------------------------------------------ cassandra_probe */ + +/* Cassandra speaks the CQL native protocol on 9042: a plain frame header + * (version, flags, stream, opcode, length) with no handshake before it. OPCODE + * 5 is OPTIONS and answers with SUPPORTED (6), which needs no authentication + * and therefore proves the port speaks CQL even on a locked-down node. When + * the authenticator is not set, a STARTUP (1) for CQL_VERSION=3.0.0 is + * answered with READY (2) and the cluster accepts queries from anyone; + * Cassandra 4 answers with ERROR 0x2200 "Required auth" only when an + * authenticator is configured. */ +static void cassandra_frame(unsigned char *out, unsigned char opcode, + int stream, const char *body, size_t body_len) +{ + out[0] = 0x04; + out[1] = 0x00; + out[2] = (unsigned char)((stream >> 8) & 0xFF); + out[3] = (unsigned char)(stream & 0xFF); + out[4] = opcode; + out[5] = (unsigned char)((body_len >> 24) & 0xFF); + out[6] = (unsigned char)((body_len >> 16) & 0xFF); + out[7] = (unsigned char)((body_len >> 8) & 0xFF); + out[8] = (unsigned char)(body_len & 0xFF); + if (body_len > 0) + memcpy(out + 9, body, body_len); +} + +/* One reply: header into hdr, body into buf. Returns the opcode or -1. */ +static int cassandra_read(int fd, unsigned char *hdr, unsigned char *buf, + size_t cap, size_t *got) +{ + size_t len; + size_t done = 0; + + *got = 0; + if (apex_net_exact(fd, hdr, 9) != 0) + return -1; + len = ((size_t)hdr[5] << 24) | ((size_t)hdr[6] << 16) | + ((size_t)hdr[7] << 8) | (size_t)hdr[8]; + if (len > cap) + return -1; + while (done < len) { + int r = (int)read(fd, buf + done, len - done); + + if (r <= 0) + return -1; + done += (size_t)r; + } + *got = len; + return hdr[4]; +} + +/* A SUPPORTED body is a [string map]: two-byte count, then key/value pairs of + * [short] length + bytes. The "CQL_VERSION" value is what we report. */ +static void cassandra_supported(const unsigned char *buf, size_t len, + char *cqlver, size_t n) +{ + size_t p = 0; + unsigned count; + unsigned i; + + cqlver[0] = '\0'; + if (len < 2) + return; + count = ((unsigned)buf[0] << 8) | buf[1]; + p = 2; + for (i = 0; i < count && p + 2 <= len; i++) { + unsigned klen = ((unsigned)buf[p] << 8) | buf[p + 1]; + const char *key; + unsigned vlen; + const char *val; + + p += 2; + if (klen == 0 || p + klen > len) + break; + key = (const char *)(buf + p); + p += klen; + if (p + 2 > len) + break; + vlen = ((unsigned)buf[p] << 8) | buf[p + 1]; + p += 2; + if (p + vlen > len) + break; + val = (const char *)(buf + p); + p += vlen; + if (klen == 11 && memcmp(key, "CQL_VERSION", 11) == 0 && + vlen < n) { + memcpy(cqlver, val, vlen); + cqlver[vlen] = '\0'; + } + } +} + +/* An ERROR body is [int code][string message]. Cassandra 4 puts "Required auth" + * into the message when an authenticator is configured. */ +static int cassandra_error_is_auth(const unsigned char *buf, size_t len) +{ + unsigned mlen; + const char *msg; + + if (len < 6) + return 0; + mlen = ((unsigned)buf[4] << 8) | buf[5]; + if (mlen == 0 || 6 + (size_t)mlen > len) + return 0; + msg = (const char *)(buf + 6); + if (strstr(msg, "Required auth") != NULL) + return 1; + if (strstr(msg, "authenticator") != NULL) + return 1; + return 0; +} + +static void t_cassandra_probe(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + int port = mcp_arg_int(args, "port", 9042); + unsigned char frame[256]; + unsigned char hdr[9]; + unsigned char body[65536]; + size_t got = 0; + char cqlver[64]; + int fd; + int speaks_cql = 0; + int auth_required = -1; + int ready = 0; + int opcode; + mcp_buf b; + + (void)user; + if (target == NULL || *target == '\0') { + mcp_reply_error(c, "target is required"); + return; + } + if (port <= 0 || port > 65535) { + mcp_reply_error(c, "port out of range"); + return; + } + if (!gated(c, "cassandra_probe", target, port)) + return; + fd = tcp_connect_host(target, port, 6000); + if (fd < 0) { + mcp_reply_error(c, "cannot connect to the Cassandra service"); + return; + } + cqlver[0] = '\0'; + cassandra_frame(frame, 5, 1, NULL, 0); + if (write(fd, frame, 9) == 9 && + (opcode = cassandra_read(fd, hdr, body, sizeof(body), &got)) == 6) { + speaks_cql = 1; + cassandra_supported(body, got, cqlver, sizeof(cqlver)); + } + if (speaks_cql) { + static const char startup[] = "\x00\x0b" "CQL_VERSION" "\x00\x05" + "3.0.0"; + size_t sl = sizeof(startup) - 1; + + cassandra_frame(frame, 1, 2, startup, sl); + if (write(fd, frame, 9 + sl) == (ssize_t)(9 + sl)) { + opcode = cassandra_read(fd, hdr, body, sizeof(body), &got); + if (opcode == 2) { + ready = 1; + auth_required = 0; + } else if (opcode == 0 && + cassandra_error_is_auth(body, got)) { + auth_required = 1; + } + } + } + close(fd); + + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"cql\":%s,\"cql_version\":", + port, speaks_cql ? "true" : "false"); + if (cqlver[0] != '\0') + apex_json_str(&b, cqlver); + else + mcp_buf_puts(&b, "null"); + mcp_buf_printf(&b, ",\"open\":%s,\"auth_required\":", + ready ? "true" : "false"); + if (auth_required < 0) + mcp_buf_puts(&b, "null"); + else + mcp_buf_puts(&b, auth_required ? "true" : "false"); + mcp_buf_puts(&b, "}"); + apex_audit("cassandra_probe", target, port, !ready, + ready ? "the CQL native protocol answers STARTUP without " + "authentication" + : "the CQL native protocol requires authentication", + "startup"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + const mcp_tool TOOLS_RED[] = { { "vuln_check", "Non-destructive verification of exposed artifacts on one web target: " @@ -11648,6 +11843,16 @@ const mcp_tool TOOLS_RED[] = { "\"tls\":{\"type\":\"boolean\"}}," "\"required\":[\"target\"]}", t_jupyter_probe }, + { "cassandra_probe", + "Speak the CQL native protocol to 9042: OPTIONS for SUPPORTED, then " + "STARTUP. A READY answer means the cluster accepts queries without " + "authentication; an ERROR carrying \"Required auth\" means an " + "authenticator is set. Read-only, no query is sent.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 9042\"}}," + "\"required\":[\"target\"]}", + t_cassandra_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 aec9ae9..ce14a1e 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 = 410 +EXPECTED_TOOLS = 414 GATE = ("gated(", "gated_cmd(", "gated_run(", "apex_scope_check(") # Handlers may hand argv to a shared runner instead of calling the gate # themselves. That runner has to call the gate; both halves are checked diff --git a/tests/run.py b/tests/run.py index 324ef3f..b8ce23a 100755 --- a/tests/run.py +++ b/tests/run.py @@ -18,6 +18,7 @@ import select import shutil import signal import socket +import socketserver import ssl import struct import subprocess @@ -134,7 +135,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("410 tools registered", len(tools) == 410, len(tools)) +check("414 tools registered", len(tools) == 414, 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 +1561,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"]) == 410) + check("http tools/list", len(listing["result"]["tools"]) == 414) 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 @@ -14851,6 +14852,286 @@ 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) + +# --- 1.96.0: PAM restriction, pwhistory and firewalld audits plus Cassandra --- +print("\n== PAM restrictions, pwhistory, firewalld and Cassandra ==") +pamr_root = tempfile.mkdtemp(prefix="apex-pamr-") +os.makedirs(os.path.join(pamr_root, "etc", "security")) +with open(os.path.join(pamr_root, "etc", "group"), "w") as f: + f.write("root:x:0:\n") + f.write("wheel:x:10:\n") +pamr_group = os.path.join(pamr_root, "etc", "security", "group.conf") +with open(pamr_group, "w") as f: + f.write("login;tty*;*;Al0000-2400;wheel\n") + f.write(";tty*;*;Al0000-2400;nosuchgroup\n") + f.write("su;tty*;*;Al0000-2400;*\n") + f.write("sshd;tty*;*\n") +os.chmod(pamr_group, 0o666) +with open(os.path.join(pamr_root, "etc", "security", "time.conf"), "w") as f: + f.write("login;tty*;!root;!Al0000-2400\n") + f.write(";tty*;*;Al0000-2400\n") + f.write("games;*;*;*\n") + f.write("su;tty*;*;Mo2500-9900\n") + +pamr_good_root = tempfile.mkdtemp(prefix="apex-pamrg-") +os.makedirs(os.path.join(pamr_good_root, "etc", "security")) +with open(os.path.join(pamr_good_root, "etc", "group"), "w") as f: + f.write("wheel:x:10:\n") +with open(os.path.join(pamr_good_root, "etc", "security", "group.conf"), + "w") as f: + f.write("login;tty*;*;Al0000-2400;wheel\n") +with open(os.path.join(pamr_good_root, "etc", "security", "time.conf"), + "w") as f: + f.write("login;tty*;!root;!Al0000-2400\n") + +pwh_root = tempfile.mkdtemp(prefix="apex-pwh-") +os.makedirs(os.path.join(pwh_root, "etc", "security")) +pwh_conf = os.path.join(pwh_root, "etc", "security", "pwhistory.conf") +with open(pwh_conf, "w") as f: + f.write("# history\n") + f.write("remember = 0\n") + f.write("use_authtok\n") +with open(os.path.join(pwh_root, "etc", "security", "sepermit.conf"), + "w") as f: + f.write(":\n") + f.write("wheel:admin\n") + +pwh_good_root = tempfile.mkdtemp(prefix="apex-pwhg-") +os.makedirs(os.path.join(pwh_good_root, "etc", "security")) +with open(os.path.join(pwh_good_root, "etc", "security", "pwhistory.conf"), + "w") as f: + f.write("remember = 12\n") + f.write("enforce_for_root = yes\n") + f.write("use_authtok = yes\n") +with open(os.path.join(pwh_good_root, "etc", "security", "sepermit.conf"), + "w") as f: + f.write("wheel:admin\n") + +fwd_root = tempfile.mkdtemp(prefix="apex-fwd-") +os.makedirs(os.path.join(fwd_root, "etc", "firewalld", "zones")) +fwd_conf = os.path.join(fwd_root, "etc", "firewalld", "firewalld.conf") +with open(fwd_conf, "w") as f: + f.write("DefaultZone=trusted\n") + f.write("PanicMode=yes\n") + f.write("CleanupOnExit=no\n") +os.chmod(fwd_conf, 0o666) +with open(os.path.join(fwd_root, "etc", "firewalld", "zones", + "public.xml"), "w") as f: + f.write("\n\n") + f.write(" ACCEPT\n\n") +with open(os.path.join(fwd_root, "etc", "firewalld", "zones", + "dmz.xml"), "w") as f: + f.write("\n\n") + f.write(" \n\n") + +fwd_good_root = tempfile.mkdtemp(prefix="apex-fwdg-") +os.makedirs(os.path.join(fwd_good_root, "etc", "firewalld", "zones")) +with open(os.path.join(fwd_good_root, "etc", "firewalld", + "firewalld.conf"), "w") as f: + f.write("DefaultZone=public\n") + f.write("PanicMode=no\n") + f.write("CleanupOnExit=yes\n") +with open(os.path.join(fwd_good_root, "etc", "firewalld", "zones", + "public.xml"), "w") as f: + f.write("\n\n") + f.write(" \n") + f.write(" default\n\n") + +cfg45_home = tempfile.mkdtemp(prefix="apex-cfg45-home-") +write_scope(cfg45_home, + {"label": "cfg45", "expires": "2099-01-01T00:00:00Z", + "allow_port": ["1-65535"], "allow_ip": ["127.0.0.1/32"], + "allow_private": True}) + +res, _ = run([ + call(1, "pam_restrict_audit", root=pamr_root), + call(2, "pam_restrict_audit", root=pamr_good_root), + call(3, "pwhistory_audit", root=pwh_root), + call(4, "pwhistory_audit", root=pwh_good_root), + call(5, "firewalld_audit", root=fwd_root), + call(6, "firewalld_audit", root=fwd_good_root), +], home=cfg45_home) +by_id = {r["id"]: r for r in res if "id" in r} +pamr = json.loads(text(by_id[1])) +pamr_kinds = {f["id"] for f in pamr["findings"]} +check("pam_restrict_audit flags a dead rule, an unknown group, a wildcard " + "and a bad time list", + {"dead-rule", "unknown-group", "wildcard-groups", "bad-times"} <= + pamr_kinds and pamr["group_lines"] == 4 and pamr["time_lines"] == 4, + pamr) +pamr_good = json.loads(text(by_id[2])) +check("pam_restrict_audit accepts a single tight rule per file", + pamr_good["findings_count"] == 1 and + pamr_good["findings"][0]["id"] == "no-findings", pamr_good) +pwh = json.loads(text(by_id[3])) +pwh_kinds = {f["id"] for f in pwh["findings"]} +check("pwhistory_audit flags remember 0, no root enforcement and a bare " + "separator", + {"no-remember", "no-root-enforce", "separator-unconfined"} <= + pwh_kinds and pwh["remember"] == 0 and + pwh["separator_unconfined"] == 1, pwh) +pwh_good = json.loads(text(by_id[4])) +check("pwhistory_audit accepts remember 12 with root enforcement", + pwh_good["remember"] == 12 and pwh_good["enforce_for_root"] is True and + pwh_good["use_authtok"] is True and pwh_good["findings_count"] == 1, + pwh_good) +fwd = json.loads(text(by_id[5])) +fwd_kinds = {f["id"] for f in fwd["findings"]} +check("firewalld_audit flags panic mode, cleanup off, a trusted default " + "and an ACCEPT target", + {"panic-mode", "cleanup-off", "default-trusted", "accept-target"} <= + fwd_kinds and fwd["conf_files"] == 1 and fwd["zone_files"] == 2, + fwd) +fwd_good = json.loads(text(by_id[6])) +check("firewalld_audit accepts a bound zone with the default target", + fwd_good["panic_mode"] is False and + fwd_good["accept_target"] is False and fwd_good["findings_count"] == 1, + fwd_good) + +# An unbound zone is reported on its own. +fwd_unbound = tempfile.mkdtemp(prefix="apex-fwdu-") +os.makedirs(os.path.join(fwd_unbound, "etc", "firewalld", "zones")) +with open(os.path.join(fwd_unbound, "etc", "firewalld", "zones", + "internal.xml"), "w") as f: + f.write("\n \n\n") +res, _ = run([call(1, "firewalld_audit", root=fwd_unbound)], home=cfg45_home) +by_id = {r["id"]: r for r in res if "id" in r} +fwdu = json.loads(text(by_id[1])) +check("firewalld_audit flags a zone with no source and no interface", + fwdu["unbound_zones"] == 1 and + any(f["id"] == "unbound-zone" for f in fwdu["findings"]), fwdu) +shutil.rmtree(fwd_unbound, ignore_errors=True) + + +# --- Cassandra: a fake CQL endpoint that speaks SUPPORTED, READY or ERROR --- +def _cql_frame(opcode, stream, body): + return bytes([4, 0, (stream >> 8) & 0xFF, stream & 0xFF, opcode, + (len(body) >> 24) & 0xFF, (len(body) >> 16) & 0xFF, + (len(body) >> 8) & 0xFF, len(body) & 0xFF]) + body + + +def _cql_str(s): + raw = s.encode() + return bytes([(len(raw) >> 8) & 0xFF, len(raw) & 0xFF]) + raw + + +_CQL_SUPPORTED = _cql_frame(6, 1, bytes([0, 1]) + _cql_str("CQL_VERSION") + + _cql_str("3.0.0")) + + +class _CassandraHandler(socketserver.BaseRequestHandler): + def handle(self): + self.request.settimeout(3.0) + try: + head = self.request.recv(9) + if len(head) < 9: + return + blen = ((head[5] << 24) | (head[6] << 16) | (head[7] << 8) | + head[8]) + body = b"" + while len(body) < blen: + chunk = self.request.recv(blen - len(body)) + if not chunk: + break + body += chunk + if head[4] == 5: + self.request.sendall(_CQL_SUPPORTED) + again = self.request.recv(9) + if len(again) < 9: + return + blen = ((again[5] << 24) | (again[6] << 16) | + (again[7] << 8) | again[8]) + rest = b"" + while len(rest) < blen: + chunk = self.request.recv(blen - len(rest)) + if not chunk: + break + rest += chunk + if again[4] == 1: + self.request.sendall(_cql_frame(2, 2, b"")) + elif head[4] == 1: + self.request.sendall(_cql_frame(2, 2, b"")) + except (OSError, ValueError): + return + + +class _CassandraAuthHandler(socketserver.BaseRequestHandler): + def handle(self): + self.request.settimeout(3.0) + try: + head = self.request.recv(9) + if len(head) < 9: + return + blen = ((head[5] << 24) | (head[6] << 16) | (head[7] << 8) | + head[8]) + body = b"" + while len(body) < blen: + chunk = self.request.recv(blen - len(body)) + if not chunk: + break + body += chunk + if head[4] == 5: + self.request.sendall(_CQL_SUPPORTED) + again = self.request.recv(9) + if len(again) < 9: + return + blen = ((again[5] << 24) | (again[6] << 16) | + (again[7] << 8) | again[8]) + rest = b"" + while len(rest) < blen: + chunk = self.request.recv(blen - len(rest)) + if not chunk: + break + rest += chunk + if again[4] == 1: + msg = _cql_str("PasswordAuthenticator: Required auth") + err = bytes([0, 0, 0x22, 0x00]) + msg + self.request.sendall(_cql_frame(0, 2, err)) + elif head[4] == 1: + msg = _cql_str("Required auth") + err = bytes([0, 0, 0x22, 0x00]) + msg + self.request.sendall(_cql_frame(0, 2, err)) + except (OSError, ValueError): + return + + +class _CassandraThread(socketserver.ThreadingTCPServer): + allow_reuse_address = True + daemon_threads = True + + +cql_open = _CassandraThread(("127.0.0.1", 0), _CassandraHandler) +cql_open_port = cql_open.server_address[1] +threading.Thread(target=cql_open.serve_forever, daemon=True).start() +cql_auth = _CassandraThread(("127.0.0.1", 0), _CassandraAuthHandler) +cql_auth_port = cql_auth.server_address[1] +threading.Thread(target=cql_auth.serve_forever, daemon=True).start() + +res, _ = run([ + call(1, "cassandra_probe", target="127.0.0.1", port=cql_open_port), + call(2, "cassandra_probe", target="127.0.0.1", port=cql_auth_port), +], home=cfg45_home) +by_id = {r["id"]: r for r in res if "id" in r} +cql_o = json.loads(text(by_id[1])) +check("cassandra_probe finds an open CQL endpoint and its version", + cql_o["cql"] is True and cql_o["open"] is True and + cql_o["auth_required"] is False and cql_o["cql_version"] == "3.0.0", + cql_o) +cql_a = json.loads(text(by_id[2])) +check("cassandra_probe reports a CQL endpoint that demands authentication", + cql_a["cql"] is True and cql_a["open"] is False and + cql_a["auth_required"] is True, cql_a) +cql_open.shutdown() +cql_auth.shutdown() + +shutil.rmtree(pamr_root, ignore_errors=True) +shutil.rmtree(pamr_good_root, ignore_errors=True) +shutil.rmtree(pwh_root, ignore_errors=True) +shutil.rmtree(pwh_good_root, ignore_errors=True) +shutil.rmtree(fwd_root, ignore_errors=True) +shutil.rmtree(fwd_good_root, ignore_errors=True) +shutil.rmtree(cfg45_home, ignore_errors=True) + print("\n== esp32 tools ==") esp_home = tempfile.mkdtemp(prefix="apex-esp-")