Skip to content

Commit 11ebdfc

Browse files
authored
fix(gateway): normalize TLS certificate pins (#125276)
* fix(gateway): normalize TLS certificate pins * test(gateway): use valid TLS pin fixtures
1 parent 08622cd commit 11ebdfc

35 files changed

Lines changed: 425 additions & 174 deletions
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { describe, expect, it } from "vitest";
2+
import { normalizeTlsFingerprint } from "./client-address-utils.js";
3+
4+
const CANONICAL_FINGERPRINT = "ab".repeat(32);
5+
const COLON_FINGERPRINT = CANONICAL_FINGERPRINT.match(/.{2}/gu)?.join(":") ?? "";
6+
7+
describe("TLS fingerprint normalization", () => {
8+
it.each([
9+
`sha256:${CANONICAL_FINGERPRINT.toUpperCase()}`,
10+
CANONICAL_FINGERPRINT.toUpperCase(),
11+
COLON_FINGERPRINT,
12+
`ShA256:${COLON_FINGERPRINT.toUpperCase()}`,
13+
])("canonicalizes %s", (fingerprint) => {
14+
expect(normalizeTlsFingerprint(fingerprint)).toBe(CANONICAL_FINGERPRINT);
15+
});
16+
17+
it.each([
18+
"",
19+
"abc123",
20+
"sha256:abc123",
21+
"g".repeat(64),
22+
`${CANONICAL_FINGERPRINT}:`,
23+
`sha256:${CANONICAL_FINGERPRINT}-junk`,
24+
`sha256:${CANONICAL_FINGERPRINT.slice(2)}`,
25+
])("rejects invalid fingerprint %s", (fingerprint) => {
26+
expect(normalizeTlsFingerprint(fingerprint)).toBe("");
27+
});
28+
});

‎packages/gateway-client/src/client-address-utils.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,23 @@ export function isSensitiveUrlQueryParamName(key: string): boolean {
1212
return /(?:token|password|secret|key|auth|credential)/iu.test(key);
1313
}
1414

15-
export function normalizeFingerprint(fingerprint: string | undefined): string {
16-
return (fingerprint ?? "").replaceAll(":", "").trim().toLowerCase();
15+
const SHA256_HEX_FINGERPRINT = /^[a-fA-F0-9]{64}$/u;
16+
const SHA256_COLON_FINGERPRINT = /^(?:[a-fA-F0-9]{2}:){31}[a-fA-F0-9]{2}$/u;
17+
18+
export function normalizeTlsFingerprint(fingerprint: string | undefined): string {
19+
const value = (fingerprint ?? "").trim().replace(/^sha256:/iu, "");
20+
if (SHA256_HEX_FINGERPRINT.test(value)) {
21+
return value.toLowerCase();
22+
}
23+
return SHA256_COLON_FINGERPRINT.test(value) ? value.replaceAll(":", "").toLowerCase() : "";
24+
}
25+
26+
export function requireTlsFingerprint(fingerprint: string): string {
27+
const normalized = normalizeTlsFingerprint(fingerprint);
28+
if (!normalized) {
29+
throw new Error("Invalid TLS fingerprint; expected a SHA-256 certificate fingerprint.");
30+
}
31+
return normalized;
1732
}
1833

1934
export function parseHostForAddressChecks(

‎packages/gateway-client/src/client.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import {
2121
import { WebSocket } from "ws";
2222
import {
2323
isSensitiveUrlQueryParamName,
24-
normalizeFingerprint,
24+
normalizeTlsFingerprint,
2525
normalizeGatewayErrorText,
2626
} from "./client-address-utils.js";
2727
import {
@@ -120,7 +120,7 @@ const DEFAULT_HOST_DEPS: Required<GatewayClientHostDeps> = {
120120
logDebug: () => {},
121121
logError: () => {},
122122
redactForLog: (message) => message,
123-
normalizeTlsFingerprint: normalizeFingerprint,
123+
normalizeTlsFingerprint,
124124
};
125125

126126
function resolveHostDeps(overrides?: GatewayClientHostDeps): Required<GatewayClientHostDeps> {

‎packages/gateway-client/src/client.watchdog.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1105,7 +1105,7 @@ r1USnb+wUdA7Zoj/mQ==
11051105
client = new GatewayClient({
11061106
url: `wss://127.0.0.1:${port}`,
11071107
connectChallengeTimeoutMs: 0,
1108-
tlsFingerprint: "deadbeef",
1108+
tlsFingerprint: "ab".repeat(32),
11091109
onConnectError: (err) => {
11101110
clearTimeout(timeout);
11111111
client?.stop();

‎packages/gateway-client/src/protocol-client.socket-factory.test.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ describe("GatewayClient socket factory recovery", () => {
219219
});
220220
const client = new GatewayClient({
221221
url: "WSS://gateway.example:18789",
222-
tlsFingerprint: "deadbeef",
222+
tlsFingerprint: "ab".repeat(32),
223223
onConnectError,
224224
hostDeps: { beforeConnect },
225225
});
@@ -278,6 +278,12 @@ describe("GatewayClient socket factory recovery", () => {
278278
tlsFingerprint: "deadbeef",
279279
expectedMessage: "gateway tls fingerprint requires wss:// gateway url",
280280
},
281+
{
282+
label: "invalid TLS fingerprint",
283+
url: "wss://gateway.example:18789",
284+
tlsFingerprint: "deadbeef",
285+
expectedMessage: "gateway tls fingerprint must be a SHA-256 fingerprint",
286+
},
281287
])("does not retry $label", async ({ url, tlsFingerprint, expectedMessage }) => {
282288
vi.useFakeTimers();
283289
const onConnectError = vi.fn<(error: Error) => void>();

‎packages/gateway-client/src/websocket-transport.ts‎

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { isLoopbackIpAddress, type ParsedIpAddress } from "@openclaw/net-policy/
22
import { isWssUrl } from "@openclaw/net-policy/url-protocol";
33
import type { ClientOptions, CertMeta, WebSocket } from "ws";
44
import {
5-
normalizeFingerprint,
5+
normalizeTlsFingerprint,
66
parseGatewayIpAddress,
77
parseHostForAddressChecks,
88
} from "./client-address-utils.js";
@@ -124,20 +124,28 @@ export function resolveGatewayWebSocketTransport(params: {
124124
);
125125
}
126126

127-
const normalize = params.normalizeTlsFingerprint ?? normalizeFingerprint;
127+
const normalize = params.normalizeTlsFingerprint ?? normalizeTlsFingerprint;
128+
const expectedFingerprint = params.tlsFingerprint
129+
? normalizeTlsFingerprint(params.tlsFingerprint)
130+
: undefined;
131+
if (params.tlsFingerprint && !expectedFingerprint) {
132+
throw new GatewayWebSocketTransportConfigurationError(
133+
"gateway tls fingerprint must be a SHA-256 fingerprint",
134+
);
135+
}
128136
const options: FingerprintCheckingClientOptions = { ...params.options };
129-
if (usesTls && params.tlsFingerprint) {
137+
if (usesTls && expectedFingerprint) {
130138
options.rejectUnauthorized = false;
131139
options.checkServerIdentity = (_hostValue: string, cert: CertMeta) => {
132140
const fingerprintValue =
133141
typeof cert === "object" && cert && "fingerprint256" in cert
134142
? ((cert as { fingerprint256?: string }).fingerprint256 ?? "")
135143
: "";
136-
const fingerprint = normalize(typeof fingerprintValue === "string" ? fingerprintValue : "");
137-
const expected = normalize(params.tlsFingerprint);
138-
if (!expected) {
139-
return undefined;
140-
}
144+
const canonicalFingerprint = normalizeTlsFingerprint(
145+
typeof fingerprintValue === "string" ? fingerprintValue : "",
146+
);
147+
const fingerprint = canonicalFingerprint ? normalize(canonicalFingerprint) : "";
148+
const expected = normalize(expectedFingerprint);
141149
if (!fingerprint) {
142150
return new Error("Missing server TLS fingerprint");
143151
}
@@ -154,7 +162,7 @@ export function resolveGatewayWebSocketTransport(params: {
154162
if (!params.tlsFingerprint) {
155163
return null;
156164
}
157-
const expected = normalize(params.tlsFingerprint);
165+
const expected = expectedFingerprint ? normalize(expectedFingerprint) : "";
158166
if (!expected) {
159167
return new Error("gateway tls fingerprint missing");
160168
}
@@ -167,7 +175,8 @@ export function resolveGatewayWebSocketTransport(params: {
167175
return new Error("gateway tls fingerprint unavailable");
168176
}
169177
const cert = rawSocket.getPeerCertificate();
170-
const fingerprint = normalize(cert?.fingerprint256 ?? "");
178+
const canonicalFingerprint = normalizeTlsFingerprint(cert?.fingerprint256 ?? "");
179+
const fingerprint = canonicalFingerprint ? normalize(canonicalFingerprint) : "";
171180
if (!fingerprint) {
172181
return new Error("gateway tls fingerprint unavailable");
173182
}

‎src/cli/gateway-cli/run.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
normalizeOptionalLowercaseString,
1010
normalizeOptionalString,
1111
} from "@openclaw/normalization-core/string-coerce";
12+
import { normalizeTlsFingerprint } from "../../../packages/gateway-client/src/client-address-utils.js";
1213
import type {
1314
ConfigFileSnapshot,
1415
GatewayAuthMode,
@@ -54,7 +55,6 @@ import {
5455
formatGatewayPidList,
5556
} from "../../infra/gateway-processes.js";
5657
import type { RespawnSupervisor } from "../../infra/supervisor-markers.js";
57-
import { normalizeFingerprint } from "../../infra/tls/fingerprint.js";
5858
import { setConsoleSubsystemFilter, setConsoleTimestampPrefix } from "../../logging/console.js";
5959
import { withDiagnosticPhase } from "../../logging/diagnostic-phase.js";
6060
import { createSubsystemLogger } from "../../logging/subsystem.js";
@@ -536,9 +536,9 @@ async function probeGatewayHealthz(params: {
536536
if (params.tlsFingerprint) {
537537
const peerFingerprint =
538538
res.socket instanceof TLSSocket
539-
? normalizeFingerprint(res.socket.getPeerCertificate().fingerprint256 ?? "")
539+
? normalizeTlsFingerprint(res.socket.getPeerCertificate().fingerprint256 ?? "")
540540
: "";
541-
if (peerFingerprint !== normalizeFingerprint(params.tlsFingerprint)) {
541+
if (peerFingerprint !== normalizeTlsFingerprint(params.tlsFingerprint)) {
542542
res.resume();
543543
finish(false);
544544
return;

‎src/cli/node-cli/daemon.test.ts‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import {
1111
runNodeDaemonUninstall,
1212
} from "./daemon.js";
1313

14+
const TLS_FINGERPRINT = "ab".repeat(32);
15+
1416
const mocks = vi.hoisted(() => {
1517
const service = {
1618
label: "Node service",
@@ -147,7 +149,7 @@ describe("runNodeDaemonInstall", () => {
147149
port: 18789,
148150
contextPath: "/saved",
149151
tls: true,
150-
tlsFingerprint: "saved-fingerprint",
152+
tlsFingerprint: TLS_FINGERPRINT,
151153
},
152154
});
153155
mocks.isSystemdUserServiceAvailable.mockReset().mockResolvedValue(true);
@@ -182,7 +184,7 @@ describe("runNodeDaemonInstall", () => {
182184
port: 18789,
183185
contextPath: "/saved",
184186
tls: true,
185-
tlsFingerprint: "saved-fingerprint",
187+
tlsFingerprint: TLS_FINGERPRINT,
186188
}),
187189
);
188190
});
@@ -197,7 +199,7 @@ describe("runNodeDaemonInstall", () => {
197199
expect.objectContaining({
198200
contextPath: "/saved",
199201
tls: true,
200-
tlsFingerprint: "saved-fingerprint",
202+
tlsFingerprint: TLS_FINGERPRINT,
201203
}),
202204
);
203205
});
@@ -217,14 +219,23 @@ describe("runNodeDaemonInstall", () => {
217219
});
218220

219221
it("rejects a TLS fingerprint when installing an explicitly plaintext node", async () => {
220-
await runNodeDaemonInstall({ force: true, tls: false, tlsFingerprint: "new-fingerprint" });
222+
await runNodeDaemonInstall({ force: true, tls: false, tlsFingerprint: TLS_FINGERPRINT });
221223

222224
expect(mocks.buildNodeInstallPlan).not.toHaveBeenCalled();
223225
expect(mocks.runtime.error).toHaveBeenCalledWith(
224226
expect.stringContaining("--no-tls cannot be combined with --tls-fingerprint"),
225227
);
226228
});
227229

230+
it("rejects an invalid TLS fingerprint before building an install plan", async () => {
231+
await runNodeDaemonInstall({ force: true, tlsFingerprint: "sha256:abc123" });
232+
233+
expect(mocks.buildNodeInstallPlan).not.toHaveBeenCalled();
234+
expect(mocks.runtime.error).toHaveBeenCalledWith(
235+
expect.stringContaining("Invalid TLS fingerprint"),
236+
);
237+
});
238+
228239
it("rejects Access credentials before installing a plaintext node service", async () => {
229240
mocks.loadNodeHostConfig.mockResolvedValue({
230241
gateway: {

‎src/cli/node-cli/daemon.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -116,8 +116,14 @@ export async function runNodeDaemonInstall(opts: NodeDaemonInstallOptions) {
116116
}
117117

118118
const config = await loadNodeHostConfig();
119-
const { host, port, contextPath, tls, tlsFingerprint, cloudflareAccess } =
120-
resolveNodeGatewayOptions(opts, config);
119+
let gatewayOptions;
120+
try {
121+
gatewayOptions = resolveNodeGatewayOptions(opts, config);
122+
} catch (error) {
123+
fail(error instanceof Error ? error.message : String(error));
124+
return;
125+
}
126+
const { host, port, contextPath, tls, tlsFingerprint, cloudflareAccess } = gatewayOptions;
121127
if (!Number.isFinite(port ?? Number.NaN) || (port ?? 0) <= 0 || (port ?? 0) > 65_535) {
122128
fail(
123129
opts.port !== undefined

‎src/cli/node-cli/gateway-options.test.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,16 @@ import { describe, expect, it } from "vitest";
22
import { encodePairingSetupCode } from "../../pairing/setup-code.js";
33
import { resolveNodeGatewayOptions, resolveNodePairGatewayOptions } from "./gateway-options.js";
44

5+
const TLS_FINGERPRINT = "ab".repeat(32);
6+
57
describe("node gateway options", () => {
68
it("preserves ordered pairing endpoint candidates and pins only the direct endpoint", () => {
79
const pair = resolveNodePairGatewayOptions(
810
encodePairingSetupCode({
911
url: "wss://192.168.1.20:8443/openclaw-gw",
1012
urls: ["wss://192.168.1.20:8443/openclaw-gw", "wss://gateway.tailnet.example/tailnet-gw"],
1113
bootstrapToken: "bootstrap-123",
12-
tlsFingerprint: "sha256:direct-leaf",
14+
tlsFingerprint: `sha256:${TLS_FINGERPRINT.toUpperCase()}`,
1315
}),
1416
);
1517

@@ -19,7 +21,7 @@ describe("node gateway options", () => {
1921
port: 8443,
2022
contextPath: "/openclaw-gw",
2123
tls: true,
22-
tlsFingerprint: "sha256:direct-leaf",
24+
tlsFingerprint: TLS_FINGERPRINT,
2325
},
2426
{
2527
host: "gateway.tailnet.example",
@@ -59,4 +61,14 @@ describe("node gateway options", () => {
5961
gatewayCandidates: undefined,
6062
});
6163
});
64+
65+
it("canonicalizes explicit TLS pins and rejects invalid values", () => {
66+
const colonFingerprint = (TLS_FINGERPRINT.match(/.{2}/gu)?.join(":") ?? "").toUpperCase();
67+
expect(
68+
resolveNodeGatewayOptions({ tlsFingerprint: `SHA256:${colonFingerprint}` }, null),
69+
).toMatchObject({ tls: true, tlsFingerprint: TLS_FINGERPRINT });
70+
expect(() => resolveNodeGatewayOptions({ tlsFingerprint: "abc123" }, null)).toThrow(
71+
"Invalid TLS fingerprint",
72+
);
73+
});
6274
});

0 commit comments

Comments
 (0)