Skip to content
Merged
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
53 changes: 42 additions & 11 deletions lib/src/reader/xls_compound.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ class _CompoundFile {
final ByteData _data;

late final int _sectorSize;

/// Sectors the file physically holds after the header: the bound on every
/// chain and count the header declares, since those are 32-bit fields the
/// file controls.
late final int _sectorCount;
late final int _miniCutoff;
final List<int> _fat = [];
final List<int> _miniFat = [];
Expand All @@ -35,6 +40,7 @@ class _CompoundFile {
);
}
_sectorSize = 1 << sectorShift;
_sectorCount = _bytes.length ~/ _sectorSize - 1;
_miniCutoff = _u32(56);
_readFat();
_readDirectory(_u32(48));
Expand Down Expand Up @@ -63,21 +69,36 @@ class _CompoundFile {
}
var difatSector = _u32(68);
final entriesPerSector = _sectorSize ~/ 4;
// Each DIFAT sector names the next; a sector that names itself or an
// earlier one would otherwise be read as often as the header's count
// says, and that count is not trusted.
final seenDifat = <int>{};
for (
var i = 0;
i < numDifatSectors && difatSector <= _maxRegularSector;
i++
) {
_checkSector(difatSector);
if (!seenDifat.add(difatSector)) {
throw ExcelFormatException('Compound file DIFAT chain is cyclic.');
}
final base = _sectorOffset(difatSector);
for (var j = 0; j < entriesPerSector - 1; j++) {
difat.add(_u32(base + j * 4));
}
difatSector = _u32(base + (entriesPerSector - 1) * 4);
}
// A FAT sector is listed once; a repeat would shift every sector number
// after it, so the file is corrupt rather than merely unusual.
final seenFat = <int>{};
for (final fatSector in difat) {
if (fatSector > _maxRegularSector) continue;
_checkSector(fatSector);
if (!seenFat.add(fatSector)) {
throw ExcelFormatException(
'Compound file lists FAT sector $fatSector twice.',
);
}
final base = _sectorOffset(fatSector);
for (var j = 0; j < entriesPerSector; j++) {
_fat.add(_u32(base + j * 4));
Expand All @@ -86,15 +107,12 @@ class _CompoundFile {
}

void _readMiniFat(int firstSector, int count) {
var sector = firstSector;
final entriesPerSector = _sectorSize ~/ 4;
for (var i = 0; i < count && sector <= _maxRegularSector; i++) {
_checkSector(sector);
for (final sector in _chain(firstSector).take(count)) {
final base = _sectorOffset(sector);
for (var j = 0; j < entriesPerSector; j++) {
_miniFat.add(_u32(base + j * 4));
}
sector = sector < _fat.length ? _fat[sector] : _endOfChain;
}
}

Expand Down Expand Up @@ -127,15 +145,16 @@ class _CompoundFile {
}
}

/// Walks a FAT chain from [first], bounded by the FAT size to guard against
/// cycles in corrupt files.
/// Walks a FAT chain from [first]. Every sector in it lies inside the file,
/// so a chain longer than the file's sector count repeats one: that bounds
/// the walk against cycles in corrupt files.
List<int> _chain(int first) {
final sectors = <int>[];
var sector = first;
while (sector <= _maxRegularSector) {
_checkSector(sector);
sectors.add(sector);
if (sectors.length > _fat.length + 1) {
if (sectors.length > _sectorCount) {
throw ExcelFormatException('Compound file sector chain is cyclic.');
}
sector = sector < _fat.length ? _fat[sector] : _endOfChain;
Expand All @@ -157,26 +176,38 @@ class _CompoundFile {
}

Uint8List _readRegularStream(_CfbEntry entry) {
// The size is a field the file controls: it has to fit the chain before
// a buffer of that size is made for it.
final sectors = _chain(entry.startSector);
if (entry.size > sectors.length * _sectorSize) {
throw ExcelFormatException('Compound file stream is truncated.');
}
final out = Uint8List(entry.size);
var written = 0;
for (final sector in _chain(entry.startSector)) {
for (final sector in sectors) {
if (written >= entry.size) break;
final take = min(_sectorSize, entry.size - written);
out.setRange(written, written + take, _bytes, _sectorOffset(sector));
written += take;
}
if (written < entry.size) {
throw ExcelFormatException('Compound file stream is truncated.');
}
return out;
}

Uint8List _readMiniStream(_CfbEntry entry) {
if (entry.size > _miniContainerSectors.length * _sectorSize) {
throw ExcelFormatException('Compound file mini stream is truncated.');
}
final out = Uint8List(entry.size);
var written = 0;
var mini = entry.startSector;
final miniPerSector = _sectorSize ~/ 64;
var steps = 0;
while (mini <= _maxRegularSector && written < entry.size) {
if (++steps > _miniFat.length + 1) {
throw ExcelFormatException(
'Compound file mini sector chain is cyclic.',
);
}
final container = mini ~/ miniPerSector;
if (container >= _miniContainerSectors.length) {
throw ExcelFormatException(
Expand Down
103 changes: 103 additions & 0 deletions test/xls_compound_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import 'dart:typed_data';

import 'package:excel_plus/excel_plus.dart';
import 'package:test/test.dart';

import 'xls_builder.dart';

const _endOfChain = 0xFFFFFFFE;
const _free = 0xFFFFFFFF;

/// A bare 512-byte-sector compound-file header followed by [sectors] sectors
/// filled with free markers: no FAT, directory or mini FAT unless a test
/// points the header at one.
Uint8List _container({
int sectors = 1,
int difatCount = 0,
int firstDifat = _endOfChain,
int miniFatFirst = _endOfChain,
int miniFatCount = 0,
}) {
final bytes = Uint8List(512 * (1 + sectors));
bytes.setRange(0, 8, [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]);
bytes.fillRange(76, bytes.length, 0xFF);
final data = ByteData.sublistView(bytes);
data.setUint16(30, 9, Endian.little); // 512-byte sectors
data.setUint32(48, _endOfChain, Endian.little); // no directory
data.setUint32(56, 4096, Endian.little); // mini stream cutoff
data.setUint32(60, miniFatFirst, Endian.little);
data.setUint32(64, miniFatCount, Endian.little);
data.setUint32(68, firstDifat, Endian.little);
data.setUint32(72, difatCount, Endian.little);
return bytes;
}

void _set32(Uint8List bytes, int offset, int value) =>
ByteData.sublistView(bytes).setUint32(offset, value, Endian.little);

/// A valid one-sheet workbook laid out in regular sectors, for tests that
/// corrupt one field of an otherwise sound container.
Uint8List _validWorkbook() {
final builder = XlsBuilder()..minStreamBytes = 5000;
builder.sheet('Sheet1').number(0, 0, 1);
return builder.build();
}

void main() {
group('Compound File Container', () {
// Every case is a file of a few KB whose header claims far more structure
// than it holds; the reader must reject it as corrupt without first
// reading the claimed structure, however large the claim.
test('rejects a DIFAT chain that loops back on itself', () {
final bytes = _container(sectors: 1, difatCount: 50000, firstDifat: 0);
// Sector 0 is a DIFAT sector of free entries that names itself next.
_set32(bytes, 512 + 508, 0);
expect(
() => Excel.decodeBytes(bytes),
throwsA(isA<ExcelFormatException>()),
);
});

test('rejects a mini FAT chain that loops back on itself', () {
final bytes = _container(
sectors: 2,
miniFatFirst: 1,
miniFatCount: 50000,
);
_set32(bytes, 76, 0); // the FAT is sector 0 ...
_set32(bytes, 512 + 4, 1); // ... and it says sector 1 follows itself
expect(
() => Excel.decodeBytes(bytes),
throwsA(isA<ExcelFormatException>()),
);
});

test('rejects a FAT sector listed twice in the DIFAT', () {
final bytes = _validWorkbook();
final first = ByteData.sublistView(bytes).getUint32(76, Endian.little);
_set32(bytes, 80, first);
expect(
() => Excel.decodeBytes(bytes),
throwsA(isA<ExcelFormatException>()),
);
});

test('rejects a stream whose declared size exceeds its sector chain', () {
final bytes = _validWorkbook();
// Directory slot 1 is the Workbook stream; its size field is at +120.
_set32(bytes, 512 + 128 + 120, _free);
expect(
() => Excel.decodeBytes(bytes),
throwsA(isA<ExcelFormatException>()),
);
});

test('reads a sound workbook laid out in regular sectors', () {
final excel = Excel.decodeBytes(_validWorkbook());
expect(
excel['Sheet1'].cell(CellIndex.indexByString('A1')).value,
const IntCellValue(1),
);
});
});
}
Loading