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
@@ -0,0 +1,14 @@
|
||||
import type { NextFunction, Request, Response } from "express";
|
||||
|
||||
/**
|
||||
* The app's last-resort error handler. A body that's too large or isn't valid JSON is the caller's doing, so it's answered
|
||||
* as such (413 / 400) rather than as a server error — an agent whose report is too big then sees "payload_too_large", not a
|
||||
* vague 500.
|
||||
*/
|
||||
export function apiErrorHandler(err: unknown, _req: Request, res: Response, _next: NextFunction) {
|
||||
const status = (err as { status?: unknown } | null)?.status;
|
||||
if (status === 413) return res.status(413).json({ error: "payload_too_large" });
|
||||
if (status === 400 && (err as { type?: unknown }).type === "entity.parse.failed") return res.status(400).json({ error: "invalid_json" });
|
||||
console.error(err);
|
||||
res.status(500).json({ error: "internal_error" });
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Where the server itself may be pointed.
|
||||
*
|
||||
* A few features make the server connect to a host a person typed in: the certificate check on a secret, the WHOIS server a
|
||||
* registry names, a port scan. Left open, each is a way to ask "what can the server reach?" from the server's own position —
|
||||
* its loopback services, the cloud metadata address that hands out instance credentials, whatever sits behind it. This module
|
||||
* is the one place that says which addresses are off limits, and resolves a name to the single address it will then connect to,
|
||||
* so a name can't pass the check and be pointed somewhere else a moment later (DNS rebinding).
|
||||
*
|
||||
* Always refused: loopback, "this host" (0.0.0.0), link-local (169.254/16, fe80::/10 — where metadata services live),
|
||||
* multicast/reserved, and the known cloud metadata addresses wherever they sit. Private LAN ranges are allowed or not
|
||||
* depending on the caller: a homelab's own services are private, a registry's WHOIS server never is.
|
||||
*/
|
||||
import net from "node:net";
|
||||
import dns from "node:dns/promises";
|
||||
|
||||
export type AddressClass = "public" | "private" | "loopback" | "unspecified" | "link-local" | "multicast" | "metadata";
|
||||
|
||||
function list(...subnets: [string, number, "ipv4" | "ipv6"][]): net.BlockList {
|
||||
const l = new net.BlockList();
|
||||
for (const [address, prefix, family] of subnets) l.addSubnet(address, prefix, family);
|
||||
return l;
|
||||
}
|
||||
|
||||
const METADATA = list(
|
||||
["169.254.169.254", 32, "ipv4"], // AWS, Azure, GCP, most others
|
||||
["169.254.170.2", 32, "ipv4"], // AWS ECS task credentials
|
||||
["100.100.100.200", 32, "ipv4"], // Alibaba Cloud (inside the CGNAT range that Tailscale also uses)
|
||||
["fd00:ec2::254", 128, "ipv6"], // AWS over IPv6
|
||||
);
|
||||
const LOOPBACK = list(["127.0.0.0", 8, "ipv4"], ["::1", 128, "ipv6"]);
|
||||
const UNSPECIFIED = list(["0.0.0.0", 8, "ipv4"], ["::", 128, "ipv6"]);
|
||||
const LINK_LOCAL = list(["169.254.0.0", 16, "ipv4"], ["fe80::", 10, "ipv6"]);
|
||||
const MULTICAST = list(["224.0.0.0", 4, "ipv4"], ["240.0.0.0", 4, "ipv4"], ["ff00::", 8, "ipv6"]);
|
||||
const PRIVATE = list(
|
||||
["10.0.0.0", 8, "ipv4"],
|
||||
["172.16.0.0", 12, "ipv4"],
|
||||
["192.168.0.0", 16, "ipv4"],
|
||||
["100.64.0.0", 10, "ipv4"], // CGNAT — where Tailscale addresses live
|
||||
["fc00::", 7, "ipv6"],
|
||||
);
|
||||
|
||||
/** Which kind of address this is. Checked in order, so a metadata address is "metadata" even though it is also link-local or CGNAT. */
|
||||
export function classifyAddress(ip: string): AddressClass {
|
||||
const kind = net.isIP(ip);
|
||||
if (kind === 0) throw new Error(`Not an IP address: ${ip}`);
|
||||
const family = kind === 4 ? "ipv4" : "ipv6";
|
||||
// net.BlockList treats an IPv4-mapped IPv6 address (::ffff:127.0.0.1) as the IPv4 address it wraps.
|
||||
if (METADATA.check(ip, family)) return "metadata";
|
||||
if (LOOPBACK.check(ip, family)) return "loopback";
|
||||
if (UNSPECIFIED.check(ip, family)) return "unspecified";
|
||||
if (LINK_LOCAL.check(ip, family)) return "link-local";
|
||||
if (MULTICAST.check(ip, family)) return "multicast";
|
||||
if (PRIVATE.check(ip, family)) return "private";
|
||||
return "public";
|
||||
}
|
||||
|
||||
export class BlockedTargetError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly kind: AddressClass | "unresolvable",
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
const WHY: Record<Exclude<AddressClass, "public" | "private">, string> = {
|
||||
loopback: "it's this server itself (loopback)",
|
||||
unspecified: "it isn't a real destination (0.0.0.0 / ::)",
|
||||
"link-local": "it's a link-local address, where cloud metadata services live",
|
||||
multicast: "it's a multicast or reserved address",
|
||||
metadata: "it's a cloud metadata address",
|
||||
};
|
||||
|
||||
/**
|
||||
* The address to connect to for `host` (an IP or a name), or a BlockedTargetError. When a name resolves to several addresses
|
||||
* every one of them must be allowed — a name that also points at loopback is refused — and the first is the one to connect to.
|
||||
*/
|
||||
export async function resolveTarget(host: string, options: { allowPrivate: boolean }): Promise<string> {
|
||||
const trimmed = host.trim();
|
||||
let addresses: string[];
|
||||
if (net.isIP(trimmed)) {
|
||||
addresses = [trimmed];
|
||||
} else {
|
||||
try {
|
||||
addresses = (await dns.lookup(trimmed, { all: true })).map((r) => r.address);
|
||||
} catch {
|
||||
throw new BlockedTargetError(`Couldn't resolve "${trimmed}".`, "unresolvable");
|
||||
}
|
||||
if (addresses.length === 0) throw new BlockedTargetError(`Couldn't resolve "${trimmed}".`, "unresolvable");
|
||||
}
|
||||
|
||||
for (const address of addresses) {
|
||||
const kind = classifyAddress(address);
|
||||
if (kind === "public") continue;
|
||||
if (kind === "private") {
|
||||
if (options.allowPrivate) continue;
|
||||
throw new BlockedTargetError(`"${trimmed}" is on a private network, which isn't allowed here.`, kind);
|
||||
}
|
||||
throw new BlockedTargetError(
|
||||
`"${trimmed}"${trimmed === address ? "" : ` (${address})`} can't be used: ${WHY[kind]}.`,
|
||||
kind,
|
||||
);
|
||||
}
|
||||
return addresses[0];
|
||||
}
|
||||
Reference in new issue
Block a user