diff --git a/src/ipc/metadata/file.ts b/src/ipc/metadata/file.ts index 69675b28..448fe146 100644 --- a/src/ipc/metadata/file.ts +++ b/src/ipc/metadata/file.ts @@ -28,6 +28,7 @@ import { MetadataVersion } from '../../enum.js'; import { toUint8Array } from '../../util/buffer.js'; import { ArrayBufferViewInput } from '../../util/buffer.js'; import { bigIntToNumber } from '../../util/bigint.js'; +import { validateFlatBufferVector } from './message.js'; /** @ignore */ class Footer_ { @@ -36,7 +37,13 @@ class Footer_ { public static decode(buf: ArrayBufferViewInput) { buf = new ByteBuffer(toUint8Array(buf)); const footer = _Footer.getRootAsFooter(buf); - const schema = Schema.decode(footer.schema()!, new Map(), footer.version()); + const _schema = footer.schema(); + if (!_schema) { + throw new Error('Invalid IPC metadata: Footer is missing schema'); + } + const schema = Schema.decode(_schema, new Map(), footer.version()); + validateFlatBufferVector(footer, 8, 24, 'Footer.dictionaries'); + validateFlatBufferVector(footer, 10, 24, 'Footer.recordBatches'); return new OffHeapFooter(schema, footer) as Footer_; } diff --git a/src/ipc/metadata/message.ts b/src/ipc/metadata/message.ts index 71adb8bd..c8550481 100644 --- a/src/ipc/metadata/message.ts +++ b/src/ipc/metadata/message.ts @@ -365,9 +365,59 @@ function decodeRecordBatch(batch: _RecordBatch, version = MetadataVersion.V5) { return recordBatch; } +/** @ignore */ +export function validateFlatBufferVector( + table: { bb: ByteBuffer | null; bb_pos: number }, + vtableOffset: number, + elementSize: number, + name: string +): number { + const bb = table.bb; + if (!bb) { + return 0; + } + const capacity = bb.capacity(); + if (table.bb_pos < 0 || table.bb_pos + 4 > capacity) { + throw new Error(`Invalid IPC metadata: ${name} table offset ${table.bb_pos} is out of bounds (buffer size ${capacity})`); + } + const vtable = table.bb_pos - bb.readInt32(table.bb_pos); + if (vtable < 0 || vtable + 2 > capacity) { + throw new Error(`Invalid IPC metadata: ${name} vtable offset ${vtable} is out of bounds (buffer size ${capacity})`); + } + const vtableLength = bb.readUint16(vtable); + if (vtable + vtableLength > capacity) { + throw new Error(`Invalid IPC metadata: ${name} vtable length ${vtableLength} exceeds buffer size ${capacity}`); + } + if (vtableOffset + 2 > vtableLength) { + return 0; + } + const fieldOffset = bb.readUint16(vtable + vtableOffset); + if (fieldOffset === 0) { + return 0; + } + const vectorFieldPos = table.bb_pos + fieldOffset; + if (vectorFieldPos < 0 || vectorFieldPos + 4 > capacity) { + throw new Error(`Invalid IPC metadata: ${name} field offset ${vectorFieldPos} is out of bounds (buffer size ${capacity})`); + } + const vectorLenPos = vectorFieldPos + bb.readInt32(vectorFieldPos); + if (vectorLenPos < 0 || vectorLenPos + 4 > capacity) { + throw new Error(`Invalid IPC metadata: ${name} vector offset ${vectorLenPos} is out of bounds (buffer size ${capacity})`); + } + const length = bb.readInt32(vectorLenPos); + const dataStart = vectorLenPos + 4; + if (length < 0 || length * elementSize > capacity - dataStart) { + throw new Error(`Invalid IPC metadata: ${name} vector length ${length} exceeds buffer size ${capacity}`); + } + return length; +} + /** @ignore */ function decodeDictionaryBatch(batch: _DictionaryBatch, version = MetadataVersion.V5) { - return new DictionaryBatch(RecordBatch.decode(batch.data()!, version), batch.id(), batch.isDelta()); + const data = batch.data(); + if (!data) { + throw new Error('Invalid IPC metadata: DictionaryBatch is missing data'); + } + return new DictionaryBatch(RecordBatch.decode(data, version), batch.id(), batch.isDelta()); } /** @ignore */ @@ -383,7 +433,8 @@ function decodeFieldNode(f: _FieldNode) { /** @ignore */ function decodeFieldNodes(batch: _RecordBatch) { const nodes = [] as FieldNode[]; - for (let f, i = -1, j = -1, n = batch.nodesLength(); ++i < n;) { + const n = validateFlatBufferVector(batch, 6, 16, 'RecordBatch.nodes'); + for (let f, i = -1, j = -1; ++i < n;) { if (f = batch.nodes(i)) { nodes[++j] = FieldNode.decode(f); } @@ -394,7 +445,9 @@ function decodeFieldNodes(batch: _RecordBatch) { /** @ignore */ function decodeBuffers(batch: _RecordBatch, version: MetadataVersion) { const bufferRegions = [] as BufferRegion[]; - for (let b, i = -1, j = -1, n = batch.buffersLength(); ++i < n;) { + const elementSize = version < MetadataVersion.V4 ? 24 : 16; + const n = validateFlatBufferVector(batch, 8, elementSize, 'RecordBatch.buffers'); + for (let b, i = -1, j = -1; ++i < n;) { if (b = batch.buffers(i)) { // If this Arrow buffer was written before version 4, // advance the buffer's bb_pos 8 bytes to skip past @@ -411,7 +464,7 @@ function decodeBuffers(batch: _RecordBatch, version: MetadataVersion) { /** @ignore */ function decodeVariadicBufferCounts(batch: _RecordBatch) { const counts = [] as number[]; - const length = Math.trunc(batch.variadicBufferCountsLength()); + const length = validateFlatBufferVector(batch, 12, 8, 'RecordBatch.variadicBufferCounts'); for (let i = 0; i < length; ++i) { counts.push(bigIntToNumber(batch.variadicBufferCounts(i)!)); } @@ -421,7 +474,8 @@ function decodeVariadicBufferCounts(batch: _RecordBatch) { /** @ignore */ function decodeSchemaFields(schema: _Schema, dictionaries?: Map) { const fields = [] as Field[]; - for (let f, i = -1, j = -1, n = schema.fieldsLength(); ++i < n;) { + const n = validateFlatBufferVector(schema, 6, 4, 'Schema.fields'); + for (let f, i = -1, j = -1; ++i < n;) { if (f = schema.fields(i)) { fields[++j] = Field.decode(f, dictionaries); } @@ -432,7 +486,8 @@ function decodeSchemaFields(schema: _Schema, dictionaries?: Map): Field[] { const children = [] as Field[]; - for (let f, i = -1, j = -1, n = field.childrenLength(); ++i < n;) { + const n = validateFlatBufferVector(field, 14, 4, 'Field.children'); + for (let f, i = -1, j = -1; ++i < n;) { if (f = field.children(i)) { children[++j] = Field.decode(f, dictionaries); } @@ -480,7 +535,9 @@ function decodeField(f: _Field, dictionaries?: Map) { function decodeCustomMetadata(parent?: _Schema | _Field | null) { const data = new Map(); if (parent) { - for (let entry, key, i = -1, n = Math.trunc(parent.customMetadataLength()); ++i < n;) { + const vtableOffset = parent instanceof _Schema ? 8 : 16; + const n = validateFlatBufferVector(parent, vtableOffset, 4, 'customMetadata'); + for (let entry, key, i = -1; ++i < n;) { if ((entry = parent.customMetadata(i)) && (key = entry.key()) != null) { data.set(key, entry.value()!); } @@ -492,7 +549,8 @@ function decodeCustomMetadata(parent?: _Schema | _Field | null) { /** @ignore */ function decodeMessageCustomMetadata(message: _Message) { const data = new Map(); - for (let entry, key, i = -1, n = Math.trunc(message.customMetadataLength()); ++i < n;) { + const n = validateFlatBufferVector(message, 12, 4, 'Message.customMetadata'); + for (let entry, key, i = -1; ++i < n;) { if ((entry = message.customMetadata(i)) && (key = entry.key()) != null) { data.set(key, entry.value()!); } @@ -560,6 +618,7 @@ function decodeFieldType(f: _Field, children?: Field[]): DataType { } case Type['Union']: { const t = f.type(new _Union())!; + validateFlatBufferVector(t, 6, 4, 'Union.typeIds'); return new Union(t.mode(), t.typeIdsArray() || [], children || []); } case Type['FixedSizeBinary']: { diff --git a/test/unit/ipc/reader/corrupted-metadata-tests.ts b/test/unit/ipc/reader/corrupted-metadata-tests.ts new file mode 100644 index 00000000..aecade70 --- /dev/null +++ b/test/unit/ipc/reader/corrupted-metadata-tests.ts @@ -0,0 +1,108 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import { tableFromArrays, tableFromIPC, tableToIPC } from 'apache-arrow'; + +// Valid IPC stream for tableFromArrays({ id: Int32Array.from([0, 0]), name: ['', ''] }) +// containing a Schema, DictionaryBatch, and RecordBatch. +const VALID_DICT_STREAM_BASE64 = + '/////9gAAAAQAAAAAAAKABAADgAHAAgACgAAAAAAAAEIAAAAAAAEAKj///8EAAAAAgAAAHgAAAA' + + 'UAAAAEAAcAAgADwAXABgABAAQABAAAAA4AAAAFAAAAAAAAAEYAAAAAAAABRgAAAAEAAAAbmFtZQA' + + 'AAAAAAAAABAAEAAQAAAAIAAgAAAAEAAgAAAAEAAAAxP///wAAAAEgAAAAEAAUAAQAAAAPABAAAAA' + + 'IABAAAAAQAAAAFAAAAAAAAAIYAAAAAgAAAGlkAAAAAAAACAAMAAgABwAIAAAAAAAAASAAAAD////' + + '/sAAAABQAAAAAAAAADAAcABoAEwAUAAQADAAAAAgAAAAAAAAAAAAAAAAAAAIQAAAAAAAEAAgACgA' + + 'AAAQACAAAABAAAAAAAAoAGAAMAAgABAAKAAAAFAAAAEgAAAABAAAAAAAAAAAAAAADAAAAAAAAAAA' + + 'AAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAABAAAAAAA' + + 'AAAAAAAAAAAAAAAAAAAAAAAD/////uAAAABQAAAAAAAAADAAWABQADwAQAAQADAAAABAAAAAAAAA' + + 'AAAAAAxAAAAAEAAoAGAAMAAgABAAKAAAAFAAAAFgAAAACAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAA' + + 'AAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAIAAAAAAAAAAA' + + 'AAAACAAAAAgAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA///' + + '//wAAAAA='; + +function decodeBase64(b64: string): Uint8Array { + return new Uint8Array(Buffer.from(b64, 'base64')); +} + +describe('Corrupted IPC metadata headers', () => { + test('valid dictionary stream fixture decodes cleanly', () => { + const table = tableFromIPC(decodeBase64(VALID_DICT_STREAM_BASE64)); + expect(table.numRows).toBe(2); + }); + + test('throws on corrupted DictionaryBatch buffers vector length (high byte)', () => { + const bytes = decodeBase64(VALID_DICT_STREAM_BASE64); + // Corrupt the dictionary batch's buffers vector length from 3 to 0x06000003 + bytes[335] = 6; + expect(() => tableFromIPC(bytes)).toThrow(/Invalid IPC metadata: RecordBatch\.buffers/); + }); + + test('throws on corrupted DictionaryBatch buffers vector length (mid byte)', () => { + const bytes = decodeBase64(VALID_DICT_STREAM_BASE64); + // Corrupt the dictionary batch's buffers vector length from 3 to 0x00ff0003 + bytes[334] = 255; + expect(() => tableFromIPC(bytes)).toThrow(/Invalid IPC metadata: RecordBatch\.buffers/); + }); + + test('throws on corrupted DictionaryBatch buffers vector length (negative int32)', () => { + const bytes = decodeBase64(VALID_DICT_STREAM_BASE64); + // Set sign bit of int32 vector length + bytes[335] = 0xFF; + expect(() => tableFromIPC(bytes)).toThrow(/Invalid IPC metadata: RecordBatch\.buffers/); + }); + + test('throws on corrupted DictionaryBatch nodes vector length', () => { + const bytes = decodeBase64(VALID_DICT_STREAM_BASE64); + // Corrupt the dictionary batch's nodes vector length + bytes[390] = 0xFF; + bytes[391] = 0x06; + expect(() => tableFromIPC(bytes)).toThrow(/Invalid IPC metadata: RecordBatch\.nodes/); + }); + + test('throws on corrupted Schema fields vector length', () => { + const table = tableFromArrays({ id: Int32Array.from([1, 2]) }); + const stream = tableToIPC(table, 'stream'); + const view = new DataView(stream.buffer, stream.byteOffset, stream.byteLength); + const metaLen = view.getInt32(4, true); + const msgStart = 8; + const msgRoot = msgStart + view.getInt32(msgStart, true); + const msgVtable = msgRoot - view.getInt32(msgRoot, true); + const headerFieldOff = view.getInt16(msgVtable + 8, true); + const schemaRoot = msgRoot + headerFieldOff + view.getInt32(msgRoot + headerFieldOff, true); + const schemaVtable = schemaRoot - view.getInt32(schemaRoot, true); + const fieldsFieldOff = view.getInt16(schemaVtable + 6, true); + const fieldsVecPos = schemaRoot + fieldsFieldOff + view.getInt32(schemaRoot + fieldsFieldOff, true); + expect(view.getInt32(fieldsVecPos, true)).toBe(1); + view.setInt32(fieldsVecPos, metaLen, true); + expect(() => tableFromIPC(stream)).toThrow(/Invalid IPC metadata: Schema\.fields/); + }); + + test('throws on corrupted Footer recordBatches vector length', () => { + const table = tableFromArrays({ id: Int32Array.from([1, 2]) }); + const file = tableToIPC(table, 'file'); + const view = new DataView(file.buffer, file.byteOffset, file.byteLength); + // Last 6 bytes are "ARROW1", 4 bytes before that are footerLength + const footerLen = view.getInt32(file.byteLength - 10, true); + const footerStart = file.byteLength - 10 - footerLen; + const footerRoot = footerStart + view.getInt32(footerStart, true); + const footerVtable = footerRoot - view.getInt32(footerRoot, true); + const batchesFieldOff = view.getInt16(footerVtable + 10, true); + const batchesVecPos = footerRoot + batchesFieldOff + view.getInt32(footerRoot + batchesFieldOff, true); + expect(view.getInt32(batchesVecPos, true)).toBe(1); + view.setInt32(batchesVecPos, 0x06000001, true); + expect(() => tableFromIPC(file)).toThrow(/Invalid IPC metadata: Footer\.recordBatches/); + }); +});