From 759d9f8351f5ae68be04afbad616f39583507c94 Mon Sep 17 00:00:00 2001 From: lotherk Date: Tue, 24 Nov 2026 02:58:17 +0000 Subject: [PATCH] apex-twin 1.99.0: hydra, medusa and msfvenom wrappers Three gated wrappers in tools_ext.c. hydra_scan and medusa_scan name a target and go through gated_run(); msfvenom_build has no target, runs locally and writes an audit line before the action. Flag sets read from the tools' own sources (hydra.1 in the thc repo, Debian medusa(1), the msfvenom opt list), not remembered. A hit is the tool's verdict, not ours: medusa documents exit 1/2 as FOUND_PAIR_EXIT_HOST/_AUDIT, hydra returns 0 either way and prints the hit, so each wrapper parses its tool's own output and records it as evidence. A run that finds nothing writes no finding. Refused on purpose: hydra -M, medusa -H/-C and the host-file options read targets out of a file the gate never parsed; msfvenom -l/--list/--help/ --refresh-cache print and exit without rendering a payload. The --list hole was found by a test, not by review. Test evidence: 1600/1600 (was 1576); tools_ext.c line coverage 80.9 -> 83.8, total 84.8%. Red proof, both directions: forcing hydra_found to return 0 turns exactly "hydra_scan reads the tool's own 'valid password found' as a hit" red with 32 green; putting -M/-H/-C back on the allowlists turns exactly the three host-file checks red with 37 green; restored, 40/40. Full release-check exit 0, distcheck apex-twin-1.99.0 builds and passes 1600/1600 from the tarball. --- CHANGELOG.md | 26 ++ README.md | 23 +- SECURITY.md | 2 +- docs/apex-twin.1 | 5 +- src/apex.h | 2 +- src/tools_ext.c | 588 +++++++++++++++++++++++++++++++++++++++++++- src/tools_recon.c | 2 +- tests/gate_audit.py | 13 +- tests/run.py | 143 ++++++++++- 9 files changed, 780 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6474257..fff0f75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,31 @@ # Changelog +## 1.99.0 - 2026-11-24 - this change + +- **hydra, medusa and msfvenom get gated wrappers** (`hydra_scan`, + `medusa_scan`, `msfvenom_build`). hydra and medusa name a target and go + through `gated_run()` like every other wrapper; msfvenom has no target, so it + runs locally and writes an audit line before the action. Flag sets were read + from the tools' own sources, not remembered: `hydra.1` in the thc repo, the + Debian `medusa(1)` page and the `msfvenom` option list. +- **A hit is the tool's verdict, not ours.** medusa documents exit 1/2 as + `FOUND_PAIR_EXIT_HOST`/`_AUDIT`, hydra returns 0 either way and prints the + hit. So the wrapper parses each tool's own output (`valid password found`, + `[SUCCESS]`), records the raw output as evidence and writes a finding with + it. A run that finds nothing writes no finding. +- **Three flags are refused because they would hide a target from the gate**: + hydra `-M`, medusa `-H`/`-C` and the host-file options read their targets + out of a file the gate never parsed, so the gate would check one host while + the tool walks another. They stay out until the file is parsed and each + entry checked. +- **msfvenom's mode switches are refused** (`-l`/`--list`, `--list-options`, + `-h`/`--help`, `--refresh-cache`). They print and exit without rendering + anything, and the tool would have reported a payload it never built. Found + by a test, not by review: `extra: ["--list"]` was accepted. +- Relative output paths are refused; the operator's absolute + path is passed through unchanged. +- Checks: 1600 (was 1576). Tools: 423 (was 420). + ## 1.98.0 - 2026-11-24 - this change - **Three more modules** in the exploit registry: `weblogic_console` diff --git a/README.md b/README.md index 777291a..4c04658 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. -**420 tools · 1576 end-to-end checks · 240 fuzz cases · 84.8% line coverage · ~1402 KiB** +**423 tools · 1600 end-to-end checks · 240 fuzz cases · 84.8% line coverage · ~1402 KiB** ``` $ ./apex-twin --check -{"version":"1.98.0","tools":420,...,"scope":{"loaded":true,...}} +{"version":"1.99.0","tools":423,...,"scope":{"loaded":true,...}} ``` APEX TWIN was inspired by [ARTEX](https://github.com/Autumn-27/artex) (scope @@ -156,7 +156,7 @@ closes a request whose head or body does not arrive within --- -## Tools (420) +## Tools (423) ### Scope and bookkeeping @@ -409,6 +409,9 @@ operator decides everything else. | `ffuf_scan` | Content discovery with a wordlist the operator already has | | `gobuster_scan` | Directory, DNS or vhost brute force with an existing wordlist | | `sqlmap_scan` | SQL injection verification in `--batch`; no shell, no file read | +| `hydra_scan` | Login testing against one in-scope service; a hit is a finding with the tool's own output as evidence | +| `medusa_scan` | Same for medusa; `[SUCCESS]` or exit 1/2 is the hit, the raw output is the evidence | +| `msfvenom_build` | Renders the operator's payload locally (no target); the bytes are saved as evidence | Every wrapper follows the same three rules: the target goes through `gated_run()` so the scope gate and the audit line happen **before** anything @@ -416,9 +419,15 @@ executes; each argument is checked against a per-tool allowlist and a flag that is not on it is refused rather than passed through; and there is no shell — argv is built in C and handed to `exec`, so no string is ever parsed by `/bin/sh`. A missing binary is a plain sentence from `apex_have()`, not exit -127 in the middle of a scan. `hydra`, `medusa` and `msfvenom` have no wrapper: -mass credential guessing and payload generation are outside what this project -does. +127 in the middle of a scan. + +Three flags are refused on purpose, and not for taste: hydra `-M`, medusa +`-H`/`-C` and hydra/medusa host files read their targets out of a file the +gate never sees, so the gate would be checking one host while the tool walks +another. Those stay out until the file is parsed and each entry checked. The +msfvenom mode switches (`-l`, `--list`, `--help`, `--refresh-cache`) are out +for a different reason: they print and exit without building anything, and the +tool would then report a payload it never rendered. ### Blue team @@ -1195,7 +1204,7 @@ examples/ scope.json ## Status -1.98.0. Built and run: 420 tools, 1576 checks, 240 fuzz cases and 84.8% line +1.99.0. Built and run: 423 tools, 1600 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 f188d1a..915c0cf 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.98.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.99.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 5e9d75b..b11b10c 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.98.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-24" "apex-twin 1.99.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS @@ -54,7 +54,8 @@ 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, cassandra_probe, -nuclei_scan, nikto_scan, ffuf_scan, gobuster_scan, sqlmap_scan), +nuclei_scan, nikto_scan, ffuf_scan, gobuster_scan, sqlmap_scan, +hydra_scan, medusa_scan, msfvenom_build), defensive audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, persistence_audit, diff --git a/src/apex.h b/src/apex.h index 64f276b..77d4f19 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.98.0" +#define APEX_VERSION "1.99.0" #define APEX_MAX_OUT (1u << 20) #define APEX_PATH_MAX 512 #define APEX_PATH_FULL 1024 diff --git a/src/tools_ext.c b/src/tools_ext.c index 25c5011..93b6954 100644 --- a/src/tools_ext.c +++ b/src/tools_ext.c @@ -25,6 +25,7 @@ #include #include #include +#include #include #include @@ -82,6 +83,49 @@ static const char *const FLAGS_SQLMAP[] = { "--no-cast", "--hex", "--forms", NULL }; +/* + * hydra and medusa: the flag sets below are the ones their own manuals + * document (thc-hydra hydra.1; medusa(1) from the Debian package). The + * operator decides what to run, so the whole documented surface is here - + * except the three flags that name hosts the gate cannot see, because they are + * read out of a file after the check has already happened: + * + * hydra -M FILE server list for parallel attacks + * medusa -H FILE target hosts from a file + * medusa -C FILE combo entries, host:user:password + * + * A host that comes out of a file never passed apex_scope_check(), so these + * are refused by omission. Everything else reaches the process unchanged, and + * there is no shell, so a value can never become a second command. + */ +static const char *const FLAGS_HYDRA[] = { + "-l", "-L", "-p", "-P", "-C", "-e", "-u", "-f", "-F", "-o", + "-b", "-t", "-T", "-w", "-W", "-m", "-s", "-S", "-O", "-x", "-y", + "-4", "-6", "-v", "-V", "-d", "-I", "-R", "-h", "--help", NULL +}; + +static const char *const FLAGS_MEDUSA[] = { + "-h", "-u", "-U", "-p", "-P", "-O", "-e", "-M", "-m", + "-d", "-n", "-s", "-g", "-r", "-R", "-c", "-t", "-T", "-L", "-f", + "-F", "-b", "-q", "-v", "-w", "-V", "-Z", NULL +}; + +/* msfvenom build options, from the msfvenom script's own opt.on() list. + * The mode switches (-l/--list, --list-options, -h/--help, --refresh-cache) + * are left out: they make msfvenom print and exit without rendering the + * payload, and this tool's answer would then claim a payload it never built. + * Every option that shapes the output is here. */ +static const char *const FLAGS_MSFVENOM[] = { + "-p", "--payload", "-f", "--format", + "-e", "--encoder", "--service-name", "--sec-name", "--smallest", + "--encrypt", "--encrypt-key", "--encrypt-iv", "-a", "--arch", + "--platform", "-o", "--out", "-b", "--bad-chars", "-n", "--nopsled", + "--pad-nops", "-s", "--space", "--encoder-space", "-i", "--iterations", + "-c", "--add-code", "-x", "--template", "-k", "--keep", "-v", + "--var-name", "-t", "--timeout", + NULL +}; + static const ext_spec EXT_SPECS[] = { { "nuclei_scan", "nuclei", FLAGS_NUCLEI, "Template scan against one in-scope URL; -jsonl output saved as " @@ -95,8 +139,15 @@ static const ext_spec EXT_SPECS[] = { { "gobuster_scan", "gobuster", FLAGS_GOBUSTER, "Directory/DNS/vhost brute force with an existing wordlist" }, { "sqlmap_scan", "sqlmap", FLAGS_SQLMAP, - "SQL injection verification in --batch mode, no shell and no file " - "read; the log is evidence" }, + "SQL injection verification in --batch mode; the log is evidence" }, + { "hydra_scan", "hydra", FLAGS_HYDRA, + "Parallel login testing against one in-scope service; a hit is a " + "finding with the output as evidence" }, + { "medusa_scan", "medusa", FLAGS_MEDUSA, + "Modular login testing against one in-scope service; [SUCCESS] or " + "exit 1/2 is the hit" }, + { "msfvenom_build", "msfvenom", FLAGS_MSFVENOM, + "Render the operator's payload with msfvenom; local, no target" }, }; /* --------------------------------------------------------------- helpers */ @@ -152,12 +203,26 @@ static int argv_allowed(const ext_spec *s, char *const argv[], char *bad, return 1; } +/* + * A tool that decides its own verdict hands it in here. The output stays the + * evidence either way; the finding is only written when the tool said so. + */ +typedef struct { + int (*hit)(const char *out, int exit_code); + const char *title; + const char *severity; + const char *cwe; + const char *remediation; + const char *tags; +} ext_verdict; + /* * Run one spec: gate, allowlist, presence check, execute, save, reply. * The argv handed in must already carry argv[0] = prog. */ -static void ext_run(mcp_conn *c, const ext_spec *s, char *const argv[], - const char *target, int port, int timeout_ms) +static void ext_runx(mcp_conn *c, const ext_spec *s, char *const argv[], + const char *target, int port, int timeout_ms, + const ext_verdict *v) { char bad[128]; apex_proc p; @@ -219,6 +284,25 @@ static void ext_run(mcp_conn *c, const ext_spec *s, char *const argv[], apex_json_str(&b, evidence); else mcp_buf_puts(&b, "null"); + if (v != NULL) { + int hit = v->hit(p.out, p.exit_code); + + mcp_buf_printf(&b, ",\"hit\":%s", hit ? "true" : "false"); + if (hit) { + char *fid = apex_finding_add(target, v->title, v->severity, + "firm", s->tool, + evidence != NULL ? evidence : "", + v->cwe, v->remediation, v->tags); + + mcp_buf_puts(&b, ",\"finding\":"); + if (fid != NULL) { + apex_json_str(&b, fid); + free(fid); + } else { + mcp_buf_puts(&b, "null"); + } + } + } mcp_buf_puts(&b, ",\"output\":"); if (p.out != NULL) apex_json_str(&b, p.out); @@ -231,6 +315,162 @@ static void ext_run(mcp_conn *c, const ext_spec *s, char *const argv[], apex_proc_free(&p); } +/* No verdict of its own: the scanner output is the answer, nothing more. */ +static void ext_run(mcp_conn *c, const ext_spec *s, char *const argv[], + const char *target, int port, int timeout_ms) +{ + ext_runx(c, s, argv, target, port, timeout_ms, NULL); +} + +/* Local programs: no target to gate, but the action is still recorded first. */ +static void ext_run_local(mcp_conn *c, const ext_spec *s, char *const argv[], + int timeout_ms, const char *note) +{ + char bad[128]; + char *cmd; + apex_proc p; + mcp_buf b; + char *evidence = NULL; + int rc; + + if (s == NULL) { + mcp_reply_error(c, "internal: no allowlist entry for this tool"); + return; + } + if (!apex_have(s->prog)) { + mcp_buf_init(&b); + mcp_buf_printf(&b, "%s is not installed on this host", s->prog); + mcp_reply_error(c, b.p); + mcp_buf_free(&b); + return; + } + if (!argv_allowed(s, argv, bad, sizeof(bad))) { + mcp_buf_init(&b); + mcp_buf_printf(&b, "argument %s is not on the allowlist for %s; " + "refused", bad, s->tool); + mcp_reply_error(c, b.p); + mcp_buf_free(&b); + return; + } + cmd = apex_join_argv(argv); + apex_audit(s->tool, "", 0, 1, note != NULL ? note : "local build", cmd); + free(cmd); + if (g_cfg.dry_run) { + mcp_reply_text(c, "DRY RUN, not executed"); + return; + } + rc = apex_run(argv, timeout_ms, g_cfg.max_output, &p); + if (rc != 0) { + mcp_reply_error(c, "cannot run the program"); + return; + } + if (p.out != NULL && p.out_len > 0) + evidence = apex_evidence_save(s->tool, p.out, p.out_len); + mcp_buf_init(&b); + mcp_buf_printf(&b, "{\"tool\":\"%s\",\"exit\":%d,\"timed_out\":%s," + "\"truncated\":%s,\"elapsed_ms\":%ld,\"bytes\":%zu,", + s->tool, p.exit_code, p.timed_out ? "true" : "false", + p.truncated ? "true" : "false", p.elapsed_ms, p.out_len); + mcp_buf_puts(&b, "\"evidence\":"); + if (evidence != NULL) + apex_json_str(&b, evidence); + else + mcp_buf_puts(&b, "null"); + mcp_buf_puts(&b, ",\"output\":"); + if (p.out != NULL) + apex_json_str(&b, p.out); + else + mcp_buf_puts(&b, "\"\""); + mcp_buf_puts(&b, "}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + free(evidence); + apex_proc_free(&p); +} + +/* ------------------------------------------------------ operator extras */ + +/* + * The "extra" array carries further tokens for the underlying program. They + * are appended verbatim and then go through argv_allowed() with everything + * else, so a flag reaches the process only if the allowlist has it. Nothing is + * filtered by hand here: one place decides, and it is the one above. + * Returns the new argc, or -1 if the array would overflow. + */ +static int ext_extra(const mcp_json *args, char *argv[], int n, int max) +{ + const mcp_json *extra = mcp_arg(args, "extra"); + size_t i; + size_t len = mcp_array_len(extra); + + for (i = 0; i < len; i++) { + const char *tok = mcp_json_string(mcp_array_at(extra, i)); + + if (tok == NULL || *tok == '\0') + continue; + if (n + 1 >= max) + return -1; + argv[n++] = (char *)tok; + } + argv[n] = NULL; + return n; +} + +/* + * The tools state a hit in their own words, so that is what is read: + * hydra ends with "N valid passwords found", medusa marks a line "[SUCCESS]" + * and exits 1 (per host) or 2 (per audit) - FOUND_PAIR_EXIT_HOST and + * FOUND_PAIR_EXIT_AUDIT in its source. Nothing is inferred past the output. + */ +static int hydra_found(const char *out, int exit_code) +{ + const char *p; + const char *q; + long count = 0; + + (void)exit_code; + if (out == NULL) + return 0; + p = strstr(out, " valid password"); + if (p == NULL) + return 0; + q = p; + while (q > out && q[-1] >= '0' && q[-1] <= '9') + q--; + if (q == p) + return 0; + while (q < p) { + count = count * 10 + (*q - '0'); + q++; + } + return count > 0; +} + +static int medusa_found(const char *out, int exit_code) +{ + if (exit_code == 1 || exit_code == 2) + return 1; + return out != NULL && strstr(out, "[SUCCESS]") != NULL; +} + +static const ext_verdict HYDRA_VERDICT = { + hydra_found, + "Credentials accepted by the service (hydra)", + "high", "CWE-521", + "Rotate every credential that answered, and remove the account or the " + "service exposure the hit proves reachable", + "credential,hydra,brute-force" +}; + +static const ext_verdict MEDUSA_VERDICT = { + medusa_found, + "Credentials accepted by the service (medusa)", + "high", "CWE-521", + "Rotate every credential that answered, and remove the account or the " + "service exposure the hit proves reachable", + "credential,medusa,brute-force" +}; + /* ------------------------------------------------------------- the tools */ static void t_nuclei_scan(mcp_conn *c, const mcp_json *args, void *user) @@ -426,6 +666,270 @@ static void t_sqlmap_scan(mcp_conn *c, const mcp_json *args, void *user) ext_run(c, spec_by_tool("sqlmap_scan"), argv, target, 0, timeout); } +/* hydra and medusa share the shape: one host, one service, one credential + * list. The service name is a positional argument in both, so it is passed + * through as a value and never as a flag. */ + +/* + * The port a service uses when the operator names none. getservbyname() reads + * /etc/services, so it is the host's answer and not a table invented here; a + * name it does not know returns 0, and then the caller passes 0 on - the + * program's own default applies and the gate still checks the host. + */ +static int apex_service_port(const char *service, int dflt) +{ + struct servent *se; + + if (service == NULL || *service == '\0') + return dflt; + se = getservbyname(service, "tcp"); + if (se == NULL) + se = getservbyname(service, NULL); + if (se == NULL) + return dflt; + return ntohs((uint16_t)se->s_port); +} + +static void t_hydra_scan(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + const char *service = mcp_arg_string(args, "service"); + const char *login = mcp_arg_string(args, "login"); + const char *password = mcp_arg_string(args, "password"); + const char *login_file = mcp_arg_string(args, "login_file"); + const char *pass_file = mcp_arg_string(args, "password_file"); + int port = mcp_arg_int(args, "port", 0); + int tasks = mcp_arg_int(args, "tasks", 16); + int timeout = mcp_arg_int(args, "timeout_ms", 900000); + char portbuf[16]; + char taskbuf[16]; + char *argv[40]; + int n = 0; + + (void)user; + if (target == NULL || *target == '\0') { + mcp_reply_error(c, "target is required"); + return; + } + if (service == NULL || *service == '\0') { + mcp_reply_error(c, "service is required, e.g. ssh, ftp, smb, " + "http-get, rdp, mysql, postgres, vnc, telnet, " + "imap, pop3, smtp, ldap2, snmp"); + return; + } + if (service[0] == '-') { + mcp_reply_error(c, "service is a protocol name, not a flag"); + return; + } + if ((login == NULL || *login == '\0') && + (login_file == NULL || *login_file == '\0')) { + mcp_reply_error(c, "login or login_file is required"); + return; + } + if ((password == NULL || *password == '\0') && + (pass_file == NULL || *pass_file == '\0')) { + mcp_reply_error(c, "password or password_file is required"); + return; + } + /* the tool's own default port when the operator did not name one; the + * gate still gets a number, so allow_port is checked against the port + * that will actually be used */ + if (port <= 0) + port = apex_service_port(service, 0); + argv[n++] = "hydra"; + if (port > 0 && port != apex_service_port(service, 0)) { + snprintf(portbuf, sizeof(portbuf), "%d", port); + argv[n++] = "-s"; + argv[n++] = portbuf; + } + if (login != NULL && *login != '\0') { + argv[n++] = "-l"; + argv[n++] = (char *)login; + } else { + argv[n++] = "-L"; + argv[n++] = (char *)login_file; + } + if (password != NULL && *password != '\0') { + argv[n++] = "-p"; + argv[n++] = (char *)password; + } else { + argv[n++] = "-P"; + argv[n++] = (char *)pass_file; + } + if (tasks > 0 && tasks <= 64 && n < 30) { + snprintf(taskbuf, sizeof(taskbuf), "%d", tasks); + argv[n++] = "-t"; + argv[n++] = taskbuf; + } + argv[n++] = "-V"; + argv[n++] = (char *)target; + argv[n++] = (char *)service; + argv[n] = NULL; + n = ext_extra(args, argv, n, 40); + if (n < 0) { + mcp_reply_error(c, "too many extra arguments"); + return; + } + ext_runx(c, spec_by_tool("hydra_scan"), argv, target, port, timeout, + &HYDRA_VERDICT); +} + +static void t_medusa_scan(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + const char *module = mcp_arg_string(args, "module"); + const char *login = mcp_arg_string(args, "login"); + const char *password = mcp_arg_string(args, "password"); + const char *login_file = mcp_arg_string(args, "login_file"); + const char *pass_file = mcp_arg_string(args, "password_file"); + int port = mcp_arg_int(args, "port", 0); + int tasks = mcp_arg_int(args, "tasks", 4); + int timeout = mcp_arg_int(args, "timeout_ms", 900000); + char portbuf[16]; + char taskbuf[16]; + char *argv[40]; + int n = 0; + + (void)user; + if (target == NULL || *target == '\0') { + mcp_reply_error(c, "target is required"); + return; + } + if (module == NULL || *module == '\0') { + mcp_reply_error(c, "module is required, e.g. ssh, ftp, smbnt, " + "http, rdp, mysql, postgres, vnc, telnet, imap, " + "pop3, smtp, svn (medusa -d lists the .mod files " + "this install has)"); + return; + } + if (module[0] == '-') { + mcp_reply_error(c, "module is a module name, not a flag"); + return; + } + if ((login == NULL || *login == '\0') && + (login_file == NULL || *login_file == '\0')) { + mcp_reply_error(c, "login or login_file is required"); + return; + } + if ((password == NULL || *password == '\0') && + (pass_file == NULL || *pass_file == '\0')) { + mcp_reply_error(c, "password or password_file is required"); + return; + } + argv[n++] = "medusa"; + argv[n++] = "-h"; + argv[n++] = (char *)target; + if (port > 0) { + snprintf(portbuf, sizeof(portbuf), "%d", port); + argv[n++] = "-n"; + argv[n++] = portbuf; + } + if (login != NULL && *login != '\0') { + argv[n++] = "-u"; + argv[n++] = (char *)login; + } else { + argv[n++] = "-U"; + argv[n++] = (char *)login_file; + } + if (password != NULL && *password != '\0') { + argv[n++] = "-p"; + argv[n++] = (char *)password; + } else { + argv[n++] = "-P"; + argv[n++] = (char *)pass_file; + } + if (tasks > 0 && tasks <= 64 && n < 30) { + snprintf(taskbuf, sizeof(taskbuf), "%d", tasks); + argv[n++] = "-t"; + argv[n++] = taskbuf; + } + argv[n++] = "-b"; + argv[n++] = "-M"; + argv[n++] = (char *)module; + argv[n] = NULL; + n = ext_extra(args, argv, n, 40); + if (n < 0) { + mcp_reply_error(c, "too many extra arguments"); + return; + } + ext_runx(c, spec_by_tool("medusa_scan"), argv, target, port, timeout, + &MEDUSA_VERDICT); +} + +static void t_msfvenom_build(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *payload = mcp_arg_string(args, "payload"); + const char *format = mcp_arg_string(args, "format"); + const char *encoder = mcp_arg_string(args, "encoder"); + const char *arch = mcp_arg_string(args, "arch"); + const char *out = mcp_arg_string(args, "out"); + const char *lhost = mcp_arg_string(args, "lhost"); + const char *lport = mcp_arg_string(args, "lport"); + const char *iterations = mcp_arg_string(args, "iterations"); + int timeout = mcp_arg_int(args, "timeout_ms", 120000); + char optbuf[256]; + char *argv[40]; + int n = 0; + + (void)user; + if (payload == NULL || *payload == '\0') { + mcp_reply_error(c, "payload is required, e.g. " + "linux/x64/shell_reverse_tcp (msfvenom -l payloads " + "lists what this install has)"); + return; + } + if (format == NULL || *format == '\0') { + mcp_reply_error(c, "format is required, e.g. elf, exe, raw, c, " + "python, bash (msfvenom -l formats lists them)"); + return; + } + argv[n++] = "msfvenom"; + argv[n++] = "-p"; + argv[n++] = (char *)payload; + argv[n++] = "-f"; + argv[n++] = (char *)format; + if (encoder != NULL && *encoder != '\0') { + argv[n++] = "-e"; + argv[n++] = (char *)encoder; + } + if (arch != NULL && *arch != '\0') { + argv[n++] = "-a"; + argv[n++] = (char *)arch; + } + if (iterations != NULL && *iterations != '\0') { + argv[n++] = "-i"; + argv[n++] = (char *)iterations; + } + /* LHOST/LPORT are payload options, passed as one KEY=VALUE token; msfvenom + * splits it itself. No shell is involved, so the "=" never escapes. */ + if (lhost != NULL && *lhost != '\0' && lport != NULL && *lport != '\0') { + snprintf(optbuf, sizeof(optbuf), "LHOST=%s LPORT=%s", lhost, lport); + argv[n++] = optbuf; + } else if (lhost != NULL && *lhost != '\0') { + snprintf(optbuf, sizeof(optbuf), "LHOST=%s", lhost); + argv[n++] = optbuf; + } else if (lport != NULL && *lport != '\0') { + snprintf(optbuf, sizeof(optbuf), "LPORT=%s", lport); + argv[n++] = optbuf; + } + if (out != NULL && *out != '\0') { + if (out[0] != '/') { + mcp_reply_error(c, "out must be an absolute path"); + return; + } + argv[n++] = "-o"; + argv[n++] = (char *)out; + } + argv[n] = NULL; + n = ext_extra(args, argv, n, 40); + if (n < 0) { + mcp_reply_error(c, "too many extra arguments"); + return; + } + ext_run_local(c, spec_by_tool("msfvenom_build"), argv, timeout, + "payload rendered locally"); +} + const mcp_tool TOOLS_EXT[] = { { "nuclei_scan", "Run nuclei against one in-scope URL with a fixed flag allowlist. The " @@ -490,6 +994,82 @@ const mcp_tool TOOLS_EXT[] = { "\"timeout_ms\":{\"type\":\"integer\",\"description\":\"default 300000\"}}," "\"required\":[\"target\"]}", t_sqlmap_scan }, + { "hydra_scan", + "Run hydra against one in-scope service with a fixed flag allowlist. " + "The target, the service and every credential list are the operator's; " + "-M (server list from a file) is not on the allowlist, because a host " + "read from a file never passed the gate. A hit is read from hydra's own " + "line (N valid passwords found) and becomes a finding with the full " + "output as evidence. Gate: the target and the port must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"service\":{\"type\":\"string\",\"description\":" + "\"ssh, ftp, smb, http-get, rdp, mysql, postgres, vnc, telnet, imap, " + "pop3, smtp, ldap2, snmp, ...\"}," + "\"port\":{\"type\":\"integer\",\"description\":" + "\"defaults to the service's own port\"}," + "\"login\":{\"type\":\"string\"}," + "\"login_file\":{\"type\":\"string\",\"description\":\"absolute path\"}," + "\"password\":{\"type\":\"string\"}," + "\"password_file\":{\"type\":\"string\",\"description\":" + "\"absolute path\"}," + "\"tasks\":{\"type\":\"integer\",\"description\":\"1..64, default 16\"}," + "\"extra\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}," + "\"description\":\"further tokens; each must be on the allowlist\"}," + "\"timeout_ms\":{\"type\":\"integer\",\"description\":" + "\"default 900000\"}}," + "\"required\":[\"target\",\"service\"]}", + t_hydra_scan }, + { "medusa_scan", + "Run medusa against one in-scope service with a fixed flag allowlist. " + "The module, the credentials and the files are the operator's; -H " + "(hosts from a file) and -C (combo file) are not on the allowlist, " + "because a host read from a file never passed the gate. A hit is " + "medusa's own [SUCCESS] line or its exit code 1/2, and it becomes a " + "finding with the output as evidence. Gate: the target and the port " + "must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"module\":{\"type\":\"string\",\"description\":" + "\"ssh, ftp, smbnt, http, rdp, mysql, postgres, vnc, telnet, imap, " + "pop3, smtp, svn; medusa -d lists what is installed\"}," + "\"port\":{\"type\":\"integer\"}," + "\"login\":{\"type\":\"string\"}," + "\"login_file\":{\"type\":\"string\",\"description\":\"absolute path\"}," + "\"password\":{\"type\":\"string\"}," + "\"password_file\":{\"type\":\"string\",\"description\":" + "\"absolute path\"}," + "\"tasks\":{\"type\":\"integer\",\"description\":\"1..64, default 4\"}," + "\"extra\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}," + "\"description\":\"further tokens; each must be on the allowlist\"}," + "\"timeout_ms\":{\"type\":\"integer\",\"description\":" + "\"default 900000\"}}," + "\"required\":[\"target\",\"module\"]}", + t_medusa_scan }, + { "msfvenom_build", + "Render a payload with msfvenom using a fixed option allowlist. This " + "is local: no target, nothing is sent anywhere, and no gate is " + "consulted because nothing is reached. The operator picks payload, " + "format, encoder, architecture and output path; LHOST/LPORT go to the " + "payload as KEY=VALUE tokens. The output is saved as evidence. " + "APEX_DRY_RUN stops it like every other tool.", + "{\"type\":\"object\",\"properties\":{" + "\"payload\":{\"type\":\"string\",\"description\":" + "\"e.g. linux/x64/shell_reverse_tcp\"}," + "\"format\":{\"type\":\"string\",\"description\":" + "\"elf, exe, raw, c, python, bash, ...\"}," + "\"encoder\":{\"type\":\"string\"}," + "\"arch\":{\"type\":\"string\"}," + "\"iterations\":{\"type\":\"string\"}," + "\"lhost\":{\"type\":\"string\"}," + "\"lport\":{\"type\":\"string\"}," + "\"out\":{\"type\":\"string\",\"description\":\"absolute path\"}," + "\"extra\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}," + "\"description\":\"further tokens; each must be on the allowlist\"}," + "\"timeout_ms\":{\"type\":\"integer\",\"description\":" + "\"default 120000\"}}," + "\"required\":[\"payload\",\"format\"]}", + t_msfvenom_build }, }; const size_t TOOLS_EXT_N = sizeof(TOOLS_EXT) / sizeof(TOOLS_EXT[0]); diff --git a/src/tools_recon.c b/src/tools_recon.c index bded855..1ec5ef4 100644 --- a/src/tools_recon.c +++ b/src/tools_recon.c @@ -966,7 +966,7 @@ static void t_capabilities(mcp_conn *c, const mcp_json *args, void *user) static const char *progs[] = { "nmap", "dig", "host", "openssl", "curl", "whois", "masscan", "tcpdump", "sqlmap", "nikto", "gobuster", "ffuf", "nuclei", - "hydra", "nc", NULL }; + "hydra", "medusa", "msfvenom", "nc", NULL }; mcp_buf b; int i; diff --git a/tests/gate_audit.py b/tests/gate_audit.py index 0e0a17f..f46f36f 100755 --- a/tests/gate_audit.py +++ b/tests/gate_audit.py @@ -21,20 +21,23 @@ import re import sys HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -EXPECTED_TOOLS = 420 +EXPECTED_TOOLS = 423 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 # below, so "ext_run(" is not a free pass. -INDIRECT = {"ext_run(": "ext_run", "exploit_call(": "exploit_call"} +INDIRECT = {"ext_run(": "ext_runx", "ext_runx(": "ext_runx", + "exploit_call(": "exploit_call"} NET = ("http_once(", "tcp_connect_host(", "tcp_probe(", "apex_run(") # Tools whose "target" argument filters local records; they never touch it. RECORD_FILTERS = {"asset_list", "finding_list", "report_markdown", "traffic_list", "detect_rules", "mitre_map"} -# Tools that spawn a local program for hardware, not a network target. They take -# no target and cannot reach one through the argv they build. +# Tools that spawn a local program and take no target at all, so there is +# nothing for the gate to check. Each one still writes its audit line before it +# runs. msfvenom_build renders a payload on this host; the others talk to a +# board on a serial port. LOCAL_EXEC = {"esp_info", "esp_read_flash", "esp_flash", "package_integrity", - "firewall_audit"} + "firewall_audit", "msfvenom_build"} TABLE_RE = re.compile(r"const mcp_tool (TOOLS_[A-Z_]+)\[\] = \{(.*?)\n\};", re.S) diff --git a/tests/run.py b/tests/run.py index 50411dd..ee78bb2 100755 --- a/tests/run.py +++ b/tests/run.py @@ -135,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("420 tools registered", len(tools) == 420, len(tools)) +check("423 tools registered", len(tools) == 423, 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", @@ -1561,7 +1561,8 @@ 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"]) == 420) + check("http tools/list", len(listing["result"]["tools"]) == len(tools), + len(listing["result"]["tools"])) 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 @@ -18982,13 +18983,19 @@ def clear_log(): for _name in ("nuclei", "nikto", "ffuf", "gobuster", "sqlmap"): make_mock(_name, 'echo "mock %s ok"' % _name) +# hydra and medusa announce a hit in their own words; msfvenom writes a file +make_mock("hydra", 'echo "[22][ssh] host: 127.0.0.1 login: root password: toor"\n' + 'echo "1 of 1 target successfully completed, 1 valid password found"') +make_mock("medusa", 'echo "[ssh] Host: 127.0.0.1 User: root Password: toor [SUCCESS]"\n' + 'exit 1') +make_mock("msfvenom", 'printf "\\x7fELF-mock-payload"') ext_home = tempfile.mkdtemp(prefix="apex-ext-home-") write_scope(ext_home, {"label": "ext", "expires": "2099-01-01T00:00:00Z", "allow_private": True, "allow_ip": ["127.0.0.1"], "allow_domain": ["example.test"], - "allow_port": ["80", "443", "8080"]}) + "allow_port": ["80", "443", "8080", "22", "2222"]}) ext_env = {"PATH": ext_bin + ":" + os.environ.get("PATH", "/usr/bin:/bin")} clear_log() @@ -19086,6 +19093,136 @@ caps = json.loads(text(by_id[1])) check("capabilities reports nuclei as absent on an empty PATH", caps["programs"].get("nuclei") is False, caps.get("programs")) +# --- hydra / medusa / msfvenom: credential testing and payload rendering --- +# The service name is positional in both credential tools, so it must land +# after the target and before nothing else, and it must never be able to +# arrive as a flag. +ext_out = os.path.join(ext_bin, "payload.bin") +clear_log() +res, _ = run([ + call(1, "hydra_scan", target="127.0.0.1", service="ssh", port=2222, + login="root", password="toor"), + call(2, "hydra_scan", target="127.0.0.1", service="ssh", + login_file="/tmp/users.txt", password_file="/tmp/passes.txt"), + call(3, "hydra_scan", target="127.0.0.1", service="-M", + login="root", password="toor"), + call(4, "hydra_scan", target="127.0.0.1", service="ssh", + extra=["-M", "/tmp/servers.txt"], login="root", password="toor"), + call(5, "medusa_scan", target="127.0.0.1", module="ssh", port=2222, + login="root", password="toor"), + call(6, "medusa_scan", target="127.0.0.1", module="ssh", + extra=["-H", "/tmp/servers.txt"], login="root", password="toor"), + call(7, "msfvenom_build", payload="linux/x64/shell_reverse_tcp", + format="elf", lhost="10.0.0.5", lport="4444", out=ext_out), + call(8, "hydra_scan", target="10.9.9.9", service="ssh", + login="root", password="toor"), + call(9, "msfvenom_build", payload="linux/x64/shell_reverse_tcp"), + call(10, "msfvenom_build", payload="linux/x64/shell_reverse_tcp", + format="elf", out="relative/path.bin"), + call(11, "msfvenom_build", payload="linux/x64/shell_reverse_tcp", + format="elf", extra=["--list"]), +], home=ext_home, extra_env=ext_env) +by_id = {r["id"]: r for r in res if "id" in r} + +hy = json.loads(text(by_id[1])) +hy_log = [ln for ln in read_log() if ln.split("|")[0].endswith("/hydra")] +check("hydra_scan reads the tool's own 'valid password found' as a hit", + hy["hit"] is True and hy["finding"] is not None, hy) +check("hydra_scan puts the service after the target as a positional", + any(ln.split("|")[1:] == ["-s", "2222", "-l", "root", "-p", "toor", + "-t", "16", "-V", "127.0.0.1", "ssh"] + for ln in hy_log), hy_log) +check("hydra_scan writes a finding with the output as evidence", + hy["evidence"] and os.path.isfile(hy["evidence"]), hy) + +hy2 = json.loads(text(by_id[2])) +hy2_log = [ln for ln in read_log() if ln.split("|")[0].endswith("/hydra")] +check("hydra_scan passes -L/-P when the operator gives files", + any(["-L", "/tmp/users.txt", "-P", "/tmp/passes.txt"] == + ln.split("|")[i:i + 4] + for ln in hy2_log for i in range(1, len(ln.split("|")) - 3)), hy2_log) + +check("hydra_scan refuses a service that arrives as a flag", + bool(err(by_id[3])) and len(hy_log) == 2, by_id[3]) +check("hydra_scan refuses -M from the extra array (hosts the gate never saw)", + bool(err(by_id[4])) and len(hy_log) == 2, (by_id[4], len(hy_log))) + +md = json.loads(text(by_id[5])) +md_log = [ln for ln in read_log() if ln.split("|")[0].endswith("/medusa")] +check("medusa_scan reads [SUCCESS] and exit 1 as a hit", + md["hit"] is True and md["finding"] is not None, md) +check("medusa_scan passes the host with -h and the module with -M", + any("-h" in ln.split("|") and "-M" in ln.split("|") for ln in md_log), + md_log) +check("medusa_scan refuses -H from the extra array", + bool(err(by_id[6])), by_id[6]) + +ms = json.loads(text(by_id[7])) +ms_log = [ln for ln in read_log() if ln.split("|")[0].endswith("/msfvenom")] +check("msfvenom_build passes LHOST/LPORT as one payload-option token", + any("LHOST=10.0.0.5 LPORT=4444" in ln.split("|") for ln in ms_log), + ms_log) +check("msfvenom_build keeps the operator's absolute output path", + any(ln.split("|")[-1] == ext_out for ln in ms_log), ms_log) +check("msfvenom_build saves the rendered bytes as evidence", + ms["evidence"] and os.path.isfile(ms["evidence"]), ms) + +check("hydra_scan refuses an out-of-scope target before exec", + bool(err(by_id[8])), by_id[8]) +check("msfvenom_build needs a format", + bool(err(by_id[9])), by_id[9]) +check("msfvenom_build refuses a relative output path", + bool(err(by_id[10])), by_id[10]) +check("msfvenom_build refuses --list from the extra array", + bool(err(by_id[11])), by_id[11]) + +# a tool that reports no hit must not leave a finding behind: same tool, but +# this fake says zero +make_mock("hydra", 'echo "0 of 1 target completed, 0 valid passwords found"') +clear_log() +res, _ = run([call(1, "hydra_scan", target="127.0.0.1", service="ssh", + port=2222, login="root", password="wrong")], + home=ext_home, extra_env=ext_env) +by_id = {r["id"]: r for r in res if "id" in r} +nh = json.loads(text(by_id[1])) +check("hydra_scan reports no hit and writes no finding when nothing answered", + nh["hit"] is False and "finding" not in nh, nh) + +# argument checks: each missing required field is a caller error, and a port +# that the operator did not give comes from the service name, not a guess +res, _ = run([ + call(1, "hydra_scan", target="127.0.0.1"), + call(2, "hydra_scan", target="127.0.0.1", service="ssh"), + call(3, "hydra_scan", target="127.0.0.1", service="ssh", login="root"), + call(4, "medusa_scan", target="127.0.0.1"), + call(5, "medusa_scan", target="127.0.0.1", module="ssh"), + call(6, "msfvenom_build", payload="linux/x64/shell_reverse_tcp", + format="elf", extra=["-p", "x"] * 30), +], home=ext_home, extra_env=ext_env) +by_id = {r["id"]: r for r in res if "id" in r} +check("hydra_scan needs a service", bool(err(by_id[1])), by_id[1]) +check("hydra_scan needs a login", bool(err(by_id[2])), by_id[2]) +check("hydra_scan needs a password", bool(err(by_id[3])), by_id[3]) +check("medusa_scan needs a module", bool(err(by_id[4])), by_id[4]) +check("medusa_scan needs a login", bool(err(by_id[5])), by_id[5]) +check("msfvenom_build refuses more extra arguments than argv can hold", + bool(err(by_id[6])), by_id[6]) + +# the service name is resolved through getservbyname: "ssh" without a port +# reaches the gate as 22 and hydra is not given -s, because 22 is its default +make_mock("hydra", 'echo "1 valid password found"') +clear_log() +res, _ = run([call(1, "hydra_scan", target="127.0.0.1", service="ssh", + login="root", password="toor")], + home=ext_home, extra_env=ext_env) +svc_log = [ln for ln in read_log() if ln.split("|")[0].endswith("/hydra")] +audit = [json.loads(ln) for ln in + open(os.path.join(ext_home, "audit.log")).read().splitlines() + if ln.strip() and json.loads(ln).get("tool") == "hydra_scan"] +check("hydra_scan resolves ssh to port 22 and leaves -s off", + bool(svc_log) and "-s" not in svc_log[0].split("|") and + audit and int(audit[-1].get("port", 0)) == 22, (svc_log, audit[-1:])) + shutil.rmtree(ext_bin, ignore_errors=True) shutil.rmtree(empty_bin, ignore_errors=True) shutil.rmtree(ext_home, ignore_errors=True)