diff --git a/control/src/fuzz/signature.property.test.ts b/control/src/fuzz/signature.property.test.ts new file mode 100644 index 0000000..5a83f00 --- /dev/null +++ b/control/src/fuzz/signature.property.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, test } from 'bun:test'; +import fc from 'fast-check'; +import { budget } from '../../test-support/fuzz-budget'; +import { parseSignature, type SignatureNode, signatureFromNode } from '../transport/signature'; + +// Every character D-Bus signatures use, plus the ones the parser lists as known but the +// wire format does not define (`e`, `r`) and stray closers. +const ALPHABET = 'ybnqiuxtdsogarvh{}()e'.split(''); +const signatures = fc.string({ unit: fc.constantFrom(...ALPHABET), maxLength: 40 }); + +const BASIC = new Set('ybnqiuxtdsogvh'.split('')); + +function violations(node: SignatureNode, inArray = false): string[] { + const found: string[] = []; + switch (node.type) { + case 'a': + if (node.child.length !== 1) found.push('array without exactly one element type'); + for (const child of node.child) found.push(...violations(child, true)); + break; + case '(': + if (node.child.length === 0) found.push('empty struct'); + for (const child of node.child) found.push(...violations(child)); + break; + case '{': + if (!inArray) found.push('dict entry outside an array'); + if (node.child.length !== 2) found.push('dict entry without exactly two members'); + for (const child of node.child) found.push(...violations(child)); + break; + default: + if (!BASIC.has(node.type)) found.push(`type "${node.type}" is not a D-Bus type`); + } + return found; +} + +describe('parseSignature on arbitrary signatures', () => { + test('either throws an Error or returns a structurally valid tree that round-trips', () => { + fc.assert( + fc.property(signatures, (signature) => { + let nodes: SignatureNode[]; + try { + nodes = parseSignature(signature); + } catch (error) { + expect(error).toBeInstanceOf(Error); + return; + } + for (const node of nodes) expect(violations(node)).toEqual([]); + expect(nodes.map(signatureFromNode).join('')).toBe(signature); + }), + budget(), + ); + }); + + test('nesting far past the D-Bus limits is rejected with an Error, not a stack overflow', () => { + for (const depth of [33, 65, 1_000, 200_000]) { + const signature = `${'a'.repeat(depth)}y`; + let thrown: unknown; + try { + parseSignature(signature); + } catch (error) { + thrown = error; + } + expect(thrown).toBeInstanceOf(Error); + expect(thrown).not.toBeInstanceOf(RangeError); + } + }); +}); diff --git a/control/src/transport/signature.test.ts b/control/src/transport/signature.test.ts new file mode 100644 index 0000000..2bc6d55 --- /dev/null +++ b/control/src/transport/signature.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, test } from 'bun:test'; +import { parseSignature, signatureFromNode } from './signature'; + +const roundTrip = (signature: string) => parseSignature(signature).map(signatureFromNode).join(''); + +describe('parseSignature accepts the signatures ModemManager uses', () => { + test.each([ + '', + 'u', + 'ss', + 'a{sv}', + 'aa{sv}', + 'a{oa{sa{sv}}}', + '(uu)', + 'a(ss)', + 'ay', + 'v', + 'a{uv}', + ])('%p', (signature) => { + expect(roundTrip(signature)).toBe(signature); + }); + + test('nesting up to the specification limits', () => { + expect(roundTrip(`${'a'.repeat(32)}y`)).toBe(`${'a'.repeat(32)}y`); + expect(roundTrip(`${'('.repeat(32)}y${')'.repeat(32)}`)).toBe( + `${'('.repeat(32)}y${')'.repeat(32)}`, + ); + }); +}); + +describe('dict entries are not counted as structs', () => { + test('32 nested structs plus a dict entry inside them is accepted', () => { + const signature = `${'('.repeat(32)}a{sv}${')'.repeat(32)}`; + expect(roundTrip(signature)).toBe(signature); + }); +}); + +describe('parseSignature rejects what the wire format does not allow', () => { + test.each([ + ['a stray struct closer', ')'], + ['a stray dict closer', '}'], + ['a mismatched closer', '(s}'], + ['an empty struct', '()'], + ['a dict entry outside an array', '{sv}'], + ['a dict entry with one member', 'a{s}'], + ['a dict entry with three members', 'a{ssv}'], + ['a dict entry with a container key', 'a{avs}'], + ['a binding-only struct marker', 'r'], + ['a binding-only dict marker', 'e'], + ['an array with no element type', 'a'], + ['an unterminated struct', '(ss'], + ['arrays nested past 32', `${'a'.repeat(33)}y`], + ['structs nested past 32', `${'('.repeat(33)}y${')'.repeat(33)}`], + ['dict entries nested past 32', `${'a{s'.repeat(33)}y${'}'.repeat(33)}`], + ['a signature past 255 bytes', 'y'.repeat(256)], + ])('%s', (_name, signature) => { + expect(() => parseSignature(signature)).toThrow(Error); + }); + + test('a very deep signature is an error, not a stack overflow', () => { + let thrown: unknown; + try { + parseSignature(`${'a'.repeat(200_000)}y`); + } catch (error) { + thrown = error; + } + expect(thrown).toBeInstanceOf(Error); + expect(thrown).not.toBeInstanceOf(RangeError); + }); +}); diff --git a/control/src/transport/signature.ts b/control/src/transport/signature.ts index cb56992..e01fca7 100644 --- a/control/src/transport/signature.ts +++ b/control/src/transport/signature.ts @@ -37,9 +37,25 @@ export function assertSupportedSignature(signature: string): void { } } +// The D-Bus limits: a signature is at most 255 bytes, with at most 32 nested arrays, +// 32 nested structs and 32 nested dict entries (libdbus counts each separately). +const MAX_SIGNATURE_LENGTH = 255; +const MAX_ARRAY_DEPTH = 32; +const MAX_STRUCT_DEPTH = 32; +const MAX_DICT_DEPTH = 32; + +// Types a dict entry key may have: the basic types (no `v`, no containers). +const BASIC_TYPES = new Set('ybnqiuxtdsogh'.split('')); + // Parse a full signature (which may contain several top-level complete types) into a -// flat list of nodes. +// flat list of nodes. Rejects what the wire format does not allow: stray or mismatched +// closers, empty structs, dict entries that are not exactly `{key value}` directly inside +// an array, the binding-only `r` and `e`, and nesting or length past the specification's +// limits (which also keeps the recursion bounded). export function parseSignature(signature: string): SignatureNode[] { + if (signature.length > MAX_SIGNATURE_LENGTH) { + throw new Error(`Bad signature: longer than ${MAX_SIGNATURE_LENGTH} bytes`); + } let index = 0; function next(): string | null { @@ -51,7 +67,13 @@ export function parseSignature(signature: string): SignatureNode[] { return null; } - function parseOne(char: string): SignatureNode { + function parseOne( + char: string, + arrayDepth: number, + structDepth: number, + dictDepth: number, + inArray: boolean, + ): SignatureNode { if (!KNOWN_TYPES.has(char)) { throw new Error(`Unknown D-Bus type "${char}" in signature "${signature}"`); } @@ -59,26 +81,62 @@ export function parseSignature(signature: string): SignatureNode[] { const children: SignatureNode[] = []; switch (char) { case 'a': { + if (arrayDepth >= MAX_ARRAY_DEPTH) { + throw new Error( + `Bad signature "${signature}": arrays nested deeper than ${MAX_ARRAY_DEPTH}`, + ); + } const element = next(); if (element === null) { throw new Error(`Bad signature "${signature}": array with no element type`); } - children.push(parseOne(element)); + children.push(parseOne(element, arrayDepth + 1, structDepth, dictDepth, true)); return { type: 'a', child: children }; } case '{': case '(': { + if (char === '{' && !inArray) { + throw new Error(`Bad signature "${signature}": dict entry outside an array`); + } + // Structs and dict entries have separate depth limits, as in libdbus. + if (char === '(' ? structDepth >= MAX_STRUCT_DEPTH : dictDepth >= MAX_DICT_DEPTH) { + throw new Error( + `Bad signature "${signature}": nested deeper than ${char === '(' ? MAX_STRUCT_DEPTH : MAX_DICT_DEPTH}`, + ); + } const close = CONTAINER_CLOSE[char]; let element = next(); while (element !== null && element !== close) { - children.push(parseOne(element)); + children.push( + parseOne( + element, + arrayDepth, + char === '(' ? structDepth + 1 : structDepth, + char === '{' ? dictDepth + 1 : dictDepth, + false, + ), + ); element = next(); } if (element === null) { throw new Error(`Bad signature "${signature}": unterminated "${char}"`); } + if (char === '(' && children.length === 0) { + throw new Error(`Bad signature "${signature}": empty struct`); + } + if (char === '{') { + const key = children[0]; + if (children.length !== 2 || key === undefined || !BASIC_TYPES.has(key.type)) { + throw new Error(`Bad signature "${signature}": dict entry must be {basic-key value}`); + } + } return { type: char, child: children }; } + case ')': + case '}': + case 'r': + case 'e': + throw new Error(`Bad signature "${signature}": unexpected "${char}"`); default: return { type: char, child: children }; } @@ -87,7 +145,7 @@ export function parseSignature(signature: string): SignatureNode[] { const nodes: SignatureNode[] = []; let char = next(); while (char !== null) { - nodes.push(parseOne(char)); + nodes.push(parseOne(char, 0, 0, 0, false)); char = next(); } return nodes;