Commit 55b0495

Browse files
pipobscureaduh95
authored andcommitted
zlib: reject local/central ZIP header mismatch
The reader treats the central directory as authoritative for a member's method, sizes, CRC, and name, but read the local header only for its signature. An archive whose local file header disagrees with the central directory therefore extracts different bytes here than in a reader that uses the local header (e.g. Info-ZIP unzip), and its encrypted bit was read from the local header while its identity came from the central directory - a parser-confusion split that defeats inspect-then-consume pipelines and can slip an encrypted member past a central-directory scanner. Cross-check the local header against the central entry when a member is read: method, CRC, and both sizes (exempting a data-descriptor entry, whose local crc/sizes are legitimately zero), plus the encryption flag. Reject a mismatch with ERR_ZIP_INVALID_ARCHIVE, consistent with the reject-rather-than-silently-choose stance already taken for ambiguous archive ends. The existing hardening/coverage tests that forged a decode-time size, CRC, or Zip64 lie in the central header alone now trip this earlier check; update them to patch both headers consistently so they still exercise the decode-time guards they target. Signed-off-by: Philipp Dunkel <pip@pipobscure.com> PR-URL: #65016 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
1 parent 31742f2 commit 55b0495

4 files changed

Lines changed: 92 additions & 21 deletions

File tree

β€Žlib/internal/zip/entry.jsβ€Ž

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ const {
7676
const{
7777
CentralFileHeader,
7878
LocalFileHeader,
79+
assertConsistentLocalHeader,
7980
findArchiveEnd,
8081
}=require('internal/zip/headers');
8182
const{
@@ -399,6 +400,9 @@ class ZipEntry {
399400
awaitreadFdFully(fd,full.subarray(30),this.#localOffset +30);
400401
}
401402
this.#local =newLocalFileHeader(full,0);
403+
if(this.#central !==null){
404+
assertConsistentLocalHeader(this.#local,this.#central);
405+
}
402406
this.#contentOffset =this.#localOffset +length;
403407
returnthis.#local;
404408
}
@@ -419,6 +423,9 @@ class ZipEntry {
419423
readFdFullySync(fd,full.subarray(30),this.#localOffset +30);
420424
}
421425
this.#local =newLocalFileHeader(full,0);
426+
if(this.#central !==null){
427+
assertConsistentLocalHeader(this.#local,this.#central);
428+
}
422429
this.#contentOffset =this.#localOffset +length;
423430
returnthis.#local;
424431
}
@@ -930,6 +937,7 @@ function* readArchiveEntries(buf, end) {
930937
}
931938
constlocalOffset=central.localFileHeaderOffset+end.prefix;
932939
constlocal=newLocalFileHeader(buf,localOffset);
940+
assertConsistentLocalHeader(local,central);
933941
constdataStart=localOffset+local.byteLength;
934942
constlength=central.compressedSize;
935943
validateArchiveRange(buf,dataStart,length,'entry data');

β€Žlib/internal/zip/headers.jsβ€Ž

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ const {
2525
SIG_ZIP64_EOCD_LOCATOR,
2626
SIG_EOCD,
2727
MADE_BY_UNIX,
28+
FLAG_ENCRYPTED,
29+
FLAG_DATA_DESCRIPTOR,
2830
SENTINEL16,
2931
SENTINEL32,
3032
TAIL_LENGTH,
@@ -267,6 +269,7 @@ class CentralFileHeader {
267269
classLocalFileHeader{
268270
#buffer;
269271
#offset;
272+
#zip64 =null;
270273
constructor(buffer,offset=0){
271274
validateArchiveRange(buffer,offset,30,'local file header');
272275
if(buffer.readUInt32LE(offset)!==SIG_LOCAL_FILE_HEADER){
@@ -280,9 +283,31 @@ class LocalFileHeader {
280283
}
281284
getbyteLength(){return30+this.fileNameLength+this.extraFieldLength;}
282285
getflags(){returnthis.#buffer.readUInt16LE(this.#offset +6);}
283-
// Spec field (sec. 4.4.5); the central directory's method is authoritative,
284-
// so the local copy is not consumed today.
285-
// get compressionMethod() { return this.#buffer.readUInt16LE(this.#offset + 8); }
286+
// The central directory is authoritative, but these local fields are read to
287+
// reject an archive whose local header contradicts it (assertConsistentLocalHeader).
288+
getcompressionMethod(){returnthis.#buffer.readUInt16LE(this.#offset +8);}
289+
getcrc32(){returnthis.#buffer.readUInt32LE(this.#offset +14);}
290+
// The Zip64 extra supplies the true 64-bit sizes for whichever classic size
291+
// field holds an overflow sentinel; a local header has no offset/disk field.
292+
#resolveZip64(){
293+
if(this.#zip64 ===null){
294+
this.#zip64 =parseZip64Extra(this.extraField,{
295+
uncompressedSize: this.#buffer.readUInt32LE(this.#offset +22)===SENTINEL32,
296+
compressedSize: this.#buffer.readUInt32LE(this.#offset +18)===SENTINEL32,
297+
localFileHeaderOffset: false,
298+
diskNumber: false,
299+
});
300+
}
301+
returnthis.#zip64;
302+
}
303+
getcompressedSize(){
304+
constvalue=this.#buffer.readUInt32LE(this.#offset +18);
305+
returnvalue===SENTINEL32 ? this.#resolveZip64().compressedSize : value;
306+
}
307+
getuncompressedSize(){
308+
constvalue=this.#buffer.readUInt32LE(this.#offset +22);
309+
returnvalue===SENTINEL32 ? this.#resolveZip64().uncompressedSize : value;
310+
}
286311
getfileNameLength(){returnthis.#buffer.readUInt16LE(this.#offset +26);}
287312
getextraFieldLength(){returnthis.#buffer.readUInt16LE(this.#offset +28);}
288313
getextraField(){
@@ -311,6 +336,35 @@ class LocalFileHeader {
311336
}
312337
}
313338

339+
// Reject an archive whose local file header contradicts the central directory
340+
// on a field that decides which bytes a member yields. This reader treats the
341+
// central directory as authoritative, but a divergent local header lets a
342+
// local-header-based extractor (Info-ZIP unzip, and others) read a different
343+
// member, method, or size from the same archive - a parser-confusion split that
344+
// defeats inspect-then-consume pipelines. Reject rather than silently diverge.
345+
functionassertConsistentLocalHeader(local,central){
346+
if(local.compressionMethod!==central.compressionMethod){
347+
thrownewERR_ZIP_INVALID_ARCHIVE(
348+
'local and central compression methods disagree');
349+
}
350+
if((local.flags&FLAG_ENCRYPTED)!==(central.flags&FLAG_ENCRYPTED)){
351+
thrownewERR_ZIP_INVALID_ARCHIVE(
352+
'local and central encryption flags disagree');
353+
}
354+
// A streamed entry (data-descriptor bit) writes zero crc and sizes in the
355+
// local header, deferring the true values to the central directory; only then
356+
// is a difference on those three fields expected.
357+
constdeferred=(local.flags&FLAG_DATA_DESCRIPTOR)!==0&&
358+
local.crc32===0&&local.compressedSize===0&&local.uncompressedSize===0;
359+
if(!deferred&&
360+
(local.crc32!==central.crc32||
361+
local.compressedSize!==central.compressedSize||
362+
local.uncompressedSize!==central.uncompressedSize)){
363+
thrownewERR_ZIP_INVALID_ARCHIVE(
364+
'local and central header crc-32 or sizes disagree');
365+
}
366+
}
367+
314368
// Returns whether an EOCD-looking record could describe an archive this
315369
// implementation supports. This is deliberately only a cheap preflight: the
316370
// selected record still receives the complete Zip64 and central-directory
@@ -563,6 +617,7 @@ function readCentralDirectory(buffer, count) {
563617
module.exports={
564618
CentralFileHeader,
565619
LocalFileHeader,
620+
assertConsistentLocalHeader,
566621
findArchiveEnd,
567622
readCentralDirectory,
568623
};

β€Žtest/parallel/test-zlib-zip-coverage.jsβ€Ž

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -288,8 +288,9 @@ test('a Zip64 extra field value beyond Number.MAX_SAFE_INTEGER is rejected', asy
288288
uncompressedSize: 0xffffffffffffffffn,
289289
});
290290

291-
const[read]=zlib.ZipEntry.read(patched);
292-
assert.throws(()=>read.size,{
291+
// The header cross-check resolves the sizes as the archive is read, so a
292+
// malformed Zip64 value is rejected at read time rather than at .size access.
293+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
293294
code: 'ERR_ZIP_INVALID_ARCHIVE',
294295
message: /exceedsthesafeintegerrange/,
295296
});
@@ -325,8 +326,7 @@ test('a Zip64 extra-field TLV whose declared size overflows the extra field is r
325326
tlv.writeUInt16LE(100,2);// claims 100 bytes of data, but none follow
326327
constpatched=injectRawZip64Extra(archive,name,content.length,tlv);
327328

328-
const[read]=zlib.ZipEntry.read(patched);
329-
assert.throws(()=>read.size,{
329+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
330330
code: 'ERR_ZIP_INVALID_ARCHIVE',
331331
message: /extrafieldismalformed/,
332332
});
@@ -345,8 +345,7 @@ test('a Zip64 extra-field TLV too short for the field it claims to carry is reje
345345
tlv.writeUInt32LE(123,4);
346346
constpatched=injectRawZip64Extra(archive,name,content.length,tlv);
347347

348-
const[read]=zlib.ZipEntry.read(patched);
349-
assert.throws(()=>read.size,{
348+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
350349
code: 'ERR_ZIP_INVALID_ARCHIVE',
351350
message: /Zip64extendedinformationextrafieldistruncated/,
352351
});
@@ -500,7 +499,8 @@ test('contentIterator() enforces the same guards as content() and contentSync()'
500499
constarchive=awaitbuildArchive([entry]);
501500
consttampered=Buffer.from(archive);
502501
constcentralStart=30+'f.txt'.length+'hello world'.length;
503-
tampered.writeUInt32LE(1,centralStart+24);
502+
tampered.writeUInt32LE(1,22);// Local uncompressed size
503+
tampered.writeUInt32LE(1,centralStart+24);// Central uncompressed size
504504
const[read]=zlib.ZipEntry.read(tampered);
505505
awaitassert.rejects(drain(read.contentIterator()),{code: 'ERR_ZIP_ENTRY_CORRUPT'});
506506
}
@@ -593,7 +593,8 @@ test('ZipFile getSync().contentSync() enforces the same guards via decodeMemberS
593593
constarchive=awaitbuildArchive([entry]);
594594
consttampered=Buffer.from(archive);
595595
constcentralStart=30+'f.txt'.length+'hello world'.length;
596-
tampered.writeUInt32LE(1,centralStart+24);
596+
tampered.writeUInt32LE(1,22);// Local uncompressed size
597+
tampered.writeUInt32LE(1,centralStart+24);// Central uncompressed size
597598
constfilePath=awaitwriteTempArchive(tampered,'size-mismatch');
598599
constzf=zlib.ZipFile.openSync(filePath);
599600
assert.throws(()=>zf.getSync('f.txt').contentSync(),{code: 'ERR_ZIP_ENTRY_CORRUPT'});
@@ -607,7 +608,8 @@ test('contentIterator() rejects an entry that inflates to less than its declared
607608
constarchive=awaitbuildArchive([entry]);
608609
consttampered=Buffer.from(archive);
609610
constcentralStart=30+'f.txt'.length+'hi'.length;
610-
tampered.writeUInt32LE(1000,centralStart+24);// Declared size grown beyond reality
611+
tampered.writeUInt32LE(1000,22);// Local declared size
612+
tampered.writeUInt32LE(1000,centralStart+24);// Central declared size grown beyond reality
611613
const[read]=zlib.ZipEntry.read(tampered);
612614
awaitassert.rejects(drain(read.contentIterator()),{
613615
code: 'ERR_ZIP_ENTRY_CORRUPT',

β€Žtest/parallel/test-zlib-zip-hardening.jsβ€Ž

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -118,13 +118,14 @@ test('a declared-size mismatch is rejected as corrupt', async () => {
118118
constentry=awaitzlib.ZipEntry.create('f.txt',Buffer.from('hello world'),{method: 'store'});
119119
constarchive=awaitbuildArchive([entry]);
120120

121-
// Shrink the *declared* uncompressed size in the central directory record
122-
// without touching the stored bytes themselves, so the amount of data
123-
// produced no longer matches what the header promised.
121+
// Shrink the *declared* uncompressed size in both the local and central
122+
// headers (kept consistent so the header cross-check passes) without touching
123+
// the stored bytes, so the produced amount no longer matches the headers'
124+
// promise and the decode-time size check fires.
124125
consttampered=Buffer.from(archive);
125126
constcentralHeaderStart=30+'f.txt'.length+'hello world'.length;
126-
constuncompressedSizeOffset=centralHeaderStart+24;
127-
tampered.writeUInt32LE(1,uncompressedSizeOffset);
127+
tampered.writeUInt32LE(1,22);// Local uncompressed size
128+
tampered.writeUInt32LE(1,centralHeaderStart+24);// Central uncompressed size
128129

129130
const[tamperedEntry]=zlib.ZipEntry.read(tampered);
130131
assert.strictEqual(tamperedEntry.size,1);
@@ -165,7 +166,10 @@ test('a forged small header whose content inflates past its declared size is rej
165166
consttampered=Buffer.from(archive);
166167
consteocd=tampered.length-22;// No comment, so EOCD is the last 22 bytes
167168
constcdOffset=tampered.readUInt32LE(eocd+16);
168-
tampered.writeUInt32LE(50,cdOffset+24);// Forge declared uncompressedSize
169+
// Forge the declared uncompressedSize in both headers (kept consistent so
170+
// the header cross-check passes; the decompressor still catches the lie).
171+
tampered.writeUInt32LE(50,22);// Local uncompressedSize
172+
tampered.writeUInt32LE(50,cdOffset+24);// Central uncompressedSize
169173

170174
const[e]=zlib.ZipEntry.read(tampered);
171175
assert.strictEqual(e.size,50);// 50 <= maxSize 100 clears the up-front check
@@ -413,9 +417,11 @@ test('a member whose data crosses into the central directory is rejected', async
413417
constarchive=Buffer.from(awaitbuildArchive(
414418
[awaitzlib.ZipEntry.create(name,content,{method: 'store'})]));
415419
constcentralHeaderStart=30+name.length+content.length;
416-
// Lie about the compressed size so the member's data range reaches into
417-
// the central directory (while staying inside the buffer).
418-
archive.writeUInt32LE(content.length+40,centralHeaderStart+20);
420+
// Lie about the compressed size in both headers (kept consistent so the
421+
// header cross-check passes) so the member's data range reaches into the
422+
// central directory (while staying inside the buffer).
423+
archive.writeUInt32LE(content.length+40,18);// Local compressed size
424+
archive.writeUInt32LE(content.length+40,centralHeaderStart+20);// Central
419425
assert.throws(()=>[...zlib.ZipEntry.read(archive)],
420426
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /possiblezipbomb/});
421427
});

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Commit 55b0495

Browse files
pipobscureaduh95
authored andcommitted
zlib: reject local/central ZIP header mismatch
The reader treats the central directory as authoritative for a member's method, sizes, CRC, and name, but read the local header only for its signature. An archive whose local file header disagrees with the central directory therefore extracts different bytes here than in a reader that uses the local header (e.g. Info-ZIP unzip), and its encrypted bit was read from the local header while its identity came from the central directory - a parser-confusion split that defeats inspect-then-consume pipelines and can slip an encrypted member past a central-directory scanner. Cross-check the local header against the central entry when a member is read: method, CRC, and both sizes (exempting a data-descriptor entry, whose local crc/sizes are legitimately zero), plus the encryption flag. Reject a mismatch with ERR_ZIP_INVALID_ARCHIVE, consistent with the reject-rather-than-silently-choose stance already taken for ambiguous archive ends. The existing hardening/coverage tests that forged a decode-time size, CRC, or Zip64 lie in the central header alone now trip this earlier check; update them to patch both headers consistently so they still exercise the decode-time guards they target. Signed-off-by: Philipp Dunkel <pip@pipobscure.com> PR-URL: #65016 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
1 parent 31742f2 commit 55b0495

4 files changed

Lines changed: 92 additions & 21 deletions

File tree

β€Žlib/internal/zip/entry.jsβ€Ž

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ const {
7676
const{
7777
CentralFileHeader,
7878
LocalFileHeader,
79+
assertConsistentLocalHeader,
7980
findArchiveEnd,
8081
}=require('internal/zip/headers');
8182
const{
@@ -399,6 +400,9 @@ class ZipEntry {
399400
awaitreadFdFully(fd,full.subarray(30),this.#localOffset +30);
400401
}
401402
this.#local =newLocalFileHeader(full,0);
403+
if(this.#central !==null){
404+
assertConsistentLocalHeader(this.#local,this.#central);
405+
}
402406
this.#contentOffset =this.#localOffset +length;
403407
returnthis.#local;
404408
}
@@ -419,6 +423,9 @@ class ZipEntry {
419423
readFdFullySync(fd,full.subarray(30),this.#localOffset +30);
420424
}
421425
this.#local =newLocalFileHeader(full,0);
426+
if(this.#central !==null){
427+
assertConsistentLocalHeader(this.#local,this.#central);
428+
}
422429
this.#contentOffset =this.#localOffset +length;
423430
returnthis.#local;
424431
}
@@ -930,6 +937,7 @@ function* readArchiveEntries(buf, end) {
930937
}
931938
constlocalOffset=central.localFileHeaderOffset+end.prefix;
932939
constlocal=newLocalFileHeader(buf,localOffset);
940+
assertConsistentLocalHeader(local,central);
933941
constdataStart=localOffset+local.byteLength;
934942
constlength=central.compressedSize;
935943
validateArchiveRange(buf,dataStart,length,'entry data');

β€Žlib/internal/zip/headers.jsβ€Ž

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ const {
2525
SIG_ZIP64_EOCD_LOCATOR,
2626
SIG_EOCD,
2727
MADE_BY_UNIX,
28+
FLAG_ENCRYPTED,
29+
FLAG_DATA_DESCRIPTOR,
2830
SENTINEL16,
2931
SENTINEL32,
3032
TAIL_LENGTH,
@@ -267,6 +269,7 @@ class CentralFileHeader {
267269
classLocalFileHeader{
268270
#buffer;
269271
#offset;
272+
#zip64 =null;
270273
constructor(buffer,offset=0){
271274
validateArchiveRange(buffer,offset,30,'local file header');
272275
if(buffer.readUInt32LE(offset)!==SIG_LOCAL_FILE_HEADER){
@@ -280,9 +283,31 @@ class LocalFileHeader {
280283
}
281284
getbyteLength(){return30+this.fileNameLength+this.extraFieldLength;}
282285
getflags(){returnthis.#buffer.readUInt16LE(this.#offset +6);}
283-
// Spec field (sec. 4.4.5); the central directory's method is authoritative,
284-
// so the local copy is not consumed today.
285-
// get compressionMethod() { return this.#buffer.readUInt16LE(this.#offset + 8); }
286+
// The central directory is authoritative, but these local fields are read to
287+
// reject an archive whose local header contradicts it (assertConsistentLocalHeader).
288+
getcompressionMethod(){returnthis.#buffer.readUInt16LE(this.#offset +8);}
289+
getcrc32(){returnthis.#buffer.readUInt32LE(this.#offset +14);}
290+
// The Zip64 extra supplies the true 64-bit sizes for whichever classic size
291+
// field holds an overflow sentinel; a local header has no offset/disk field.
292+
#resolveZip64(){
293+
if(this.#zip64 ===null){
294+
this.#zip64 =parseZip64Extra(this.extraField,{
295+
uncompressedSize: this.#buffer.readUInt32LE(this.#offset +22)===SENTINEL32,
296+
compressedSize: this.#buffer.readUInt32LE(this.#offset +18)===SENTINEL32,
297+
localFileHeaderOffset: false,
298+
diskNumber: false,
299+
});
300+
}
301+
returnthis.#zip64;
302+
}
303+
getcompressedSize(){
304+
constvalue=this.#buffer.readUInt32LE(this.#offset +18);
305+
returnvalue===SENTINEL32 ? this.#resolveZip64().compressedSize : value;
306+
}
307+
getuncompressedSize(){
308+
constvalue=this.#buffer.readUInt32LE(this.#offset +22);
309+
returnvalue===SENTINEL32 ? this.#resolveZip64().uncompressedSize : value;
310+
}
286311
getfileNameLength(){returnthis.#buffer.readUInt16LE(this.#offset +26);}
287312
getextraFieldLength(){returnthis.#buffer.readUInt16LE(this.#offset +28);}
288313
getextraField(){
@@ -311,6 +336,35 @@ class LocalFileHeader {
311336
}
312337
}
313338

339+
// Reject an archive whose local file header contradicts the central directory
340+
// on a field that decides which bytes a member yields. This reader treats the
341+
// central directory as authoritative, but a divergent local header lets a
342+
// local-header-based extractor (Info-ZIP unzip, and others) read a different
343+
// member, method, or size from the same archive - a parser-confusion split that
344+
// defeats inspect-then-consume pipelines. Reject rather than silently diverge.
345+
functionassertConsistentLocalHeader(local,central){
346+
if(local.compressionMethod!==central.compressionMethod){
347+
thrownewERR_ZIP_INVALID_ARCHIVE(
348+
'local and central compression methods disagree');
349+
}
350+
if((local.flags&FLAG_ENCRYPTED)!==(central.flags&FLAG_ENCRYPTED)){
351+
thrownewERR_ZIP_INVALID_ARCHIVE(
352+
'local and central encryption flags disagree');
353+
}
354+
// A streamed entry (data-descriptor bit) writes zero crc and sizes in the
355+
// local header, deferring the true values to the central directory; only then
356+
// is a difference on those three fields expected.
357+
constdeferred=(local.flags&FLAG_DATA_DESCRIPTOR)!==0&&
358+
local.crc32===0&&local.compressedSize===0&&local.uncompressedSize===0;
359+
if(!deferred&&
360+
(local.crc32!==central.crc32||
361+
local.compressedSize!==central.compressedSize||
362+
local.uncompressedSize!==central.uncompressedSize)){
363+
thrownewERR_ZIP_INVALID_ARCHIVE(
364+
'local and central header crc-32 or sizes disagree');
365+
}
366+
}
367+
314368
// Returns whether an EOCD-looking record could describe an archive this
315369
// implementation supports. This is deliberately only a cheap preflight: the
316370
// selected record still receives the complete Zip64 and central-directory
@@ -563,6 +617,7 @@ function readCentralDirectory(buffer, count) {
563617
module.exports={
564618
CentralFileHeader,
565619
LocalFileHeader,
620+
assertConsistentLocalHeader,
566621
findArchiveEnd,
567622
readCentralDirectory,
568623
};

β€Žtest/parallel/test-zlib-zip-coverage.jsβ€Ž

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -288,8 +288,9 @@ test('a Zip64 extra field value beyond Number.MAX_SAFE_INTEGER is rejected', asy
288288
uncompressedSize: 0xffffffffffffffffn,
289289
});
290290

291-
const[read]=zlib.ZipEntry.read(patched);
292-
assert.throws(()=>read.size,{
291+
// The header cross-check resolves the sizes as the archive is read, so a
292+
// malformed Zip64 value is rejected at read time rather than at .size access.
293+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
293294
code: 'ERR_ZIP_INVALID_ARCHIVE',
294295
message: /exceedsthesafeintegerrange/,
295296
});
@@ -325,8 +326,7 @@ test('a Zip64 extra-field TLV whose declared size overflows the extra field is r
325326
tlv.writeUInt16LE(100,2);// claims 100 bytes of data, but none follow
326327
constpatched=injectRawZip64Extra(archive,name,content.length,tlv);
327328

328-
const[read]=zlib.ZipEntry.read(patched);
329-
assert.throws(()=>read.size,{
329+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
330330
code: 'ERR_ZIP_INVALID_ARCHIVE',
331331
message: /extrafieldismalformed/,
332332
});
@@ -345,8 +345,7 @@ test('a Zip64 extra-field TLV too short for the field it claims to carry is reje
345345
tlv.writeUInt32LE(123,4);
346346
constpatched=injectRawZip64Extra(archive,name,content.length,tlv);
347347

348-
const[read]=zlib.ZipEntry.read(patched);
349-
assert.throws(()=>read.size,{
348+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
350349
code: 'ERR_ZIP_INVALID_ARCHIVE',
351350
message: /Zip64extendedinformationextrafieldistruncated/,
352351
});
@@ -500,7 +499,8 @@ test('contentIterator() enforces the same guards as content() and contentSync()'
500499
constarchive=awaitbuildArchive([entry]);
501500
consttampered=Buffer.from(archive);
502501
constcentralStart=30+'f.txt'.length+'hello world'.length;
503-
tampered.writeUInt32LE(1,centralStart+24);
502+
tampered.writeUInt32LE(1,22);// Local uncompressed size
503+
tampered.writeUInt32LE(1,centralStart+24);// Central uncompressed size
504504
const[read]=zlib.ZipEntry.read(tampered);
505505
awaitassert.rejects(drain(read.contentIterator()),{code: 'ERR_ZIP_ENTRY_CORRUPT'});
506506
}
@@ -593,7 +593,8 @@ test('ZipFile getSync().contentSync() enforces the same guards via decodeMemberS
593593
constarchive=awaitbuildArchive([entry]);
594594
consttampered=Buffer.from(archive);
595595
constcentralStart=30+'f.txt'.length+'hello world'.length;
596-
tampered.writeUInt32LE(1,centralStart+24);
596+
tampered.writeUInt32LE(1,22);// Local uncompressed size
597+
tampered.writeUInt32LE(1,centralStart+24);// Central uncompressed size
597598
constfilePath=awaitwriteTempArchive(tampered,'size-mismatch');
598599
constzf=zlib.ZipFile.openSync(filePath);
599600
assert.throws(()=>zf.getSync('f.txt').contentSync(),{code: 'ERR_ZIP_ENTRY_CORRUPT'});
@@ -607,7 +608,8 @@ test('contentIterator() rejects an entry that inflates to less than its declared
607608
constarchive=awaitbuildArchive([entry]);
608609
consttampered=Buffer.from(archive);
609610
constcentralStart=30+'f.txt'.length+'hi'.length;
610-
tampered.writeUInt32LE(1000,centralStart+24);// Declared size grown beyond reality
611+
tampered.writeUInt32LE(1000,22);// Local declared size
612+
tampered.writeUInt32LE(1000,centralStart+24);// Central declared size grown beyond reality
611613
const[read]=zlib.ZipEntry.read(tampered);
612614
awaitassert.rejects(drain(read.contentIterator()),{
613615
code: 'ERR_ZIP_ENTRY_CORRUPT',

β€Žtest/parallel/test-zlib-zip-hardening.jsβ€Ž

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -118,13 +118,14 @@ test('a declared-size mismatch is rejected as corrupt', async () => {
118118
constentry=awaitzlib.ZipEntry.create('f.txt',Buffer.from('hello world'),{method: 'store'});
119119
constarchive=awaitbuildArchive([entry]);
120120

121-
// Shrink the *declared* uncompressed size in the central directory record
122-
// without touching the stored bytes themselves, so the amount of data
123-
// produced no longer matches what the header promised.
121+
// Shrink the *declared* uncompressed size in both the local and central
122+
// headers (kept consistent so the header cross-check passes) without touching
123+
// the stored bytes, so the produced amount no longer matches the headers'
124+
// promise and the decode-time size check fires.
124125
consttampered=Buffer.from(archive);
125126
constcentralHeaderStart=30+'f.txt'.length+'hello world'.length;
126-
constuncompressedSizeOffset=centralHeaderStart+24;
127-
tampered.writeUInt32LE(1,uncompressedSizeOffset);
127+
tampered.writeUInt32LE(1,22);// Local uncompressed size
128+
tampered.writeUInt32LE(1,centralHeaderStart+24);// Central uncompressed size
128129

129130
const[tamperedEntry]=zlib.ZipEntry.read(tampered);
130131
assert.strictEqual(tamperedEntry.size,1);
@@ -165,7 +166,10 @@ test('a forged small header whose content inflates past its declared size is rej
165166
consttampered=Buffer.from(archive);
166167
consteocd=tampered.length-22;// No comment, so EOCD is the last 22 bytes
167168
constcdOffset=tampered.readUInt32LE(eocd+16);
168-
tampered.writeUInt32LE(50,cdOffset+24);// Forge declared uncompressedSize
169+
// Forge the declared uncompressedSize in both headers (kept consistent so
170+
// the header cross-check passes; the decompressor still catches the lie).
171+
tampered.writeUInt32LE(50,22);// Local uncompressedSize
172+
tampered.writeUInt32LE(50,cdOffset+24);// Central uncompressedSize
169173

170174
const[e]=zlib.ZipEntry.read(tampered);
171175
assert.strictEqual(e.size,50);// 50 <= maxSize 100 clears the up-front check
@@ -413,9 +417,11 @@ test('a member whose data crosses into the central directory is rejected', async
413417
constarchive=Buffer.from(awaitbuildArchive(
414418
[awaitzlib.ZipEntry.create(name,content,{method: 'store'})]));
415419
constcentralHeaderStart=30+name.length+content.length;
416-
// Lie about the compressed size so the member's data range reaches into
417-
// the central directory (while staying inside the buffer).
418-
archive.writeUInt32LE(content.length+40,centralHeaderStart+20);
420+
// Lie about the compressed size in both headers (kept consistent so the
421+
// header cross-check passes) so the member's data range reaches into the
422+
// central directory (while staying inside the buffer).
423+
archive.writeUInt32LE(content.length+40,18);// Local compressed size
424+
archive.writeUInt32LE(content.length+40,centralHeaderStart+20);// Central
419425
assert.throws(()=>[...zlib.ZipEntry.read(archive)],
420426
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /possiblezipbomb/});
421427
});

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 55b0495

Browse files
pipobscureaduh95
authored andcommitted
zlib: reject local/central ZIP header mismatch
The reader treats the central directory as authoritative for a member's method, sizes, CRC, and name, but read the local header only for its signature. An archive whose local file header disagrees with the central directory therefore extracts different bytes here than in a reader that uses the local header (e.g. Info-ZIP unzip), and its encrypted bit was read from the local header while its identity came from the central directory - a parser-confusion split that defeats inspect-then-consume pipelines and can slip an encrypted member past a central-directory scanner. Cross-check the local header against the central entry when a member is read: method, CRC, and both sizes (exempting a data-descriptor entry, whose local crc/sizes are legitimately zero), plus the encryption flag. Reject a mismatch with ERR_ZIP_INVALID_ARCHIVE, consistent with the reject-rather-than-silently-choose stance already taken for ambiguous archive ends. The existing hardening/coverage tests that forged a decode-time size, CRC, or Zip64 lie in the central header alone now trip this earlier check; update them to patch both headers consistently so they still exercise the decode-time guards they target. Signed-off-by: Philipp Dunkel <pip@pipobscure.com> PR-URL: #65016 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
1 parent 31742f2 commit 55b0495

4 files changed

Lines changed: 92 additions & 21 deletions

File tree

β€Žlib/internal/zip/entry.jsβ€Ž

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ const {
7676
const{
7777
CentralFileHeader,
7878
LocalFileHeader,
79+
assertConsistentLocalHeader,
7980
findArchiveEnd,
8081
}=require('internal/zip/headers');
8182
const{
@@ -399,6 +400,9 @@ class ZipEntry {
399400
awaitreadFdFully(fd,full.subarray(30),this.#localOffset +30);
400401
}
401402
this.#local =newLocalFileHeader(full,0);
403+
if(this.#central !==null){
404+
assertConsistentLocalHeader(this.#local,this.#central);
405+
}
402406
this.#contentOffset =this.#localOffset +length;
403407
returnthis.#local;
404408
}
@@ -419,6 +423,9 @@ class ZipEntry {
419423
readFdFullySync(fd,full.subarray(30),this.#localOffset +30);
420424
}
421425
this.#local =newLocalFileHeader(full,0);
426+
if(this.#central !==null){
427+
assertConsistentLocalHeader(this.#local,this.#central);
428+
}
422429
this.#contentOffset =this.#localOffset +length;
423430
returnthis.#local;
424431
}
@@ -930,6 +937,7 @@ function* readArchiveEntries(buf, end) {
930937
}
931938
constlocalOffset=central.localFileHeaderOffset+end.prefix;
932939
constlocal=newLocalFileHeader(buf,localOffset);
940+
assertConsistentLocalHeader(local,central);
933941
constdataStart=localOffset+local.byteLength;
934942
constlength=central.compressedSize;
935943
validateArchiveRange(buf,dataStart,length,'entry data');

β€Žlib/internal/zip/headers.jsβ€Ž

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ const {
2525
SIG_ZIP64_EOCD_LOCATOR,
2626
SIG_EOCD,
2727
MADE_BY_UNIX,
28+
FLAG_ENCRYPTED,
29+
FLAG_DATA_DESCRIPTOR,
2830
SENTINEL16,
2931
SENTINEL32,
3032
TAIL_LENGTH,
@@ -267,6 +269,7 @@ class CentralFileHeader {
267269
classLocalFileHeader{
268270
#buffer;
269271
#offset;
272+
#zip64 =null;
270273
constructor(buffer,offset=0){
271274
validateArchiveRange(buffer,offset,30,'local file header');
272275
if(buffer.readUInt32LE(offset)!==SIG_LOCAL_FILE_HEADER){
@@ -280,9 +283,31 @@ class LocalFileHeader {
280283
}
281284
getbyteLength(){return30+this.fileNameLength+this.extraFieldLength;}
282285
getflags(){returnthis.#buffer.readUInt16LE(this.#offset +6);}
283-
// Spec field (sec. 4.4.5); the central directory's method is authoritative,
284-
// so the local copy is not consumed today.
285-
// get compressionMethod() { return this.#buffer.readUInt16LE(this.#offset + 8); }
286+
// The central directory is authoritative, but these local fields are read to
287+
// reject an archive whose local header contradicts it (assertConsistentLocalHeader).
288+
getcompressionMethod(){returnthis.#buffer.readUInt16LE(this.#offset +8);}
289+
getcrc32(){returnthis.#buffer.readUInt32LE(this.#offset +14);}
290+
// The Zip64 extra supplies the true 64-bit sizes for whichever classic size
291+
// field holds an overflow sentinel; a local header has no offset/disk field.
292+
#resolveZip64(){
293+
if(this.#zip64 ===null){
294+
this.#zip64 =parseZip64Extra(this.extraField,{
295+
uncompressedSize: this.#buffer.readUInt32LE(this.#offset +22)===SENTINEL32,
296+
compressedSize: this.#buffer.readUInt32LE(this.#offset +18)===SENTINEL32,
297+
localFileHeaderOffset: false,
298+
diskNumber: false,
299+
});
300+
}
301+
returnthis.#zip64;
302+
}
303+
getcompressedSize(){
304+
constvalue=this.#buffer.readUInt32LE(this.#offset +18);
305+
returnvalue===SENTINEL32 ? this.#resolveZip64().compressedSize : value;
306+
}
307+
getuncompressedSize(){
308+
constvalue=this.#buffer.readUInt32LE(this.#offset +22);
309+
returnvalue===SENTINEL32 ? this.#resolveZip64().uncompressedSize : value;
310+
}
286311
getfileNameLength(){returnthis.#buffer.readUInt16LE(this.#offset +26);}
287312
getextraFieldLength(){returnthis.#buffer.readUInt16LE(this.#offset +28);}
288313
getextraField(){
@@ -311,6 +336,35 @@ class LocalFileHeader {
311336
}
312337
}
313338

339+
// Reject an archive whose local file header contradicts the central directory
340+
// on a field that decides which bytes a member yields. This reader treats the
341+
// central directory as authoritative, but a divergent local header lets a
342+
// local-header-based extractor (Info-ZIP unzip, and others) read a different
343+
// member, method, or size from the same archive - a parser-confusion split that
344+
// defeats inspect-then-consume pipelines. Reject rather than silently diverge.
345+
functionassertConsistentLocalHeader(local,central){
346+
if(local.compressionMethod!==central.compressionMethod){
347+
thrownewERR_ZIP_INVALID_ARCHIVE(
348+
'local and central compression methods disagree');
349+
}
350+
if((local.flags&FLAG_ENCRYPTED)!==(central.flags&FLAG_ENCRYPTED)){
351+
thrownewERR_ZIP_INVALID_ARCHIVE(
352+
'local and central encryption flags disagree');
353+
}
354+
// A streamed entry (data-descriptor bit) writes zero crc and sizes in the
355+
// local header, deferring the true values to the central directory; only then
356+
// is a difference on those three fields expected.
357+
constdeferred=(local.flags&FLAG_DATA_DESCRIPTOR)!==0&&
358+
local.crc32===0&&local.compressedSize===0&&local.uncompressedSize===0;
359+
if(!deferred&&
360+
(local.crc32!==central.crc32||
361+
local.compressedSize!==central.compressedSize||
362+
local.uncompressedSize!==central.uncompressedSize)){
363+
thrownewERR_ZIP_INVALID_ARCHIVE(
364+
'local and central header crc-32 or sizes disagree');
365+
}
366+
}
367+
314368
// Returns whether an EOCD-looking record could describe an archive this
315369
// implementation supports. This is deliberately only a cheap preflight: the
316370
// selected record still receives the complete Zip64 and central-directory
@@ -563,6 +617,7 @@ function readCentralDirectory(buffer, count) {
563617
module.exports={
564618
CentralFileHeader,
565619
LocalFileHeader,
620+
assertConsistentLocalHeader,
566621
findArchiveEnd,
567622
readCentralDirectory,
568623
};

β€Žtest/parallel/test-zlib-zip-coverage.jsβ€Ž

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -288,8 +288,9 @@ test('a Zip64 extra field value beyond Number.MAX_SAFE_INTEGER is rejected', asy
288288
uncompressedSize: 0xffffffffffffffffn,
289289
});
290290

291-
const[read]=zlib.ZipEntry.read(patched);
292-
assert.throws(()=>read.size,{
291+
// The header cross-check resolves the sizes as the archive is read, so a
292+
// malformed Zip64 value is rejected at read time rather than at .size access.
293+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
293294
code: 'ERR_ZIP_INVALID_ARCHIVE',
294295
message: /exceedsthesafeintegerrange/,
295296
});
@@ -325,8 +326,7 @@ test('a Zip64 extra-field TLV whose declared size overflows the extra field is r
325326
tlv.writeUInt16LE(100,2);// claims 100 bytes of data, but none follow
326327
constpatched=injectRawZip64Extra(archive,name,content.length,tlv);
327328

328-
const[read]=zlib.ZipEntry.read(patched);
329-
assert.throws(()=>read.size,{
329+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
330330
code: 'ERR_ZIP_INVALID_ARCHIVE',
331331
message: /extrafieldismalformed/,
332332
});
@@ -345,8 +345,7 @@ test('a Zip64 extra-field TLV too short for the field it claims to carry is reje
345345
tlv.writeUInt32LE(123,4);
346346
constpatched=injectRawZip64Extra(archive,name,content.length,tlv);
347347

348-
const[read]=zlib.ZipEntry.read(patched);
349-
assert.throws(()=>read.size,{
348+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
350349
code: 'ERR_ZIP_INVALID_ARCHIVE',
351350
message: /Zip64extendedinformationextrafieldistruncated/,
352351
});
@@ -500,7 +499,8 @@ test('contentIterator() enforces the same guards as content() and contentSync()'
500499
constarchive=awaitbuildArchive([entry]);
501500
consttampered=Buffer.from(archive);
502501
constcentralStart=30+'f.txt'.length+'hello world'.length;
503-
tampered.writeUInt32LE(1,centralStart+24);
502+
tampered.writeUInt32LE(1,22);// Local uncompressed size
503+
tampered.writeUInt32LE(1,centralStart+24);// Central uncompressed size
504504
const[read]=zlib.ZipEntry.read(tampered);
505505
awaitassert.rejects(drain(read.contentIterator()),{code: 'ERR_ZIP_ENTRY_CORRUPT'});
506506
}
@@ -593,7 +593,8 @@ test('ZipFile getSync().contentSync() enforces the same guards via decodeMemberS
593593
constarchive=awaitbuildArchive([entry]);
594594
consttampered=Buffer.from(archive);
595595
constcentralStart=30+'f.txt'.length+'hello world'.length;
596-
tampered.writeUInt32LE(1,centralStart+24);
596+
tampered.writeUInt32LE(1,22);// Local uncompressed size
597+
tampered.writeUInt32LE(1,centralStart+24);// Central uncompressed size
597598
constfilePath=awaitwriteTempArchive(tampered,'size-mismatch');
598599
constzf=zlib.ZipFile.openSync(filePath);
599600
assert.throws(()=>zf.getSync('f.txt').contentSync(),{code: 'ERR_ZIP_ENTRY_CORRUPT'});
@@ -607,7 +608,8 @@ test('contentIterator() rejects an entry that inflates to less than its declared
607608
constarchive=awaitbuildArchive([entry]);
608609
consttampered=Buffer.from(archive);
609610
constcentralStart=30+'f.txt'.length+'hi'.length;
610-
tampered.writeUInt32LE(1000,centralStart+24);// Declared size grown beyond reality
611+
tampered.writeUInt32LE(1000,22);// Local declared size
612+
tampered.writeUInt32LE(1000,centralStart+24);// Central declared size grown beyond reality
611613
const[read]=zlib.ZipEntry.read(tampered);
612614
awaitassert.rejects(drain(read.contentIterator()),{
613615
code: 'ERR_ZIP_ENTRY_CORRUPT',

β€Žtest/parallel/test-zlib-zip-hardening.jsβ€Ž

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -118,13 +118,14 @@ test('a declared-size mismatch is rejected as corrupt', async () => {
118118
constentry=awaitzlib.ZipEntry.create('f.txt',Buffer.from('hello world'),{method: 'store'});
119119
constarchive=awaitbuildArchive([entry]);
120120

121-
// Shrink the *declared* uncompressed size in the central directory record
122-
// without touching the stored bytes themselves, so the amount of data
123-
// produced no longer matches what the header promised.
121+
// Shrink the *declared* uncompressed size in both the local and central
122+
// headers (kept consistent so the header cross-check passes) without touching
123+
// the stored bytes, so the produced amount no longer matches the headers'
124+
// promise and the decode-time size check fires.
124125
consttampered=Buffer.from(archive);
125126
constcentralHeaderStart=30+'f.txt'.length+'hello world'.length;
126-
constuncompressedSizeOffset=centralHeaderStart+24;
127-
tampered.writeUInt32LE(1,uncompressedSizeOffset);
127+
tampered.writeUInt32LE(1,22);// Local uncompressed size
128+
tampered.writeUInt32LE(1,centralHeaderStart+24);// Central uncompressed size
128129

129130
const[tamperedEntry]=zlib.ZipEntry.read(tampered);
130131
assert.strictEqual(tamperedEntry.size,1);
@@ -165,7 +166,10 @@ test('a forged small header whose content inflates past its declared size is rej
165166
consttampered=Buffer.from(archive);
166167
consteocd=tampered.length-22;// No comment, so EOCD is the last 22 bytes
167168
constcdOffset=tampered.readUInt32LE(eocd+16);
168-
tampered.writeUInt32LE(50,cdOffset+24);// Forge declared uncompressedSize
169+
// Forge the declared uncompressedSize in both headers (kept consistent so
170+
// the header cross-check passes; the decompressor still catches the lie).
171+
tampered.writeUInt32LE(50,22);// Local uncompressedSize
172+
tampered.writeUInt32LE(50,cdOffset+24);// Central uncompressedSize
169173

170174
const[e]=zlib.ZipEntry.read(tampered);
171175
assert.strictEqual(e.size,50);// 50 <= maxSize 100 clears the up-front check
@@ -413,9 +417,11 @@ test('a member whose data crosses into the central directory is rejected', async
413417
constarchive=Buffer.from(awaitbuildArchive(
414418
[awaitzlib.ZipEntry.create(name,content,{method: 'store'})]));
415419
constcentralHeaderStart=30+name.length+content.length;
416-
// Lie about the compressed size so the member's data range reaches into
417-
// the central directory (while staying inside the buffer).
418-
archive.writeUInt32LE(content.length+40,centralHeaderStart+20);
420+
// Lie about the compressed size in both headers (kept consistent so the
421+
// header cross-check passes) so the member's data range reaches into the
422+
// central directory (while staying inside the buffer).
423+
archive.writeUInt32LE(content.length+40,18);// Local compressed size
424+
archive.writeUInt32LE(content.length+40,centralHeaderStart+20);// Central
419425
assert.throws(()=>[...zlib.ZipEntry.read(archive)],
420426
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /possiblezipbomb/});
421427
});

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 55b0495

Browse files
pipobscureaduh95
authored andcommitted
zlib: reject local/central ZIP header mismatch
The reader treats the central directory as authoritative for a member's method, sizes, CRC, and name, but read the local header only for its signature. An archive whose local file header disagrees with the central directory therefore extracts different bytes here than in a reader that uses the local header (e.g. Info-ZIP unzip), and its encrypted bit was read from the local header while its identity came from the central directory - a parser-confusion split that defeats inspect-then-consume pipelines and can slip an encrypted member past a central-directory scanner. Cross-check the local header against the central entry when a member is read: method, CRC, and both sizes (exempting a data-descriptor entry, whose local crc/sizes are legitimately zero), plus the encryption flag. Reject a mismatch with ERR_ZIP_INVALID_ARCHIVE, consistent with the reject-rather-than-silently-choose stance already taken for ambiguous archive ends. The existing hardening/coverage tests that forged a decode-time size, CRC, or Zip64 lie in the central header alone now trip this earlier check; update them to patch both headers consistently so they still exercise the decode-time guards they target. Signed-off-by: Philipp Dunkel <pip@pipobscure.com> PR-URL: #65016 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
1 parent 31742f2 commit 55b0495

4 files changed

Lines changed: 92 additions & 21 deletions

File tree

β€Žlib/internal/zip/entry.jsβ€Ž

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ const {
7676
const{
7777
CentralFileHeader,
7878
LocalFileHeader,
79+
assertConsistentLocalHeader,
7980
findArchiveEnd,
8081
}=require('internal/zip/headers');
8182
const{
@@ -399,6 +400,9 @@ class ZipEntry {
399400
awaitreadFdFully(fd,full.subarray(30),this.#localOffset +30);
400401
}
401402
this.#local =newLocalFileHeader(full,0);
403+
if(this.#central !==null){
404+
assertConsistentLocalHeader(this.#local,this.#central);
405+
}
402406
this.#contentOffset =this.#localOffset +length;
403407
returnthis.#local;
404408
}
@@ -419,6 +423,9 @@ class ZipEntry {
419423
readFdFullySync(fd,full.subarray(30),this.#localOffset +30);
420424
}
421425
this.#local =newLocalFileHeader(full,0);
426+
if(this.#central !==null){
427+
assertConsistentLocalHeader(this.#local,this.#central);
428+
}
422429
this.#contentOffset =this.#localOffset +length;
423430
returnthis.#local;
424431
}
@@ -930,6 +937,7 @@ function* readArchiveEntries(buf, end) {
930937
}
931938
constlocalOffset=central.localFileHeaderOffset+end.prefix;
932939
constlocal=newLocalFileHeader(buf,localOffset);
940+
assertConsistentLocalHeader(local,central);
933941
constdataStart=localOffset+local.byteLength;
934942
constlength=central.compressedSize;
935943
validateArchiveRange(buf,dataStart,length,'entry data');

β€Žlib/internal/zip/headers.jsβ€Ž

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ const {
2525
SIG_ZIP64_EOCD_LOCATOR,
2626
SIG_EOCD,
2727
MADE_BY_UNIX,
28+
FLAG_ENCRYPTED,
29+
FLAG_DATA_DESCRIPTOR,
2830
SENTINEL16,
2931
SENTINEL32,
3032
TAIL_LENGTH,
@@ -267,6 +269,7 @@ class CentralFileHeader {
267269
classLocalFileHeader{
268270
#buffer;
269271
#offset;
272+
#zip64 =null;
270273
constructor(buffer,offset=0){
271274
validateArchiveRange(buffer,offset,30,'local file header');
272275
if(buffer.readUInt32LE(offset)!==SIG_LOCAL_FILE_HEADER){
@@ -280,9 +283,31 @@ class LocalFileHeader {
280283
}
281284
getbyteLength(){return30+this.fileNameLength+this.extraFieldLength;}
282285
getflags(){returnthis.#buffer.readUInt16LE(this.#offset +6);}
283-
// Spec field (sec. 4.4.5); the central directory's method is authoritative,
284-
// so the local copy is not consumed today.
285-
// get compressionMethod() { return this.#buffer.readUInt16LE(this.#offset + 8); }
286+
// The central directory is authoritative, but these local fields are read to
287+
// reject an archive whose local header contradicts it (assertConsistentLocalHeader).
288+
getcompressionMethod(){returnthis.#buffer.readUInt16LE(this.#offset +8);}
289+
getcrc32(){returnthis.#buffer.readUInt32LE(this.#offset +14);}
290+
// The Zip64 extra supplies the true 64-bit sizes for whichever classic size
291+
// field holds an overflow sentinel; a local header has no offset/disk field.
292+
#resolveZip64(){
293+
if(this.#zip64 ===null){
294+
this.#zip64 =parseZip64Extra(this.extraField,{
295+
uncompressedSize: this.#buffer.readUInt32LE(this.#offset +22)===SENTINEL32,
296+
compressedSize: this.#buffer.readUInt32LE(this.#offset +18)===SENTINEL32,
297+
localFileHeaderOffset: false,
298+
diskNumber: false,
299+
});
300+
}
301+
returnthis.#zip64;
302+
}
303+
getcompressedSize(){
304+
constvalue=this.#buffer.readUInt32LE(this.#offset +18);
305+
returnvalue===SENTINEL32 ? this.#resolveZip64().compressedSize : value;
306+
}
307+
getuncompressedSize(){
308+
constvalue=this.#buffer.readUInt32LE(this.#offset +22);
309+
returnvalue===SENTINEL32 ? this.#resolveZip64().uncompressedSize : value;
310+
}
286311
getfileNameLength(){returnthis.#buffer.readUInt16LE(this.#offset +26);}
287312
getextraFieldLength(){returnthis.#buffer.readUInt16LE(this.#offset +28);}
288313
getextraField(){
@@ -311,6 +336,35 @@ class LocalFileHeader {
311336
}
312337
}
313338

339+
// Reject an archive whose local file header contradicts the central directory
340+
// on a field that decides which bytes a member yields. This reader treats the
341+
// central directory as authoritative, but a divergent local header lets a
342+
// local-header-based extractor (Info-ZIP unzip, and others) read a different
343+
// member, method, or size from the same archive - a parser-confusion split that
344+
// defeats inspect-then-consume pipelines. Reject rather than silently diverge.
345+
functionassertConsistentLocalHeader(local,central){
346+
if(local.compressionMethod!==central.compressionMethod){
347+
thrownewERR_ZIP_INVALID_ARCHIVE(
348+
'local and central compression methods disagree');
349+
}
350+
if((local.flags&FLAG_ENCRYPTED)!==(central.flags&FLAG_ENCRYPTED)){
351+
thrownewERR_ZIP_INVALID_ARCHIVE(
352+
'local and central encryption flags disagree');
353+
}
354+
// A streamed entry (data-descriptor bit) writes zero crc and sizes in the
355+
// local header, deferring the true values to the central directory; only then
356+
// is a difference on those three fields expected.
357+
constdeferred=(local.flags&FLAG_DATA_DESCRIPTOR)!==0&&
358+
local.crc32===0&&local.compressedSize===0&&local.uncompressedSize===0;
359+
if(!deferred&&
360+
(local.crc32!==central.crc32||
361+
local.compressedSize!==central.compressedSize||
362+
local.uncompressedSize!==central.uncompressedSize)){
363+
thrownewERR_ZIP_INVALID_ARCHIVE(
364+
'local and central header crc-32 or sizes disagree');
365+
}
366+
}
367+
314368
// Returns whether an EOCD-looking record could describe an archive this
315369
// implementation supports. This is deliberately only a cheap preflight: the
316370
// selected record still receives the complete Zip64 and central-directory
@@ -563,6 +617,7 @@ function readCentralDirectory(buffer, count) {
563617
module.exports={
564618
CentralFileHeader,
565619
LocalFileHeader,
620+
assertConsistentLocalHeader,
566621
findArchiveEnd,
567622
readCentralDirectory,
568623
};

β€Žtest/parallel/test-zlib-zip-coverage.jsβ€Ž

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -288,8 +288,9 @@ test('a Zip64 extra field value beyond Number.MAX_SAFE_INTEGER is rejected', asy
288288
uncompressedSize: 0xffffffffffffffffn,
289289
});
290290

291-
const[read]=zlib.ZipEntry.read(patched);
292-
assert.throws(()=>read.size,{
291+
// The header cross-check resolves the sizes as the archive is read, so a
292+
// malformed Zip64 value is rejected at read time rather than at .size access.
293+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
293294
code: 'ERR_ZIP_INVALID_ARCHIVE',
294295
message: /exceedsthesafeintegerrange/,
295296
});
@@ -325,8 +326,7 @@ test('a Zip64 extra-field TLV whose declared size overflows the extra field is r
325326
tlv.writeUInt16LE(100,2);// claims 100 bytes of data, but none follow
326327
constpatched=injectRawZip64Extra(archive,name,content.length,tlv);
327328

328-
const[read]=zlib.ZipEntry.read(patched);
329-
assert.throws(()=>read.size,{
329+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
330330
code: 'ERR_ZIP_INVALID_ARCHIVE',
331331
message: /extrafieldismalformed/,
332332
});
@@ -345,8 +345,7 @@ test('a Zip64 extra-field TLV too short for the field it claims to carry is reje
345345
tlv.writeUInt32LE(123,4);
346346
constpatched=injectRawZip64Extra(archive,name,content.length,tlv);
347347

348-
const[read]=zlib.ZipEntry.read(patched);
349-
assert.throws(()=>read.size,{
348+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
350349
code: 'ERR_ZIP_INVALID_ARCHIVE',
351350
message: /Zip64extendedinformationextrafieldistruncated/,
352351
});
@@ -500,7 +499,8 @@ test('contentIterator() enforces the same guards as content() and contentSync()'
500499
constarchive=awaitbuildArchive([entry]);
501500
consttampered=Buffer.from(archive);
502501
constcentralStart=30+'f.txt'.length+'hello world'.length;
503-
tampered.writeUInt32LE(1,centralStart+24);
502+
tampered.writeUInt32LE(1,22);// Local uncompressed size
503+
tampered.writeUInt32LE(1,centralStart+24);// Central uncompressed size
504504
const[read]=zlib.ZipEntry.read(tampered);
505505
awaitassert.rejects(drain(read.contentIterator()),{code: 'ERR_ZIP_ENTRY_CORRUPT'});
506506
}
@@ -593,7 +593,8 @@ test('ZipFile getSync().contentSync() enforces the same guards via decodeMemberS
593593
constarchive=awaitbuildArchive([entry]);
594594
consttampered=Buffer.from(archive);
595595
constcentralStart=30+'f.txt'.length+'hello world'.length;
596-
tampered.writeUInt32LE(1,centralStart+24);
596+
tampered.writeUInt32LE(1,22);// Local uncompressed size
597+
tampered.writeUInt32LE(1,centralStart+24);// Central uncompressed size
597598
constfilePath=awaitwriteTempArchive(tampered,'size-mismatch');
598599
constzf=zlib.ZipFile.openSync(filePath);
599600
assert.throws(()=>zf.getSync('f.txt').contentSync(),{code: 'ERR_ZIP_ENTRY_CORRUPT'});
@@ -607,7 +608,8 @@ test('contentIterator() rejects an entry that inflates to less than its declared
607608
constarchive=awaitbuildArchive([entry]);
608609
consttampered=Buffer.from(archive);
609610
constcentralStart=30+'f.txt'.length+'hi'.length;
610-
tampered.writeUInt32LE(1000,centralStart+24);// Declared size grown beyond reality
611+
tampered.writeUInt32LE(1000,22);// Local declared size
612+
tampered.writeUInt32LE(1000,centralStart+24);// Central declared size grown beyond reality
611613
const[read]=zlib.ZipEntry.read(tampered);
612614
awaitassert.rejects(drain(read.contentIterator()),{
613615
code: 'ERR_ZIP_ENTRY_CORRUPT',

β€Žtest/parallel/test-zlib-zip-hardening.jsβ€Ž

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -118,13 +118,14 @@ test('a declared-size mismatch is rejected as corrupt', async () => {
118118
constentry=awaitzlib.ZipEntry.create('f.txt',Buffer.from('hello world'),{method: 'store'});
119119
constarchive=awaitbuildArchive([entry]);
120120

121-
// Shrink the *declared* uncompressed size in the central directory record
122-
// without touching the stored bytes themselves, so the amount of data
123-
// produced no longer matches what the header promised.
121+
// Shrink the *declared* uncompressed size in both the local and central
122+
// headers (kept consistent so the header cross-check passes) without touching
123+
// the stored bytes, so the produced amount no longer matches the headers'
124+
// promise and the decode-time size check fires.
124125
consttampered=Buffer.from(archive);
125126
constcentralHeaderStart=30+'f.txt'.length+'hello world'.length;
126-
constuncompressedSizeOffset=centralHeaderStart+24;
127-
tampered.writeUInt32LE(1,uncompressedSizeOffset);
127+
tampered.writeUInt32LE(1,22);// Local uncompressed size
128+
tampered.writeUInt32LE(1,centralHeaderStart+24);// Central uncompressed size
128129

129130
const[tamperedEntry]=zlib.ZipEntry.read(tampered);
130131
assert.strictEqual(tamperedEntry.size,1);
@@ -165,7 +166,10 @@ test('a forged small header whose content inflates past its declared size is rej
165166
consttampered=Buffer.from(archive);
166167
consteocd=tampered.length-22;// No comment, so EOCD is the last 22 bytes
167168
constcdOffset=tampered.readUInt32LE(eocd+16);
168-
tampered.writeUInt32LE(50,cdOffset+24);// Forge declared uncompressedSize
169+
// Forge the declared uncompressedSize in both headers (kept consistent so
170+
// the header cross-check passes; the decompressor still catches the lie).
171+
tampered.writeUInt32LE(50,22);// Local uncompressedSize
172+
tampered.writeUInt32LE(50,cdOffset+24);// Central uncompressedSize
169173

170174
const[e]=zlib.ZipEntry.read(tampered);
171175
assert.strictEqual(e.size,50);// 50 <= maxSize 100 clears the up-front check
@@ -413,9 +417,11 @@ test('a member whose data crosses into the central directory is rejected', async
413417
constarchive=Buffer.from(awaitbuildArchive(
414418
[awaitzlib.ZipEntry.create(name,content,{method: 'store'})]));
415419
constcentralHeaderStart=30+name.length+content.length;
416-
// Lie about the compressed size so the member's data range reaches into
417-
// the central directory (while staying inside the buffer).
418-
archive.writeUInt32LE(content.length+40,centralHeaderStart+20);
420+
// Lie about the compressed size in both headers (kept consistent so the
421+
// header cross-check passes) so the member's data range reaches into the
422+
// central directory (while staying inside the buffer).
423+
archive.writeUInt32LE(content.length+40,18);// Local compressed size
424+
archive.writeUInt32LE(content.length+40,centralHeaderStart+20);// Central
419425
assert.throws(()=>[...zlib.ZipEntry.read(archive)],
420426
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /possiblezipbomb/});
421427
});

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Commit 55b0495

Browse files
pipobscureaduh95
authored andcommitted
zlib: reject local/central ZIP header mismatch
The reader treats the central directory as authoritative for a member's method, sizes, CRC, and name, but read the local header only for its signature. An archive whose local file header disagrees with the central directory therefore extracts different bytes here than in a reader that uses the local header (e.g. Info-ZIP unzip), and its encrypted bit was read from the local header while its identity came from the central directory - a parser-confusion split that defeats inspect-then-consume pipelines and can slip an encrypted member past a central-directory scanner. Cross-check the local header against the central entry when a member is read: method, CRC, and both sizes (exempting a data-descriptor entry, whose local crc/sizes are legitimately zero), plus the encryption flag. Reject a mismatch with ERR_ZIP_INVALID_ARCHIVE, consistent with the reject-rather-than-silently-choose stance already taken for ambiguous archive ends. The existing hardening/coverage tests that forged a decode-time size, CRC, or Zip64 lie in the central header alone now trip this earlier check; update them to patch both headers consistently so they still exercise the decode-time guards they target. Signed-off-by: Philipp Dunkel <pip@pipobscure.com> PR-URL: #65016 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
1 parent 31742f2 commit 55b0495

4 files changed

Lines changed: 92 additions & 21 deletions

File tree

β€Žlib/internal/zip/entry.jsβ€Ž

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ const {
7676
const{
7777
CentralFileHeader,
7878
LocalFileHeader,
79+
assertConsistentLocalHeader,
7980
findArchiveEnd,
8081
}=require('internal/zip/headers');
8182
const{
@@ -399,6 +400,9 @@ class ZipEntry {
399400
awaitreadFdFully(fd,full.subarray(30),this.#localOffset +30);
400401
}
401402
this.#local =newLocalFileHeader(full,0);
403+
if(this.#central !==null){
404+
assertConsistentLocalHeader(this.#local,this.#central);
405+
}
402406
this.#contentOffset =this.#localOffset +length;
403407
returnthis.#local;
404408
}
@@ -419,6 +423,9 @@ class ZipEntry {
419423
readFdFullySync(fd,full.subarray(30),this.#localOffset +30);
420424
}
421425
this.#local =newLocalFileHeader(full,0);
426+
if(this.#central !==null){
427+
assertConsistentLocalHeader(this.#local,this.#central);
428+
}
422429
this.#contentOffset =this.#localOffset +length;
423430
returnthis.#local;
424431
}
@@ -930,6 +937,7 @@ function* readArchiveEntries(buf, end) {
930937
}
931938
constlocalOffset=central.localFileHeaderOffset+end.prefix;
932939
constlocal=newLocalFileHeader(buf,localOffset);
940+
assertConsistentLocalHeader(local,central);
933941
constdataStart=localOffset+local.byteLength;
934942
constlength=central.compressedSize;
935943
validateArchiveRange(buf,dataStart,length,'entry data');

β€Žlib/internal/zip/headers.jsβ€Ž

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ const {
2525
SIG_ZIP64_EOCD_LOCATOR,
2626
SIG_EOCD,
2727
MADE_BY_UNIX,
28+
FLAG_ENCRYPTED,
29+
FLAG_DATA_DESCRIPTOR,
2830
SENTINEL16,
2931
SENTINEL32,
3032
TAIL_LENGTH,
@@ -267,6 +269,7 @@ class CentralFileHeader {
267269
classLocalFileHeader{
268270
#buffer;
269271
#offset;
272+
#zip64 =null;
270273
constructor(buffer,offset=0){
271274
validateArchiveRange(buffer,offset,30,'local file header');
272275
if(buffer.readUInt32LE(offset)!==SIG_LOCAL_FILE_HEADER){
@@ -280,9 +283,31 @@ class LocalFileHeader {
280283
}
281284
getbyteLength(){return30+this.fileNameLength+this.extraFieldLength;}
282285
getflags(){returnthis.#buffer.readUInt16LE(this.#offset +6);}
283-
// Spec field (sec. 4.4.5); the central directory's method is authoritative,
284-
// so the local copy is not consumed today.
285-
// get compressionMethod() { return this.#buffer.readUInt16LE(this.#offset + 8); }
286+
// The central directory is authoritative, but these local fields are read to
287+
// reject an archive whose local header contradicts it (assertConsistentLocalHeader).
288+
getcompressionMethod(){returnthis.#buffer.readUInt16LE(this.#offset +8);}
289+
getcrc32(){returnthis.#buffer.readUInt32LE(this.#offset +14);}
290+
// The Zip64 extra supplies the true 64-bit sizes for whichever classic size
291+
// field holds an overflow sentinel; a local header has no offset/disk field.
292+
#resolveZip64(){
293+
if(this.#zip64 ===null){
294+
this.#zip64 =parseZip64Extra(this.extraField,{
295+
uncompressedSize: this.#buffer.readUInt32LE(this.#offset +22)===SENTINEL32,
296+
compressedSize: this.#buffer.readUInt32LE(this.#offset +18)===SENTINEL32,
297+
localFileHeaderOffset: false,
298+
diskNumber: false,
299+
});
300+
}
301+
returnthis.#zip64;
302+
}
303+
getcompressedSize(){
304+
constvalue=this.#buffer.readUInt32LE(this.#offset +18);
305+
returnvalue===SENTINEL32 ? this.#resolveZip64().compressedSize : value;
306+
}
307+
getuncompressedSize(){
308+
constvalue=this.#buffer.readUInt32LE(this.#offset +22);
309+
returnvalue===SENTINEL32 ? this.#resolveZip64().uncompressedSize : value;
310+
}
286311
getfileNameLength(){returnthis.#buffer.readUInt16LE(this.#offset +26);}
287312
getextraFieldLength(){returnthis.#buffer.readUInt16LE(this.#offset +28);}
288313
getextraField(){
@@ -311,6 +336,35 @@ class LocalFileHeader {
311336
}
312337
}
313338

339+
// Reject an archive whose local file header contradicts the central directory
340+
// on a field that decides which bytes a member yields. This reader treats the
341+
// central directory as authoritative, but a divergent local header lets a
342+
// local-header-based extractor (Info-ZIP unzip, and others) read a different
343+
// member, method, or size from the same archive - a parser-confusion split that
344+
// defeats inspect-then-consume pipelines. Reject rather than silently diverge.
345+
functionassertConsistentLocalHeader(local,central){
346+
if(local.compressionMethod!==central.compressionMethod){
347+
thrownewERR_ZIP_INVALID_ARCHIVE(
348+
'local and central compression methods disagree');
349+
}
350+
if((local.flags&FLAG_ENCRYPTED)!==(central.flags&FLAG_ENCRYPTED)){
351+
thrownewERR_ZIP_INVALID_ARCHIVE(
352+
'local and central encryption flags disagree');
353+
}
354+
// A streamed entry (data-descriptor bit) writes zero crc and sizes in the
355+
// local header, deferring the true values to the central directory; only then
356+
// is a difference on those three fields expected.
357+
constdeferred=(local.flags&FLAG_DATA_DESCRIPTOR)!==0&&
358+
local.crc32===0&&local.compressedSize===0&&local.uncompressedSize===0;
359+
if(!deferred&&
360+
(local.crc32!==central.crc32||
361+
local.compressedSize!==central.compressedSize||
362+
local.uncompressedSize!==central.uncompressedSize)){
363+
thrownewERR_ZIP_INVALID_ARCHIVE(
364+
'local and central header crc-32 or sizes disagree');
365+
}
366+
}
367+
314368
// Returns whether an EOCD-looking record could describe an archive this
315369
// implementation supports. This is deliberately only a cheap preflight: the
316370
// selected record still receives the complete Zip64 and central-directory
@@ -563,6 +617,7 @@ function readCentralDirectory(buffer, count) {
563617
module.exports={
564618
CentralFileHeader,
565619
LocalFileHeader,
620+
assertConsistentLocalHeader,
566621
findArchiveEnd,
567622
readCentralDirectory,
568623
};

β€Žtest/parallel/test-zlib-zip-coverage.jsβ€Ž

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -288,8 +288,9 @@ test('a Zip64 extra field value beyond Number.MAX_SAFE_INTEGER is rejected', asy
288288
uncompressedSize: 0xffffffffffffffffn,
289289
});
290290

291-
const[read]=zlib.ZipEntry.read(patched);
292-
assert.throws(()=>read.size,{
291+
// The header cross-check resolves the sizes as the archive is read, so a
292+
// malformed Zip64 value is rejected at read time rather than at .size access.
293+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
293294
code: 'ERR_ZIP_INVALID_ARCHIVE',
294295
message: /exceedsthesafeintegerrange/,
295296
});
@@ -325,8 +326,7 @@ test('a Zip64 extra-field TLV whose declared size overflows the extra field is r
325326
tlv.writeUInt16LE(100,2);// claims 100 bytes of data, but none follow
326327
constpatched=injectRawZip64Extra(archive,name,content.length,tlv);
327328

328-
const[read]=zlib.ZipEntry.read(patched);
329-
assert.throws(()=>read.size,{
329+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
330330
code: 'ERR_ZIP_INVALID_ARCHIVE',
331331
message: /extrafieldismalformed/,
332332
});
@@ -345,8 +345,7 @@ test('a Zip64 extra-field TLV too short for the field it claims to carry is reje
345345
tlv.writeUInt32LE(123,4);
346346
constpatched=injectRawZip64Extra(archive,name,content.length,tlv);
347347

348-
const[read]=zlib.ZipEntry.read(patched);
349-
assert.throws(()=>read.size,{
348+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
350349
code: 'ERR_ZIP_INVALID_ARCHIVE',
351350
message: /Zip64extendedinformationextrafieldistruncated/,
352351
});
@@ -500,7 +499,8 @@ test('contentIterator() enforces the same guards as content() and contentSync()'
500499
constarchive=awaitbuildArchive([entry]);
501500
consttampered=Buffer.from(archive);
502501
constcentralStart=30+'f.txt'.length+'hello world'.length;
503-
tampered.writeUInt32LE(1,centralStart+24);
502+
tampered.writeUInt32LE(1,22);// Local uncompressed size
503+
tampered.writeUInt32LE(1,centralStart+24);// Central uncompressed size
504504
const[read]=zlib.ZipEntry.read(tampered);
505505
awaitassert.rejects(drain(read.contentIterator()),{code: 'ERR_ZIP_ENTRY_CORRUPT'});
506506
}
@@ -593,7 +593,8 @@ test('ZipFile getSync().contentSync() enforces the same guards via decodeMemberS
593593
constarchive=awaitbuildArchive([entry]);
594594
consttampered=Buffer.from(archive);
595595
constcentralStart=30+'f.txt'.length+'hello world'.length;
596-
tampered.writeUInt32LE(1,centralStart+24);
596+
tampered.writeUInt32LE(1,22);// Local uncompressed size
597+
tampered.writeUInt32LE(1,centralStart+24);// Central uncompressed size
597598
constfilePath=awaitwriteTempArchive(tampered,'size-mismatch');
598599
constzf=zlib.ZipFile.openSync(filePath);
599600
assert.throws(()=>zf.getSync('f.txt').contentSync(),{code: 'ERR_ZIP_ENTRY_CORRUPT'});
@@ -607,7 +608,8 @@ test('contentIterator() rejects an entry that inflates to less than its declared
607608
constarchive=awaitbuildArchive([entry]);
608609
consttampered=Buffer.from(archive);
609610
constcentralStart=30+'f.txt'.length+'hi'.length;
610-
tampered.writeUInt32LE(1000,centralStart+24);// Declared size grown beyond reality
611+
tampered.writeUInt32LE(1000,22);// Local declared size
612+
tampered.writeUInt32LE(1000,centralStart+24);// Central declared size grown beyond reality
611613
const[read]=zlib.ZipEntry.read(tampered);
612614
awaitassert.rejects(drain(read.contentIterator()),{
613615
code: 'ERR_ZIP_ENTRY_CORRUPT',

β€Žtest/parallel/test-zlib-zip-hardening.jsβ€Ž

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -118,13 +118,14 @@ test('a declared-size mismatch is rejected as corrupt', async () => {
118118
constentry=awaitzlib.ZipEntry.create('f.txt',Buffer.from('hello world'),{method: 'store'});
119119
constarchive=awaitbuildArchive([entry]);
120120

121-
// Shrink the *declared* uncompressed size in the central directory record
122-
// without touching the stored bytes themselves, so the amount of data
123-
// produced no longer matches what the header promised.
121+
// Shrink the *declared* uncompressed size in both the local and central
122+
// headers (kept consistent so the header cross-check passes) without touching
123+
// the stored bytes, so the produced amount no longer matches the headers'
124+
// promise and the decode-time size check fires.
124125
consttampered=Buffer.from(archive);
125126
constcentralHeaderStart=30+'f.txt'.length+'hello world'.length;
126-
constuncompressedSizeOffset=centralHeaderStart+24;
127-
tampered.writeUInt32LE(1,uncompressedSizeOffset);
127+
tampered.writeUInt32LE(1,22);// Local uncompressed size
128+
tampered.writeUInt32LE(1,centralHeaderStart+24);// Central uncompressed size
128129

129130
const[tamperedEntry]=zlib.ZipEntry.read(tampered);
130131
assert.strictEqual(tamperedEntry.size,1);
@@ -165,7 +166,10 @@ test('a forged small header whose content inflates past its declared size is rej
165166
consttampered=Buffer.from(archive);
166167
consteocd=tampered.length-22;// No comment, so EOCD is the last 22 bytes
167168
constcdOffset=tampered.readUInt32LE(eocd+16);
168-
tampered.writeUInt32LE(50,cdOffset+24);// Forge declared uncompressedSize
169+
// Forge the declared uncompressedSize in both headers (kept consistent so
170+
// the header cross-check passes; the decompressor still catches the lie).
171+
tampered.writeUInt32LE(50,22);// Local uncompressedSize
172+
tampered.writeUInt32LE(50,cdOffset+24);// Central uncompressedSize
169173

170174
const[e]=zlib.ZipEntry.read(tampered);
171175
assert.strictEqual(e.size,50);// 50 <= maxSize 100 clears the up-front check
@@ -413,9 +417,11 @@ test('a member whose data crosses into the central directory is rejected', async
413417
constarchive=Buffer.from(awaitbuildArchive(
414418
[awaitzlib.ZipEntry.create(name,content,{method: 'store'})]));
415419
constcentralHeaderStart=30+name.length+content.length;
416-
// Lie about the compressed size so the member's data range reaches into
417-
// the central directory (while staying inside the buffer).
418-
archive.writeUInt32LE(content.length+40,centralHeaderStart+20);
420+
// Lie about the compressed size in both headers (kept consistent so the
421+
// header cross-check passes) so the member's data range reaches into the
422+
// central directory (while staying inside the buffer).
423+
archive.writeUInt32LE(content.length+40,18);// Local compressed size
424+
archive.writeUInt32LE(content.length+40,centralHeaderStart+20);// Central
419425
assert.throws(()=>[...zlib.ZipEntry.read(archive)],
420426
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /possiblezipbomb/});
421427
});

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 55b0495

Browse files
pipobscureaduh95
authored andcommitted
zlib: reject local/central ZIP header mismatch
The reader treats the central directory as authoritative for a member's method, sizes, CRC, and name, but read the local header only for its signature. An archive whose local file header disagrees with the central directory therefore extracts different bytes here than in a reader that uses the local header (e.g. Info-ZIP unzip), and its encrypted bit was read from the local header while its identity came from the central directory - a parser-confusion split that defeats inspect-then-consume pipelines and can slip an encrypted member past a central-directory scanner. Cross-check the local header against the central entry when a member is read: method, CRC, and both sizes (exempting a data-descriptor entry, whose local crc/sizes are legitimately zero), plus the encryption flag. Reject a mismatch with ERR_ZIP_INVALID_ARCHIVE, consistent with the reject-rather-than-silently-choose stance already taken for ambiguous archive ends. The existing hardening/coverage tests that forged a decode-time size, CRC, or Zip64 lie in the central header alone now trip this earlier check; update them to patch both headers consistently so they still exercise the decode-time guards they target. Signed-off-by: Philipp Dunkel <pip@pipobscure.com> PR-URL: #65016 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
1 parent 31742f2 commit 55b0495

4 files changed

Lines changed: 92 additions & 21 deletions

File tree

β€Žlib/internal/zip/entry.jsβ€Ž

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ const {
7676
const{
7777
CentralFileHeader,
7878
LocalFileHeader,
79+
assertConsistentLocalHeader,
7980
findArchiveEnd,
8081
}=require('internal/zip/headers');
8182
const{
@@ -399,6 +400,9 @@ class ZipEntry {
399400
awaitreadFdFully(fd,full.subarray(30),this.#localOffset +30);
400401
}
401402
this.#local =newLocalFileHeader(full,0);
403+
if(this.#central !==null){
404+
assertConsistentLocalHeader(this.#local,this.#central);
405+
}
402406
this.#contentOffset =this.#localOffset +length;
403407
returnthis.#local;
404408
}
@@ -419,6 +423,9 @@ class ZipEntry {
419423
readFdFullySync(fd,full.subarray(30),this.#localOffset +30);
420424
}
421425
this.#local =newLocalFileHeader(full,0);
426+
if(this.#central !==null){
427+
assertConsistentLocalHeader(this.#local,this.#central);
428+
}
422429
this.#contentOffset =this.#localOffset +length;
423430
returnthis.#local;
424431
}
@@ -930,6 +937,7 @@ function* readArchiveEntries(buf, end) {
930937
}
931938
constlocalOffset=central.localFileHeaderOffset+end.prefix;
932939
constlocal=newLocalFileHeader(buf,localOffset);
940+
assertConsistentLocalHeader(local,central);
933941
constdataStart=localOffset+local.byteLength;
934942
constlength=central.compressedSize;
935943
validateArchiveRange(buf,dataStart,length,'entry data');

β€Žlib/internal/zip/headers.jsβ€Ž

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ const {
2525
SIG_ZIP64_EOCD_LOCATOR,
2626
SIG_EOCD,
2727
MADE_BY_UNIX,
28+
FLAG_ENCRYPTED,
29+
FLAG_DATA_DESCRIPTOR,
2830
SENTINEL16,
2931
SENTINEL32,
3032
TAIL_LENGTH,
@@ -267,6 +269,7 @@ class CentralFileHeader {
267269
classLocalFileHeader{
268270
#buffer;
269271
#offset;
272+
#zip64 =null;
270273
constructor(buffer,offset=0){
271274
validateArchiveRange(buffer,offset,30,'local file header');
272275
if(buffer.readUInt32LE(offset)!==SIG_LOCAL_FILE_HEADER){
@@ -280,9 +283,31 @@ class LocalFileHeader {
280283
}
281284
getbyteLength(){return30+this.fileNameLength+this.extraFieldLength;}
282285
getflags(){returnthis.#buffer.readUInt16LE(this.#offset +6);}
283-
// Spec field (sec. 4.4.5); the central directory's method is authoritative,
284-
// so the local copy is not consumed today.
285-
// get compressionMethod() { return this.#buffer.readUInt16LE(this.#offset + 8); }
286+
// The central directory is authoritative, but these local fields are read to
287+
// reject an archive whose local header contradicts it (assertConsistentLocalHeader).
288+
getcompressionMethod(){returnthis.#buffer.readUInt16LE(this.#offset +8);}
289+
getcrc32(){returnthis.#buffer.readUInt32LE(this.#offset +14);}
290+
// The Zip64 extra supplies the true 64-bit sizes for whichever classic size
291+
// field holds an overflow sentinel; a local header has no offset/disk field.
292+
#resolveZip64(){
293+
if(this.#zip64 ===null){
294+
this.#zip64 =parseZip64Extra(this.extraField,{
295+
uncompressedSize: this.#buffer.readUInt32LE(this.#offset +22)===SENTINEL32,
296+
compressedSize: this.#buffer.readUInt32LE(this.#offset +18)===SENTINEL32,
297+
localFileHeaderOffset: false,
298+
diskNumber: false,
299+
});
300+
}
301+
returnthis.#zip64;
302+
}
303+
getcompressedSize(){
304+
constvalue=this.#buffer.readUInt32LE(this.#offset +18);
305+
returnvalue===SENTINEL32 ? this.#resolveZip64().compressedSize : value;
306+
}
307+
getuncompressedSize(){
308+
constvalue=this.#buffer.readUInt32LE(this.#offset +22);
309+
returnvalue===SENTINEL32 ? this.#resolveZip64().uncompressedSize : value;
310+
}
286311
getfileNameLength(){returnthis.#buffer.readUInt16LE(this.#offset +26);}
287312
getextraFieldLength(){returnthis.#buffer.readUInt16LE(this.#offset +28);}
288313
getextraField(){
@@ -311,6 +336,35 @@ class LocalFileHeader {
311336
}
312337
}
313338

339+
// Reject an archive whose local file header contradicts the central directory
340+
// on a field that decides which bytes a member yields. This reader treats the
341+
// central directory as authoritative, but a divergent local header lets a
342+
// local-header-based extractor (Info-ZIP unzip, and others) read a different
343+
// member, method, or size from the same archive - a parser-confusion split that
344+
// defeats inspect-then-consume pipelines. Reject rather than silently diverge.
345+
functionassertConsistentLocalHeader(local,central){
346+
if(local.compressionMethod!==central.compressionMethod){
347+
thrownewERR_ZIP_INVALID_ARCHIVE(
348+
'local and central compression methods disagree');
349+
}
350+
if((local.flags&FLAG_ENCRYPTED)!==(central.flags&FLAG_ENCRYPTED)){
351+
thrownewERR_ZIP_INVALID_ARCHIVE(
352+
'local and central encryption flags disagree');
353+
}
354+
// A streamed entry (data-descriptor bit) writes zero crc and sizes in the
355+
// local header, deferring the true values to the central directory; only then
356+
// is a difference on those three fields expected.
357+
constdeferred=(local.flags&FLAG_DATA_DESCRIPTOR)!==0&&
358+
local.crc32===0&&local.compressedSize===0&&local.uncompressedSize===0;
359+
if(!deferred&&
360+
(local.crc32!==central.crc32||
361+
local.compressedSize!==central.compressedSize||
362+
local.uncompressedSize!==central.uncompressedSize)){
363+
thrownewERR_ZIP_INVALID_ARCHIVE(
364+
'local and central header crc-32 or sizes disagree');
365+
}
366+
}
367+
314368
// Returns whether an EOCD-looking record could describe an archive this
315369
// implementation supports. This is deliberately only a cheap preflight: the
316370
// selected record still receives the complete Zip64 and central-directory
@@ -563,6 +617,7 @@ function readCentralDirectory(buffer, count) {
563617
module.exports={
564618
CentralFileHeader,
565619
LocalFileHeader,
620+
assertConsistentLocalHeader,
566621
findArchiveEnd,
567622
readCentralDirectory,
568623
};

β€Žtest/parallel/test-zlib-zip-coverage.jsβ€Ž

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -288,8 +288,9 @@ test('a Zip64 extra field value beyond Number.MAX_SAFE_INTEGER is rejected', asy
288288
uncompressedSize: 0xffffffffffffffffn,
289289
});
290290

291-
const[read]=zlib.ZipEntry.read(patched);
292-
assert.throws(()=>read.size,{
291+
// The header cross-check resolves the sizes as the archive is read, so a
292+
// malformed Zip64 value is rejected at read time rather than at .size access.
293+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
293294
code: 'ERR_ZIP_INVALID_ARCHIVE',
294295
message: /exceedsthesafeintegerrange/,
295296
});
@@ -325,8 +326,7 @@ test('a Zip64 extra-field TLV whose declared size overflows the extra field is r
325326
tlv.writeUInt16LE(100,2);// claims 100 bytes of data, but none follow
326327
constpatched=injectRawZip64Extra(archive,name,content.length,tlv);
327328

328-
const[read]=zlib.ZipEntry.read(patched);
329-
assert.throws(()=>read.size,{
329+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
330330
code: 'ERR_ZIP_INVALID_ARCHIVE',
331331
message: /extrafieldismalformed/,
332332
});
@@ -345,8 +345,7 @@ test('a Zip64 extra-field TLV too short for the field it claims to carry is reje
345345
tlv.writeUInt32LE(123,4);
346346
constpatched=injectRawZip64Extra(archive,name,content.length,tlv);
347347

348-
const[read]=zlib.ZipEntry.read(patched);
349-
assert.throws(()=>read.size,{
348+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
350349
code: 'ERR_ZIP_INVALID_ARCHIVE',
351350
message: /Zip64extendedinformationextrafieldistruncated/,
352351
});
@@ -500,7 +499,8 @@ test('contentIterator() enforces the same guards as content() and contentSync()'
500499
constarchive=awaitbuildArchive([entry]);
501500
consttampered=Buffer.from(archive);
502501
constcentralStart=30+'f.txt'.length+'hello world'.length;
503-
tampered.writeUInt32LE(1,centralStart+24);
502+
tampered.writeUInt32LE(1,22);// Local uncompressed size
503+
tampered.writeUInt32LE(1,centralStart+24);// Central uncompressed size
504504
const[read]=zlib.ZipEntry.read(tampered);
505505
awaitassert.rejects(drain(read.contentIterator()),{code: 'ERR_ZIP_ENTRY_CORRUPT'});
506506
}
@@ -593,7 +593,8 @@ test('ZipFile getSync().contentSync() enforces the same guards via decodeMemberS
593593
constarchive=awaitbuildArchive([entry]);
594594
consttampered=Buffer.from(archive);
595595
constcentralStart=30+'f.txt'.length+'hello world'.length;
596-
tampered.writeUInt32LE(1,centralStart+24);
596+
tampered.writeUInt32LE(1,22);// Local uncompressed size
597+
tampered.writeUInt32LE(1,centralStart+24);// Central uncompressed size
597598
constfilePath=awaitwriteTempArchive(tampered,'size-mismatch');
598599
constzf=zlib.ZipFile.openSync(filePath);
599600
assert.throws(()=>zf.getSync('f.txt').contentSync(),{code: 'ERR_ZIP_ENTRY_CORRUPT'});
@@ -607,7 +608,8 @@ test('contentIterator() rejects an entry that inflates to less than its declared
607608
constarchive=awaitbuildArchive([entry]);
608609
consttampered=Buffer.from(archive);
609610
constcentralStart=30+'f.txt'.length+'hi'.length;
610-
tampered.writeUInt32LE(1000,centralStart+24);// Declared size grown beyond reality
611+
tampered.writeUInt32LE(1000,22);// Local declared size
612+
tampered.writeUInt32LE(1000,centralStart+24);// Central declared size grown beyond reality
611613
const[read]=zlib.ZipEntry.read(tampered);
612614
awaitassert.rejects(drain(read.contentIterator()),{
613615
code: 'ERR_ZIP_ENTRY_CORRUPT',

β€Žtest/parallel/test-zlib-zip-hardening.jsβ€Ž

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -118,13 +118,14 @@ test('a declared-size mismatch is rejected as corrupt', async () => {
118118
constentry=awaitzlib.ZipEntry.create('f.txt',Buffer.from('hello world'),{method: 'store'});
119119
constarchive=awaitbuildArchive([entry]);
120120

121-
// Shrink the *declared* uncompressed size in the central directory record
122-
// without touching the stored bytes themselves, so the amount of data
123-
// produced no longer matches what the header promised.
121+
// Shrink the *declared* uncompressed size in both the local and central
122+
// headers (kept consistent so the header cross-check passes) without touching
123+
// the stored bytes, so the produced amount no longer matches the headers'
124+
// promise and the decode-time size check fires.
124125
consttampered=Buffer.from(archive);
125126
constcentralHeaderStart=30+'f.txt'.length+'hello world'.length;
126-
constuncompressedSizeOffset=centralHeaderStart+24;
127-
tampered.writeUInt32LE(1,uncompressedSizeOffset);
127+
tampered.writeUInt32LE(1,22);// Local uncompressed size
128+
tampered.writeUInt32LE(1,centralHeaderStart+24);// Central uncompressed size
128129

129130
const[tamperedEntry]=zlib.ZipEntry.read(tampered);
130131
assert.strictEqual(tamperedEntry.size,1);
@@ -165,7 +166,10 @@ test('a forged small header whose content inflates past its declared size is rej
165166
consttampered=Buffer.from(archive);
166167
consteocd=tampered.length-22;// No comment, so EOCD is the last 22 bytes
167168
constcdOffset=tampered.readUInt32LE(eocd+16);
168-
tampered.writeUInt32LE(50,cdOffset+24);// Forge declared uncompressedSize
169+
// Forge the declared uncompressedSize in both headers (kept consistent so
170+
// the header cross-check passes; the decompressor still catches the lie).
171+
tampered.writeUInt32LE(50,22);// Local uncompressedSize
172+
tampered.writeUInt32LE(50,cdOffset+24);// Central uncompressedSize
169173

170174
const[e]=zlib.ZipEntry.read(tampered);
171175
assert.strictEqual(e.size,50);// 50 <= maxSize 100 clears the up-front check
@@ -413,9 +417,11 @@ test('a member whose data crosses into the central directory is rejected', async
413417
constarchive=Buffer.from(awaitbuildArchive(
414418
[awaitzlib.ZipEntry.create(name,content,{method: 'store'})]));
415419
constcentralHeaderStart=30+name.length+content.length;
416-
// Lie about the compressed size so the member's data range reaches into
417-
// the central directory (while staying inside the buffer).
418-
archive.writeUInt32LE(content.length+40,centralHeaderStart+20);
420+
// Lie about the compressed size in both headers (kept consistent so the
421+
// header cross-check passes) so the member's data range reaches into the
422+
// central directory (while staying inside the buffer).
423+
archive.writeUInt32LE(content.length+40,18);// Local compressed size
424+
archive.writeUInt32LE(content.length+40,centralHeaderStart+20);// Central
419425
assert.throws(()=>[...zlib.ZipEntry.read(archive)],
420426
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /possiblezipbomb/});
421427
});

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 55b0495

Browse files
pipobscureaduh95
authored andcommitted
zlib: reject local/central ZIP header mismatch
The reader treats the central directory as authoritative for a member's method, sizes, CRC, and name, but read the local header only for its signature. An archive whose local file header disagrees with the central directory therefore extracts different bytes here than in a reader that uses the local header (e.g. Info-ZIP unzip), and its encrypted bit was read from the local header while its identity came from the central directory - a parser-confusion split that defeats inspect-then-consume pipelines and can slip an encrypted member past a central-directory scanner. Cross-check the local header against the central entry when a member is read: method, CRC, and both sizes (exempting a data-descriptor entry, whose local crc/sizes are legitimately zero), plus the encryption flag. Reject a mismatch with ERR_ZIP_INVALID_ARCHIVE, consistent with the reject-rather-than-silently-choose stance already taken for ambiguous archive ends. The existing hardening/coverage tests that forged a decode-time size, CRC, or Zip64 lie in the central header alone now trip this earlier check; update them to patch both headers consistently so they still exercise the decode-time guards they target. Signed-off-by: Philipp Dunkel <pip@pipobscure.com> PR-URL: #65016 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
1 parent 31742f2 commit 55b0495

4 files changed

Lines changed: 92 additions & 21 deletions

File tree

β€Žlib/internal/zip/entry.jsβ€Ž

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ const {
7676
const{
7777
CentralFileHeader,
7878
LocalFileHeader,
79+
assertConsistentLocalHeader,
7980
findArchiveEnd,
8081
}=require('internal/zip/headers');
8182
const{
@@ -399,6 +400,9 @@ class ZipEntry {
399400
awaitreadFdFully(fd,full.subarray(30),this.#localOffset +30);
400401
}
401402
this.#local =newLocalFileHeader(full,0);
403+
if(this.#central !==null){
404+
assertConsistentLocalHeader(this.#local,this.#central);
405+
}
402406
this.#contentOffset =this.#localOffset +length;
403407
returnthis.#local;
404408
}
@@ -419,6 +423,9 @@ class ZipEntry {
419423
readFdFullySync(fd,full.subarray(30),this.#localOffset +30);
420424
}
421425
this.#local =newLocalFileHeader(full,0);
426+
if(this.#central !==null){
427+
assertConsistentLocalHeader(this.#local,this.#central);
428+
}
422429
this.#contentOffset =this.#localOffset +length;
423430
returnthis.#local;
424431
}
@@ -930,6 +937,7 @@ function* readArchiveEntries(buf, end) {
930937
}
931938
constlocalOffset=central.localFileHeaderOffset+end.prefix;
932939
constlocal=newLocalFileHeader(buf,localOffset);
940+
assertConsistentLocalHeader(local,central);
933941
constdataStart=localOffset+local.byteLength;
934942
constlength=central.compressedSize;
935943
validateArchiveRange(buf,dataStart,length,'entry data');

β€Žlib/internal/zip/headers.jsβ€Ž

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ const {
2525
SIG_ZIP64_EOCD_LOCATOR,
2626
SIG_EOCD,
2727
MADE_BY_UNIX,
28+
FLAG_ENCRYPTED,
29+
FLAG_DATA_DESCRIPTOR,
2830
SENTINEL16,
2931
SENTINEL32,
3032
TAIL_LENGTH,
@@ -267,6 +269,7 @@ class CentralFileHeader {
267269
classLocalFileHeader{
268270
#buffer;
269271
#offset;
272+
#zip64 =null;
270273
constructor(buffer,offset=0){
271274
validateArchiveRange(buffer,offset,30,'local file header');
272275
if(buffer.readUInt32LE(offset)!==SIG_LOCAL_FILE_HEADER){
@@ -280,9 +283,31 @@ class LocalFileHeader {
280283
}
281284
getbyteLength(){return30+this.fileNameLength+this.extraFieldLength;}
282285
getflags(){returnthis.#buffer.readUInt16LE(this.#offset +6);}
283-
// Spec field (sec. 4.4.5); the central directory's method is authoritative,
284-
// so the local copy is not consumed today.
285-
// get compressionMethod() { return this.#buffer.readUInt16LE(this.#offset + 8); }
286+
// The central directory is authoritative, but these local fields are read to
287+
// reject an archive whose local header contradicts it (assertConsistentLocalHeader).
288+
getcompressionMethod(){returnthis.#buffer.readUInt16LE(this.#offset +8);}
289+
getcrc32(){returnthis.#buffer.readUInt32LE(this.#offset +14);}
290+
// The Zip64 extra supplies the true 64-bit sizes for whichever classic size
291+
// field holds an overflow sentinel; a local header has no offset/disk field.
292+
#resolveZip64(){
293+
if(this.#zip64 ===null){
294+
this.#zip64 =parseZip64Extra(this.extraField,{
295+
uncompressedSize: this.#buffer.readUInt32LE(this.#offset +22)===SENTINEL32,
296+
compressedSize: this.#buffer.readUInt32LE(this.#offset +18)===SENTINEL32,
297+
localFileHeaderOffset: false,
298+
diskNumber: false,
299+
});
300+
}
301+
returnthis.#zip64;
302+
}
303+
getcompressedSize(){
304+
constvalue=this.#buffer.readUInt32LE(this.#offset +18);
305+
returnvalue===SENTINEL32 ? this.#resolveZip64().compressedSize : value;
306+
}
307+
getuncompressedSize(){
308+
constvalue=this.#buffer.readUInt32LE(this.#offset +22);
309+
returnvalue===SENTINEL32 ? this.#resolveZip64().uncompressedSize : value;
310+
}
286311
getfileNameLength(){returnthis.#buffer.readUInt16LE(this.#offset +26);}
287312
getextraFieldLength(){returnthis.#buffer.readUInt16LE(this.#offset +28);}
288313
getextraField(){
@@ -311,6 +336,35 @@ class LocalFileHeader {
311336
}
312337
}
313338

339+
// Reject an archive whose local file header contradicts the central directory
340+
// on a field that decides which bytes a member yields. This reader treats the
341+
// central directory as authoritative, but a divergent local header lets a
342+
// local-header-based extractor (Info-ZIP unzip, and others) read a different
343+
// member, method, or size from the same archive - a parser-confusion split that
344+
// defeats inspect-then-consume pipelines. Reject rather than silently diverge.
345+
functionassertConsistentLocalHeader(local,central){
346+
if(local.compressionMethod!==central.compressionMethod){
347+
thrownewERR_ZIP_INVALID_ARCHIVE(
348+
'local and central compression methods disagree');
349+
}
350+
if((local.flags&FLAG_ENCRYPTED)!==(central.flags&FLAG_ENCRYPTED)){
351+
thrownewERR_ZIP_INVALID_ARCHIVE(
352+
'local and central encryption flags disagree');
353+
}
354+
// A streamed entry (data-descriptor bit) writes zero crc and sizes in the
355+
// local header, deferring the true values to the central directory; only then
356+
// is a difference on those three fields expected.
357+
constdeferred=(local.flags&FLAG_DATA_DESCRIPTOR)!==0&&
358+
local.crc32===0&&local.compressedSize===0&&local.uncompressedSize===0;
359+
if(!deferred&&
360+
(local.crc32!==central.crc32||
361+
local.compressedSize!==central.compressedSize||
362+
local.uncompressedSize!==central.uncompressedSize)){
363+
thrownewERR_ZIP_INVALID_ARCHIVE(
364+
'local and central header crc-32 or sizes disagree');
365+
}
366+
}
367+
314368
// Returns whether an EOCD-looking record could describe an archive this
315369
// implementation supports. This is deliberately only a cheap preflight: the
316370
// selected record still receives the complete Zip64 and central-directory
@@ -563,6 +617,7 @@ function readCentralDirectory(buffer, count) {
563617
module.exports={
564618
CentralFileHeader,
565619
LocalFileHeader,
620+
assertConsistentLocalHeader,
566621
findArchiveEnd,
567622
readCentralDirectory,
568623
};

β€Žtest/parallel/test-zlib-zip-coverage.jsβ€Ž

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -288,8 +288,9 @@ test('a Zip64 extra field value beyond Number.MAX_SAFE_INTEGER is rejected', asy
288288
uncompressedSize: 0xffffffffffffffffn,
289289
});
290290

291-
const[read]=zlib.ZipEntry.read(patched);
292-
assert.throws(()=>read.size,{
291+
// The header cross-check resolves the sizes as the archive is read, so a
292+
// malformed Zip64 value is rejected at read time rather than at .size access.
293+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
293294
code: 'ERR_ZIP_INVALID_ARCHIVE',
294295
message: /exceedsthesafeintegerrange/,
295296
});
@@ -325,8 +326,7 @@ test('a Zip64 extra-field TLV whose declared size overflows the extra field is r
325326
tlv.writeUInt16LE(100,2);// claims 100 bytes of data, but none follow
326327
constpatched=injectRawZip64Extra(archive,name,content.length,tlv);
327328

328-
const[read]=zlib.ZipEntry.read(patched);
329-
assert.throws(()=>read.size,{
329+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
330330
code: 'ERR_ZIP_INVALID_ARCHIVE',
331331
message: /extrafieldismalformed/,
332332
});
@@ -345,8 +345,7 @@ test('a Zip64 extra-field TLV too short for the field it claims to carry is reje
345345
tlv.writeUInt32LE(123,4);
346346
constpatched=injectRawZip64Extra(archive,name,content.length,tlv);
347347

348-
const[read]=zlib.ZipEntry.read(patched);
349-
assert.throws(()=>read.size,{
348+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
350349
code: 'ERR_ZIP_INVALID_ARCHIVE',
351350
message: /Zip64extendedinformationextrafieldistruncated/,
352351
});
@@ -500,7 +499,8 @@ test('contentIterator() enforces the same guards as content() and contentSync()'
500499
constarchive=awaitbuildArchive([entry]);
501500
consttampered=Buffer.from(archive);
502501
constcentralStart=30+'f.txt'.length+'hello world'.length;
503-
tampered.writeUInt32LE(1,centralStart+24);
502+
tampered.writeUInt32LE(1,22);// Local uncompressed size
503+
tampered.writeUInt32LE(1,centralStart+24);// Central uncompressed size
504504
const[read]=zlib.ZipEntry.read(tampered);
505505
awaitassert.rejects(drain(read.contentIterator()),{code: 'ERR_ZIP_ENTRY_CORRUPT'});
506506
}
@@ -593,7 +593,8 @@ test('ZipFile getSync().contentSync() enforces the same guards via decodeMemberS
593593
constarchive=awaitbuildArchive([entry]);
594594
consttampered=Buffer.from(archive);
595595
constcentralStart=30+'f.txt'.length+'hello world'.length;
596-
tampered.writeUInt32LE(1,centralStart+24);
596+
tampered.writeUInt32LE(1,22);// Local uncompressed size
597+
tampered.writeUInt32LE(1,centralStart+24);// Central uncompressed size
597598
constfilePath=awaitwriteTempArchive(tampered,'size-mismatch');
598599
constzf=zlib.ZipFile.openSync(filePath);
599600
assert.throws(()=>zf.getSync('f.txt').contentSync(),{code: 'ERR_ZIP_ENTRY_CORRUPT'});
@@ -607,7 +608,8 @@ test('contentIterator() rejects an entry that inflates to less than its declared
607608
constarchive=awaitbuildArchive([entry]);
608609
consttampered=Buffer.from(archive);
609610
constcentralStart=30+'f.txt'.length+'hi'.length;
610-
tampered.writeUInt32LE(1000,centralStart+24);// Declared size grown beyond reality
611+
tampered.writeUInt32LE(1000,22);// Local declared size
612+
tampered.writeUInt32LE(1000,centralStart+24);// Central declared size grown beyond reality
611613
const[read]=zlib.ZipEntry.read(tampered);
612614
awaitassert.rejects(drain(read.contentIterator()),{
613615
code: 'ERR_ZIP_ENTRY_CORRUPT',

β€Žtest/parallel/test-zlib-zip-hardening.jsβ€Ž

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -118,13 +118,14 @@ test('a declared-size mismatch is rejected as corrupt', async () => {
118118
constentry=awaitzlib.ZipEntry.create('f.txt',Buffer.from('hello world'),{method: 'store'});
119119
constarchive=awaitbuildArchive([entry]);
120120

121-
// Shrink the *declared* uncompressed size in the central directory record
122-
// without touching the stored bytes themselves, so the amount of data
123-
// produced no longer matches what the header promised.
121+
// Shrink the *declared* uncompressed size in both the local and central
122+
// headers (kept consistent so the header cross-check passes) without touching
123+
// the stored bytes, so the produced amount no longer matches the headers'
124+
// promise and the decode-time size check fires.
124125
consttampered=Buffer.from(archive);
125126
constcentralHeaderStart=30+'f.txt'.length+'hello world'.length;
126-
constuncompressedSizeOffset=centralHeaderStart+24;
127-
tampered.writeUInt32LE(1,uncompressedSizeOffset);
127+
tampered.writeUInt32LE(1,22);// Local uncompressed size
128+
tampered.writeUInt32LE(1,centralHeaderStart+24);// Central uncompressed size
128129

129130
const[tamperedEntry]=zlib.ZipEntry.read(tampered);
130131
assert.strictEqual(tamperedEntry.size,1);
@@ -165,7 +166,10 @@ test('a forged small header whose content inflates past its declared size is rej
165166
consttampered=Buffer.from(archive);
166167
consteocd=tampered.length-22;// No comment, so EOCD is the last 22 bytes
167168
constcdOffset=tampered.readUInt32LE(eocd+16);
168-
tampered.writeUInt32LE(50,cdOffset+24);// Forge declared uncompressedSize
169+
// Forge the declared uncompressedSize in both headers (kept consistent so
170+
// the header cross-check passes; the decompressor still catches the lie).
171+
tampered.writeUInt32LE(50,22);// Local uncompressedSize
172+
tampered.writeUInt32LE(50,cdOffset+24);// Central uncompressedSize
169173

170174
const[e]=zlib.ZipEntry.read(tampered);
171175
assert.strictEqual(e.size,50);// 50 <= maxSize 100 clears the up-front check
@@ -413,9 +417,11 @@ test('a member whose data crosses into the central directory is rejected', async
413417
constarchive=Buffer.from(awaitbuildArchive(
414418
[awaitzlib.ZipEntry.create(name,content,{method: 'store'})]));
415419
constcentralHeaderStart=30+name.length+content.length;
416-
// Lie about the compressed size so the member's data range reaches into
417-
// the central directory (while staying inside the buffer).
418-
archive.writeUInt32LE(content.length+40,centralHeaderStart+20);
420+
// Lie about the compressed size in both headers (kept consistent so the
421+
// header cross-check passes) so the member's data range reaches into the
422+
// central directory (while staying inside the buffer).
423+
archive.writeUInt32LE(content.length+40,18);// Local compressed size
424+
archive.writeUInt32LE(content.length+40,centralHeaderStart+20);// Central
419425
assert.throws(()=>[...zlib.ZipEntry.read(archive)],
420426
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /possiblezipbomb/});
421427
});

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Commit 55b0495

Browse files
pipobscureaduh95
authored andcommitted
zlib: reject local/central ZIP header mismatch
The reader treats the central directory as authoritative for a member's method, sizes, CRC, and name, but read the local header only for its signature. An archive whose local file header disagrees with the central directory therefore extracts different bytes here than in a reader that uses the local header (e.g. Info-ZIP unzip), and its encrypted bit was read from the local header while its identity came from the central directory - a parser-confusion split that defeats inspect-then-consume pipelines and can slip an encrypted member past a central-directory scanner. Cross-check the local header against the central entry when a member is read: method, CRC, and both sizes (exempting a data-descriptor entry, whose local crc/sizes are legitimately zero), plus the encryption flag. Reject a mismatch with ERR_ZIP_INVALID_ARCHIVE, consistent with the reject-rather-than-silently-choose stance already taken for ambiguous archive ends. The existing hardening/coverage tests that forged a decode-time size, CRC, or Zip64 lie in the central header alone now trip this earlier check; update them to patch both headers consistently so they still exercise the decode-time guards they target. Signed-off-by: Philipp Dunkel <pip@pipobscure.com> PR-URL: #65016 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
1 parent 31742f2 commit 55b0495

4 files changed

Lines changed: 92 additions & 21 deletions

File tree

β€Žlib/internal/zip/entry.jsβ€Ž

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ const {
7676
const{
7777
CentralFileHeader,
7878
LocalFileHeader,
79+
assertConsistentLocalHeader,
7980
findArchiveEnd,
8081
}=require('internal/zip/headers');
8182
const{
@@ -399,6 +400,9 @@ class ZipEntry {
399400
awaitreadFdFully(fd,full.subarray(30),this.#localOffset +30);
400401
}
401402
this.#local =newLocalFileHeader(full,0);
403+
if(this.#central !==null){
404+
assertConsistentLocalHeader(this.#local,this.#central);
405+
}
402406
this.#contentOffset =this.#localOffset +length;
403407
returnthis.#local;
404408
}
@@ -419,6 +423,9 @@ class ZipEntry {
419423
readFdFullySync(fd,full.subarray(30),this.#localOffset +30);
420424
}
421425
this.#local =newLocalFileHeader(full,0);
426+
if(this.#central !==null){
427+
assertConsistentLocalHeader(this.#local,this.#central);
428+
}
422429
this.#contentOffset =this.#localOffset +length;
423430
returnthis.#local;
424431
}
@@ -930,6 +937,7 @@ function* readArchiveEntries(buf, end) {
930937
}
931938
constlocalOffset=central.localFileHeaderOffset+end.prefix;
932939
constlocal=newLocalFileHeader(buf,localOffset);
940+
assertConsistentLocalHeader(local,central);
933941
constdataStart=localOffset+local.byteLength;
934942
constlength=central.compressedSize;
935943
validateArchiveRange(buf,dataStart,length,'entry data');

β€Žlib/internal/zip/headers.jsβ€Ž

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ const {
2525
SIG_ZIP64_EOCD_LOCATOR,
2626
SIG_EOCD,
2727
MADE_BY_UNIX,
28+
FLAG_ENCRYPTED,
29+
FLAG_DATA_DESCRIPTOR,
2830
SENTINEL16,
2931
SENTINEL32,
3032
TAIL_LENGTH,
@@ -267,6 +269,7 @@ class CentralFileHeader {
267269
classLocalFileHeader{
268270
#buffer;
269271
#offset;
272+
#zip64 =null;
270273
constructor(buffer,offset=0){
271274
validateArchiveRange(buffer,offset,30,'local file header');
272275
if(buffer.readUInt32LE(offset)!==SIG_LOCAL_FILE_HEADER){
@@ -280,9 +283,31 @@ class LocalFileHeader {
280283
}
281284
getbyteLength(){return30+this.fileNameLength+this.extraFieldLength;}
282285
getflags(){returnthis.#buffer.readUInt16LE(this.#offset +6);}
283-
// Spec field (sec. 4.4.5); the central directory's method is authoritative,
284-
// so the local copy is not consumed today.
285-
// get compressionMethod() { return this.#buffer.readUInt16LE(this.#offset + 8); }
286+
// The central directory is authoritative, but these local fields are read to
287+
// reject an archive whose local header contradicts it (assertConsistentLocalHeader).
288+
getcompressionMethod(){returnthis.#buffer.readUInt16LE(this.#offset +8);}
289+
getcrc32(){returnthis.#buffer.readUInt32LE(this.#offset +14);}
290+
// The Zip64 extra supplies the true 64-bit sizes for whichever classic size
291+
// field holds an overflow sentinel; a local header has no offset/disk field.
292+
#resolveZip64(){
293+
if(this.#zip64 ===null){
294+
this.#zip64 =parseZip64Extra(this.extraField,{
295+
uncompressedSize: this.#buffer.readUInt32LE(this.#offset +22)===SENTINEL32,
296+
compressedSize: this.#buffer.readUInt32LE(this.#offset +18)===SENTINEL32,
297+
localFileHeaderOffset: false,
298+
diskNumber: false,
299+
});
300+
}
301+
returnthis.#zip64;
302+
}
303+
getcompressedSize(){
304+
constvalue=this.#buffer.readUInt32LE(this.#offset +18);
305+
returnvalue===SENTINEL32 ? this.#resolveZip64().compressedSize : value;
306+
}
307+
getuncompressedSize(){
308+
constvalue=this.#buffer.readUInt32LE(this.#offset +22);
309+
returnvalue===SENTINEL32 ? this.#resolveZip64().uncompressedSize : value;
310+
}
286311
getfileNameLength(){returnthis.#buffer.readUInt16LE(this.#offset +26);}
287312
getextraFieldLength(){returnthis.#buffer.readUInt16LE(this.#offset +28);}
288313
getextraField(){
@@ -311,6 +336,35 @@ class LocalFileHeader {
311336
}
312337
}
313338

339+
// Reject an archive whose local file header contradicts the central directory
340+
// on a field that decides which bytes a member yields. This reader treats the
341+
// central directory as authoritative, but a divergent local header lets a
342+
// local-header-based extractor (Info-ZIP unzip, and others) read a different
343+
// member, method, or size from the same archive - a parser-confusion split that
344+
// defeats inspect-then-consume pipelines. Reject rather than silently diverge.
345+
functionassertConsistentLocalHeader(local,central){
346+
if(local.compressionMethod!==central.compressionMethod){
347+
thrownewERR_ZIP_INVALID_ARCHIVE(
348+
'local and central compression methods disagree');
349+
}
350+
if((local.flags&FLAG_ENCRYPTED)!==(central.flags&FLAG_ENCRYPTED)){
351+
thrownewERR_ZIP_INVALID_ARCHIVE(
352+
'local and central encryption flags disagree');
353+
}
354+
// A streamed entry (data-descriptor bit) writes zero crc and sizes in the
355+
// local header, deferring the true values to the central directory; only then
356+
// is a difference on those three fields expected.
357+
constdeferred=(local.flags&FLAG_DATA_DESCRIPTOR)!==0&&
358+
local.crc32===0&&local.compressedSize===0&&local.uncompressedSize===0;
359+
if(!deferred&&
360+
(local.crc32!==central.crc32||
361+
local.compressedSize!==central.compressedSize||
362+
local.uncompressedSize!==central.uncompressedSize)){
363+
thrownewERR_ZIP_INVALID_ARCHIVE(
364+
'local and central header crc-32 or sizes disagree');
365+
}
366+
}
367+
314368
// Returns whether an EOCD-looking record could describe an archive this
315369
// implementation supports. This is deliberately only a cheap preflight: the
316370
// selected record still receives the complete Zip64 and central-directory
@@ -563,6 +617,7 @@ function readCentralDirectory(buffer, count) {
563617
module.exports={
564618
CentralFileHeader,
565619
LocalFileHeader,
620+
assertConsistentLocalHeader,
566621
findArchiveEnd,
567622
readCentralDirectory,
568623
};

β€Žtest/parallel/test-zlib-zip-coverage.jsβ€Ž

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -288,8 +288,9 @@ test('a Zip64 extra field value beyond Number.MAX_SAFE_INTEGER is rejected', asy
288288
uncompressedSize: 0xffffffffffffffffn,
289289
});
290290

291-
const[read]=zlib.ZipEntry.read(patched);
292-
assert.throws(()=>read.size,{
291+
// The header cross-check resolves the sizes as the archive is read, so a
292+
// malformed Zip64 value is rejected at read time rather than at .size access.
293+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
293294
code: 'ERR_ZIP_INVALID_ARCHIVE',
294295
message: /exceedsthesafeintegerrange/,
295296
});
@@ -325,8 +326,7 @@ test('a Zip64 extra-field TLV whose declared size overflows the extra field is r
325326
tlv.writeUInt16LE(100,2);// claims 100 bytes of data, but none follow
326327
constpatched=injectRawZip64Extra(archive,name,content.length,tlv);
327328

328-
const[read]=zlib.ZipEntry.read(patched);
329-
assert.throws(()=>read.size,{
329+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
330330
code: 'ERR_ZIP_INVALID_ARCHIVE',
331331
message: /extrafieldismalformed/,
332332
});
@@ -345,8 +345,7 @@ test('a Zip64 extra-field TLV too short for the field it claims to carry is reje
345345
tlv.writeUInt32LE(123,4);
346346
constpatched=injectRawZip64Extra(archive,name,content.length,tlv);
347347

348-
const[read]=zlib.ZipEntry.read(patched);
349-
assert.throws(()=>read.size,{
348+
assert.throws(()=>[...zlib.ZipEntry.read(patched)],{
350349
code: 'ERR_ZIP_INVALID_ARCHIVE',
351350
message: /Zip64extendedinformationextrafieldistruncated/,
352351
});
@@ -500,7 +499,8 @@ test('contentIterator() enforces the same guards as content() and contentSync()'
500499
constarchive=awaitbuildArchive([entry]);
501500
consttampered=Buffer.from(archive);
502501
constcentralStart=30+'f.txt'.length+'hello world'.length;
503-
tampered.writeUInt32LE(1,centralStart+24);
502+
tampered.writeUInt32LE(1,22);// Local uncompressed size
503+
tampered.writeUInt32LE(1,centralStart+24);// Central uncompressed size
504504
const[read]=zlib.ZipEntry.read(tampered);
505505
awaitassert.rejects(drain(read.contentIterator()),{code: 'ERR_ZIP_ENTRY_CORRUPT'});
506506
}
@@ -593,7 +593,8 @@ test('ZipFile getSync().contentSync() enforces the same guards via decodeMemberS
593593
constarchive=awaitbuildArchive([entry]);
594594
consttampered=Buffer.from(archive);
595595
constcentralStart=30+'f.txt'.length+'hello world'.length;
596-
tampered.writeUInt32LE(1,centralStart+24);
596+
tampered.writeUInt32LE(1,22);// Local uncompressed size
597+
tampered.writeUInt32LE(1,centralStart+24);// Central uncompressed size
597598
constfilePath=awaitwriteTempArchive(tampered,'size-mismatch');
598599
constzf=zlib.ZipFile.openSync(filePath);
599600
assert.throws(()=>zf.getSync('f.txt').contentSync(),{code: 'ERR_ZIP_ENTRY_CORRUPT'});
@@ -607,7 +608,8 @@ test('contentIterator() rejects an entry that inflates to less than its declared
607608
constarchive=awaitbuildArchive([entry]);
608609
consttampered=Buffer.from(archive);
609610
constcentralStart=30+'f.txt'.length+'hi'.length;
610-
tampered.writeUInt32LE(1000,centralStart+24);// Declared size grown beyond reality
611+
tampered.writeUInt32LE(1000,22);// Local declared size
612+
tampered.writeUInt32LE(1000,centralStart+24);// Central declared size grown beyond reality
611613
const[read]=zlib.ZipEntry.read(tampered);
612614
awaitassert.rejects(drain(read.contentIterator()),{
613615
code: 'ERR_ZIP_ENTRY_CORRUPT',

β€Žtest/parallel/test-zlib-zip-hardening.jsβ€Ž

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -118,13 +118,14 @@ test('a declared-size mismatch is rejected as corrupt', async () => {
118118
constentry=awaitzlib.ZipEntry.create('f.txt',Buffer.from('hello world'),{method: 'store'});
119119
constarchive=awaitbuildArchive([entry]);
120120

121-
// Shrink the *declared* uncompressed size in the central directory record
122-
// without touching the stored bytes themselves, so the amount of data
123-
// produced no longer matches what the header promised.
121+
// Shrink the *declared* uncompressed size in both the local and central
122+
// headers (kept consistent so the header cross-check passes) without touching
123+
// the stored bytes, so the produced amount no longer matches the headers'
124+
// promise and the decode-time size check fires.
124125
consttampered=Buffer.from(archive);
125126
constcentralHeaderStart=30+'f.txt'.length+'hello world'.length;
126-
constuncompressedSizeOffset=centralHeaderStart+24;
127-
tampered.writeUInt32LE(1,uncompressedSizeOffset);
127+
tampered.writeUInt32LE(1,22);// Local uncompressed size
128+
tampered.writeUInt32LE(1,centralHeaderStart+24);// Central uncompressed size
128129

129130
const[tamperedEntry]=zlib.ZipEntry.read(tampered);
130131
assert.strictEqual(tamperedEntry.size,1);
@@ -165,7 +166,10 @@ test('a forged small header whose content inflates past its declared size is rej
165166
consttampered=Buffer.from(archive);
166167
consteocd=tampered.length-22;// No comment, so EOCD is the last 22 bytes
167168
constcdOffset=tampered.readUInt32LE(eocd+16);
168-
tampered.writeUInt32LE(50,cdOffset+24);// Forge declared uncompressedSize
169+
// Forge the declared uncompressedSize in both headers (kept consistent so
170+
// the header cross-check passes; the decompressor still catches the lie).
171+
tampered.writeUInt32LE(50,22);// Local uncompressedSize
172+
tampered.writeUInt32LE(50,cdOffset+24);// Central uncompressedSize
169173

170174
const[e]=zlib.ZipEntry.read(tampered);
171175
assert.strictEqual(e.size,50);// 50 <= maxSize 100 clears the up-front check
@@ -413,9 +417,11 @@ test('a member whose data crosses into the central directory is rejected', async
413417
constarchive=Buffer.from(awaitbuildArchive(
414418
[awaitzlib.ZipEntry.create(name,content,{method: 'store'})]));
415419
constcentralHeaderStart=30+name.length+content.length;
416-
// Lie about the compressed size so the member's data range reaches into
417-
// the central directory (while staying inside the buffer).
418-
archive.writeUInt32LE(content.length+40,centralHeaderStart+20);
420+
// Lie about the compressed size in both headers (kept consistent so the
421+
// header cross-check passes) so the member's data range reaches into the
422+
// central directory (while staying inside the buffer).
423+
archive.writeUInt32LE(content.length+40,18);// Local compressed size
424+
archive.writeUInt32LE(content.length+40,centralHeaderStart+20);// Central
419425
assert.throws(()=>[...zlib.ZipEntry.read(archive)],
420426
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /possiblezipbomb/});
421427
});

0 commit comments

Comments
Β (0)