Refuse loopback and metadata targets; check the agent's token before reading its report
Certificate check, WHOIS lookup and port scanner connect to hosts that are typed in or named by a plain-text reply. utils/networkGuard.ts now refuses loopback, link-local (cloud metadata) and similar addresses for all three -- and a WHOIS server on a private network -- and the connection goes to the address that was checked rather than looking the name up again (no DNS rebinding). LAN hosts remain fine for certificate checks and scans. Agent endpoint: the token is checked before the body is read, the route is mounted ahead of the 100 KB JSON parser so a real agent can send a large report (up to 4 MB), and overlong text is trimmed instead of costing the host its whole report. An oversized or malformed body is answered with 413 / 400 instead of a generic 500. Tests (npm test --workspace server): the guard, the secrets route, the agent endpoint, the Linux upload run against a fake server (token never on curl's arguments, private temp dir removed), the systemd unit's directives, and the Windows folder permissions read back by SID. 19 of the 26 new tests fail against the previous code. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
047fcb403e
commit
dbbe4180e0
9 files changed
+710
-40
No files matched your search
@@ -1,4 +1,4 @@
|
||||
import { Router } from "express";
|
||||
import express, { Router, type NextFunction, type Request, type Response } from "express";
|
||||
import { z } from "zod";
|
||||
import { db } from "../db/client.js";
|
||||
import { hashToken } from "../services/tokens.js";
|
||||
@@ -7,18 +7,30 @@ import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
|
||||
export const agentReportRouter = Router();
|
||||
|
||||
// A host with a lot of listening sockets and cron entries sends a big report, so this endpoint takes far more than the
|
||||
// 100 KB the rest of the API does. It's only safe to read that much from someone who has proved they're an agent, so the
|
||||
// token is checked before the body is — and this route is mounted ahead of the app-wide JSON parser (see index.ts).
|
||||
const AGENT_BODY_LIMIT = "4mb";
|
||||
|
||||
/** Text from an agent is trimmed to a sane length rather than rejected: a report that's refused over one long line costs the host its whole report. */
|
||||
const text = (max: number) => z.string().transform((s) => (s.length > max ? s.slice(0, max) : s));
|
||||
const cap = <T>(max: number) => (items: T[]) => (items.length > max ? items.slice(0, max) : items);
|
||||
|
||||
const listeningPortSchema = z.object({
|
||||
protocol: z.enum(["tcp", "udp"]),
|
||||
port: z.number().int().min(1).max(65535),
|
||||
address: z.string().max(100),
|
||||
process: z.string().max(100).optional(),
|
||||
address: text(100),
|
||||
process: text(100).optional(),
|
||||
});
|
||||
|
||||
const systemSchema = z.object({
|
||||
ip_addresses: z.array(z.string()).optional(),
|
||||
cpu: z.object({ model: z.string().optional(), cores: z.number().optional(), load_percent: z.number().nullable().optional() }).optional(),
|
||||
ip_addresses: z.array(text(100)).transform(cap(200)).optional(),
|
||||
cpu: z.object({ model: text(200).optional(), cores: z.number().optional(), load_percent: z.number().nullable().optional() }).optional(),
|
||||
memory: z.object({ total_bytes: z.number().optional(), used_bytes: z.number().optional() }).optional(),
|
||||
disks: z.array(z.object({ mount: z.string(), size_bytes: z.number(), used_bytes: z.number() })).optional(),
|
||||
disks: z
|
||||
.array(z.object({ mount: text(500), size_bytes: z.number(), used_bytes: z.number() }))
|
||||
.transform(cap(500))
|
||||
.optional(),
|
||||
// Deliberately lenient: one odd line from `ss` must never cost the agent its whole report (tasks included),
|
||||
// so entries are validated one by one and bad ones dropped rather than failing the request.
|
||||
listening_ports: z
|
||||
@@ -31,39 +43,50 @@ const systemSchema = z.object({
|
||||
})),
|
||||
});
|
||||
|
||||
// What a task's free-form metadata may weigh once written out; more than this is dropped, the task itself kept.
|
||||
const MAX_METADATA_JSON = 50_000;
|
||||
|
||||
const reportSchema = z.object({
|
||||
hostname: z.string().max(255).optional(),
|
||||
os_type: z.string().optional(),
|
||||
reported_at: z.string().optional(),
|
||||
hostname: text(255).optional(),
|
||||
os_type: text(50).optional(),
|
||||
reported_at: text(50).optional(),
|
||||
system: systemSchema.nullable().optional(),
|
||||
tasks: z.array(
|
||||
z.object({
|
||||
schedule_type: z.enum(["cron", "systemd_timer", "windows_task"]),
|
||||
name: z.string().min(1),
|
||||
command: z.string().optional(),
|
||||
schedule_expression: z.string().optional(),
|
||||
source: z.string().optional(),
|
||||
enabled: z.boolean().optional(),
|
||||
next_run_at: z.string().optional(),
|
||||
metadata: z.unknown().optional(),
|
||||
}),
|
||||
),
|
||||
tasks: z
|
||||
.array(
|
||||
z.object({
|
||||
schedule_type: z.enum(["cron", "systemd_timer", "windows_task"]),
|
||||
name: z.string().min(1).transform((s) => (s.length > 500 ? s.slice(0, 500) : s)),
|
||||
command: text(8000).optional(),
|
||||
schedule_expression: text(500).optional(),
|
||||
source: text(500).optional(),
|
||||
enabled: z.boolean().optional(),
|
||||
next_run_at: text(100).optional(),
|
||||
metadata: z
|
||||
.unknown()
|
||||
.optional()
|
||||
.transform((m) => (m !== undefined && (JSON.stringify(m) ?? "").length > MAX_METADATA_JSON ? undefined : m)),
|
||||
}),
|
||||
)
|
||||
.transform(cap(5000)),
|
||||
});
|
||||
|
||||
agentReportRouter.post("/", asyncHandler(async (req, res) => {
|
||||
const authHeader = req.header("authorization") ?? "";
|
||||
const match = authHeader.match(/^Bearer\s+(.+)$/i);
|
||||
if (!match) {
|
||||
return res.status(401).json({ error: "missing_token" });
|
||||
}
|
||||
/** Who's calling: the server a bearer token belongs to. Runs before the body is read. */
|
||||
async function authenticateAgent(req: Request, res: Response, next: NextFunction) {
|
||||
const match = (req.header("authorization") ?? "").match(/^Bearer\s+(.+)$/i);
|
||||
if (!match) return res.status(401).json({ error: "missing_token" });
|
||||
|
||||
const tokenHash = hashToken(match[1]);
|
||||
const server = await db.query.servers.findFirst({
|
||||
where: (s, { eq }) => eq(s.apiTokenHash, tokenHash),
|
||||
});
|
||||
if (!server) {
|
||||
return res.status(401).json({ error: "invalid_token" });
|
||||
}
|
||||
if (!server) return res.status(401).json({ error: "invalid_token" });
|
||||
|
||||
res.locals.agentServer = server;
|
||||
next();
|
||||
}
|
||||
|
||||
agentReportRouter.post("/", asyncHandler(authenticateAgent), express.json({ limit: AGENT_BODY_LIMIT }), asyncHandler(async (req, res) => {
|
||||
const server = res.locals.agentServer as { id: number };
|
||||
|
||||
const parsed = reportSchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
|
||||
Reference in new issue
Block a user