diff --git a/README.md b/README.md index 3639224..e75daf0 100644 --- a/README.md +++ b/README.md @@ -17,8 +17,8 @@ separate, explicitly armed switch. ## Build ```sh -make # apex-twin, ~225 kB static-ish binary, zero warnings under -Werror -make test # 222 end-to-end checks, no mocks +make # apex-twin, ~239 kB static-ish binary, zero warnings under -Werror +make test # 232 end-to-end checks, no mocks make install # /usr/local/bin/apex-twin ``` @@ -147,6 +147,27 @@ 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. +Before forwarding, the proxy loads `$APEX_HOME/rewrite.json` (`APEX_REWRITE` +overrides the path) and applies the first matching rule: + +```json +{"rules": [ + {"match_host": "app.example.com", "match_path_prefix": "/api", + "set": [{"name": "X-Test", "value": "1"}], + "remove": ["User-Agent"], "note": "mark the request"}, + {"match_host": "*", "match_path_prefix": "/admin", + "block": true, "note": "not part of this engagement"} +]} +``` + +`match_host` is case-insensitive, `*` matches any host, and `match_path_prefix` +is a prefix. `set` replaces a header the client sent and adds one it did not; +`remove` drops a header; `block` answers `403` with the note and writes a deny +line to `audit.log`. The applied rule is named in the traffic record and audited. +`kill -HUP` reloads the file; an invalid file is rejected whole and the previous +rules stay active. The scope gate still runs first: a rule can only narrow what +the proxy does, never widen the engagement. + ## Checks that end in a finding Three web checks exist because the header audit alone leaves money on the table: @@ -263,6 +284,7 @@ APEX_SERIAL=/dev/ttyACM0 APEX_BAUD=115200 | `APEX_MAX_TIMEOUT_MS` | `900000` | hard cap | | `APEX_WEBHOOK` | unset | URL POSTed on a finding at or above the floor | | `APEX_WEBHOOK_MIN_SEVERITY` | `critical` | floor for the webhook | +| `APEX_REWRITE` | `$APEX_HOME/rewrite.json` | proxy rewrite rules (SIGHUP reloads) | ## Files it writes @@ -289,7 +311,7 @@ finding and the next report no longer mentions it. make test ``` -222 checks, real binary, real DNS, real files written; no mocks. The suite was +232 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 @@ -309,7 +331,9 @@ 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. Disabling the notification severity floor made a low finding post, and "a low -finding stays quiet" went red. +finding stays quiet" went red. Making the rewrite matcher return -1 turned seven +checks red: headers stayed, the block rule did not block, the traffic record lost +the rule name, and the rewrite audit was empty. 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 @@ -317,13 +341,14 @@ this host is an SSH forward to another machine, and a foreign server answered ## Status -0.9.0. Built and run: 45 tools, 222 checks. The loop closes: a probe captures +0.10.0. Built and run: 45 tools, 232 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, `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, and `APEX_WEBHOOK` wakes someone when the +in front of curl and a browser, with optional rewrite rules that can set or +remove a header or block a path, and `APEX_WEBHOOK` wakes someone when the severity floor is crossed. Not yet wired into a fleet router. Licence: AGPL-3.0, same as ARTEX. diff --git a/docs/artex-port.md b/docs/artex-port.md index 81a785c..6eb5b9a 100644 --- a/docs/artex-port.md +++ b/docs/artex-port.md @@ -22,7 +22,8 @@ module, deliberately left out, or still open. | Asset inventory (`server/assets*.go`) | `src/store.c` assets + `asset_*` | One file per target, merged by target, gated on add | | Traffic archive (`traffic/`) | `src/store.c` traffic + `http_capture`/`traffic_*` | Request/response pair on disk; a capture is a proof | | Notifications (`notify/`) | `src/notify.c`, `notify_test` | Webhook via curl, severity floor, fire-and-forget, audited; not gated (operator infrastructure) | -| Intercepting proxy (`intercept/`, `traffic/proxy.go`) | `src/proxy.c`, `--proxy` | Loopback forward proxy, gate before connect, HTTP captured, CONNECT tunnelled blind; no TLS interception, no rewrite rules | +| Intercepting proxy (`intercept/`, `traffic/proxy.go`) | `src/proxy.c`, `--proxy` | Loopback forward proxy, gate before connect, HTTP captured, CONNECT tunnelled blind; no TLS interception | +| Request rewriting (`traffic/rewrite`, `intercept`) | `src/rewrite.c`, `rewrite.json` | Ordered host/path rules: set/remove headers or block, first match, SIGHUP reload, rule named in traffic and audit; scope still first | | Report export (`report/findings.go`) | `tools_report.c` `report_markdown` | Markdown and CSV, severity-sorted, severity and lifecycle tables, optional asset table | | Budgets / timeouts (`agent/budget.go`) | `APEX_DEFAULT_TIMEOUT_MS`, `APEX_MAX_TIMEOUT_MS` | Per-tool timeout, process-group kill | | Skills / methodology (`skills/`) | `src/tools_kb.c` | 12 techniques + per-tool pitfalls as data tables | @@ -42,9 +43,9 @@ module, deliberately left out, or still open. ## Open -1. **Request rewriting** (`traffic/rewrite`, `intercept`): the proxy forwards - and captures, but does not yet modify a request in flight on a rule. -2. **TLS interception**: deliberately absent; CONNECT is a blind tunnel. +1. **TLS interception**: deliberately absent; CONNECT is a blind tunnel. +2. **Agent engine, planner, LLM pool**: deliberately absent; the MCP client is + the agent and the serving path stays deterministic. The rule for every item: it may observe or prove, it may not add a shell, and it must call `gated()`/`apex_scope_check()` before it opens a socket or spawns a diff --git a/src/apex.h b/src/apex.h index 38dd339..4167bb1 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "0.9.0" +#define APEX_VERSION "0.10.0" #define APEX_MAX_OUT (1u << 20) #define APEX_PATH_MAX 512 #define APEX_PATH_FULL 1024 @@ -69,6 +69,7 @@ typedef struct { char traffic_dir[APEX_PATH_MAX]; char webhook[1024]; char webhook_min[16]; + char rewrite_file[APEX_PATH_MAX]; char serial[128]; int baud; int default_timeout_ms; diff --git a/src/config.c b/src/config.c index 364d73f..2549bcf 100644 --- a/src/config.c +++ b/src/config.c @@ -151,6 +151,7 @@ void apex_config_init(void) path_join(g_cfg.report_dir, sizeof(g_cfg.report_dir), g_cfg.home, "reports"); path_join(g_cfg.asset_dir, sizeof(g_cfg.asset_dir), g_cfg.home, "assets"); path_join(g_cfg.traffic_dir, sizeof(g_cfg.traffic_dir), g_cfg.home, "traffic"); + path_join(g_cfg.rewrite_file, sizeof(g_cfg.rewrite_file), g_cfg.home, "rewrite.json"); if (scope != NULL && *scope != '\0') copy_str(g_cfg.scope_file, sizeof(g_cfg.scope_file), scope); @@ -172,6 +173,12 @@ void apex_config_init(void) env_int("APEX_BAUD", &g_cfg.baud); if (dry != NULL && (*dry == '1' || *dry == 'y' || *dry == 't')) g_cfg.dry_run = 1; + { + const char *rw = getenv("APEX_REWRITE"); + + if (rw != NULL && *rw != '\0') + copy_str(g_cfg.rewrite_file, sizeof(g_cfg.rewrite_file), rw); + } { const char *hook = getenv("APEX_WEBHOOK"); const char *min = getenv("APEX_WEBHOOK_MIN_SEVERITY"); diff --git a/src/proxy.c b/src/proxy.c index 6946d74..7e9ace7 100644 --- a/src/proxy.c +++ b/src/proxy.c @@ -32,6 +32,7 @@ #include "apex.h" #include "proxy.h" +#include "rewrite.h" #include "tools.h" #define PROXY_HEAD_MAX (64u * 1024) @@ -43,6 +44,24 @@ #define PROXY_TUNNEL_MS 60000 #define PROXY_TUNNEL_CAP (64L << 20) +static volatile sig_atomic_t g_rules_dirty; + +static void on_hup(int sig) +{ + (void)sig; + g_rules_dirty = 1; +} + +static void reload_rules(void) +{ + if (apex_rewrite_load() == 0) + fprintf(stderr, "apex-twin: rewrite rules: %d\n", + apex_rewrite_count()); + else + fprintf(stderr, "apex-twin: rewrite file rejected; keeping the " + "previous rules\n"); +} + static long now_ms(void) { struct timeval tv; @@ -419,12 +438,13 @@ static int parse_request(const char *head, proxy_req *r) } static void build_forward(const char *head, int head_end, const proxy_req *r, - mcp_buf *out) + mcp_buf *out, int rule) { char *copy = malloc((size_t)head_end + 1); char *save = NULL; char *line; int had_host = 0; + int i; mcp_buf_printf(out, "%s %s HTTP/1.1\r\n", r->method, r->path); if (copy == NULL) { @@ -435,16 +455,35 @@ static void build_forward(const char *head, int head_end, const proxy_req *r, copy[head_end] = '\0'; line = strtok_r(copy, "\r\n", &save); /* the request line */ while ((line = strtok_r(NULL, "\r\n", &save)) != NULL) { + char hname[64]; + const char *colon = strchr(line, ':'); + size_t hl = colon != NULL ? (size_t)(colon - line) : strlen(line); + + if (hl >= sizeof(hname)) + hl = sizeof(hname) - 1; + memcpy(hname, line, hl); + hname[hl] = '\0'; if (ci_prefix(line, "proxy-connection:") || ci_prefix(line, "proxy-authorization:") || ci_prefix(line, "connection:") || ci_prefix(line, "keep-alive:")) continue; + /* the rule removes this header or replaces it with its own */ + if (apex_rewrite_should_remove(rule, hname)) + continue; if (ci_prefix(line, "host:")) had_host = 1; mcp_buf_puts(out, line); mcp_buf_puts(out, "\r\n"); } + for (i = 0; i < apex_rewrite_set_count(rule); i++) { + const char *name = apex_rewrite_set_name(rule, i); + const char *value = apex_rewrite_set_value(rule, i); + + if (ci_prefix(name, "host")) + had_host = 1; + mcp_buf_printf(out, "%s: %s\r\n", name, value); + } if (!had_host) mcp_buf_printf(out, "Host: %s\r\n", r->host); mcp_buf_puts(out, "Connection: close\r\n\r\n"); @@ -572,17 +611,28 @@ static void handle_forward(int cfd, const char *head, int head_end, { char reason[512]; int ofd; + int rule; mcp_buf req; size_t prefix; size_t remaining; char *resp; size_t rlen = 0; - char note[160]; + char note[320]; if (!proxy_gate(r->host, r->port, line, reason, sizeof(reason))) { reply_error(cfd, 403, "Forbidden", reason); return; } + rule = apex_rewrite_match(r->host, r->path); + if (rule >= 0 && apex_rewrite_blocked(rule)) { + const char *why = apex_rewrite_note(rule); + + if (why[0] == '\0') + why = "blocked by rewrite rule"; + apex_audit("rewrite", r->host, r->port, 0, why, line); + reply_error(cfd, 403, "Forbidden", why); + return; + } ofd = tcp_connect_host(r->host, r->port, PROXY_ORIGIN_MS); if (ofd < 0) { reply_error(cfd, 502, "Bad Gateway", @@ -591,7 +641,7 @@ static void handle_forward(int cfd, const char *head, int head_end, } mcp_buf_init(&req); - build_forward(head, head_end, r, &req); + build_forward(head, head_end, r, &req, rule); prefix = total > (size_t)head_end ? total - (size_t)head_end : 0; if (prefix > (size_t)r->content_length) prefix = (size_t)r->content_length; @@ -623,12 +673,31 @@ static void handle_forward(int cfd, const char *head, int head_end, return; } (void)send_all(cfd, resp, rlen); - if (rlen >= PROXY_RESP_MAX) - snprintf(note, sizeof(note), - "proxy capture (response truncated at %u bytes)", - (unsigned)PROXY_RESP_MAX); - else - copy_to(note, sizeof(note), "proxy capture"); + { + const char *rnote = rule >= 0 ? apex_rewrite_note(rule) : ""; + + if (rlen >= PROXY_RESP_MAX) { + if (rule >= 0) + snprintf(note, sizeof(note), + "proxy capture (response truncated); rewrite rule %d", + rule); + else + snprintf(note, sizeof(note), + "proxy capture (response truncated at %u bytes)", + (unsigned)PROXY_RESP_MAX); + } else if (rule >= 0 && rnote[0] != '\0') { + snprintf(note, sizeof(note), + "proxy capture; rewrite rule %d: %.120s", rule, rnote); + } else if (rule >= 0) { + snprintf(note, sizeof(note), "proxy capture; rewrite rule %d", + rule); + } else { + copy_to(note, sizeof(note), "proxy capture"); + } + if (rule >= 0) + apex_audit("rewrite", r->host, r->port, 1, + rnote[0] != '\0' ? rnote : "rewrite rule applied", line); + } { char *id = apex_traffic_add(r->host, r->port, 0, r->method, r->path, status_code_of(resp), req.p, req.len, resp, @@ -708,8 +777,16 @@ int apex_serve_proxy(int port) int one = 1; struct sockaddr_in sa; socklen_t sl; + struct sigaction sa_hup; signal(SIGPIPE, SIG_IGN); + memset(&sa_hup, 0, sizeof(sa_hup)); + sa_hup.sa_handler = on_hup; + sigemptyset(&sa_hup.sa_mask); + sa_hup.sa_flags = 0; /* accept() must return EINTR on SIGHUP */ + sigaction(SIGHUP, &sa_hup, NULL); + reload_rules(); + ls = socket(AF_INET, SOCK_STREAM, 0); if (ls < 0) { perror("apex-twin: proxy socket"); @@ -735,13 +812,22 @@ int apex_serve_proxy(int port) fprintf(stderr, "apex-twin: proxy on 127.0.0.1:%d\n", ntohs(sa.sin_port)); for (;;) { - int fd = accept(ls, NULL, NULL); + int fd; + if (g_rules_dirty) { + g_rules_dirty = 0; + reload_rules(); + } + fd = accept(ls, NULL, NULL); if (fd < 0) { if (errno == EINTR) continue; break; } + if (g_rules_dirty) { + g_rules_dirty = 0; + reload_rules(); + } handle_client(fd); close(fd); } diff --git a/src/rewrite.c b/src/rewrite.c new file mode 100644 index 0000000..0e34e40 --- /dev/null +++ b/src/rewrite.c @@ -0,0 +1,270 @@ +/* + * rewrite.c - the rule file behind the proxy's "change it in flight" mode. + * + * Format: + * + * { + * "rules": [ + * { "match_host": "example.com", "match_path_prefix": "/api", + * "set": [{"name": "X-Test", "value": "1"}], + * "remove": ["User-Agent"], + * "note": "mark the request" }, + * { "match_host": "*", "match_path_prefix": "/admin", + * "block": true, "note": "not part of this engagement" } + * ] + * } + * + * Values are validated for header injection (no CR/LF in a name or value; the + * name must be a token). A file with an invalid rule is rejected as a whole and + * the previous rules stay active: half a rule set is worse than the old one. + */ +#include +#include +#include +#include +#include + +#include "apex.h" +#include "rewrite.h" + +typedef struct { + char name[64]; + char value[256]; +} rewrite_set; + +typedef struct { + char match_host[256]; + char match_path[256]; + int block; + rewrite_set set[REWRITE_MAX_SET]; + int n_set; + char remove[REWRITE_MAX_REMOVE][64]; + int n_remove; + char note[256]; +} rewrite_rule; + +static rewrite_rule g_rules[REWRITE_MAX_RULES]; +static int g_nrules; + +static int header_name_ok(const char *s) +{ + size_t i; + + if (s == NULL || *s == '\0' || strlen(s) >= 64) + return 0; + for (i = 0; s[i] != '\0'; i++) + if (!isalnum((unsigned char)s[i]) && s[i] != '-' && s[i] != '_') + return 0; + return 1; +} + +static int header_value_ok(const char *s) +{ + for (; s != NULL && *s != '\0'; s++) + if (*s == '\r' || *s == '\n' || *s == '\0') + return 0; + return 1; +} + +static void field_copy(char *dst, size_t n, const char *src) +{ + size_t len; + + if (src == NULL) { + dst[0] = '\0'; + return; + } + len = strlen(src); + if (len >= n) + len = n - 1; + memcpy(dst, src, len); + dst[len] = '\0'; +} + +static int parse_rule(const mcp_json *item, rewrite_rule *r) +{ + const char *host = mcp_arg_string(item, "match_host"); + const char *path = mcp_arg_string(item, "match_path_prefix"); + const char *note = mcp_arg_string(item, "note"); + const mcp_json *set; + const mcp_json *remove; + size_t i; + + memset(r, 0, sizeof(*r)); + field_copy(r->match_host, sizeof(r->match_host), + host != NULL && *host != '\0' ? host : "*"); + field_copy(r->match_path, sizeof(r->match_path), + path != NULL && *path != '\0' ? path : "/"); + field_copy(r->note, sizeof(r->note), note); + r->block = mcp_arg_bool(item, "block", 0); + + set = mcp_arg(item, "set"); + for (i = 0; i < mcp_array_len(set) && r->n_set < REWRITE_MAX_SET; i++) { + const mcp_json *entry = mcp_array_at(set, i); + const char *name = mcp_arg_string(entry, "name"); + const char *value = mcp_arg_string(entry, "value"); + + if (!header_name_ok(name) || !header_value_ok(value)) { + fprintf(stderr, "apex-twin: rewrite rule has an invalid header\n"); + return -1; + } + field_copy(r->set[r->n_set].name, sizeof(r->set[r->n_set].name), name); + field_copy(r->set[r->n_set].value, sizeof(r->set[r->n_set].value), + value != NULL ? value : ""); + r->n_set++; + } + remove = mcp_arg(item, "remove"); + for (i = 0; i < mcp_array_len(remove) && r->n_remove < REWRITE_MAX_REMOVE; + i++) { + const char *name = mcp_json_string(mcp_array_at(remove, i)); + + if (!header_name_ok(name)) { + fprintf(stderr, "apex-twin: rewrite rule removes an invalid " + "header name\n"); + return -1; + } + field_copy(r->remove[r->n_remove], sizeof(r->remove[r->n_remove]), name); + r->n_remove++; + } + if (r->match_path[0] != '/') { + fprintf(stderr, "apex-twin: rewrite match_path_prefix must start " + "with /\n"); + return -1; + } + return 0; +} + +int apex_rewrite_load(void) +{ + FILE *f; + char *text; + long size; + mcp_json *root; + const mcp_json *rules; + rewrite_rule parsed[REWRITE_MAX_RULES]; + size_t count; + size_t i; + int n = 0; + + f = fopen(g_cfg.rewrite_file, "rb"); + if (f == NULL) { + g_nrules = 0; + return 0; + } + if (fseek(f, 0, SEEK_END) != 0) { + fclose(f); + return -1; + } + size = ftell(f); + if (size <= 0 || size > 65536) { + fclose(f); + fprintf(stderr, "apex-twin: rewrite file is empty or too large\n"); + return -1; + } + rewind(f); + text = malloc((size_t)size + 1); + if (text == NULL) { + fclose(f); + return -1; + } + if (fread(text, 1, (size_t)size, f) != (size_t)size) { + free(text); + fclose(f); + return -1; + } + text[size] = '\0'; + fclose(f); + + root = mcp_parse(text); + free(text); + if (root == NULL) { + fprintf(stderr, "apex-twin: rewrite file is not valid JSON\n"); + return -1; + } + rules = mcp_arg(root, "rules"); + count = mcp_array_len(rules); + if (count > REWRITE_MAX_RULES) + count = REWRITE_MAX_RULES; + for (i = 0; i < count; i++) { + if (parse_rule(mcp_array_at(rules, i), &parsed[n]) != 0) { + mcp_json_free(root); + return -1; + } + n++; + } + mcp_json_free(root); + memcpy(g_rules, parsed, (size_t)n * sizeof(parsed[0])); + g_nrules = n; + return 0; +} + +int apex_rewrite_count(void) +{ + return g_nrules; +} + +int apex_rewrite_match(const char *host, const char *path) +{ + int i; + + if (host == NULL || path == NULL) + return -1; + for (i = 0; i < g_nrules; i++) { + const rewrite_rule *r = &g_rules[i]; + + if (strcmp(r->match_host, "*") != 0 && + strcasecmp(r->match_host, host) != 0) + continue; + if (strncmp(path, r->match_path, strlen(r->match_path)) != 0) + continue; + return i; + } + return -1; +} + +int apex_rewrite_blocked(int rule) +{ + return rule >= 0 && rule < g_nrules ? g_rules[rule].block : 0; +} + +const char *apex_rewrite_note(int rule) +{ + return rule >= 0 && rule < g_nrules ? g_rules[rule].note : ""; +} + +int apex_rewrite_should_remove(int rule, const char *header_name) +{ + const rewrite_rule *r; + int i; + + if (rule < 0 || rule >= g_nrules || header_name == NULL) + return 0; + r = &g_rules[rule]; + for (i = 0; i < r->n_remove; i++) + if (strcasecmp(r->remove[i], header_name) == 0) + return 1; + /* a set header replaces the one the client sent */ + for (i = 0; i < r->n_set; i++) + if (strcasecmp(r->set[i].name, header_name) == 0) + return 1; + return 0; +} + +int apex_rewrite_set_count(int rule) +{ + return rule >= 0 && rule < g_nrules ? g_rules[rule].n_set : 0; +} + +const char *apex_rewrite_set_name(int rule, int i) +{ + if (rule < 0 || rule >= g_nrules || i < 0 || i >= g_rules[rule].n_set) + return NULL; + return g_rules[rule].set[i].name; +} + +const char *apex_rewrite_set_value(int rule, int i) +{ + if (rule < 0 || rule >= g_nrules || i < 0 || i >= g_rules[rule].n_set) + return NULL; + return g_rules[rule].set[i].value; +} diff --git a/src/rewrite.h b/src/rewrite.h new file mode 100644 index 0000000..80e56d7 --- /dev/null +++ b/src/rewrite.h @@ -0,0 +1,35 @@ +/* + * rewrite.h - request rewriting rules for the proxy. + * + * $APEX_HOME/rewrite.json (or APEX_REWRITE) holds an ordered list of rules. The + * first rule whose host and path prefix match is applied: it may block the + * request or add/remove headers before the request goes to the origin. Rules + * are configuration, not policy: the scope gate still runs first and still + * decides whether the target may be touched at all. + */ +#ifndef APEX_REWRITE_H +#define APEX_REWRITE_H + +#include "apex.h" + +#define REWRITE_MAX_RULES 64 +#define REWRITE_MAX_SET 8 +#define REWRITE_MAX_REMOVE 8 + +/* Load the rule file. 0 = loaded (or no file), -1 = parse error (old rules are + * kept). Safe to call again on SIGHUP. */ +int apex_rewrite_load(void); +int apex_rewrite_count(void); + +/* Index of the first matching rule, or -1. host is case-insensitive, "*" + * matches every host; path is matched by prefix. */ +int apex_rewrite_match(const char *host, const char *path); + +int apex_rewrite_blocked(int rule); +const char *apex_rewrite_note(int rule); +int apex_rewrite_should_remove(int rule, const char *header_name); +int apex_rewrite_set_count(int rule); +const char *apex_rewrite_set_name(int rule, int i); +const char *apex_rewrite_set_value(int rule, int i); + +#endif /* APEX_REWRITE_H */ diff --git a/tests/run.py b/tests/run.py index 3b0cf53..19fc9ce 100755 --- a/tests/run.py +++ b/tests/run.py @@ -10,6 +10,7 @@ import http.server import json import os import shutil +import signal import socket import subprocess import sys @@ -922,6 +923,132 @@ check("proxy audits both decisions", any(e["tool"] == "proxy" and e["decision"] == "deny" for e in paudit), [e for e in paudit if e["tool"] == "proxy"][:3]) +print("\n== proxy rewrite rules ==") +rw_seen = [] + + +class _RewriteOrigin(http.server.BaseHTTPRequestHandler): + def do_GET(self): + rw_seen.append(dict(self.headers)) + body = b"ok" + self.send_response(200) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +rw_origin = http.server.HTTPServer(("127.0.0.1", 0), _RewriteOrigin) +roport = rw_origin.server_address[1] +threading.Thread(target=rw_origin.serve_forever, daemon=True).start() +rw_home = tempfile.mkdtemp(prefix="apex-rewrite-") +write_scope(rw_home, {"label": "rewrite", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_port": [str(roport)]}) +rw_rules = {"rules": [ + {"match_host": "127.0.0.1", "match_path_prefix": "/rewrite", + "set": [{"name": "X-Test", "value": "1"}], + "remove": ["User-Agent"], "note": "marker"}, + {"match_host": "127.0.0.1", "match_path_prefix": "/blocked", + "block": True, "note": "blocked by rule"}, +]} +with open(os.path.join(rw_home, "rewrite.json"), "w") as f: + json.dump(rw_rules, f) +rport = free_port() +renv = dict(env) +renv["APEX_HOME"] = rw_home +rsrv = subprocess.Popen([BIN, "--proxy", str(rport)], env=renv, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) +deadline = time.time() + 10 +rup = False +while time.time() < deadline: + probe = socket.socket() + try: + probe.connect(("127.0.0.1", rport)) + rup = True + probe.close() + break + except OSError: + probe.close() + time.sleep(0.1) +check("rewrite proxy came up", rup, rport) + + +def rw_request(path, ua="original-agent"): + s = socket.create_connection(("127.0.0.1", rport), timeout=10) + raw = ("GET http://127.0.0.1:%d%s HTTP/1.1\r\n" + "Host: 127.0.0.1:%d\r\n" + "User-Agent: %s\r\n" + "Connection: close\r\n\r\n") % (roport, path, roport, ua) + s.sendall(raw.encode()) + s.settimeout(10) + data = b"" + try: + while True: + chunk = s.recv(65536) + if not chunk: + break + data += chunk + except socket.timeout: + pass + s.close() + return data + + +try: + hit = rw_request("/rewrite") + check("rewrite rule forwards the request", hit.startswith(b"HTTP/1.") and + b" 200 " in hit.split(b"\r\n")[0], hit[:80]) + check("rewrite rule adds the header", + rw_seen and rw_seen[-1].get("X-Test") == "1", rw_seen[-1:]) + check("rewrite rule removes the header", + rw_seen and rw_seen[-1].get("User-Agent") is None, rw_seen[-1:]) + plain = rw_request("/plain") + check("an unmatched path is untouched", rw_seen[-1].get("User-Agent") == + "original-agent" and rw_seen[-1].get("X-Test") is None, rw_seen[-1:]) + blocked = rw_request("/blocked") + check("a block rule answers 403", + blocked.startswith(b"HTTP/1.1 403"), blocked[:80]) + check("the 403 carries the rule note", b"blocked by rule" in blocked, + blocked[:200]) + + with open(os.path.join(rw_home, "rewrite.json"), "w") as f: + json.dump({"rules": [{"match_host": "127.0.0.1", + "match_path_prefix": "/plain", "block": True, + "note": "reloaded block"}]}, f) + os.kill(rsrv.pid, signal.SIGHUP) + time.sleep(0.4) + after = rw_request("/plain") + check("SIGHUP reloads the rules", + after.startswith(b"HTTP/1.1 403") and b"reloaded block" in after, + after[:120]) +finally: + rsrv.terminate() + try: + rsrv.wait(timeout=5) + except subprocess.TimeoutExpired: + rsrv.kill() + rw_origin.shutdown() + rw_origin.server_close() + +res, _ = run([ + call(1, "traffic_list"), + call(2, "audit_log", limit=200), +], home=rw_home) +rwt = json.loads(text([r for r in res if r.get("id") == 1][0])) +rec = [c for c in rwt if c["path"] == "/rewrite"] +check("the traffic record names the applied rule", + len(rec) == 1 and "rewrite rule 0" in rec[0]["note"] and + "marker" in rec[0]["note"], rec) +rwa = json.loads(text([r for r in res if r.get("id") == 2][0])) +check("rewrite allow and block are audited", + any(e["tool"] == "rewrite" and e["decision"] == "allow" for e in rwa) and + any(e["tool"] == "rewrite" and e["decision"] == "deny" for e in rwa), + [e for e in rwa if e["tool"] == "rewrite"][:3]) +shutil.rmtree(rw_home, ignore_errors=True) + # ------------------------------------------------------------- serial guard print("\n== serial guard ==") fake = os.path.join(ROOT, "notamodem")