diff --git a/README.md b/README.md index d7f0aef..20a169d 100644 --- a/README.md +++ b/README.md @@ -17,8 +17,8 @@ separate, explicitly armed switch. ## Build ```sh -make # apex-twin, ~220 kB static-ish binary, zero warnings under -Werror -make test # 197 end-to-end checks, no mocks +make # apex-twin, ~225 kB static-ish binary, zero warnings under -Werror +make test # 213 end-to-end checks, no mocks make install # /usr/local/bin/apex-twin ``` @@ -147,7 +147,23 @@ It serves one connection at a time. That is a deliberate trade: serial handling keeps the gate order obvious and an origin that stalls costs one timeout, not the process. -## Tools (40) +## Checks that end in a finding + +Three web checks exist because the header audit alone leaves money on the table: + +- `cors_check` sends a GET with a marker `Origin` and grades the answer. A server + that reflects any origin and sets `Access-Control-Allow-Credentials: true` lets + any site read authenticated responses — `high`, not "a header note". +- `cookie_audit` walks every `Set-Cookie` and reports which of Secure, HttpOnly + and SameSite is missing, including the `SameSite=None` without Secure case that + browsers reject. +- `http_options` reads `Allow`/`Public` and flags TRACE, PUT and DELETE. + +`whois` covers the ownership half (registrar, dates, netblock, abuse contact). It +talks to port 43, so `allow_port` has to include 43; without it the gate refuses, +which is the correct answer rather than a silent bypass. + +## Tools (44) **Scope and bookkeeping** — `scope_show`, `scope_check` (ask the gate without touching anything), `scope_reload`, `capabilities`, `audit_log`, `evidence_save` @@ -162,14 +178,15 @@ then the scope of every target in it) `traffic_list`, `traffic_read` **Network recon** — `portscan` (in-process TCP connect, no nmap needed), `nmap` -(profiles quick/default/full/udp/vuln/http), `dns` (dig), `tls_cert` (openssl), -`banner`, `http_head` +(profiles quick/default/full/udp/vuln/http), `dns` (dig), `whois`, `tls_cert` +(openssl), `banner`, `http_head` **Web** — `http_request` (any method, body, headers), `http_headers` (HSTS/CSP/ frame/nosniff/referrer/permissions audit), `http_paths` (built-in wordlist: -`.git`, `.env`, actuator, swagger, backups), `sqli_probe` (quote + boolean pair, -reports differing answers as a lead), `xss_probe` (marked payload, returns the -reflection context), `curl` +`.git`, `.env`, actuator, swagger, backups), `cors_check` (origin reflection with +credentials), `cookie_audit` (Secure/HttpOnly/SameSite), `http_options` (Allow, +TRACE/PUT/DELETE), `sqli_probe` (quote + boolean pair, reports differing answers +as a lead), `xss_probe` (marked payload, returns the reflection context), `curl` **Radio** — `marauder_info`, `marauder_commands`, `marauder_cmd`, `marauder_scan` @@ -254,7 +271,7 @@ finding and the next report no longer mentions it. make test ``` -197 checks, real binary, real DNS, real files written; no mocks. The suite was +213 checks, real binary, real DNS, real files written; no mocks. The suite was seen red on purpose: with the "no scope" branch disabled by `if (0 && ...)`, three checks fail, because they assert the *reason* and not merely that an error came back — a gate that falls through to the next deny branch looks identical @@ -270,7 +287,9 @@ asset's port list was built on stack garbage. A `memset` fixed it; the sabotage that found it is in the history of the suite. With the old `status_code()` back, the capture reported status `1` instead of `200` and two checks went red. With the proxy's gate call bypassed, the out-of-scope request was forwarded and three -checks went red (403 became 502, and the audit had no deny). +checks went red (403 became 502, and the audit had no deny). Forcing the CORS +'reflected' flag to false and the cookie flags to true turned four checks red: +the risk grade fell to low and the missing Secure/HttpOnly issues disappeared. A port is never assumed: an earlier version of the HTTP test used 18797, which on this host is an SSH forward to another machine, and a foreign server answered @@ -278,11 +297,12 @@ this host is an SSH forward to another machine, and a foreign server answered ## Status -0.7.0. Built and run: 40 tools, 197 checks. The loop closes: a probe captures +0.8.0. Built and run: 44 tools, 213 checks. 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, `report_markdown` turns findings -and inventory into one Markdown or CSV file, and `evidence_read`/`traffic_read` -get the proof back. `--proxy` puts the same gate in front of curl and a browser. -Not yet wired into a fleet router. +state, an asset records the host it came from, `cors_check`/`cookie_audit`/ +`http_options` turn a web answer into a graded lead, `report_markdown` turns +findings and inventory into one Markdown or CSV file, and +`evidence_read`/`traffic_read` get the proof back. `--proxy` puts the same gate +in front of curl and a browser. Not yet wired into a fleet router. Licence: AGPL-3.0, same as ARTEX. diff --git a/src/apex.h b/src/apex.h index e5ec94e..0ba9912 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "0.7.0" +#define APEX_VERSION "0.8.0" #define APEX_MAX_OUT (1u << 20) #define APEX_PATH_MAX 512 #define APEX_PATH_FULL 1024 diff --git a/src/tools_recon.c b/src/tools_recon.c index c3a3110..bf20522 100644 --- a/src/tools_recon.c +++ b/src/tools_recon.c @@ -843,6 +843,24 @@ static void t_finding_update(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +static void t_whois(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + int timeout = mcp_arg_int(args, "timeout_ms", 30000); + char *argv[3]; + + (void)user; + if (target == NULL || *target == '\0') { + mcp_reply_error(c, "target is required"); + return; + } + argv[0] = "whois"; + argv[1] = (char *)target; + argv[2] = NULL; + /* whois speaks to port 43; the scope has to allow it like any other port */ + (void)gated_cmd(c, "whois", target, 43, argv, timeout, NULL); +} + static void t_capabilities(mcp_conn *c, const mcp_json *args, void *user) { static const char *progs[] = { "nmap", "dig", "host", "openssl", "curl", @@ -933,6 +951,16 @@ const mcp_tool TOOLS_RECON[] = { "\"type\":{\"type\":\"string\",\"description\":\"record type, default A\"}}," "\"required\":[\"target\"]}", t_dns }, + { "whois", + "Look up the registration and network record with whois: registrar, " + "creation and expiry dates, registrant country, netblock and abuse " + "contact. Use it for the ownership half of the report; it talks to port 43, " + "so allow_port has to include 43.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"timeout_ms\":{\"type\":\"integer\",\"description\":\"default 30000\"}}," + "\"required\":[\"target\"]}", + t_whois }, { "tls_cert", "Fetch and show the X.509 certificate a TLS service presents (issuer, " "subject, SANs, validity, chain). Use it for certificate hygiene findings " diff --git a/src/tools_web.c b/src/tools_web.c index 8245597..c49095b 100644 --- a/src/tools_web.c +++ b/src/tools_web.c @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -244,6 +245,58 @@ static int safe_token(const char *s, size_t max) return 1; } +/* One named header from a raw response, case-insensitively, value trimmed. */ +static int resp_header(const char *resp, const char *name, char *out, size_t n) +{ + const char *p; + size_t nl = strlen(name); + + if (out != NULL && n > 0) + out[0] = '\0'; + p = strstr(resp, "\r\n"); + if (p == NULL) + return 0; + p += 2; + while (*p != '\0') { + const char *eol = strstr(p, "\r\n"); + const char *colon; + + if (eol == NULL || eol == p) + break; + colon = memchr(p, ':', (size_t)(eol - p)); + if (colon != NULL && (size_t)(colon - p) == nl && + strncasecmp(p, name, nl) == 0) { + const char *v = colon + 1; + size_t len; + + while (v < eol && (*v == ' ' || *v == '\t')) + v++; + len = (size_t)(eol - v); + if (len >= n) + len = n - 1; + memcpy(out, v, len); + out[len] = '\0'; + return 1; + } + p = eol + 2; + } + return 0; +} + +/* The head of a response as a NUL-terminated copy, body excluded. */ +static char *resp_head_dup(const char *resp) +{ + const char *end = strstr(resp, "\r\n\r\n"); + size_t n = end != NULL ? (size_t)(end - resp) + 4 : strlen(resp); + char *copy = malloc(n + 1); + + if (copy == NULL) + return NULL; + memcpy(copy, resp, n); + copy[n] = '\0'; + return copy; +} + /* ------------------------------------------------------------------ tools */ static void t_http_request(mcp_conn *c, const mcp_json *args, void *user) @@ -557,6 +610,334 @@ static void t_http_headers(mcp_conn *c, const mcp_json *args, void *user) free(resp); } +static void t_cors_check(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + const char *path = mcp_arg_string(args, "path"); + const char *origin = mcp_arg_string(args, "origin"); + int port = mcp_arg_int(args, "port", 80); + int tls = mcp_arg_bool(args, "tls", looks_tls(port)); + char status[256]; + char acao[600]; + char acac[64]; + mcp_buf hdrs; + mcp_buf b; + char *resp = NULL; + size_t len = 0; + int reflected; + int wildcard; + int credentials; + const char *risk; + const char *note; + + (void)user; + if (target == NULL || *target == '\0') { + mcp_reply_error(c, "target is required"); + return; + } + if (path == NULL || *path == '\0') + path = "/"; + if (!safe_token(path, 512) || path[0] != '/') { + mcp_reply_error(c, "path must start with / and contain no control characters"); + return; + } + if (origin == NULL || *origin == '\0') + origin = "https://apex-twin.invalid"; + if (!safe_token(origin, 512)) { + mcp_reply_error(c, "origin contains control characters"); + return; + } + if (!gated(c, "cors_check", target, port)) + return; + + mcp_buf_init(&hdrs); + mcp_buf_printf(&hdrs, "Origin: %s\r\n", origin); + status[0] = '\0'; + if (http_once(target, port, tls, "GET", path, NULL, hdrs.p, 15000, &resp, + &len, status, sizeof(status), NULL, NULL) != 0) { + mcp_buf_free(&hdrs); + mcp_reply_error(c, "no response"); + return; + } + mcp_buf_free(&hdrs); + + resp_header(resp, "access-control-allow-origin", acao, sizeof(acao)); + resp_header(resp, "access-control-allow-credentials", acac, sizeof(acac)); + reflected = acao[0] != '\0' && strcmp(acao, origin) == 0; + wildcard = strcmp(acao, "*") == 0; + credentials = strcasecmp(acac, "true") == 0; + if (reflected && credentials) { + risk = "high"; + note = "the server reflects any Origin and allows credentials: any " + "site can read authenticated responses"; + } else if (wildcard && credentials) { + risk = "high"; + note = "wildcard with credentials: browsers usually reject this, but " + "the intent is to expose authenticated data"; + } else if (reflected) { + risk = "medium"; + note = "the server reflects any Origin; without credentials the read " + "is limited, with them it is a finding"; + } else if (wildcard) { + risk = "low"; + note = "wildcard CORS: public data only, unless credentials are added"; + } else if (acao[0] == '\0') { + risk = "none"; + note = "no Access-Control-Allow-Origin in the answer"; + } else { + risk = "low"; + note = "an allow-origin is present but does not reflect this Origin"; + } + + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"path\":", port); + apex_json_str(&b, path); + mcp_buf_puts(&b, ",\"origin\":"); + apex_json_str(&b, origin); + mcp_buf_printf(&b, ",\"status\":%d,\"allow_origin\":", + status_code(status)); + apex_json_str(&b, acao); + mcp_buf_puts(&b, ",\"allow_credentials\":"); + apex_json_str(&b, acac); + mcp_buf_printf(&b, ",\"reflected\":%s,\"wildcard\":%s,\"credentials\":%s," + "\"risk\":\"%s\",\"note\":", + reflected ? "true" : "false", wildcard ? "true" : "false", + credentials ? "true" : "false", risk); + apex_json_str(&b, note); + mcp_buf_puts(&b, "}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + free(resp); +} + +typedef struct { + char name[128]; + int secure; + int httponly; + char samesite[16]; + char issues[256]; +} cookie_info; + +static void cookie_issue(cookie_info *ci, const char *text) +{ + size_t used = strlen(ci->issues); + + if (used + strlen(text) + 3 >= sizeof(ci->issues)) + return; + if (used > 0) { + memcpy(ci->issues + used, ", ", 2); + used += 2; + } + memcpy(ci->issues + used, text, strlen(text) + 1); +} + +static int parse_cookie(const char *value, cookie_info *ci, int *issue_count) +{ + char buf[1024]; + char *save = NULL; + char *tok; + int first = 1; + + memset(ci, 0, sizeof(*ci)); + snprintf(buf, sizeof(buf), "%s", value); + tok = strtok_r(buf, ";", &save); + while (tok != NULL) { + while (*tok == ' ' || *tok == '\t') + tok++; + { + size_t len = strlen(tok); + + while (len > 0 && + (tok[len - 1] == ' ' || tok[len - 1] == '\t')) + tok[--len] = '\0'; + } + if (first) { + char *eq = strchr(tok, '='); + size_t n = eq != NULL ? (size_t)(eq - tok) : strlen(tok); + + if (n >= sizeof(ci->name)) + n = sizeof(ci->name) - 1; + memcpy(ci->name, tok, n); + ci->name[n] = '\0'; + first = 0; + } else if (strcasecmp(tok, "secure") == 0) { + ci->secure = 1; + } else if (strcasecmp(tok, "httponly") == 0) { + ci->httponly = 1; + } else if (strncasecmp(tok, "samesite", 8) == 0) { + char *eq = strchr(tok, '='); + + if (eq != NULL) { + snprintf(ci->samesite, sizeof(ci->samesite), "%s", + eq + 1); + } + } + tok = strtok_r(NULL, ";", &save); + } + if (!ci->secure) { + cookie_issue(ci, "no Secure"); + (*issue_count)++; + } + if (!ci->httponly) { + cookie_issue(ci, "no HttpOnly"); + (*issue_count)++; + } + if (ci->samesite[0] == '\0') { + cookie_issue(ci, "no SameSite"); + (*issue_count)++; + } else if (strcasecmp(ci->samesite, "none") == 0 && !ci->secure) { + cookie_issue(ci, "SameSite=None without Secure"); + (*issue_count)++; + } + return 0; +} + +static void t_cookie_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + const char *path = mcp_arg_string(args, "path"); + int port = mcp_arg_int(args, "port", 80); + int tls = mcp_arg_bool(args, "tls", looks_tls(port)); + char status[256]; + char *resp = NULL; + size_t len = 0; + char *head; + char *save = NULL; + char *line; + cookie_info cookies[16]; + int n = 0; + int issues = 0; + mcp_buf b; + int i; + + (void)user; + if (target == NULL || *target == '\0') { + mcp_reply_error(c, "target is required"); + return; + } + if (path == NULL || *path == '\0') + path = "/"; + if (!safe_token(path, 512) || path[0] != '/') { + mcp_reply_error(c, "path must start with / and contain no control characters"); + return; + } + if (!gated(c, "cookie_audit", target, port)) + return; + + status[0] = '\0'; + if (http_once(target, port, tls, "GET", path, NULL, NULL, 15000, &resp, + &len, status, sizeof(status), NULL, NULL) != 0) { + mcp_reply_error(c, "no response"); + return; + } + head = resp_head_dup(resp); + free(resp); + if (head == NULL) { + mcp_reply_error(c, "out of memory"); + return; + } + line = strtok_r(head, "\r\n", &save); /* status line */ + while (line != NULL && n < 16) { + line = strtok_r(NULL, "\r\n", &save); + if (line == NULL) + break; + if (strncasecmp(line, "set-cookie:", 11) == 0) { + const char *v = line + 11; + + while (*v == ' ' || *v == '\t') + v++; + parse_cookie(v, &cookies[n], &issues); + n++; + } + } + free(head); + + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"path\":", port); + apex_json_str(&b, path); + mcp_buf_printf(&b, ",\"status\":%d,\"count\":%d,\"issues\":%d," + "\"cookies\":[", status_code(status), n, issues); + for (i = 0; i < n; i++) { + if (i > 0) + mcp_buf_puts(&b, ","); + mcp_buf_puts(&b, "{\"name\":"); + apex_json_str(&b, cookies[i].name); + mcp_buf_printf(&b, ",\"secure\":%s,\"httponly\":%s,\"samesite\":", + cookies[i].secure ? "true" : "false", + cookies[i].httponly ? "true" : "false"); + apex_json_str(&b, cookies[i].samesite); + mcp_buf_puts(&b, ",\"issues\":"); + apex_json_str(&b, cookies[i].issues); + mcp_buf_puts(&b, "}"); + } + mcp_buf_puts(&b, "]}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + +static void t_http_options(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + const char *path = mcp_arg_string(args, "path"); + int port = mcp_arg_int(args, "port", 80); + int tls = mcp_arg_bool(args, "tls", looks_tls(port)); + char status[256]; + char allow[600]; + char public[600]; + char *resp = NULL; + size_t len = 0; + int risky; + mcp_buf b; + + (void)user; + if (target == NULL || *target == '\0') { + mcp_reply_error(c, "target is required"); + return; + } + if (path == NULL || *path == '\0') + path = "/"; + if (!safe_token(path, 512) || path[0] != '/') { + mcp_reply_error(c, "path must start with / and contain no control characters"); + return; + } + if (!gated(c, "http_options", target, port)) + return; + + status[0] = '\0'; + if (http_once(target, port, tls, "OPTIONS", path, NULL, NULL, 15000, &resp, + &len, status, sizeof(status), NULL, NULL) != 0) { + mcp_reply_error(c, "no response"); + return; + } + resp_header(resp, "allow", allow, sizeof(allow)); + resp_header(resp, "public", public, sizeof(public)); + { + char methods[1200]; + + snprintf(methods, sizeof(methods), "%s,%s", allow, public); + risky = find_ci(methods, "TRACE") != NULL || + find_ci(methods, "PUT") != NULL || + find_ci(methods, "DELETE") != NULL; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"path\":", port); + apex_json_str(&b, path); + mcp_buf_printf(&b, ",\"status\":%d,\"allow\":", status_code(status)); + apex_json_str(&b, allow); + mcp_buf_puts(&b, ",\"public\":"); + apex_json_str(&b, public); + mcp_buf_printf(&b, ",\"risky\":%s}", risky ? "true" : "false"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + free(resp); +} + static void t_http_paths(mcp_conn *c, const mcp_json *args, void *user) { static const char *wordlist[] = { @@ -986,6 +1367,45 @@ const mcp_tool TOOLS_WEB[] = { "\"tls\":{\"type\":\"boolean\"}}," "\"required\":[\"target\"]}", t_http_headers }, + { "cors_check", + "Send a GET with a marker Origin and report what the server allows: " + "whether it reflects any origin, whether it uses a wildcard, whether " + "credentials are allowed, and the risk that combination creates. A " + "reflected origin with credentials lets any site read authenticated " + "responses - that is a finding, not a header note.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 80\"}," + "\"path\":{\"type\":\"string\",\"description\":\"default /\"}," + "\"origin\":{\"type\":\"string\",\"description\":\"default " + "https://apex-twin.invalid\"}," + "\"tls\":{\"type\":\"boolean\"}}," + "\"required\":[\"target\"]}", + t_cors_check }, + { "cookie_audit", + "Collect the Set-Cookie headers and audit each cookie: Secure, HttpOnly, " + "SameSite, and the SameSite=None-without-Secure combination browsers " + "reject. Use it on the login and session endpoints; a session cookie " + "without HttpOnly is a finding with an exploit path.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 80\"}," + "\"path\":{\"type\":\"string\",\"description\":\"default /\"}," + "\"tls\":{\"type\":\"boolean\"}}," + "\"required\":[\"target\"]}", + t_cookie_audit }, + { "http_options", + "Send OPTIONS and read the Allow and Public headers: which methods the " + "endpoint admits, and whether TRACE, PUT or DELETE are among them. TRACE " + "enables cross-site tracing; PUT/DELETE on a public path is a write " + "surface worth a finding.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 80\"}," + "\"path\":{\"type\":\"string\",\"description\":\"default /\"}," + "\"tls\":{\"type\":\"boolean\"}}," + "\"required\":[\"target\"]}", + t_http_options }, { "http_paths", "Probe a built-in wordlist of common paths and endpoints (.git, .env, " "admin, actuator, swagger, backups) and report which answer with 200, 30x, " diff --git a/tests/run.py b/tests/run.py index e783843..368ac8e 100755 --- a/tests/run.py +++ b/tests/run.py @@ -6,6 +6,7 @@ that is in scope, and assertions on the files the server actually wrote. The point of the suite is the gate: everything else is a tool, the gate is the product. """ +import http.server import json import os import shutil @@ -13,6 +14,7 @@ import socket import subprocess import sys import tempfile +import threading import time import urllib.request @@ -79,7 +81,7 @@ SCOPE = { "allow_ip": ["192.0.2.0/24", "198.51.100.7"], "deny_ip": ["192.0.2.66"], "allow_domain": ["example.com"], - "allow_port": ["80", "8080", "443"], + "allow_port": ["80", "8080", "443", "43"], } print("== binary ==") @@ -99,13 +101,14 @@ 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("40 tools registered", len(tools) == 40, len(tools)) +check("44 tools registered", len(tools) == 44, 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", "report_markdown", "evidence_list", "evidence_read", "guard_check", "asset_add", "asset_list", "asset_read", - "asset_update", "http_capture", "traffic_list", "traffic_read"): + "asset_update", "http_capture", "traffic_list", "traffic_read", + "whois", "cors_check", "cookie_audit", "http_options"): check("tool present: " + need, need in names) for r in res: if r.get("id") in (2, 3, 4): @@ -621,6 +624,83 @@ check("http_capture is audited", for e in json.loads(text(by_id[5]))), [e for e in json.loads(text(by_id[5])) if e["tool"] == "http_capture"][:2]) +print("\n== web checks (local origin) ==") + + +class _AuditHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(200) + self.send_header("Access-Control-Allow-Origin", + self.headers.get("Origin", "")) + self.send_header("Access-Control-Allow-Credentials", "true") + self.send_header("Set-Cookie", "sid=abc; Path=/") + self.send_header("Set-Cookie", + "theme=dark; Secure; HttpOnly; SameSite=Lax") + self.send_header("Content-Length", "2") + self.end_headers() + self.wfile.write(b"ok") + + def do_OPTIONS(self): + self.send_response(204) + self.send_header("Allow", "GET, OPTIONS, TRACE") + self.end_headers() + + def log_message(self, *args): + pass + + +origin = http.server.HTTPServer(("127.0.0.1", 0), _AuditHandler) +oport = origin.server_address[1] +threading.Thread(target=origin.serve_forever, daemon=True).start() +web_home = tempfile.mkdtemp(prefix="apex-web-") +write_scope(web_home, {"label": "web", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_port": [str(oport)]}) +try: + res, _ = run([ + call(1, "cors_check", target="127.0.0.1", port=oport, path="/"), + call(2, "cookie_audit", target="127.0.0.1", port=oport, path="/"), + call(3, "http_options", target="127.0.0.1", port=oport, path="/"), + ], home=web_home) + by_id = {r.get("id"): r for r in res} + cors = json.loads(text(by_id[1])) + check("cors_check sees a reflected origin and credentials", + cors["reflected"] is True and cors["credentials"] is True, cors) + check("cors_check rates reflection with credentials as high risk", + cors["risk"] == "high", cors) + cookies = json.loads(text(by_id[2])) + check("cookie_audit counts the cookies", cookies["count"] == 2, cookies) + check("cookie_audit counts the missing flags", cookies["issues"] == 3, + cookies) + sid = [c for c in cookies["cookies"] if c["name"] == "sid"][0] + check("cookie_audit names every missing attribute", + "no Secure" in sid["issues"] and "no HttpOnly" in sid["issues"] and + "no SameSite" in sid["issues"], sid) + theme = [c for c in cookies["cookies"] if c["name"] == "theme"][0] + check("cookie_audit clears a fully flagged cookie", + theme["issues"] == "" and theme["secure"] is True and + theme["httponly"] is True, theme) + opts = json.loads(text(by_id[3])) + check("http_options reads the Allow header", + "TRACE" in opts["allow"], opts) + check("http_options flags a risky method", opts["risky"] is True, opts) + check("http_options reports the status", opts["status"] == 204, opts) +finally: + origin.shutdown() + origin.server_close() + shutil.rmtree(web_home, ignore_errors=True) + +print("\n== whois ==") +res, _ = run([ + call(1, "whois", target="example.com"), + call(2, "whois", target="198.51.100.9"), +]) +check("whois runs through the gate", not err(res[0]) and + "exit=" in text(res[0]), text(res[0])[:200]) +check("whois refuses an out-of-scope target", err(res[1]), text(res[1])) +check("whois refusal names the scope", "outside allow_ip" in text(res[1]), + text(res[1])) + # --------------------------------------------------------------- transport print("\n== http transport ==") @@ -665,7 +745,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"]) == 40) + check("http tools/list", len(listing["result"]["tools"]) == 44) 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