Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Refuse partial revocation lists and stop reading redirect bodies

Claudec472d0286e54
diff --git a/src/lib/services/pdf-ltv.test.ts b/src/lib/services/pdf-ltv.test.ts
index 98db568..d0ad8d4 100644
--- a/src/lib/services/pdf-ltv.test.ts
+++ b/src/lib/services/pdf-ltv.test.ts
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { createServer } from "node:http";
import os from "node:os";
import path from "node:path";
import test from "node:test";
@@ -15,7 +16,16 @@ import {
StandardFonts,
} from "pdf-lib";
-import { children, contentBytes, readOid, readTlv } from "./der.ts";
+import {
+ children,
+ contentBytes,
+ der,
+ encode,
+ encodeSmallInteger,
+ readOid,
+ readTlv,
+ TAG,
+} from "./der.ts";
import { findSignatures, hasDocumentSecurityStore } from "./pdf-incremental.ts";
import {
addLongTermValidation,
@@ -433,6 +443,50 @@ test("one lookup budget covers the whole document, archive timestamp included",
});
});
+test("a redirect's body is not read", async () => {
+ let streaming: ReturnType<typeof setInterval> | undefined;
+ let redirectClosed = false;
+ const server = createServer((request, response) => {
+ if (request.url === "/start") {
+ // A body that never ends, sent with the redirect.
+ response.writeHead(302, { location: "/final" });
+ streaming = setInterval(() => response.write(Buffer.alloc(65_536)), 1);
+ response.on("close", () => {
+ clearInterval(streaming);
+ redirectClosed = true;
+ });
+ return;
+ }
+
+ response.writeHead(200).end("final");
+ });
+
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+
+ try {
+ const address = server.address();
+ const port = typeof address === "object" && address ? address.port : 0;
+ const body = await createValidationFetch({
+ allowPrivateAddresses: true,
+ maxBytes: 1024,
+ timeoutMs: 2000,
+ })(`http://127.0.0.1:${String(port)}/start`);
+
+ assert.equal(body.toString(), "final");
+
+ // The redirect's connection is closed, not left downloading.
+ for (let wait = 0; wait < 20 && !redirectClosed; wait += 1) {
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+
+ assert.equal(redirectClosed, true);
+ } finally {
+ clearInterval(streaming);
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ }
+});
+
test("a host name that resolves to a private address is not fetched", async () => {
await withPki(async (pki) => {
const port = new URL(pki.timestampUrl).port;
@@ -519,6 +573,78 @@ test("out-of-date revocation answers are refused", async () => {
});
});
+/** A critical revocation list extension, as the test CA adds it. */
+function criticalExtension(oid: string, value: Buffer): Buffer {
+ return der.sequence(
+ der.oid(oid),
+ encode(TAG.boolean, Buffer.from([0xff])),
+ der.octets(value),
+ );
+}
+
+test("revocation lists that may leave a certificate out are refused", async () => {
+ const lists: { expect: RegExp | null; extension: Buffer; name: string }[] = [
+ {
+ // A delta list only has what changed since its base list.
+ expect: /delta list/,
+ extension: criticalExtension("2.5.29.27", encodeSmallInteger(1)),
+ name: "delta",
+ },
+ {
+ // Only key compromise.
+ expect: /only some certificates or reasons/,
+ extension: criticalExtension(
+ "2.5.29.28",
+ der.sequence(encode(0x83, Buffer.from([0x07, 0x40]))),
+ ),
+ name: "some reasons",
+ },
+ {
+ expect: /only some certificates or reasons/,
+ extension: criticalExtension(
+ "2.5.29.28",
+ der.sequence(encode(0x82, Buffer.from([0xff]))),
+ ),
+ name: "CA certificates only",
+ },
+ {
+ expect: /critical extension 1\.2\.3\.4/,
+ extension: criticalExtension("1.2.3.4", Buffer.from([0x05, 0x00])),
+ name: "unknown critical extension",
+ },
+ {
+ // A list of end-entity certificates covers the seal certificate.
+ expect: null,
+ extension: criticalExtension(
+ "2.5.29.28",
+ der.sequence(encode(0x81, Buffer.from([0xff]))),
+ ),
+ name: "user certificates only",
+ },
+ ];
+
+ for (const list of lists) {
+ await withPki(async (pki) => {
+ pki.state.ocspDown = true;
+ pki.state.crlExtensions = [list.extension];
+
+ const data = await collectValidationData(
+ findSignatures(await sealedWith(pki, { timestamp: false })).map(
+ (signature) => signature.contents,
+ ),
+ { fetch: localFetch },
+ );
+
+ if (list.expect) {
+ assert.equal(data.crls.length, 0, list.name);
+ assert.match(data.problems.join(" "), list.expect, list.name);
+ } else {
+ assert.equal(data.crls.length, 1, list.name);
+ }
+ });
+ }
+});
+
test("revocation answers dated in the future are refused", async () => {
await withPki(async (pki) => {
pki.state.staleByMs = -60 * 60 * 1000;
diff --git a/src/lib/services/pdf-ltv.ts b/src/lib/services/pdf-ltv.ts
index eec0df5..caf2f51 100644
--- a/src/lib/services/pdf-ltv.ts
+++ b/src/lib/services/pdf-ltv.ts
@@ -47,12 +47,17 @@ import {
// outside this install.
const OIDS = {
+ authorityKeyIdentifier: "2.5.29.35",
caIssuers: "1.3.6.1.5.5.7.48.2",
crlDistributionPoints: "2.5.29.31",
+ crlNumber: "2.5.29.20",
+ deltaCrlIndicator: "2.5.29.27",
ecdsaSha256: "1.2.840.10045.4.3.2",
ecdsaSha384: "1.2.840.10045.4.3.3",
ecdsaSha512: "1.2.840.10045.4.3.4",
+ freshestCrl: "2.5.29.46",
infoAccess: "1.3.6.1.5.5.7.1.1",
+ issuingDistributionPoint: "2.5.29.28",
ocsp: "1.3.6.1.5.5.7.48.1",
ocspBasic: "1.3.6.1.5.5.7.48.1.1",
ocspNoCheck: "1.3.6.1.5.5.7.48.1.5",
@@ -474,7 +479,8 @@ function fetchOnce(
const location = response.headers.location ?? null;
if (status >= 300 && status < 400) {
- response.resume();
+ // Not read: the next hop is fetched on its own connection.
+ response.destroy();
resolve({ body: Buffer.alloc(0), location, status });
return;
}
@@ -846,6 +852,82 @@ export function readOcspResponse(
}
/** Reads a revocation list from `issuer`, and whether it lists `certificate`. */
+/** The CRL extensions this reader understands, critical or not. */
+const KNOWN_CRL_EXTENSIONS = new Set<string>([
+ OIDS.authorityKeyIdentifier,
+ OIDS.crlNumber,
+ OIDS.freshestCrl,
+ OIDS.issuingDistributionPoint,
+]);
+
+/**
+ * Refuses a list that may leave out a revoked certificate (RFC 5280, 5.2
+ * and 6.3.3): a delta list, which only has what changed since its base
+ * list; a list for some reasons only, or for certificates of others (an
+ * indirect list); a list for the other kind of certificate (CA or end
+ * entity); and any list with a critical extension this reader does not
+ * know.
+ */
+function assertCompleteList(
+ body: Buffer,
+ wrapper: Tlv | undefined,
+ certificate: Certificate,
+) {
+ if (!wrapper) {
+ return;
+ }
+
+ const list = expectTag(
+ children(body, wrapper)[0],
+ TAG.sequence,
+ "revocation list extensions",
+ );
+
+ for (const extension of children(body, list)) {
+ const parts = children(body, extension);
+ const id = readOid(body, parts[0]!);
+ const critical =
+ parts.length === 3 &&
+ parts[1]!.tag === TAG.boolean &&
+ contentBytes(body, parts[1]!)[0] !== 0;
+ const value = parts[parts.length - 1]!;
+
+ if (id === OIDS.deltaCrlIndicator) {
+ throw new LongTermValidationError(
+ "The revocation list is a delta list, which needs its base list.",
+ );
+ }
+
+ if (id === OIDS.issuingDistributionPoint) {
+ const point = readTlv(body, value.contentStart, value.end);
+
+ for (const item of children(body, point)) {
+ // [1] only user certificates, [2] only CA certificates, [3] only
+ // some reasons, [4] indirect, [5] only attribute certificates.
+ const number = item.tag & 0x1f;
+ const set = contentBytes(body, item)[0] !== 0;
+ const isCa = certificate.x509.ca;
+
+ if (
+ (number === 1 && set && isCa) ||
+ (number === 2 && set && !isCa) ||
+ number === 3 ||
+ (number === 4 && set) ||
+ (number === 5 && set)
+ ) {
+ throw new LongTermValidationError(
+ "The revocation list covers only some certificates or reasons.",
+ );
+ }
+ }
+ } else if (critical && !KNOWN_CRL_EXTENSIONS.has(id)) {
+ throw new LongTermValidationError(
+ `The revocation list has a critical extension ${id} that is not understood.`,
+ );
+ }
+ }
+}
+
export function readCrl(
body: Buffer,
certificate: Certificate,
@@ -893,6 +975,11 @@ export function readCrl(
now,
what: "revocation list",
});
+ assertCompleteList(
+ body,
+ rest.find((field) => field.tag === contextTag(0)),
+ certificate,
+ );
const revoked = rest.find((field) => field.tag === TAG.sequence);
const listed = (revoked ? children(body, revoked) : []).some((entry) =>
contentBytes(body, children(body, entry)[0]!).equals(certificate.serial),
diff --git a/src/lib/services/pki-test-support.ts b/src/lib/services/pki-test-support.ts
index b173a83..8a33881 100644
--- a/src/lib/services/pki-test-support.ts
+++ b/src/lib/services/pki-test-support.ts
@@ -168,6 +168,8 @@ export type TestPki = {
state: {
caFetches: number;
crlFetches: number;
+ /** Extensions put in the revocation list, each an Extension, DER. */
+ crlExtensions: Buffer[];
ocspDown: boolean;
ocspRequests: number;
/**
@@ -290,6 +292,7 @@ export async function startTestPki(): Promise<TestPki> {
);
const state: TestPki["state"] = {
caFetches: 0,
+ crlExtensions: [],
crlFetches: 0,
ocspDown: false,
ocspRequests: 0,
@@ -367,6 +370,9 @@ export async function startTestPki(): Promise<TestPki> {
utcTime(now),
utcTime(new Date(now.getTime() + 24 * 60 * 60 * 1000)),
...(entries.length > 0 ? [der.sequence(...entries)] : []),
+ ...(state.crlExtensions.length > 0
+ ? [encode(0xa0, der.sequence(...state.crlExtensions))]
+ : []),
);
return der.sequence(