diff --git a/src/domain/firmware/devicetreeParser.test.ts b/src/domain/firmware/devicetreeParser.test.ts index ae90d349b1..2a14e4bc04 100644 --- a/src/domain/firmware/devicetreeParser.test.ts +++ b/src/domain/firmware/devicetreeParser.test.ts @@ -93,6 +93,43 @@ describe("flattened devicetree", () => { ] as const)("rejects %s", (_name, mutate) => expect(() => parse(mutate(devicetreeFixture()))).toThrow(), ); + it.each([16, 17])( + "checks padding and required closing tokens before the v%s property limit", + (version) => { + const valid = devicetreeFixture( + { + name: "", + properties: { first: Buffer.from([0]), second: Buffer.from([1]) }, + }, + version, + ); + expect(() => parse(valid, { max_properties: 1 })).toThrow( + "max_properties", + ); + expect( + parse(valid, { max_properties: 2 }).nodes[0]?.properties, + ).toHaveLength(2); + + const structureEnd = valid.readUInt32BE(12); + for (const removed of [4, 11]) { + // Remove END or padding plus closing tokens from the structure, + // preserving the separately declared string table. + const end = structureEnd - removed; + const truncated = Buffer.concat([ + valid.subarray(0, end), + valid.subarray(structureEnd), + ]); + truncated.writeUInt32BE(truncated.length, 4); + truncated.writeUInt32BE(end, 12); + if (version === 17) + truncated.writeUInt32BE(end - valid.readUInt32BE(8), 36); + expect(() => parse(truncated, { max_properties: 1 })).toThrow( + "Truncated FDT structure token or property", + ); + } + }, + ); + it("bounds depth, nodes and properties", () => { let root: FixtureNode = { name: "leaf" }; for (let i = 0; i < 10; i++) root = { name: `n${i}`, children: [root] }; diff --git a/src/domain/firmware/devicetreeParser.ts b/src/domain/firmware/devicetreeParser.ts index 96b0847349..5cd79c2216 100644 --- a/src/domain/firmware/devicetreeParser.ts +++ b/src/domain/firmware/devicetreeParser.ts @@ -144,7 +144,9 @@ export const parseDevicetree = ( const length = u32(cursor), nameoff = u32(cursor + 4); cursor += 8; - need(length); + const next = align(cursor + length); + // Every open node needs an END_NODE token, followed by FDT_END. + need(next - cursor + (stack.length + 1) * 4); if (++properties > input.max_properties) throw devicetreeLimitFailure("max_properties", input.max_properties); if (nameoff >= header.size_dt_strings) @@ -212,8 +214,7 @@ export const parseDevicetree = ( }; owner.node.properties.push(property); propertyMap?.set(name, property); - cursor = align(cursor + length); - need(0); + cursor = next; } else if (token === 9) { if (stack.length || nodes.length === 0) malformed("Premature FDT_END"); if (header.size_dt_struct !== null && cursor !== structEnd)