Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(integration): correct ingress HMAC substitution and constant-time challenge compare (#592)
Yudhi Armyndharis883937f52108
diff --git a/src/modules/integration/ingress-signature.spec.ts b/src/modules/integration/ingress-signature.spec.tsindex 02636a026..597cd1239 100644--- a/src/modules/integration/ingress-signature.spec.ts+++ b/src/modules/integration/ingress-signature.spec.ts@@ -71,6 +71,33 @@ describe('verifyIngressSignature', () => {);});+ it('accepts a legitimately-signed body containing $-substitution sequences (no String.replace mangling)', () => {+ // A body with $&, $', $` , $$, $1 and even a literal {timestamp} must be HMAC'd verbatim. A naive+ // String.replace would interpret these in the replacement and diverge the signed bytes.+ const trickyBody = '{"a":"$& $\' $` $$ $1","b":"{timestamp}"}';+ const r = verifyIngressSignature(spec, {+ rawBody: trickyBody,+ headers: { 'x-sig': sig(trickyBody) },+ secret,+ now: 0,+ });+ expect(r.ok).toBe(true);+ });++ it('accepts a timestamped body containing $-sequences with a multi-token template', () => {+ const withTs = { ...spec, timestampHeader: 'X-Ts', toleranceSec: 300, contentTemplate: '{timestamp}.{rawBody}' };+ const t = 1000;+ const trickyBody = 'payload-with-$&-and-$$';+ const signed = 'sha256=' + createHmac('sha256', secret).update(`${t}.${trickyBody}`).digest('hex');+ const r = verifyIngressSignature(withTs, {+ rawBody: trickyBody,+ headers: { 'x-sig': signed, 'x-ts': String(t) },+ secret,+ now: (t + 10) * 1000,+ });+ expect(r.ok).toBe(true);+ });+it('accepts scheme "none" without a signature', () => {expect(verifyIngressSignature({ scheme: 'none' }, { rawBody, headers: {}, secret, now: 0 }).ok).toBe(true);});diff --git a/src/modules/integration/ingress-signature.ts b/src/modules/integration/ingress-signature.tsindex 14fc2b555..e93310740 100644--- a/src/modules/integration/ingress-signature.ts+++ b/src/modules/integration/ingress-signature.ts@@ -42,11 +42,17 @@ export function verifyIngressSignature(return safeEqualStr(provided, input.secret) ? { ok: true } : { ok: false, reason: 'shared-secret mismatch' };}- // hmac-sha256+ // hmac-sha256. Substitute the template tokens in a SINGLE pass with a function replacer: a string+ // replacement would (a) only replace the first occurrence and (b) interpret $&, $`, $', $$, $n in the+ // replacement (the attacker-controlled rawBody), so a body containing a `$`-sequence would diverge the+ // signed bytes from the provider's and reject a legitimately-signed delivery. The function form inserts+ // each value literally and, because rawBody is substituted (not re-scanned), a `{timestamp}` embedded+ // in the body is never re-interpreted.const template = spec.contentTemplate ?? '{rawBody}';- const signedContent = template- .replace('{rawBody}', input.rawBody)- .replace('{timestamp}', header(input.headers, spec.timestampHeader) ?? '');+ const timestamp = header(input.headers, spec.timestampHeader) ?? '';+ const signedContent = template.replace(/\{rawBody\}|\{timestamp\}/g, token =>+ token === '{rawBody}' ? input.rawBody : timestamp,+ );const digest = createHmac('sha256', input.secret).update(signedContent).digest(spec.encoding ?? 'hex');@@ -54,7 +60,7 @@ export function verifyIngressSignature(return safeEqualStr(provided, expected) ? { ok: true } : { ok: false, reason: 'hmac mismatch' };}-function safeEqualStr(a: string, b: string): boolean {+export function safeEqualStr(a: string, b: string): boolean {const ba = Buffer.from(a);const bb = Buffer.from(b);if (ba.length !== bb.length) return false;diff --git a/src/modules/integration/ingress.service.spec.ts b/src/modules/integration/ingress.service.spec.tsindex 16f3367ef..3cb2f98df 100644--- a/src/modules/integration/ingress.service.spec.ts+++ b/src/modules/integration/ingress.service.spec.ts@@ -187,6 +187,41 @@ describe('IngressService.handle', () => {expect(res.status).toBe(403);});+ it('rejects a GET challenge when the instance has no verify token (no match against null)', async () => {+ const d = deps({+ instances: {+ resolve: jest.fn().mockResolvedValue({+ id: 'meta:acct1',+ pluginId: 'meta',+ instanceId: 'acct1',+ secret: 's',+ enabled: true,+ sessionScope: null,+ verifyToken: null,+ }),+ },+ manifestRoute: jest.fn().mockReturnValue({+ route: 'meta',+ mode: 'async',+ verify: 'core',+ maxBodyBytes: 1024,+ signature: { scheme: 'none' },+ challenge: { method: 'GET', tokenParam: 'hub.verify_token', echoParam: 'hub.challenge' },+ }),+ });+ const svc = new IngressService(d);+ const res = await svc.handle({+ pluginId: 'meta',+ instanceId: 'acct1',+ route: 'meta',+ method: 'GET',+ headers: {},+ query: { 'hub.verify_token': '', 'hub.challenge': 'x' },+ rawBody: '',+ });+ expect(res.status).toBe(403);+ });+it('404s for an unknown route', async () => {const d = deps({ manifestRoute: jest.fn().mockReturnValue(undefined) });const svc = new IngressService(d);diff --git a/src/modules/integration/ingress.service.ts b/src/modules/integration/ingress.service.tsindex 45df7fa66..a07ca1526 100644--- a/src/modules/integration/ingress.service.ts+++ b/src/modules/integration/ingress.service.ts@@ -1,5 +1,5 @@import { createHash } from 'node:crypto';-import { verifyIngressSignature } from './ingress-signature';+import { safeEqualStr, verifyIngressSignature } from './ingress-signature';import { PluginIngressRoute } from '../../core/plugins/plugin.interfaces';import { IngressJobData } from '../queue/processors/ingress.processor';@@ -66,7 +66,10 @@ export class IngressService {if (req.method === 'GET' && route.challenge) {const token = req.query[route.challenge.tokenParam];const echo = req.query[route.challenge.echoParam];- if (token && instance.verifyToken && token === instance.verifyToken) return { status: 200, body: echo ?? '' };+ // Constant-time compare (mirrors the signature path) so the verify token can't be probed by timing.+ if (token && instance.verifyToken && safeEqualStr(token, instance.verifyToken)) {+ return { status: 200, body: echo ?? '' };+ }return { status: 403, body: 'challenge failed' };}