Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/ipc/metadata/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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_ {
Expand All @@ -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_;
}

Expand Down
75 changes: 67 additions & 8 deletions src/ipc/metadata/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand All @@ -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);
}
Expand All @@ -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
Expand All @@ -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)!));
}
Expand All @@ -421,7 +474,8 @@ function decodeVariadicBufferCounts(batch: _RecordBatch) {
/** @ignore */
function decodeSchemaFields(schema: _Schema, dictionaries?: Map<number, DataType>) {
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);
}
Expand All @@ -432,7 +486,8 @@ function decodeSchemaFields(schema: _Schema, dictionaries?: Map<number, DataType
/** @ignore */
function decodeFieldChildren(field: _Field, dictionaries?: Map<number, DataType>): 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);
}
Expand Down Expand Up @@ -480,7 +535,9 @@ function decodeField(f: _Field, dictionaries?: Map<number, DataType>) {
function decodeCustomMetadata(parent?: _Schema | _Field | null) {
const data = new Map<string, string>();
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()!);
}
Expand All @@ -492,7 +549,8 @@ function decodeCustomMetadata(parent?: _Schema | _Field | null) {
/** @ignore */
function decodeMessageCustomMetadata(message: _Message) {
const data = new Map<string, string>();
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()!);
}
Expand Down Expand Up @@ -560,6 +618,7 @@ function decodeFieldType(f: _Field, children?: Field[]): DataType<any> {
}
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']: {
Expand Down
108 changes: 108 additions & 0 deletions test/unit/ipc/reader/corrupted-metadata-tests.ts
Original file line number Diff line number Diff line change
@@ -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/);
});
});