fix(proton): harden generated protobuf decoders

Reject malformed varints, out-of-bounds fields, and invalid groups before they escape their parent frame. Aggregate unknown-field metadata and decode signed int32 values while preserving SnowLuma's existing outbound encoding bytes.
This commit is contained in:
DrSmoothl committed 2026-07-10 13:40:53 +08:00
1 parent bb56030979
commit b7d648ea0f
7 files changed
+311 -32

No files matched your search

+73 -26
View File
@@ -10,19 +10,15 @@ function tagValue(field: ProtobufField): number {
/** Emit inline varint decode, storing result in `varName`. */
function varintDec(varName: string, ind: string): string {
return [
`${ind}let ${varName} = data[offset++];`,
`${ind}if (${varName} & 0x80) {`,
`${ind} let _s = 7, _b;`,
`${ind} ${varName} &= 0x7f;`,
`${ind} do { _b = data[offset++]; ${varName} |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80);`,
`${ind}}`,
`${ind}const [${varName}, ${varName}_offset] = __readVarint32(data, offset, end);`,
`${ind}offset = ${varName}_offset;`,
].join('\n');
}
function varintDec64(varName: string, ind: string): string {
return [
`${ind}let ${varName} = 0n, _s = 0n, _b;`,
`${ind}do { _b = data[offset++]; ${varName} |= BigInt(_b & 0x7f) << _s; _s += 7n; } while (_b & 0x80);`,
`${ind}const [${varName}, ${varName}_offset] = __readVarint64(data, offset, end);`,
`${ind}offset = ${varName}_offset;`,
].join('\n');
}
@@ -34,13 +30,7 @@ function isFixed64BigInt(typeName: string): boolean {
return typeName === 'fixed_64' || typeName === 'sfixed_64';
}
const INLINE_SKIP = [
` const wireType = _tag & 0x7;`,
` if (wireType === 0) { while (data[offset] & 0x80) offset++; offset++; }`,
` else if (wireType === 1) offset += 8;`,
` else if (wireType === 2) { let _l = data[offset++]; if (_l & 0x80) { let _s = 7, _b; _l &= 0x7f; do { _b = data[offset++]; _l |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80); } offset += _l; }`,
` else if (wireType === 5) offset += 4;`,
].join('\n');
const INLINE_SKIP = ` offset = __skipUnknownField(data, offset, end, wireType, _tag >>> 3);`;
export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry): string {
const locals = msg.fields.map((field, index) => {
@@ -51,14 +41,20 @@ export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry
const L = [
`function protobuf_decode_${msg.name}(data, offset = 0, end = data.length) {`,
` if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(end) || offset < 0 || end < offset || end > data.length) {`,
` throw new Error('protobuf decoder bounds are invalid');`,
` }`,
...locals,
` let _unknownFields = null;`,
` let _unknownFieldsByKey = null;`,
` let _unknownTotalOccurrences = 0;`,
` let _unknownOmittedOccurrences = 0;`,
` let _unknownOmittedByteLength = 0;`,
` while (offset < end) {`,
` let _tag = data[offset++];`,
` if (_tag & 0x80) {`,
` let _ts = 7, _tb;`,
` _tag &= 0x7f;`,
` do { _tb = data[offset++]; _tag |= (_tb & 0x7f) << _ts; _ts += 7; } while (_tb & 0x80);`,
` }`,
` const _fieldStart = offset;`,
` const [_tag, _tagOffset] = __readVarint32(data, offset, end);`,
` offset = _tagOffset;`,
` if ((_tag >>> 3) === 0) throw new Error('protobuf field number 0 is invalid');`,
` switch (_tag) {`,
];
@@ -68,12 +64,50 @@ export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry
L.push(
` default: {`,
` const _unknownStart = offset;`,
` const wireType = _tag & 0x7;`,
INLINE_SKIP,
` const _unknownFieldNumber = _tag >>> 3;`,
` const _unknownByteLength = offset - _unknownStart;`,
` const _unknownKey = (_unknownFieldNumber * 8) + wireType;`,
` _unknownTotalOccurrences++;`,
` const _knownUnknown = _unknownFieldsByKey?.get(_unknownKey);`,
` if (_knownUnknown) {`,
` _knownUnknown.count++;`,
` _knownUnknown.totalByteLength += _unknownByteLength;`,
` } else if ((_unknownFields?.length ?? 0) < 64) {`,
` const _unknown = {`,
` fieldNumber: _unknownFieldNumber,`,
` wireType,`,
` count: 1,`,
` totalByteLength: _unknownByteLength,`,
` };`,
` (_unknownFields ??= []).push(_unknown);`,
` (_unknownFieldsByKey ??= new Map()).set(_unknownKey, _unknown);`,
` } else {`,
` _unknownOmittedOccurrences++;`,
` _unknownOmittedByteLength += _unknownByteLength;`,
` }`,
` break;`,
` }`,
` }`,
` if (offset <= _fieldStart || offset > end) throw new Error('protobuf decoder made invalid progress');`,
` }`,
` return { ${result} };`,
` const _result = { ${result} };`,
` if (_unknownTotalOccurrences > 0) Object.defineProperty(`,
` _result,`,
` Symbol.for('snowluma.proton.unknownFields'),`,
` {`,
` value: {`,
` fields: _unknownFields ?? [],`,
` totalOccurrences: _unknownTotalOccurrences,`,
` omittedOccurrences: _unknownOmittedOccurrences,`,
` omittedByteLength: _unknownOmittedByteLength,`,
` },`,
` enumerable: false,`,
` },`,
` );`,
` return _result;`,
`}`,
);
return L.join('\n');
@@ -91,16 +125,17 @@ function decodeField(field: ProtobufField, index: number): string {
if (isMessage) {
L.push(varintDec('_len', I));
L.push(assign(`protobuf_decode_${typeName}(data, offset, offset + _len)`));
L.push(`${I}offset += _len;`);
L.push(`${I}const _end = __checkedEnd(offset, _len, end);`);
L.push(assign(`protobuf_decode_${typeName}(data, offset, _end)`));
L.push(`${I}offset = _end;`);
} else if (typeName === 'string') {
L.push(varintDec('_len', I));
L.push(`${I}const _end = offset + _len;`);
L.push(`${I}const _end = __checkedEnd(offset, _len, end);`);
L.push(assign(`__td.decode(data.subarray(offset, _end))`));
L.push(`${I}offset = _end;`);
} else if (typeName === 'bytes') {
L.push(varintDec('_len', I));
L.push(`${I}const _end = offset + _len;`);
L.push(`${I}const _end = __checkedEnd(offset, _len, end);`);
L.push(assign(`data.slice(offset, _end)`));
L.push(`${I}offset = _end;`);
} else if (typeName === 'bool') {
@@ -115,6 +150,13 @@ function decodeField(field: ProtobufField, index: number): string {
} else {
L.push(assign(`__zigZagDecode64(_val)`));
}
} else if (typeName === 'int_32') {
// Protobuf encodes negative int32 values as a sign-extended 10-byte
// varint. Read the full uint64 representation, then keep its signed low
// 32 bits. uint32/sint32/tag/length values must remain on the stricter
// five-byte reader.
L.push(varintDec64('_val', I));
L.push(assign(`Number(BigInt.asIntN(32, _val))`));
} else if (typeName === 'sint_32') {
L.push(varintDec('_val', I));
L.push(assign(`(_val >>> 1) ^ -(_val & 1)`));
@@ -122,15 +164,19 @@ function decodeField(field: ProtobufField, index: number): string {
L.push(varintDec('_val', I));
L.push(assign(`_val >>> 0`));
} else if (typeName === 'float') {
L.push(`${I}if (end - offset < 4) throw new Error('protobuf truncated float field');`);
L.push(assign(`__readFloat32(data, offset)`));
L.push(`${I}offset += 4;`);
} else if (wireType === WireType.Bit32) {
L.push(`${I}if (end - offset < 4) throw new Error('protobuf truncated fixed32 field');`);
L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`));
L.push(`${I}offset += 4;`);
} else if (typeName === 'double') {
L.push(`${I}if (end - offset < 8) throw new Error('protobuf truncated double field');`);
L.push(assign(`__readFloat64(data, offset)`));
L.push(`${I}offset += 8;`);
} else if (isFixed64BigInt(typeName)) {
L.push(`${I}if (end - offset < 8) throw new Error('protobuf truncated fixed64 field');`);
if (typeName === 'fixed_64') {
L.push(assign(`__readFixed64(data, offset)`));
} else {
@@ -138,6 +184,7 @@ function decodeField(field: ProtobufField, index: number): string {
}
L.push(`${I}offset += 8;`);
} else if (wireType === WireType.Bit64) {
L.push(`${I}if (end - offset < 8) throw new Error('protobuf truncated fixed64 field');`);
L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`));
L.push(`${I}offset += 8;`);
}
+68
View File
@@ -95,6 +95,74 @@ function __zigZagEncode64(value) {
function __zigZagDecode64(value) {
return BigInt.asIntN(64, (value >> 1n) ^ -(value & 1n));
}
function __readVarint32(data, offset, end) {
let value = 0;
for (let i = 0; i < 5; i++) {
if (offset >= end) throw new Error('protobuf truncated uint32 varint');
const byte = data[offset++];
if (i === 4 && (byte & 0xf0) !== 0) throw new Error('protobuf uint32 varint overflow');
value += (byte & 0x7f) * (2 ** (i * 7));
if ((byte & 0x80) === 0) return [value >>> 0, offset];
}
throw new Error('protobuf uint32 varint overflow');
}
function __readVarint64(data, offset, end) {
let value = 0n;
for (let i = 0; i < 10; i++) {
if (offset >= end) throw new Error('protobuf truncated uint64 varint');
const byte = data[offset++];
if (i === 9 && byte > 1) throw new Error('protobuf uint64 varint overflow');
value |= BigInt(byte & 0x7f) << BigInt(i * 7);
if ((byte & 0x80) === 0) return [value, offset];
}
throw new Error('protobuf uint64 varint overflow');
}
function __skipVarint(data, offset, end) {
for (let i = 0; i < 10; i++) {
if (offset >= end) throw new Error('protobuf truncated varint');
const byte = data[offset++];
if (i === 9 && byte > 1) throw new Error('protobuf varint overflow');
if ((byte & 0x80) === 0) return offset;
}
throw new Error('protobuf varint overflow');
}
function __checkedEnd(offset, length, end) {
if (length > end - offset) throw new Error('protobuf length-delimited field exceeds parent bounds');
return offset + length;
}
function __skipUnknownField(data, offset, end, wireType, fieldNumber, depth = 0) {
if (depth > 64) throw new Error('protobuf group nesting exceeds 64');
if (wireType === 0) return __skipVarint(data, offset, end);
if (wireType === 1) {
if (end - offset < 8) throw new Error('protobuf truncated fixed64 field');
return offset + 8;
}
if (wireType === 2) {
const [length, next] = __readVarint32(data, offset, end);
return __checkedEnd(next, length, end);
}
if (wireType === 3) {
while (offset < end) {
const [tag, next] = __readVarint32(data, offset, end);
offset = next;
const nestedField = tag >>> 3;
const nestedWire = tag & 0x7;
if (nestedField === 0) throw new Error('protobuf field number 0 is invalid');
if (nestedWire === 4) {
if (nestedField !== fieldNumber) throw new Error('protobuf mismatched end-group tag');
return offset;
}
offset = __skipUnknownField(data, offset, end, nestedWire, nestedField, depth + 1);
}
throw new Error('protobuf unterminated group');
}
if (wireType === 4) throw new Error('protobuf unexpected end-group tag');
if (wireType === 5) {
if (end - offset < 4) throw new Error('protobuf truncated fixed32 field');
return offset + 4;
}
throw new Error('protobuf invalid wire type ' + wireType);
}
function __writeFloat32(buf, offset, value) {
__scratch.setFloat32(0, value, true);
buf[offset++] = __scratch.getUint8(0);