apex-twin 0.7.0: a loopback proxy that refuses what the scope refuses
apex-twin --proxy 8798 puts the gate in front of clients that do not speak MCP: curl -x, a browser, an agent's fetch. Bind is loopback only. - absolute-URI HTTP requests are parsed, checked with apex_scope_check() BEFORE the origin socket is opened, audited, and forwarded with the request line rewritten to origin form; headers lose Proxy-Connection/Connection and gain Connection: close; - Content-Length bodies are forwarded; chunked request bodies are refused with 501 rather than silently truncated; - the exchange is stored through the same traffic store as http_capture, so proxied and explicit captures sit together; - CONNECT is tunnelled blind and recorded as metadata (host, port, bytes), because this binary links no TLS stack; a half-close is propagated with shutdown so the tunnel ends when the client does; - out of scope -> 403 with the gate's reason in the body and a deny line in audit.log. The gate-bypass sabotage was seen red: with proxy_gate() skipped, the out-of-scope request went out, 403 became 502, and the audit had no deny - three checks failed. 197 checks, 40 tools. New systemd/apex-twin-proxy.service, loopback port, no CAP_NET_RAW. Parser stores numbers unquoted; the proxy is serial on purpose.
This commit is contained in:
1 parent
a99da9315c
commit
d81f51645b
8 files changed
+932
-18
No files matched your search
@@ -17,8 +17,8 @@ separate, explicitly armed switch.
|
||||
## Build
|
||||
|
||||
```sh
|
||||
make # apex-twin, ~210 kB static-ish binary, zero warnings under -Werror
|
||||
make test # 185 end-to-end checks, no mocks
|
||||
make # apex-twin, ~220 kB static-ish binary, zero warnings under -Werror
|
||||
make test # 197 end-to-end checks, no mocks
|
||||
make install # /usr/local/bin/apex-twin
|
||||
```
|
||||
|
||||
@@ -131,6 +131,22 @@ took the first number in `HTTP/1.1 200 OK`, which is the `1` of the version, so
|
||||
path discovery and both probes had been comparing status `1` for every answer.
|
||||
The status is now parsed after the protocol token, and the test asserts `200`.
|
||||
|
||||
## The proxy
|
||||
|
||||
`apex-twin --proxy 8798` is the same gate in front of a client that is not
|
||||
MCP-aware: point `curl -x http://127.0.0.1:8798` (or a browser) at it and every
|
||||
request is checked with the scope before a socket opens, with the decision in
|
||||
`audit.log`. Plain HTTP is forwarded, the absolute request line is rewritten to
|
||||
origin form, and the exchange is stored through the same `traffic/` store as
|
||||
`http_capture`. `CONNECT` is tunnelled blind — this binary links no TLS stack,
|
||||
so the proxy records host, port and byte counts rather than pretending to see
|
||||
inside TLS. A request outside the scope gets `403 Forbidden` with the gate's
|
||||
reason in the body.
|
||||
|
||||
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)
|
||||
|
||||
**Scope and bookkeeping** — `scope_show`, `scope_check` (ask the gate without
|
||||
@@ -175,13 +191,15 @@ plus a note per tool on what people get wrong with it.
|
||||
```sh
|
||||
apex-twin # MCP over stdin/stdout (one JSON-RPC line each way)
|
||||
apex-twin --http 8797 # MCP over HTTP on 127.0.0.1:8797, POST /mcp
|
||||
apex-twin --proxy 8798 # forward proxy on 127.0.0.1:8798 (curl -x)
|
||||
apex-twin --check # scope, tool count and state dir as JSON, then exit
|
||||
```
|
||||
|
||||
HTTP binds **loopback only**. A service that can scan and transmit must not appear
|
||||
on a LAN by accident; reach it through a tunnel. `systemd/apex-twin.service` runs
|
||||
exactly that: `--http 127.0.0.1:8797`, a 0700 state dir, `dialout` for the radio,
|
||||
and a capability bounding set without `CAP_NET_RAW` (connect scans need none).
|
||||
HTTP and the proxy bind **loopback only**. A service that can scan and transmit
|
||||
must not appear on a LAN by accident; reach it through a tunnel.
|
||||
`systemd/apex-twin.service` and `systemd/apex-twin-proxy.service` run exactly
|
||||
that: loopback ports, a 0700 state dir, `dialout` for the radio, and a capability
|
||||
bounding set without `CAP_NET_RAW` (connect scans need none).
|
||||
|
||||
## The radio
|
||||
|
||||
@@ -236,7 +254,7 @@ finding and the next report no longer mentions it.
|
||||
make test
|
||||
```
|
||||
|
||||
185 checks, real binary, real DNS, real files written; no mocks. The suite was
|
||||
197 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
|
||||
@@ -250,7 +268,9 @@ unfiltered set. Disabling the asset merge turned seven red, and while it was red
|
||||
it exposed a real bug: the create path read an uninitialised struct, so a fresh
|
||||
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.
|
||||
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).
|
||||
|
||||
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
|
||||
@@ -258,10 +278,11 @@ this host is an SSH forward to another machine, and a foreign server answered
|
||||
|
||||
## Status
|
||||
|
||||
0.6.0. Built and run: 40 tools, 185 checks. The loop closes: a probe captures
|
||||
0.7.0. Built and run: 40 tools, 197 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. Not yet wired into a fleet router.
|
||||
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.
|
||||
+5
-6
@@ -20,7 +20,8 @@ module, deliberately left out, or still open.
|
||||
| Finding lifecycle (`finding_workflow.go`, `finding_verification.go`) | `finding_update`, report status filter | open/confirmed/false-positive/fixed plus a note; no retest runner |
|
||||
| Evidence (`evidence/store.go`) | `evidence/<ts>-<label>.bin` + `evidence_save`/`_list`/`_read` | 0600 blobs, base64 on read when not text |
|
||||
| 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, not a proxy |
|
||||
| Traffic archive (`traffic/`) | `src/store.c` traffic + `http_capture`/`traffic_*` | Request/response pair on disk; a capture is a proof |
|
||||
| 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 |
|
||||
| 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 |
|
||||
@@ -40,11 +41,9 @@ module, deliberately left out, or still open.
|
||||
|
||||
## Open
|
||||
|
||||
1. **Intercepting proxy** (`traffic/`, `intercept/`): `http_capture` stores a
|
||||
pair, but a forward proxy on loopback that stores every exchange a browser
|
||||
or curl makes is still missing. The pieces (HTTP parser, traffic store,
|
||||
audit, gate) are in place; the proxy loop and CONNECT tunnelling are not.
|
||||
2. **Notifications** (`notify/`): webhook on a critical finding.
|
||||
1. **Notifications** (`notify/`): webhook on a critical finding.
|
||||
2. **Request rewriting** (`traffic/rewrite`, `intercept`): the proxy forwards
|
||||
and captures, but does not yet modify a request in flight on a rule.
|
||||
|
||||
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
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
#include <unistd.h>
|
||||
|
||||
#include "apex.h"
|
||||
#include "proxy.h"
|
||||
#include "tools.h"
|
||||
|
||||
#define MAX_BODY (8u << 20)
|
||||
@@ -322,10 +323,19 @@ int main(int argc, char **argv)
|
||||
port = colon + 1;
|
||||
return serve_http(atoi(port));
|
||||
}
|
||||
if (strcmp(argv[i], "--proxy") == 0) {
|
||||
const char *port = (i + 1 < argc) ? argv[i + 1] : "8798";
|
||||
const char *colon = strrchr(port, ':');
|
||||
|
||||
if (colon != NULL)
|
||||
port = colon + 1;
|
||||
return apex_serve_proxy(atoi(port));
|
||||
}
|
||||
if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
|
||||
printf("apex-twin %s - offensive-security MCP server (C99/POSIX)\n\n"
|
||||
" apex-twin MCP over stdin/stdout\n"
|
||||
" apex-twin --http PORT MCP over HTTP on 127.0.0.1\n"
|
||||
" apex-twin --proxy PORT forward proxy on 127.0.0.1 (curl -x)\n"
|
||||
" apex-twin --check print scope and tool count\n"
|
||||
" apex-twin --version print the version\n\n"
|
||||
"Environment:\n"
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
|
||||
#include "mcp.h"
|
||||
|
||||
#define APEX_VERSION "0.6.0"
|
||||
#define APEX_VERSION "0.7.0"
|
||||
#define APEX_MAX_OUT (1u << 20)
|
||||
#define APEX_PATH_MAX 512
|
||||
#define APEX_PATH_FULL 1024
|
||||
|
||||
+750
@@ -0,0 +1,750 @@
|
||||
/*
|
||||
* proxy.c - a forward proxy that refuses what the scope refuses.
|
||||
*
|
||||
* apex-twin --proxy 8798
|
||||
*
|
||||
* Bind is loopback only. Every request the client asks the proxy to make is
|
||||
* checked with apex_scope_check() before a socket is opened, and the decision
|
||||
* is written to audit.log before the connect. A capture is stored through the
|
||||
* same store as http_capture, so proxied traffic and explicit captures sit in
|
||||
* one place.
|
||||
*
|
||||
* Plain HTTP is forwarded and captured. CONNECT is tunnelled blind and recorded
|
||||
* as metadata only: this binary links no TLS stack, so claiming to have seen
|
||||
* the inside of a TLS session would be false.
|
||||
*
|
||||
* One connection at a time is intentional. The proxy is a tool for one
|
||||
* operator, and serial handling makes the gate order easy to see; an origin
|
||||
* that stalls costs one timeout, not the process.
|
||||
*/
|
||||
#include <arpa/inet.h>
|
||||
#include <ctype.h>
|
||||
#include <errno.h>
|
||||
#include <netinet/in.h>
|
||||
#include <poll.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "apex.h"
|
||||
#include "proxy.h"
|
||||
#include "tools.h"
|
||||
|
||||
#define PROXY_HEAD_MAX (64u * 1024)
|
||||
#define PROXY_BODY_MAX (1u << 20)
|
||||
#define PROXY_RESP_MAX (1u << 20)
|
||||
#define PROXY_READ_MS 20000
|
||||
#define PROXY_ORIGIN_MS 8000
|
||||
#define PROXY_RESPONSE_MS 30000
|
||||
#define PROXY_TUNNEL_MS 60000
|
||||
#define PROXY_TUNNEL_CAP (64L << 20)
|
||||
|
||||
static long now_ms(void)
|
||||
{
|
||||
struct timeval tv;
|
||||
|
||||
gettimeofday(&tv, NULL);
|
||||
return tv.tv_sec * 1000L + tv.tv_usec / 1000;
|
||||
}
|
||||
|
||||
static int send_all(int fd, const char *p, size_t n)
|
||||
{
|
||||
size_t off = 0;
|
||||
|
||||
while (off < n) {
|
||||
ssize_t w = write(fd, p + off, n - off);
|
||||
|
||||
if (w <= 0)
|
||||
return -1;
|
||||
off += (size_t)w;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void reply_error(int fd, int code, const char *reason, const char *detail)
|
||||
{
|
||||
char body[1200];
|
||||
mcp_buf out;
|
||||
int n;
|
||||
|
||||
n = snprintf(body, sizeof(body), "%d %s\n%s\n", code, reason,
|
||||
detail != NULL ? detail : "");
|
||||
if (n < 0)
|
||||
n = 0;
|
||||
if (n > (int)sizeof(body))
|
||||
n = (int)sizeof(body);
|
||||
mcp_buf_init(&out);
|
||||
mcp_buf_printf(&out, "HTTP/1.1 %d %s\r\nContent-Type: text/plain\r\n"
|
||||
"Content-Length: %d\r\nConnection: close\r\n\r\n",
|
||||
code, reason, n);
|
||||
mcp_buf_add(&out, body, (size_t)n);
|
||||
(void)send_all(fd, out.p, out.len);
|
||||
mcp_buf_free(&out);
|
||||
}
|
||||
|
||||
/*
|
||||
* Read until the end of the request head. Returns the offset just past
|
||||
* CRLFCRLF, and sets *total to every byte read (the client may have sent part
|
||||
* of the body in the same packet). -1 on timeout, EOF or an oversized head.
|
||||
*/
|
||||
static int read_head(int fd, char *buf, size_t cap, int timeout_ms, size_t *total)
|
||||
{
|
||||
size_t used = 0;
|
||||
long start = now_ms();
|
||||
|
||||
*total = 0;
|
||||
while (used + 1 < cap) {
|
||||
struct pollfd p;
|
||||
long spent = now_ms() - start;
|
||||
ssize_t n;
|
||||
char *end;
|
||||
int pr;
|
||||
|
||||
if (spent >= timeout_ms)
|
||||
return -1;
|
||||
p.fd = fd;
|
||||
p.events = POLLIN;
|
||||
pr = poll(&p, 1, (int)(timeout_ms - spent));
|
||||
if (pr <= 0)
|
||||
return -1;
|
||||
n = read(fd, buf + used, cap - used - 1);
|
||||
if (n <= 0)
|
||||
return -1;
|
||||
used += (size_t)n;
|
||||
buf[used] = '\0';
|
||||
end = strstr(buf, "\r\n\r\n");
|
||||
if (end != NULL) {
|
||||
*total = used;
|
||||
return (int)(end - buf) + 4;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int read_into(int fd, char *dst, size_t n, int timeout_ms)
|
||||
{
|
||||
size_t got = 0;
|
||||
long start = now_ms();
|
||||
|
||||
while (got < n) {
|
||||
struct pollfd p;
|
||||
long spent = now_ms() - start;
|
||||
ssize_t r;
|
||||
int pr;
|
||||
|
||||
if (spent >= timeout_ms)
|
||||
return -1;
|
||||
p.fd = fd;
|
||||
p.events = POLLIN;
|
||||
pr = poll(&p, 1, (int)(timeout_ms - spent));
|
||||
if (pr <= 0)
|
||||
return -1;
|
||||
r = read(fd, dst + got, n - got);
|
||||
if (r <= 0)
|
||||
return -1;
|
||||
got += (size_t)r;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static char *read_all_fd(int fd, size_t cap, int timeout_ms, size_t *out_len)
|
||||
{
|
||||
char *buf = malloc(cap + 1);
|
||||
size_t used = 0;
|
||||
long start = now_ms();
|
||||
|
||||
if (buf == NULL)
|
||||
return NULL;
|
||||
while (used < cap) {
|
||||
struct pollfd p;
|
||||
long spent = now_ms() - start;
|
||||
ssize_t n;
|
||||
int pr;
|
||||
|
||||
if (spent >= timeout_ms)
|
||||
break;
|
||||
p.fd = fd;
|
||||
p.events = POLLIN;
|
||||
pr = poll(&p, 1, (int)(timeout_ms - spent));
|
||||
if (pr <= 0)
|
||||
break;
|
||||
n = read(fd, buf + used, cap - used);
|
||||
if (n <= 0)
|
||||
break;
|
||||
used += (size_t)n;
|
||||
}
|
||||
buf[used] = '\0';
|
||||
*out_len = used;
|
||||
return buf;
|
||||
}
|
||||
|
||||
static int ci_prefix(const char *s, const char *prefix)
|
||||
{
|
||||
while (*prefix != '\0') {
|
||||
if (*s == '\0')
|
||||
return 0;
|
||||
if (tolower((unsigned char)*s) != tolower((unsigned char)*prefix))
|
||||
return 0;
|
||||
s++;
|
||||
prefix++;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int ci_equal_n(const char *a, const char *b, size_t n)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < n; i++) {
|
||||
if (a[i] == '\0' || b[i] == '\0')
|
||||
return 0;
|
||||
if (tolower((unsigned char)a[i]) != tolower((unsigned char)b[i]))
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int header_value(const char *head, const char *name, char *out, size_t n)
|
||||
{
|
||||
const char *p = strstr(head, "\r\n");
|
||||
size_t nl = strlen(name);
|
||||
|
||||
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 &&
|
||||
ci_equal_n(p, name, nl)) {
|
||||
const char *v = colon + 1;
|
||||
size_t len;
|
||||
|
||||
while (*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;
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
char method[16];
|
||||
char target[1024]; /* absolute URI, or host:port for CONNECT */
|
||||
char host[256];
|
||||
char path[1024];
|
||||
int port;
|
||||
int tls;
|
||||
long content_length;
|
||||
int chunked;
|
||||
} proxy_req;
|
||||
|
||||
static int host_port(const char *s, char *host, size_t hn, int *port)
|
||||
{
|
||||
char buf[300];
|
||||
char *colon;
|
||||
|
||||
if (s == NULL || *s == '\0' || strlen(s) >= sizeof(buf))
|
||||
return -1;
|
||||
strcpy(buf, s);
|
||||
*port = 0;
|
||||
if (buf[0] == '[') {
|
||||
char *close = strchr(buf, ']');
|
||||
|
||||
if (close == NULL)
|
||||
return -1;
|
||||
*close = '\0';
|
||||
memmove(buf, buf + 1, strlen(buf + 1) + 1);
|
||||
if (close[1] == ':')
|
||||
*port = atoi(close + 2);
|
||||
} else {
|
||||
colon = strrchr(buf, ':');
|
||||
if (colon != NULL && colon[1] != '\0') {
|
||||
int all = 1;
|
||||
char *q;
|
||||
|
||||
for (q = colon + 1; *q != '\0'; q++)
|
||||
if (!isdigit((unsigned char)*q))
|
||||
all = 0;
|
||||
if (all) {
|
||||
*port = atoi(colon + 1);
|
||||
*colon = '\0';
|
||||
}
|
||||
}
|
||||
}
|
||||
if (*buf == '\0' || strlen(buf) >= hn)
|
||||
return -1;
|
||||
{
|
||||
size_t len = strlen(buf);
|
||||
|
||||
memcpy(host, buf, len + 1);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Copy a token without asking snprintf to prove it fits. */
|
||||
static void copy_to(char *dst, size_t n, const char *src)
|
||||
{
|
||||
size_t len = strlen(src);
|
||||
|
||||
if (len >= n)
|
||||
len = n - 1;
|
||||
memcpy(dst, src, len);
|
||||
dst[len] = '\0';
|
||||
}
|
||||
|
||||
static int parse_request(const char *head, proxy_req *r)
|
||||
{
|
||||
char line[2048];
|
||||
const char *eol = strstr(head, "\r\n");
|
||||
char *sp1;
|
||||
char *sp2;
|
||||
char cl[32];
|
||||
|
||||
memset(r, 0, sizeof(*r));
|
||||
if (eol == NULL || (size_t)(eol - head) >= sizeof(line))
|
||||
return -1;
|
||||
memcpy(line, head, (size_t)(eol - head));
|
||||
line[eol - head] = '\0';
|
||||
sp1 = strchr(line, ' ');
|
||||
if (sp1 == NULL)
|
||||
return -1;
|
||||
*sp1++ = '\0';
|
||||
sp2 = strchr(sp1, ' ');
|
||||
if (sp2 != NULL)
|
||||
*sp2 = '\0';
|
||||
if (strlen(line) >= sizeof(r->method) || strlen(sp1) >= sizeof(r->target))
|
||||
return -1;
|
||||
copy_to(r->method, sizeof(r->method), line);
|
||||
copy_to(r->target, sizeof(r->target), sp1);
|
||||
|
||||
if (strcmp(r->method, "CONNECT") == 0) {
|
||||
r->tls = 1;
|
||||
if (host_port(r->target, r->host, sizeof(r->host), &r->port) != 0)
|
||||
return -1;
|
||||
if (r->port <= 0)
|
||||
r->port = 443;
|
||||
copy_to(r->path, sizeof(r->path), r->target);
|
||||
return 0;
|
||||
}
|
||||
|
||||
{
|
||||
const char *scheme = strstr(r->target, "://");
|
||||
|
||||
if (scheme != NULL) {
|
||||
size_t sl = (size_t)(scheme - r->target);
|
||||
const char *auth = scheme + 3;
|
||||
const char *end = auth;
|
||||
const char *at;
|
||||
char authority[512];
|
||||
size_t al;
|
||||
|
||||
if (sl == 5 && ci_equal_n(r->target, "https", 5))
|
||||
return -2; /* needs CONNECT; no TLS in-process */
|
||||
if (sl != 4 || !ci_equal_n(r->target, "http", 4))
|
||||
return -2;
|
||||
while (*end != '\0' && *end != '/' && *end != '?' &&
|
||||
*end != '#')
|
||||
end++;
|
||||
al = (size_t)(end - auth);
|
||||
if (al == 0 || al >= sizeof(authority))
|
||||
return -1;
|
||||
memcpy(authority, auth, al);
|
||||
authority[al] = '\0';
|
||||
at = strrchr(authority, '@');
|
||||
if (host_port(at != NULL ? at + 1 : authority, r->host,
|
||||
sizeof(r->host), &r->port) != 0)
|
||||
return -1;
|
||||
if (r->port <= 0)
|
||||
r->port = 80;
|
||||
if (*end == '\0')
|
||||
copy_to(r->path, sizeof(r->path), "/");
|
||||
else if (*end == '/')
|
||||
copy_to(r->path, sizeof(r->path), end);
|
||||
else {
|
||||
size_t pl = strlen(end);
|
||||
|
||||
if (pl + 2 < sizeof(r->path)) {
|
||||
r->path[0] = '/';
|
||||
memcpy(r->path + 1, end, pl + 1);
|
||||
} else {
|
||||
copy_to(r->path, sizeof(r->path), end);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
/* origin-form request: the target is the path, Host has the name */
|
||||
char hv[300];
|
||||
|
||||
if (r->target[0] != '/')
|
||||
return -1;
|
||||
copy_to(r->path, sizeof(r->path), r->target);
|
||||
if (!header_value(head, "host", hv, sizeof(hv)))
|
||||
return -1;
|
||||
if (host_port(hv, r->host, sizeof(r->host), &r->port) != 0)
|
||||
return -1;
|
||||
if (r->port <= 0)
|
||||
r->port = 80;
|
||||
}
|
||||
}
|
||||
|
||||
if (header_value(head, "content-length", cl, sizeof(cl))) {
|
||||
long v = strtol(cl, NULL, 10);
|
||||
|
||||
if (v < 0 || v > (long)PROXY_BODY_MAX)
|
||||
return -3;
|
||||
r->content_length = v;
|
||||
}
|
||||
{
|
||||
char te[64];
|
||||
|
||||
if (header_value(head, "transfer-encoding", te, sizeof(te)) &&
|
||||
ci_prefix(te, "chunked"))
|
||||
return -4;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void build_forward(const char *head, int head_end, const proxy_req *r,
|
||||
mcp_buf *out)
|
||||
{
|
||||
char *copy = malloc((size_t)head_end + 1);
|
||||
char *save = NULL;
|
||||
char *line;
|
||||
int had_host = 0;
|
||||
|
||||
mcp_buf_printf(out, "%s %s HTTP/1.1\r\n", r->method, r->path);
|
||||
if (copy == NULL) {
|
||||
mcp_buf_printf(out, "Host: %s\r\nConnection: close\r\n\r\n", r->host);
|
||||
return;
|
||||
}
|
||||
memcpy(copy, head, (size_t)head_end);
|
||||
copy[head_end] = '\0';
|
||||
line = strtok_r(copy, "\r\n", &save); /* the request line */
|
||||
while ((line = strtok_r(NULL, "\r\n", &save)) != NULL) {
|
||||
if (ci_prefix(line, "proxy-connection:") ||
|
||||
ci_prefix(line, "proxy-authorization:") ||
|
||||
ci_prefix(line, "connection:") ||
|
||||
ci_prefix(line, "keep-alive:"))
|
||||
continue;
|
||||
if (ci_prefix(line, "host:"))
|
||||
had_host = 1;
|
||||
mcp_buf_puts(out, line);
|
||||
mcp_buf_puts(out, "\r\n");
|
||||
}
|
||||
if (!had_host)
|
||||
mcp_buf_printf(out, "Host: %s\r\n", r->host);
|
||||
mcp_buf_puts(out, "Connection: close\r\n\r\n");
|
||||
free(copy);
|
||||
}
|
||||
|
||||
static int status_code_of(const char *resp)
|
||||
{
|
||||
const char *p = resp;
|
||||
|
||||
if (p == NULL || *p == '\0')
|
||||
return 0;
|
||||
if (strncmp(p, "HTTP/", 5) == 0) {
|
||||
p = strchr(p, ' ');
|
||||
if (p == NULL)
|
||||
return 0;
|
||||
return atoi(p + 1);
|
||||
}
|
||||
return atoi(p);
|
||||
}
|
||||
|
||||
static int proxy_gate(const char *host, int port, const char *cmd, char *reason,
|
||||
size_t rn)
|
||||
{
|
||||
int ok = apex_scope_check(host, port, reason, rn);
|
||||
|
||||
apex_audit("proxy", host, port, ok, reason, cmd);
|
||||
if (!ok)
|
||||
fprintf(stderr, "apex-twin: proxy refused %s:%d: %s\n", host, port,
|
||||
reason);
|
||||
return ok;
|
||||
}
|
||||
|
||||
static void tunnel(int a, int b, long *up, long *down, int idle_ms)
|
||||
{
|
||||
char buf[16384];
|
||||
int open_a = 1;
|
||||
int open_b = 1;
|
||||
|
||||
while ((open_a || open_b) && (*up + *down) < PROXY_TUNNEL_CAP) {
|
||||
struct pollfd p[2];
|
||||
int ia = -1;
|
||||
int ib = -1;
|
||||
int nf = 0;
|
||||
int pr;
|
||||
|
||||
if (open_a) {
|
||||
p[nf].fd = a;
|
||||
p[nf].events = POLLIN;
|
||||
ia = nf++;
|
||||
}
|
||||
if (open_b) {
|
||||
p[nf].fd = b;
|
||||
p[nf].events = POLLIN;
|
||||
ib = nf++;
|
||||
}
|
||||
pr = poll(p, (nfds_t)nf, idle_ms);
|
||||
if (pr <= 0)
|
||||
break;
|
||||
if (open_a && ia >= 0 && (p[ia].revents & (POLLIN | POLLHUP))) {
|
||||
ssize_t n = read(a, buf, sizeof(buf));
|
||||
|
||||
if (n <= 0) {
|
||||
open_a = 0;
|
||||
/* tell the far side there will be no more of this */
|
||||
shutdown(b, SHUT_WR);
|
||||
} else {
|
||||
if (send_all(b, buf, (size_t)n) != 0)
|
||||
break;
|
||||
*up += n;
|
||||
}
|
||||
}
|
||||
if (open_b && ib >= 0 && (p[ib].revents & (POLLIN | POLLHUP))) {
|
||||
ssize_t n = read(b, buf, sizeof(buf));
|
||||
|
||||
if (n <= 0) {
|
||||
open_b = 0;
|
||||
shutdown(a, SHUT_WR);
|
||||
} else {
|
||||
if (send_all(a, buf, (size_t)n) != 0)
|
||||
break;
|
||||
*down += n;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void handle_connect(int cfd, const proxy_req *r, const char *line)
|
||||
{
|
||||
char reason[512];
|
||||
int ofd;
|
||||
long up = 0;
|
||||
long down = 0;
|
||||
char note[160];
|
||||
|
||||
if (!proxy_gate(r->host, r->port, line, reason, sizeof(reason))) {
|
||||
reply_error(cfd, 403, "Forbidden", reason);
|
||||
return;
|
||||
}
|
||||
ofd = tcp_connect_host(r->host, r->port, PROXY_ORIGIN_MS);
|
||||
if (ofd < 0) {
|
||||
reply_error(cfd, 502, "Bad Gateway",
|
||||
"cannot connect to the requested host");
|
||||
return;
|
||||
}
|
||||
if (send_all(cfd, "HTTP/1.1 200 Connection established\r\n\r\n",
|
||||
sizeof("HTTP/1.1 200 Connection established\r\n\r\n") - 1) != 0) {
|
||||
close(ofd);
|
||||
return;
|
||||
}
|
||||
tunnel(cfd, ofd, &up, &down, PROXY_TUNNEL_MS);
|
||||
close(ofd);
|
||||
snprintf(note, sizeof(note), "proxy tunnel: %ld bytes up, %ld bytes down",
|
||||
up, down);
|
||||
{
|
||||
char *id = apex_traffic_add(r->host, r->port, 1, "CONNECT", r->path, 200,
|
||||
NULL, 0, NULL, 0, note);
|
||||
|
||||
free(id);
|
||||
}
|
||||
}
|
||||
|
||||
static void handle_forward(int cfd, const char *head, int head_end,
|
||||
size_t total, const proxy_req *r, const char *line)
|
||||
{
|
||||
char reason[512];
|
||||
int ofd;
|
||||
mcp_buf req;
|
||||
size_t prefix;
|
||||
size_t remaining;
|
||||
char *resp;
|
||||
size_t rlen = 0;
|
||||
char note[160];
|
||||
|
||||
if (!proxy_gate(r->host, r->port, line, reason, sizeof(reason))) {
|
||||
reply_error(cfd, 403, "Forbidden", reason);
|
||||
return;
|
||||
}
|
||||
ofd = tcp_connect_host(r->host, r->port, PROXY_ORIGIN_MS);
|
||||
if (ofd < 0) {
|
||||
reply_error(cfd, 502, "Bad Gateway",
|
||||
"cannot connect to the requested host");
|
||||
return;
|
||||
}
|
||||
|
||||
mcp_buf_init(&req);
|
||||
build_forward(head, head_end, r, &req);
|
||||
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;
|
||||
if (prefix > 0)
|
||||
mcp_buf_add(&req, head + head_end, prefix);
|
||||
remaining = (size_t)r->content_length - prefix;
|
||||
while (remaining > 0) {
|
||||
char tmp[8192];
|
||||
size_t chunk = remaining < sizeof(tmp) ? remaining : sizeof(tmp);
|
||||
|
||||
if (read_into(cfd, tmp, chunk, PROXY_READ_MS) != 0) {
|
||||
mcp_buf_free(&req);
|
||||
close(ofd);
|
||||
reply_error(cfd, 400, "Bad Request", "incomplete request body");
|
||||
return;
|
||||
}
|
||||
mcp_buf_add(&req, tmp, chunk);
|
||||
remaining -= chunk;
|
||||
}
|
||||
if (send_all(ofd, req.p, req.len) != 0)
|
||||
fprintf(stderr, "apex-twin: proxy write to origin failed\n");
|
||||
|
||||
resp = read_all_fd(ofd, PROXY_RESP_MAX, PROXY_RESPONSE_MS, &rlen);
|
||||
close(ofd);
|
||||
if (resp == NULL || rlen == 0) {
|
||||
free(resp);
|
||||
mcp_buf_free(&req);
|
||||
reply_error(cfd, 504, "Gateway Timeout", "the origin sent no response");
|
||||
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");
|
||||
{
|
||||
char *id = apex_traffic_add(r->host, r->port, 0, r->method, r->path,
|
||||
status_code_of(resp), req.p, req.len, resp,
|
||||
rlen, note);
|
||||
|
||||
free(id);
|
||||
}
|
||||
free(resp);
|
||||
mcp_buf_free(&req);
|
||||
}
|
||||
|
||||
static void handle_client(int cfd)
|
||||
{
|
||||
char *head = malloc(PROXY_HEAD_MAX + 1);
|
||||
size_t total = 0;
|
||||
int head_end;
|
||||
proxy_req r;
|
||||
int pr;
|
||||
|
||||
if (head == NULL)
|
||||
return;
|
||||
head_end = read_head(cfd, head, PROXY_HEAD_MAX + 1, PROXY_READ_MS, &total);
|
||||
if (head_end < 0) {
|
||||
free(head);
|
||||
return;
|
||||
}
|
||||
pr = parse_request(head, &r);
|
||||
if (pr == -2) {
|
||||
reply_error(cfd, 501, "Not Implemented",
|
||||
"https absolute URIs need CONNECT; this proxy does not "
|
||||
"terminate TLS");
|
||||
free(head);
|
||||
return;
|
||||
}
|
||||
if (pr == -3) {
|
||||
reply_error(cfd, 413, "Payload Too Large",
|
||||
"request body over the proxy limit");
|
||||
free(head);
|
||||
return;
|
||||
}
|
||||
if (pr == -4) {
|
||||
reply_error(cfd, 501, "Not Implemented",
|
||||
"chunked request bodies are not supported");
|
||||
free(head);
|
||||
return;
|
||||
}
|
||||
if (pr != 0) {
|
||||
reply_error(cfd, 400, "Bad Request", "cannot parse the request line");
|
||||
free(head);
|
||||
return;
|
||||
}
|
||||
{
|
||||
char line[2048];
|
||||
size_t len = (size_t)head_end - 4;
|
||||
const char *eol = strstr(head, "\r\n");
|
||||
|
||||
if (len >= sizeof(line) || eol == NULL)
|
||||
snprintf(line, sizeof(line), "%s %s", r.method, r.target);
|
||||
else {
|
||||
len = (size_t)(eol - head);
|
||||
if (len >= sizeof(line))
|
||||
len = sizeof(line) - 1;
|
||||
memcpy(line, head, len);
|
||||
line[len] = '\0';
|
||||
}
|
||||
if (strcmp(r.method, "CONNECT") == 0)
|
||||
handle_connect(cfd, &r, line);
|
||||
else
|
||||
handle_forward(cfd, head, head_end, total, &r, line);
|
||||
}
|
||||
free(head);
|
||||
}
|
||||
|
||||
int apex_serve_proxy(int port)
|
||||
{
|
||||
int ls;
|
||||
int one = 1;
|
||||
struct sockaddr_in sa;
|
||||
socklen_t sl;
|
||||
|
||||
signal(SIGPIPE, SIG_IGN);
|
||||
ls = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (ls < 0) {
|
||||
perror("apex-twin: proxy socket");
|
||||
return 1;
|
||||
}
|
||||
setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
sa.sin_family = AF_INET;
|
||||
sa.sin_port = htons((unsigned short)port);
|
||||
sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
if (bind(ls, (struct sockaddr *)&sa, sizeof(sa)) != 0) {
|
||||
perror("apex-twin: proxy bind");
|
||||
close(ls);
|
||||
return 1;
|
||||
}
|
||||
if (listen(ls, 16) != 0) {
|
||||
perror("apex-twin: proxy listen");
|
||||
close(ls);
|
||||
return 1;
|
||||
}
|
||||
sl = sizeof(sa);
|
||||
if (getsockname(ls, (struct sockaddr *)&sa, &sl) == 0)
|
||||
fprintf(stderr, "apex-twin: proxy on 127.0.0.1:%d\n",
|
||||
ntohs(sa.sin_port));
|
||||
for (;;) {
|
||||
int fd = accept(ls, NULL, NULL);
|
||||
|
||||
if (fd < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
break;
|
||||
}
|
||||
handle_client(fd);
|
||||
close(fd);
|
||||
}
|
||||
close(ls);
|
||||
return 0;
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* proxy.h - the loopback forward proxy.
|
||||
*
|
||||
* The proxy exists so that a normal client (curl -x, a browser, an agent's
|
||||
* fetch tool) can be pointed at APEX TWIN and have every exchange pass the same
|
||||
* scope gate. It is not a TLS interceptor: CONNECT is tunnelled blind, because
|
||||
* this binary links no TLS stack and pretending otherwise would be a lie.
|
||||
*/
|
||||
#ifndef APEX_PROXY_H
|
||||
#define APEX_PROXY_H
|
||||
|
||||
/* Bind 127.0.0.1:port (0 = ephemeral, the real port is printed to stderr) and
|
||||
* serve until killed. Returns 1 on error. */
|
||||
int apex_serve_proxy(int port);
|
||||
|
||||
#endif /* APEX_PROXY_H */
|
||||
@@ -0,0 +1,24 @@
|
||||
[Unit]
|
||||
Description=APEX TWIN scope-gated forward proxy (loopback)
|
||||
Documentation=file:/usr/local/share/doc/apex-twin/README.md
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=lotherk
|
||||
# The proxy does not touch the radio, so no dialout here.
|
||||
Environment=APEX_HOME=/home/lotherk/stack/data/apex-twin
|
||||
EnvironmentFile=-/home/lotherk/.config/apex-twin/env
|
||||
ExecStart=/usr/local/bin/apex-twin --proxy 8798
|
||||
Restart=on-failure
|
||||
RestartSec=3
|
||||
NoNewPrivileges=yes
|
||||
ProtectSystem=strict
|
||||
ProtectHome=read-only
|
||||
PrivateTmp=yes
|
||||
ReadWritePaths=/home/lotherk/stack/data/apex-twin
|
||||
# loopback only; no CAP_NET_RAW, no CAP_NET_ADMIN, no device nodes
|
||||
CapabilityBoundingSet=~CAP_SYS_ADMIN CAP_SYS_PTRACE CAP_NET_ADMIN CAP_NET_RAW
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
+95
-1
@@ -79,7 +79,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"],
|
||||
"allow_port": ["80", "8080", "443"],
|
||||
}
|
||||
|
||||
print("== binary ==")
|
||||
@@ -686,6 +686,100 @@ finally:
|
||||
except subprocess.TimeoutExpired:
|
||||
srv.kill()
|
||||
|
||||
print("\n== proxy ==")
|
||||
pport = free_port()
|
||||
psrv = subprocess.Popen([BIN, "--proxy", str(pport)], env=env,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
deadline = time.time() + 10
|
||||
pup = False
|
||||
while time.time() < deadline:
|
||||
probe = socket.socket()
|
||||
try:
|
||||
probe.connect(("127.0.0.1", pport))
|
||||
pup = True
|
||||
probe.close()
|
||||
break
|
||||
except OSError:
|
||||
probe.close()
|
||||
time.sleep(0.1)
|
||||
check("proxy listener came up", pup, pport)
|
||||
|
||||
|
||||
def proxy_exchange(raw, wait=10):
|
||||
s = socket.create_connection(("127.0.0.1", pport), timeout=wait)
|
||||
s.sendall(raw)
|
||||
s.settimeout(wait)
|
||||
data = b""
|
||||
try:
|
||||
while True:
|
||||
chunk = s.recv(65536)
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
except socket.timeout:
|
||||
pass
|
||||
s.close()
|
||||
return data
|
||||
|
||||
|
||||
try:
|
||||
got = proxy_exchange(b"GET http://example.com/ HTTP/1.1\r\n"
|
||||
b"Host: example.com\r\n"
|
||||
b"Proxy-Connection: close\r\n"
|
||||
b"Connection: close\r\n\r\n")
|
||||
check("proxy forwards an in-scope request",
|
||||
got.startswith(b"HTTP/1.1 200"), got[:80])
|
||||
check("proxy returns the origin body", b"Example Domain" in got, len(got))
|
||||
|
||||
denied = proxy_exchange(b"GET http://198.51.100.9/ HTTP/1.1\r\n"
|
||||
b"Host: 198.51.100.9\r\n"
|
||||
b"Connection: close\r\n\r\n")
|
||||
check("proxy refuses an out-of-scope target",
|
||||
denied.startswith(b"HTTP/1.1 403"), denied[:80])
|
||||
check("proxy writes the scope reason into the 403",
|
||||
b"outside allow_ip" in denied, denied[:200])
|
||||
|
||||
conn = proxy_exchange(b"CONNECT example.com:443 HTTP/1.1\r\n"
|
||||
b"Host: example.com:443\r\n\r\n", 3)
|
||||
check("proxy answers CONNECT",
|
||||
conn.startswith(b"HTTP/1.1 200 Connection established"), conn[:80])
|
||||
finally:
|
||||
time.sleep(1.0)
|
||||
psrv.terminate()
|
||||
try:
|
||||
psrv.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
psrv.kill()
|
||||
|
||||
res, _ = run([
|
||||
call(1, "traffic_list"),
|
||||
call(2, "audit_log", limit=300),
|
||||
])
|
||||
captures = json.loads(text([r for r in res if r.get("id") == 1][0]))
|
||||
get_rec = [c for c in captures
|
||||
if c["method"] == "GET" and c["note"] == "proxy capture"]
|
||||
check("proxy stored the forwarded exchange", len(get_rec) == 1, captures)
|
||||
check("proxy record carries the target and status",
|
||||
get_rec and get_rec[0]["target"] == "example.com" and
|
||||
get_rec[0]["status"] == 200, get_rec)
|
||||
with open(get_rec[0]["raw"], "rb") as f:
|
||||
praw = f.read()
|
||||
phead = praw.split(b"=== RESPONSE (raw) ===")[0]
|
||||
check("proxy rewrote the request to origin form",
|
||||
phead.startswith(b"GET / HTTP/1.1\r\n") and
|
||||
b"http://example.com" not in phead, phead[:120])
|
||||
check("proxy record kept the raw response",
|
||||
b"HTTP/1.1 200" in praw, praw[:120])
|
||||
tun = [c for c in captures if c["method"] == "CONNECT"]
|
||||
check("proxy recorded the CONNECT tunnel",
|
||||
len(tun) == 1 and tun[0]["port"] == 443 and "tunnel" in tun[0]["note"],
|
||||
tun)
|
||||
paudit = json.loads(text([r for r in res if r.get("id") == 2][0]))
|
||||
check("proxy audits both decisions",
|
||||
any(e["tool"] == "proxy" and e["decision"] == "allow" for e in paudit) and
|
||||
any(e["tool"] == "proxy" and e["decision"] == "deny" for e in paudit),
|
||||
[e for e in paudit if e["tool"] == "proxy"][:3])
|
||||
|
||||
# ------------------------------------------------------------- serial guard
|
||||
print("\n== serial guard ==")
|
||||
fake = os.path.join(ROOT, "notamodem")
|
||||
|
||||
Reference in new issue
Block a user