Commit 8e848d9

Browse files
mcollinaaduh95
authored andcommitted
zlib: reject ambiguous ZIP archive ends
ZIP archives can contain more than one structurally plausible EOCD record. Selecting based on whether a comment reaches EOF can make the chosen central directory depend on trailing padding. Inspect all candidates in the common tail window and reject archives with multiple plausible interpretations. Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #65007 Reviewed-By: Filip Skokan <panva.ip@gmail.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent df48191 commit 8e848d9

2 files changed

Lines changed: 143 additions & 17 deletions

File tree

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

Lines changed: 68 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ const {
2727
MADE_BY_UNIX,
2828
SENTINEL16,
2929
SENTINEL32,
30+
TAIL_LENGTH,
3031
ZIP64_EOCD_MAX_LENGTH,
3132
S_IFLNK,
3233
S_IFMT,
@@ -310,6 +311,51 @@ class LocalFileHeader {
310311
}
311312
}
312313

314+
// Returns whether an EOCD-looking record could describe an archive this
315+
// implementation supports. This is deliberately only a cheap preflight: the
316+
// selected record still receives the complete Zip64 and central-directory
317+
// validation below.
318+
functionisPlausibleArchiveEnd(buffer,eocdPos,scanStart){
319+
constdiskNumber=buffer.readUInt16LE(eocdPos+4);
320+
constcentralDirectoryDiskNumber=buffer.readUInt16LE(eocdPos+6);
321+
constdiskRecords=buffer.readUInt16LE(eocdPos+8);
322+
consttotalRecords=buffer.readUInt16LE(eocdPos+10);
323+
constcentralDirectorySize=buffer.readUInt32LE(eocdPos+12);
324+
constcentralDirectoryOffset=buffer.readUInt32LE(eocdPos+16);
325+
constneedsZip64=
326+
diskNumber===SENTINEL16||
327+
centralDirectoryDiskNumber===SENTINEL16||
328+
diskRecords===SENTINEL16||
329+
totalRecords===SENTINEL16||
330+
centralDirectorySize===SENTINEL32||
331+
centralDirectoryOffset===SENTINEL32;
332+
333+
constlocatorPos=eocdPos-20;
334+
consthasZip64Locator=locatorPos>=0&&
335+
buffer.readUInt32LE(locatorPos)===SIG_ZIP64_EOCD_LOCATOR;
336+
if(needsZip64)returnhasZip64Locator;
337+
// A Zip64 end record may accompany authoritative, non-sentinel classic
338+
// fields. Its central directory does not immediately precede this EOCD.
339+
if(hasZip64Locator)returntrue;
340+
if(
341+
diskNumber!==0||
342+
centralDirectoryDiskNumber!==0||
343+
diskRecords!==totalRecords||
344+
totalRecords*46>centralDirectorySize
345+
){
346+
returnfalse;
347+
}
348+
349+
constcentralDirectoryPos=eocdPos-centralDirectorySize;
350+
if(centralDirectoryPos<scanStart){
351+
// Use the same logical tail window for memory- and file-backed archives.
352+
// The directory is not available for this cheap preflight in either case.
353+
returntrue;
354+
}
355+
if(totalRecords===0)returncentralDirectorySize===0;
356+
returnbuffer.readUInt32LE(centralDirectoryPos)===SIG_CENTRAL_FILE_HEADER;
357+
}
358+
313359
/**
314360
* Locates and validates the end-of-archive structures (EOCD, and the Zip64
315361
* EOCD locator/record when present) in `buffer`. `base` is the absolute
@@ -334,26 +380,30 @@ function findArchiveEnd(buffer, base = 0) {
334380
if(buffer.length<22){
335381
thrownewERR_ZIP_INVALID_ARCHIVE('no end of central directory record found');
336382
}
337-
constmin=MathMax(0,buffer.length-(22+SENTINEL16));
383+
// Use the same tail-sized search window for full buffers and ZipFile's tail
384+
// reads. Besides keeping candidate selection consistent, the extra tail
385+
// slack permits a maximum-length comment followed by modest writer padding.
386+
constmin=MathMax(0,buffer.length-TAIL_LENGTH);
338387
leteocdPos=-1;
339-
// Pass 1: the comment must reach exactly to the end of the buffer (this
340-
// rejects a stray EOCD-looking signature inside an earlier comment).
388+
letfallbackPos=-1;
389+
letexactFallbackPos=-1;
341390
for(letpos=buffer.length-22;pos>=min;pos--){
342391
if(buffer.readUInt32LE(pos)!==SIG_EOCD)continue;
343-
if(pos+22+buffer.readUInt16LE(pos+20)!==buffer.length)continue;
392+
constend=pos+22+buffer.readUInt16LE(pos+20);
393+
if(end>buffer.length)continue;
394+
if(fallbackPos<0)fallbackPos=pos;
395+
if(end===buffer.length&&exactFallbackPos<0)exactFallbackPos=pos;
396+
if(!isPlausibleArchiveEnd(buffer,pos,min))continue;
397+
if(eocdPos>=0){
398+
thrownewERR_ZIP_INVALID_ARCHIVE(
399+
'ambiguous end of central directory records');
400+
}
344401
eocdPos=pos;
345-
break;
346402
}
403+
// Preserve the targeted validation errors for a sole malformed or
404+
// unsupported candidate. Plausible candidates always take precedence.
347405
if(eocdPos<0){
348-
// Pass 2: tolerate trailing padding after the EOCD (some streaming
349-
// writers pad their output to a fixed block size); take the last
350-
// candidate found.
351-
for(letpos=buffer.length-22;pos>=min;pos--){
352-
if(buffer.readUInt32LE(pos)!==SIG_EOCD)continue;
353-
if(pos+22+buffer.readUInt16LE(pos+20)>buffer.length)continue;
354-
eocdPos=pos;
355-
break;
356-
}
406+
eocdPos=exactFallbackPos>=0 ? exactFallbackPos : fallbackPos;
357407
}
358408
if(eocdPos<0){
359409
thrownewERR_ZIP_INVALID_ARCHIVE('no end of central directory record found');
@@ -474,7 +524,10 @@ function findArchiveEnd(buffer, base = 0) {
474524
if(prefix<0){
475525
thrownewERR_ZIP_INVALID_ARCHIVE('central directory does not fit inside the archive');
476526
}
477-
if(totalRecords*46>centralDirectorySize){
527+
if(
528+
(totalRecords===0&&centralDirectorySize!==0)||
529+
totalRecords*46>centralDirectorySize
530+
){
478531
thrownewERR_ZIP_INVALID_ARCHIVE(
479532
'central directory record count is inconsistent with its size');
480533
}

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

Lines changed: 75 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33
require('../common');
44

55
constassert=require('node:assert');
6+
constfs=require('node:fs');
67
constzlib=require('node:zlib');
78
const{ test }=require('node:test');
9+
consttmpdir=require('../common/tmpdir');
810

911
asyncfunctionbuildArchive(entries,comment){
1012
constchunks=[];
@@ -47,13 +49,71 @@ test('an EOCD-looking signature inside a trailing comment is not mistaken for th
4749
// before it reaches the genuine EOCD signature; embedding 4 bytes that
4850
// look like one partway through must not be mistaken for the real record.
4951
constfakeSignature=String.fromCharCode(0x50,0x4b,0x05,0x06);
50-
constarchive=awaitbuildArchive([entry],`before ${fakeSignature} after`);
52+
constarchive=awaitbuildArchive(
53+
[entry],`before ${fakeSignature} this is not a valid EOCD record after`);
5154

5255
constread=[...zlib.ZipEntry.read(archive)];
5356
assert.strictEqual(read.length,1);
5457
assert.strictEqual(read[0].name,'f.txt');
5558
});
5659

60+
test('multiple plausible EOCD records describing different archives are rejected',async()=>{
61+
constfirst=awaitbuildArchive([
62+
awaitzlib.ZipEntry.create('install.sh',Buffer.from('malicious'),{method: 'store'}),
63+
]);
64+
constsecond=awaitbuildArchive([
65+
awaitzlib.ZipEntry.create('install.sh',Buffer.from('benign'),{method: 'store'}),
66+
]);
67+
constarchive=Buffer.concat([first,second,Buffer.from([0])]);
68+
constfirstEocd=first.length-22;
69+
70+
// Make the first EOCD exact-to-EOF by treating the second archive and its
71+
// padding as a comment. The second EOCD remains a plausible archive end for
72+
// readers which tolerate trailing padding and select the rightmost record.
73+
archive.writeUInt16LE(archive.length-firstEocd-22,firstEocd+20);
74+
75+
constexpected={
76+
code: 'ERR_ZIP_INVALID_ARCHIVE',
77+
message: /ambiguousendofcentraldirectory/,
78+
};
79+
assert.throws(()=>[...zlib.ZipEntry.read(archive)],expected);
80+
assert.throws(()=>newzlib.ZipBuffer(archive),expected);
81+
82+
tmpdir.refresh();
83+
constfile=tmpdir.resolve('ambiguous.zip');
84+
fs.writeFileSync(file,archive);
85+
awaitassert.rejects(zlib.ZipFile.open(file),expected);
86+
assert.throws(()=>zlib.ZipFile.openSync(file),expected);
87+
});
88+
89+
test('an exact EOCD embedded in a genuine comment is rejected as ambiguous',async()=>{
90+
constarchive=awaitbuildArchive([
91+
awaitzlib.ZipEntry.create('f.txt',Buffer.from('content'),{method: 'store'}),
92+
]);
93+
constnested=Buffer.concat([archive,buildEocd()]);
94+
nested.writeUInt16LE(22,archive.length-2);
95+
96+
assert.throws(()=>[...zlib.ZipEntry.read(nested)],{
97+
code: 'ERR_ZIP_INVALID_ARCHIVE',
98+
message: /ambiguousendofcentraldirectory/,
99+
});
100+
});
101+
102+
test('multiple padded EOCD records are rejected as ambiguous',async()=>{
103+
constfirst=awaitbuildArchive([
104+
awaitzlib.ZipEntry.create('a.txt',Buffer.from('first'),{method: 'store'}),
105+
]);
106+
constsecond=awaitbuildArchive([
107+
awaitzlib.ZipEntry.create('b.txt',Buffer.from('second'),{method: 'store'}),
108+
]);
109+
constarchive=Buffer.concat([first,second,Buffer.from('\0\0')]);
110+
111+
assert.throws(()=>newzlib.ZipBuffer(archive),{
112+
code: 'ERR_ZIP_INVALID_ARCHIVE',
113+
message: /ambiguousendofcentraldirectory/,
114+
});
115+
});
116+
57117
test('a declared-size mismatch is rejected as corrupt',async()=>{
58118
constentry=awaitzlib.ZipEntry.create('f.txt',Buffer.from('hello world'),{method: 'store'});
59119
constarchive=awaitbuildArchive([entry]);
@@ -212,7 +272,7 @@ test('every possible truncation of an archive is rejected, deterministically', a
212272

213273
test('trailing padding after the EOCD is tolerated',async()=>{
214274
// Some streaming writers pad their output to a block size; CPython
215-
// tolerates trailing newlines/NULs and so does the pass-2 EOCD scan.
275+
// tolerates trailing newlines/NULs and so does the EOCD scan.
216276
constarchive=awaitbuildArchive(
217277
[awaitzlib.ZipEntry.create('f.txt',Buffer.from('hi'),{method: 'store'})]);
218278
constpadded=Buffer.concat([archive,Buffer.from('\r\n\0\0\0')]);
@@ -221,6 +281,15 @@ test('trailing padding after the EOCD is tolerated', async () => {
221281
assert.strictEqual((awaitentry.content()).toString(),'hi');
222282
});
223283

284+
test('a maximum-length comment followed by block padding is tolerated',async()=>{
285+
constcomment='x'.repeat(0xffff);
286+
constarchive=awaitbuildArchive([],comment);
287+
constpadded=Buffer.concat([archive,Buffer.alloc(4096)]);
288+
constzip=newzlib.ZipBuffer(padded);
289+
290+
assert.strictEqual(zip.comment,comment);
291+
});
292+
224293
test('junk appended past a declared comment is tolerated and the comment preserved',async()=>{
225294
constarchive=awaitbuildArchive(
226295
[awaitzlib.ZipEntry.create('f.txt',Buffer.from('hi'),{method: 'store'})],
@@ -262,6 +331,10 @@ test('a record count inconsistent with the directory size is rejected', () => {
262331
constarchive=Buffer.concat([Buffer.alloc(46),eocd]);
263332
assert.throws(()=>[...zlib.ZipEntry.read(archive)],
264333
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /inconsistent/});
334+
335+
constzeroRecords=Buffer.concat([Buffer.alloc(46),buildEocd({cdSize: 46})]);
336+
assert.throws(()=>[...zlib.ZipEntry.read(zeroRecords)],
337+
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /inconsistent/});
265338
});
266339

267340
test('a corrupted or overrunning central directory header is rejected',async()=>{

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 8e848d9

Browse files
mcollinaaduh95
authored andcommitted
zlib: reject ambiguous ZIP archive ends
ZIP archives can contain more than one structurally plausible EOCD record. Selecting based on whether a comment reaches EOF can make the chosen central directory depend on trailing padding. Inspect all candidates in the common tail window and reject archives with multiple plausible interpretations. Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #65007 Reviewed-By: Filip Skokan <panva.ip@gmail.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent df48191 commit 8e848d9

2 files changed

Lines changed: 143 additions & 17 deletions

File tree

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

Lines changed: 68 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ const {
2727
MADE_BY_UNIX,
2828
SENTINEL16,
2929
SENTINEL32,
30+
TAIL_LENGTH,
3031
ZIP64_EOCD_MAX_LENGTH,
3132
S_IFLNK,
3233
S_IFMT,
@@ -310,6 +311,51 @@ class LocalFileHeader {
310311
}
311312
}
312313

314+
// Returns whether an EOCD-looking record could describe an archive this
315+
// implementation supports. This is deliberately only a cheap preflight: the
316+
// selected record still receives the complete Zip64 and central-directory
317+
// validation below.
318+
functionisPlausibleArchiveEnd(buffer,eocdPos,scanStart){
319+
constdiskNumber=buffer.readUInt16LE(eocdPos+4);
320+
constcentralDirectoryDiskNumber=buffer.readUInt16LE(eocdPos+6);
321+
constdiskRecords=buffer.readUInt16LE(eocdPos+8);
322+
consttotalRecords=buffer.readUInt16LE(eocdPos+10);
323+
constcentralDirectorySize=buffer.readUInt32LE(eocdPos+12);
324+
constcentralDirectoryOffset=buffer.readUInt32LE(eocdPos+16);
325+
constneedsZip64=
326+
diskNumber===SENTINEL16||
327+
centralDirectoryDiskNumber===SENTINEL16||
328+
diskRecords===SENTINEL16||
329+
totalRecords===SENTINEL16||
330+
centralDirectorySize===SENTINEL32||
331+
centralDirectoryOffset===SENTINEL32;
332+
333+
constlocatorPos=eocdPos-20;
334+
consthasZip64Locator=locatorPos>=0&&
335+
buffer.readUInt32LE(locatorPos)===SIG_ZIP64_EOCD_LOCATOR;
336+
if(needsZip64)returnhasZip64Locator;
337+
// A Zip64 end record may accompany authoritative, non-sentinel classic
338+
// fields. Its central directory does not immediately precede this EOCD.
339+
if(hasZip64Locator)returntrue;
340+
if(
341+
diskNumber!==0||
342+
centralDirectoryDiskNumber!==0||
343+
diskRecords!==totalRecords||
344+
totalRecords*46>centralDirectorySize
345+
){
346+
returnfalse;
347+
}
348+
349+
constcentralDirectoryPos=eocdPos-centralDirectorySize;
350+
if(centralDirectoryPos<scanStart){
351+
// Use the same logical tail window for memory- and file-backed archives.
352+
// The directory is not available for this cheap preflight in either case.
353+
returntrue;
354+
}
355+
if(totalRecords===0)returncentralDirectorySize===0;
356+
returnbuffer.readUInt32LE(centralDirectoryPos)===SIG_CENTRAL_FILE_HEADER;
357+
}
358+
313359
/**
314360
* Locates and validates the end-of-archive structures (EOCD, and the Zip64
315361
* EOCD locator/record when present) in `buffer`. `base` is the absolute
@@ -334,26 +380,30 @@ function findArchiveEnd(buffer, base = 0) {
334380
if(buffer.length<22){
335381
thrownewERR_ZIP_INVALID_ARCHIVE('no end of central directory record found');
336382
}
337-
constmin=MathMax(0,buffer.length-(22+SENTINEL16));
383+
// Use the same tail-sized search window for full buffers and ZipFile's tail
384+
// reads. Besides keeping candidate selection consistent, the extra tail
385+
// slack permits a maximum-length comment followed by modest writer padding.
386+
constmin=MathMax(0,buffer.length-TAIL_LENGTH);
338387
leteocdPos=-1;
339-
// Pass 1: the comment must reach exactly to the end of the buffer (this
340-
// rejects a stray EOCD-looking signature inside an earlier comment).
388+
letfallbackPos=-1;
389+
letexactFallbackPos=-1;
341390
for(letpos=buffer.length-22;pos>=min;pos--){
342391
if(buffer.readUInt32LE(pos)!==SIG_EOCD)continue;
343-
if(pos+22+buffer.readUInt16LE(pos+20)!==buffer.length)continue;
392+
constend=pos+22+buffer.readUInt16LE(pos+20);
393+
if(end>buffer.length)continue;
394+
if(fallbackPos<0)fallbackPos=pos;
395+
if(end===buffer.length&&exactFallbackPos<0)exactFallbackPos=pos;
396+
if(!isPlausibleArchiveEnd(buffer,pos,min))continue;
397+
if(eocdPos>=0){
398+
thrownewERR_ZIP_INVALID_ARCHIVE(
399+
'ambiguous end of central directory records');
400+
}
344401
eocdPos=pos;
345-
break;
346402
}
403+
// Preserve the targeted validation errors for a sole malformed or
404+
// unsupported candidate. Plausible candidates always take precedence.
347405
if(eocdPos<0){
348-
// Pass 2: tolerate trailing padding after the EOCD (some streaming
349-
// writers pad their output to a fixed block size); take the last
350-
// candidate found.
351-
for(letpos=buffer.length-22;pos>=min;pos--){
352-
if(buffer.readUInt32LE(pos)!==SIG_EOCD)continue;
353-
if(pos+22+buffer.readUInt16LE(pos+20)>buffer.length)continue;
354-
eocdPos=pos;
355-
break;
356-
}
406+
eocdPos=exactFallbackPos>=0 ? exactFallbackPos : fallbackPos;
357407
}
358408
if(eocdPos<0){
359409
thrownewERR_ZIP_INVALID_ARCHIVE('no end of central directory record found');
@@ -474,7 +524,10 @@ function findArchiveEnd(buffer, base = 0) {
474524
if(prefix<0){
475525
thrownewERR_ZIP_INVALID_ARCHIVE('central directory does not fit inside the archive');
476526
}
477-
if(totalRecords*46>centralDirectorySize){
527+
if(
528+
(totalRecords===0&&centralDirectorySize!==0)||
529+
totalRecords*46>centralDirectorySize
530+
){
478531
thrownewERR_ZIP_INVALID_ARCHIVE(
479532
'central directory record count is inconsistent with its size');
480533
}

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

Lines changed: 75 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33
require('../common');
44

55
constassert=require('node:assert');
6+
constfs=require('node:fs');
67
constzlib=require('node:zlib');
78
const{ test }=require('node:test');
9+
consttmpdir=require('../common/tmpdir');
810

911
asyncfunctionbuildArchive(entries,comment){
1012
constchunks=[];
@@ -47,13 +49,71 @@ test('an EOCD-looking signature inside a trailing comment is not mistaken for th
4749
// before it reaches the genuine EOCD signature; embedding 4 bytes that
4850
// look like one partway through must not be mistaken for the real record.
4951
constfakeSignature=String.fromCharCode(0x50,0x4b,0x05,0x06);
50-
constarchive=awaitbuildArchive([entry],`before ${fakeSignature} after`);
52+
constarchive=awaitbuildArchive(
53+
[entry],`before ${fakeSignature} this is not a valid EOCD record after`);
5154

5255
constread=[...zlib.ZipEntry.read(archive)];
5356
assert.strictEqual(read.length,1);
5457
assert.strictEqual(read[0].name,'f.txt');
5558
});
5659

60+
test('multiple plausible EOCD records describing different archives are rejected',async()=>{
61+
constfirst=awaitbuildArchive([
62+
awaitzlib.ZipEntry.create('install.sh',Buffer.from('malicious'),{method: 'store'}),
63+
]);
64+
constsecond=awaitbuildArchive([
65+
awaitzlib.ZipEntry.create('install.sh',Buffer.from('benign'),{method: 'store'}),
66+
]);
67+
constarchive=Buffer.concat([first,second,Buffer.from([0])]);
68+
constfirstEocd=first.length-22;
69+
70+
// Make the first EOCD exact-to-EOF by treating the second archive and its
71+
// padding as a comment. The second EOCD remains a plausible archive end for
72+
// readers which tolerate trailing padding and select the rightmost record.
73+
archive.writeUInt16LE(archive.length-firstEocd-22,firstEocd+20);
74+
75+
constexpected={
76+
code: 'ERR_ZIP_INVALID_ARCHIVE',
77+
message: /ambiguousendofcentraldirectory/,
78+
};
79+
assert.throws(()=>[...zlib.ZipEntry.read(archive)],expected);
80+
assert.throws(()=>newzlib.ZipBuffer(archive),expected);
81+
82+
tmpdir.refresh();
83+
constfile=tmpdir.resolve('ambiguous.zip');
84+
fs.writeFileSync(file,archive);
85+
awaitassert.rejects(zlib.ZipFile.open(file),expected);
86+
assert.throws(()=>zlib.ZipFile.openSync(file),expected);
87+
});
88+
89+
test('an exact EOCD embedded in a genuine comment is rejected as ambiguous',async()=>{
90+
constarchive=awaitbuildArchive([
91+
awaitzlib.ZipEntry.create('f.txt',Buffer.from('content'),{method: 'store'}),
92+
]);
93+
constnested=Buffer.concat([archive,buildEocd()]);
94+
nested.writeUInt16LE(22,archive.length-2);
95+
96+
assert.throws(()=>[...zlib.ZipEntry.read(nested)],{
97+
code: 'ERR_ZIP_INVALID_ARCHIVE',
98+
message: /ambiguousendofcentraldirectory/,
99+
});
100+
});
101+
102+
test('multiple padded EOCD records are rejected as ambiguous',async()=>{
103+
constfirst=awaitbuildArchive([
104+
awaitzlib.ZipEntry.create('a.txt',Buffer.from('first'),{method: 'store'}),
105+
]);
106+
constsecond=awaitbuildArchive([
107+
awaitzlib.ZipEntry.create('b.txt',Buffer.from('second'),{method: 'store'}),
108+
]);
109+
constarchive=Buffer.concat([first,second,Buffer.from('\0\0')]);
110+
111+
assert.throws(()=>newzlib.ZipBuffer(archive),{
112+
code: 'ERR_ZIP_INVALID_ARCHIVE',
113+
message: /ambiguousendofcentraldirectory/,
114+
});
115+
});
116+
57117
test('a declared-size mismatch is rejected as corrupt',async()=>{
58118
constentry=awaitzlib.ZipEntry.create('f.txt',Buffer.from('hello world'),{method: 'store'});
59119
constarchive=awaitbuildArchive([entry]);
@@ -212,7 +272,7 @@ test('every possible truncation of an archive is rejected, deterministically', a
212272

213273
test('trailing padding after the EOCD is tolerated',async()=>{
214274
// Some streaming writers pad their output to a block size; CPython
215-
// tolerates trailing newlines/NULs and so does the pass-2 EOCD scan.
275+
// tolerates trailing newlines/NULs and so does the EOCD scan.
216276
constarchive=awaitbuildArchive(
217277
[awaitzlib.ZipEntry.create('f.txt',Buffer.from('hi'),{method: 'store'})]);
218278
constpadded=Buffer.concat([archive,Buffer.from('\r\n\0\0\0')]);
@@ -221,6 +281,15 @@ test('trailing padding after the EOCD is tolerated', async () => {
221281
assert.strictEqual((awaitentry.content()).toString(),'hi');
222282
});
223283

284+
test('a maximum-length comment followed by block padding is tolerated',async()=>{
285+
constcomment='x'.repeat(0xffff);
286+
constarchive=awaitbuildArchive([],comment);
287+
constpadded=Buffer.concat([archive,Buffer.alloc(4096)]);
288+
constzip=newzlib.ZipBuffer(padded);
289+
290+
assert.strictEqual(zip.comment,comment);
291+
});
292+
224293
test('junk appended past a declared comment is tolerated and the comment preserved',async()=>{
225294
constarchive=awaitbuildArchive(
226295
[awaitzlib.ZipEntry.create('f.txt',Buffer.from('hi'),{method: 'store'})],
@@ -262,6 +331,10 @@ test('a record count inconsistent with the directory size is rejected', () => {
262331
constarchive=Buffer.concat([Buffer.alloc(46),eocd]);
263332
assert.throws(()=>[...zlib.ZipEntry.read(archive)],
264333
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /inconsistent/});
334+
335+
constzeroRecords=Buffer.concat([Buffer.alloc(46),buildEocd({cdSize: 46})]);
336+
assert.throws(()=>[...zlib.ZipEntry.read(zeroRecords)],
337+
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /inconsistent/});
265338
});
266339

267340
test('a corrupted or overrunning central directory header is rejected',async()=>{

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 8e848d9

Browse files
mcollinaaduh95
authored andcommitted
zlib: reject ambiguous ZIP archive ends
ZIP archives can contain more than one structurally plausible EOCD record. Selecting based on whether a comment reaches EOF can make the chosen central directory depend on trailing padding. Inspect all candidates in the common tail window and reject archives with multiple plausible interpretations. Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #65007 Reviewed-By: Filip Skokan <panva.ip@gmail.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent df48191 commit 8e848d9

2 files changed

Lines changed: 143 additions & 17 deletions

File tree

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

Lines changed: 68 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ const {
2727
MADE_BY_UNIX,
2828
SENTINEL16,
2929
SENTINEL32,
30+
TAIL_LENGTH,
3031
ZIP64_EOCD_MAX_LENGTH,
3132
S_IFLNK,
3233
S_IFMT,
@@ -310,6 +311,51 @@ class LocalFileHeader {
310311
}
311312
}
312313

314+
// Returns whether an EOCD-looking record could describe an archive this
315+
// implementation supports. This is deliberately only a cheap preflight: the
316+
// selected record still receives the complete Zip64 and central-directory
317+
// validation below.
318+
functionisPlausibleArchiveEnd(buffer,eocdPos,scanStart){
319+
constdiskNumber=buffer.readUInt16LE(eocdPos+4);
320+
constcentralDirectoryDiskNumber=buffer.readUInt16LE(eocdPos+6);
321+
constdiskRecords=buffer.readUInt16LE(eocdPos+8);
322+
consttotalRecords=buffer.readUInt16LE(eocdPos+10);
323+
constcentralDirectorySize=buffer.readUInt32LE(eocdPos+12);
324+
constcentralDirectoryOffset=buffer.readUInt32LE(eocdPos+16);
325+
constneedsZip64=
326+
diskNumber===SENTINEL16||
327+
centralDirectoryDiskNumber===SENTINEL16||
328+
diskRecords===SENTINEL16||
329+
totalRecords===SENTINEL16||
330+
centralDirectorySize===SENTINEL32||
331+
centralDirectoryOffset===SENTINEL32;
332+
333+
constlocatorPos=eocdPos-20;
334+
consthasZip64Locator=locatorPos>=0&&
335+
buffer.readUInt32LE(locatorPos)===SIG_ZIP64_EOCD_LOCATOR;
336+
if(needsZip64)returnhasZip64Locator;
337+
// A Zip64 end record may accompany authoritative, non-sentinel classic
338+
// fields. Its central directory does not immediately precede this EOCD.
339+
if(hasZip64Locator)returntrue;
340+
if(
341+
diskNumber!==0||
342+
centralDirectoryDiskNumber!==0||
343+
diskRecords!==totalRecords||
344+
totalRecords*46>centralDirectorySize
345+
){
346+
returnfalse;
347+
}
348+
349+
constcentralDirectoryPos=eocdPos-centralDirectorySize;
350+
if(centralDirectoryPos<scanStart){
351+
// Use the same logical tail window for memory- and file-backed archives.
352+
// The directory is not available for this cheap preflight in either case.
353+
returntrue;
354+
}
355+
if(totalRecords===0)returncentralDirectorySize===0;
356+
returnbuffer.readUInt32LE(centralDirectoryPos)===SIG_CENTRAL_FILE_HEADER;
357+
}
358+
313359
/**
314360
* Locates and validates the end-of-archive structures (EOCD, and the Zip64
315361
* EOCD locator/record when present) in `buffer`. `base` is the absolute
@@ -334,26 +380,30 @@ function findArchiveEnd(buffer, base = 0) {
334380
if(buffer.length<22){
335381
thrownewERR_ZIP_INVALID_ARCHIVE('no end of central directory record found');
336382
}
337-
constmin=MathMax(0,buffer.length-(22+SENTINEL16));
383+
// Use the same tail-sized search window for full buffers and ZipFile's tail
384+
// reads. Besides keeping candidate selection consistent, the extra tail
385+
// slack permits a maximum-length comment followed by modest writer padding.
386+
constmin=MathMax(0,buffer.length-TAIL_LENGTH);
338387
leteocdPos=-1;
339-
// Pass 1: the comment must reach exactly to the end of the buffer (this
340-
// rejects a stray EOCD-looking signature inside an earlier comment).
388+
letfallbackPos=-1;
389+
letexactFallbackPos=-1;
341390
for(letpos=buffer.length-22;pos>=min;pos--){
342391
if(buffer.readUInt32LE(pos)!==SIG_EOCD)continue;
343-
if(pos+22+buffer.readUInt16LE(pos+20)!==buffer.length)continue;
392+
constend=pos+22+buffer.readUInt16LE(pos+20);
393+
if(end>buffer.length)continue;
394+
if(fallbackPos<0)fallbackPos=pos;
395+
if(end===buffer.length&&exactFallbackPos<0)exactFallbackPos=pos;
396+
if(!isPlausibleArchiveEnd(buffer,pos,min))continue;
397+
if(eocdPos>=0){
398+
thrownewERR_ZIP_INVALID_ARCHIVE(
399+
'ambiguous end of central directory records');
400+
}
344401
eocdPos=pos;
345-
break;
346402
}
403+
// Preserve the targeted validation errors for a sole malformed or
404+
// unsupported candidate. Plausible candidates always take precedence.
347405
if(eocdPos<0){
348-
// Pass 2: tolerate trailing padding after the EOCD (some streaming
349-
// writers pad their output to a fixed block size); take the last
350-
// candidate found.
351-
for(letpos=buffer.length-22;pos>=min;pos--){
352-
if(buffer.readUInt32LE(pos)!==SIG_EOCD)continue;
353-
if(pos+22+buffer.readUInt16LE(pos+20)>buffer.length)continue;
354-
eocdPos=pos;
355-
break;
356-
}
406+
eocdPos=exactFallbackPos>=0 ? exactFallbackPos : fallbackPos;
357407
}
358408
if(eocdPos<0){
359409
thrownewERR_ZIP_INVALID_ARCHIVE('no end of central directory record found');
@@ -474,7 +524,10 @@ function findArchiveEnd(buffer, base = 0) {
474524
if(prefix<0){
475525
thrownewERR_ZIP_INVALID_ARCHIVE('central directory does not fit inside the archive');
476526
}
477-
if(totalRecords*46>centralDirectorySize){
527+
if(
528+
(totalRecords===0&&centralDirectorySize!==0)||
529+
totalRecords*46>centralDirectorySize
530+
){
478531
thrownewERR_ZIP_INVALID_ARCHIVE(
479532
'central directory record count is inconsistent with its size');
480533
}

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

Lines changed: 75 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33
require('../common');
44

55
constassert=require('node:assert');
6+
constfs=require('node:fs');
67
constzlib=require('node:zlib');
78
const{ test }=require('node:test');
9+
consttmpdir=require('../common/tmpdir');
810

911
asyncfunctionbuildArchive(entries,comment){
1012
constchunks=[];
@@ -47,13 +49,71 @@ test('an EOCD-looking signature inside a trailing comment is not mistaken for th
4749
// before it reaches the genuine EOCD signature; embedding 4 bytes that
4850
// look like one partway through must not be mistaken for the real record.
4951
constfakeSignature=String.fromCharCode(0x50,0x4b,0x05,0x06);
50-
constarchive=awaitbuildArchive([entry],`before ${fakeSignature} after`);
52+
constarchive=awaitbuildArchive(
53+
[entry],`before ${fakeSignature} this is not a valid EOCD record after`);
5154

5255
constread=[...zlib.ZipEntry.read(archive)];
5356
assert.strictEqual(read.length,1);
5457
assert.strictEqual(read[0].name,'f.txt');
5558
});
5659

60+
test('multiple plausible EOCD records describing different archives are rejected',async()=>{
61+
constfirst=awaitbuildArchive([
62+
awaitzlib.ZipEntry.create('install.sh',Buffer.from('malicious'),{method: 'store'}),
63+
]);
64+
constsecond=awaitbuildArchive([
65+
awaitzlib.ZipEntry.create('install.sh',Buffer.from('benign'),{method: 'store'}),
66+
]);
67+
constarchive=Buffer.concat([first,second,Buffer.from([0])]);
68+
constfirstEocd=first.length-22;
69+
70+
// Make the first EOCD exact-to-EOF by treating the second archive and its
71+
// padding as a comment. The second EOCD remains a plausible archive end for
72+
// readers which tolerate trailing padding and select the rightmost record.
73+
archive.writeUInt16LE(archive.length-firstEocd-22,firstEocd+20);
74+
75+
constexpected={
76+
code: 'ERR_ZIP_INVALID_ARCHIVE',
77+
message: /ambiguousendofcentraldirectory/,
78+
};
79+
assert.throws(()=>[...zlib.ZipEntry.read(archive)],expected);
80+
assert.throws(()=>newzlib.ZipBuffer(archive),expected);
81+
82+
tmpdir.refresh();
83+
constfile=tmpdir.resolve('ambiguous.zip');
84+
fs.writeFileSync(file,archive);
85+
awaitassert.rejects(zlib.ZipFile.open(file),expected);
86+
assert.throws(()=>zlib.ZipFile.openSync(file),expected);
87+
});
88+
89+
test('an exact EOCD embedded in a genuine comment is rejected as ambiguous',async()=>{
90+
constarchive=awaitbuildArchive([
91+
awaitzlib.ZipEntry.create('f.txt',Buffer.from('content'),{method: 'store'}),
92+
]);
93+
constnested=Buffer.concat([archive,buildEocd()]);
94+
nested.writeUInt16LE(22,archive.length-2);
95+
96+
assert.throws(()=>[...zlib.ZipEntry.read(nested)],{
97+
code: 'ERR_ZIP_INVALID_ARCHIVE',
98+
message: /ambiguousendofcentraldirectory/,
99+
});
100+
});
101+
102+
test('multiple padded EOCD records are rejected as ambiguous',async()=>{
103+
constfirst=awaitbuildArchive([
104+
awaitzlib.ZipEntry.create('a.txt',Buffer.from('first'),{method: 'store'}),
105+
]);
106+
constsecond=awaitbuildArchive([
107+
awaitzlib.ZipEntry.create('b.txt',Buffer.from('second'),{method: 'store'}),
108+
]);
109+
constarchive=Buffer.concat([first,second,Buffer.from('\0\0')]);
110+
111+
assert.throws(()=>newzlib.ZipBuffer(archive),{
112+
code: 'ERR_ZIP_INVALID_ARCHIVE',
113+
message: /ambiguousendofcentraldirectory/,
114+
});
115+
});
116+
57117
test('a declared-size mismatch is rejected as corrupt',async()=>{
58118
constentry=awaitzlib.ZipEntry.create('f.txt',Buffer.from('hello world'),{method: 'store'});
59119
constarchive=awaitbuildArchive([entry]);
@@ -212,7 +272,7 @@ test('every possible truncation of an archive is rejected, deterministically', a
212272

213273
test('trailing padding after the EOCD is tolerated',async()=>{
214274
// Some streaming writers pad their output to a block size; CPython
215-
// tolerates trailing newlines/NULs and so does the pass-2 EOCD scan.
275+
// tolerates trailing newlines/NULs and so does the EOCD scan.
216276
constarchive=awaitbuildArchive(
217277
[awaitzlib.ZipEntry.create('f.txt',Buffer.from('hi'),{method: 'store'})]);
218278
constpadded=Buffer.concat([archive,Buffer.from('\r\n\0\0\0')]);
@@ -221,6 +281,15 @@ test('trailing padding after the EOCD is tolerated', async () => {
221281
assert.strictEqual((awaitentry.content()).toString(),'hi');
222282
});
223283

284+
test('a maximum-length comment followed by block padding is tolerated',async()=>{
285+
constcomment='x'.repeat(0xffff);
286+
constarchive=awaitbuildArchive([],comment);
287+
constpadded=Buffer.concat([archive,Buffer.alloc(4096)]);
288+
constzip=newzlib.ZipBuffer(padded);
289+
290+
assert.strictEqual(zip.comment,comment);
291+
});
292+
224293
test('junk appended past a declared comment is tolerated and the comment preserved',async()=>{
225294
constarchive=awaitbuildArchive(
226295
[awaitzlib.ZipEntry.create('f.txt',Buffer.from('hi'),{method: 'store'})],
@@ -262,6 +331,10 @@ test('a record count inconsistent with the directory size is rejected', () => {
262331
constarchive=Buffer.concat([Buffer.alloc(46),eocd]);
263332
assert.throws(()=>[...zlib.ZipEntry.read(archive)],
264333
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /inconsistent/});
334+
335+
constzeroRecords=Buffer.concat([Buffer.alloc(46),buildEocd({cdSize: 46})]);
336+
assert.throws(()=>[...zlib.ZipEntry.read(zeroRecords)],
337+
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /inconsistent/});
265338
});
266339

267340
test('a corrupted or overrunning central directory header is rejected',async()=>{

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 8e848d9

Browse files
mcollinaaduh95
authored andcommitted
zlib: reject ambiguous ZIP archive ends
ZIP archives can contain more than one structurally plausible EOCD record. Selecting based on whether a comment reaches EOF can make the chosen central directory depend on trailing padding. Inspect all candidates in the common tail window and reject archives with multiple plausible interpretations. Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #65007 Reviewed-By: Filip Skokan <panva.ip@gmail.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent df48191 commit 8e848d9

2 files changed

Lines changed: 143 additions & 17 deletions

File tree

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

Lines changed: 68 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ const {
2727
MADE_BY_UNIX,
2828
SENTINEL16,
2929
SENTINEL32,
30+
TAIL_LENGTH,
3031
ZIP64_EOCD_MAX_LENGTH,
3132
S_IFLNK,
3233
S_IFMT,
@@ -310,6 +311,51 @@ class LocalFileHeader {
310311
}
311312
}
312313

314+
// Returns whether an EOCD-looking record could describe an archive this
315+
// implementation supports. This is deliberately only a cheap preflight: the
316+
// selected record still receives the complete Zip64 and central-directory
317+
// validation below.
318+
functionisPlausibleArchiveEnd(buffer,eocdPos,scanStart){
319+
constdiskNumber=buffer.readUInt16LE(eocdPos+4);
320+
constcentralDirectoryDiskNumber=buffer.readUInt16LE(eocdPos+6);
321+
constdiskRecords=buffer.readUInt16LE(eocdPos+8);
322+
consttotalRecords=buffer.readUInt16LE(eocdPos+10);
323+
constcentralDirectorySize=buffer.readUInt32LE(eocdPos+12);
324+
constcentralDirectoryOffset=buffer.readUInt32LE(eocdPos+16);
325+
constneedsZip64=
326+
diskNumber===SENTINEL16||
327+
centralDirectoryDiskNumber===SENTINEL16||
328+
diskRecords===SENTINEL16||
329+
totalRecords===SENTINEL16||
330+
centralDirectorySize===SENTINEL32||
331+
centralDirectoryOffset===SENTINEL32;
332+
333+
constlocatorPos=eocdPos-20;
334+
consthasZip64Locator=locatorPos>=0&&
335+
buffer.readUInt32LE(locatorPos)===SIG_ZIP64_EOCD_LOCATOR;
336+
if(needsZip64)returnhasZip64Locator;
337+
// A Zip64 end record may accompany authoritative, non-sentinel classic
338+
// fields. Its central directory does not immediately precede this EOCD.
339+
if(hasZip64Locator)returntrue;
340+
if(
341+
diskNumber!==0||
342+
centralDirectoryDiskNumber!==0||
343+
diskRecords!==totalRecords||
344+
totalRecords*46>centralDirectorySize
345+
){
346+
returnfalse;
347+
}
348+
349+
constcentralDirectoryPos=eocdPos-centralDirectorySize;
350+
if(centralDirectoryPos<scanStart){
351+
// Use the same logical tail window for memory- and file-backed archives.
352+
// The directory is not available for this cheap preflight in either case.
353+
returntrue;
354+
}
355+
if(totalRecords===0)returncentralDirectorySize===0;
356+
returnbuffer.readUInt32LE(centralDirectoryPos)===SIG_CENTRAL_FILE_HEADER;
357+
}
358+
313359
/**
314360
* Locates and validates the end-of-archive structures (EOCD, and the Zip64
315361
* EOCD locator/record when present) in `buffer`. `base` is the absolute
@@ -334,26 +380,30 @@ function findArchiveEnd(buffer, base = 0) {
334380
if(buffer.length<22){
335381
thrownewERR_ZIP_INVALID_ARCHIVE('no end of central directory record found');
336382
}
337-
constmin=MathMax(0,buffer.length-(22+SENTINEL16));
383+
// Use the same tail-sized search window for full buffers and ZipFile's tail
384+
// reads. Besides keeping candidate selection consistent, the extra tail
385+
// slack permits a maximum-length comment followed by modest writer padding.
386+
constmin=MathMax(0,buffer.length-TAIL_LENGTH);
338387
leteocdPos=-1;
339-
// Pass 1: the comment must reach exactly to the end of the buffer (this
340-
// rejects a stray EOCD-looking signature inside an earlier comment).
388+
letfallbackPos=-1;
389+
letexactFallbackPos=-1;
341390
for(letpos=buffer.length-22;pos>=min;pos--){
342391
if(buffer.readUInt32LE(pos)!==SIG_EOCD)continue;
343-
if(pos+22+buffer.readUInt16LE(pos+20)!==buffer.length)continue;
392+
constend=pos+22+buffer.readUInt16LE(pos+20);
393+
if(end>buffer.length)continue;
394+
if(fallbackPos<0)fallbackPos=pos;
395+
if(end===buffer.length&&exactFallbackPos<0)exactFallbackPos=pos;
396+
if(!isPlausibleArchiveEnd(buffer,pos,min))continue;
397+
if(eocdPos>=0){
398+
thrownewERR_ZIP_INVALID_ARCHIVE(
399+
'ambiguous end of central directory records');
400+
}
344401
eocdPos=pos;
345-
break;
346402
}
403+
// Preserve the targeted validation errors for a sole malformed or
404+
// unsupported candidate. Plausible candidates always take precedence.
347405
if(eocdPos<0){
348-
// Pass 2: tolerate trailing padding after the EOCD (some streaming
349-
// writers pad their output to a fixed block size); take the last
350-
// candidate found.
351-
for(letpos=buffer.length-22;pos>=min;pos--){
352-
if(buffer.readUInt32LE(pos)!==SIG_EOCD)continue;
353-
if(pos+22+buffer.readUInt16LE(pos+20)>buffer.length)continue;
354-
eocdPos=pos;
355-
break;
356-
}
406+
eocdPos=exactFallbackPos>=0 ? exactFallbackPos : fallbackPos;
357407
}
358408
if(eocdPos<0){
359409
thrownewERR_ZIP_INVALID_ARCHIVE('no end of central directory record found');
@@ -474,7 +524,10 @@ function findArchiveEnd(buffer, base = 0) {
474524
if(prefix<0){
475525
thrownewERR_ZIP_INVALID_ARCHIVE('central directory does not fit inside the archive');
476526
}
477-
if(totalRecords*46>centralDirectorySize){
527+
if(
528+
(totalRecords===0&&centralDirectorySize!==0)||
529+
totalRecords*46>centralDirectorySize
530+
){
478531
thrownewERR_ZIP_INVALID_ARCHIVE(
479532
'central directory record count is inconsistent with its size');
480533
}

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

Lines changed: 75 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33
require('../common');
44

55
constassert=require('node:assert');
6+
constfs=require('node:fs');
67
constzlib=require('node:zlib');
78
const{ test }=require('node:test');
9+
consttmpdir=require('../common/tmpdir');
810

911
asyncfunctionbuildArchive(entries,comment){
1012
constchunks=[];
@@ -47,13 +49,71 @@ test('an EOCD-looking signature inside a trailing comment is not mistaken for th
4749
// before it reaches the genuine EOCD signature; embedding 4 bytes that
4850
// look like one partway through must not be mistaken for the real record.
4951
constfakeSignature=String.fromCharCode(0x50,0x4b,0x05,0x06);
50-
constarchive=awaitbuildArchive([entry],`before ${fakeSignature} after`);
52+
constarchive=awaitbuildArchive(
53+
[entry],`before ${fakeSignature} this is not a valid EOCD record after`);
5154

5255
constread=[...zlib.ZipEntry.read(archive)];
5356
assert.strictEqual(read.length,1);
5457
assert.strictEqual(read[0].name,'f.txt');
5558
});
5659

60+
test('multiple plausible EOCD records describing different archives are rejected',async()=>{
61+
constfirst=awaitbuildArchive([
62+
awaitzlib.ZipEntry.create('install.sh',Buffer.from('malicious'),{method: 'store'}),
63+
]);
64+
constsecond=awaitbuildArchive([
65+
awaitzlib.ZipEntry.create('install.sh',Buffer.from('benign'),{method: 'store'}),
66+
]);
67+
constarchive=Buffer.concat([first,second,Buffer.from([0])]);
68+
constfirstEocd=first.length-22;
69+
70+
// Make the first EOCD exact-to-EOF by treating the second archive and its
71+
// padding as a comment. The second EOCD remains a plausible archive end for
72+
// readers which tolerate trailing padding and select the rightmost record.
73+
archive.writeUInt16LE(archive.length-firstEocd-22,firstEocd+20);
74+
75+
constexpected={
76+
code: 'ERR_ZIP_INVALID_ARCHIVE',
77+
message: /ambiguousendofcentraldirectory/,
78+
};
79+
assert.throws(()=>[...zlib.ZipEntry.read(archive)],expected);
80+
assert.throws(()=>newzlib.ZipBuffer(archive),expected);
81+
82+
tmpdir.refresh();
83+
constfile=tmpdir.resolve('ambiguous.zip');
84+
fs.writeFileSync(file,archive);
85+
awaitassert.rejects(zlib.ZipFile.open(file),expected);
86+
assert.throws(()=>zlib.ZipFile.openSync(file),expected);
87+
});
88+
89+
test('an exact EOCD embedded in a genuine comment is rejected as ambiguous',async()=>{
90+
constarchive=awaitbuildArchive([
91+
awaitzlib.ZipEntry.create('f.txt',Buffer.from('content'),{method: 'store'}),
92+
]);
93+
constnested=Buffer.concat([archive,buildEocd()]);
94+
nested.writeUInt16LE(22,archive.length-2);
95+
96+
assert.throws(()=>[...zlib.ZipEntry.read(nested)],{
97+
code: 'ERR_ZIP_INVALID_ARCHIVE',
98+
message: /ambiguousendofcentraldirectory/,
99+
});
100+
});
101+
102+
test('multiple padded EOCD records are rejected as ambiguous',async()=>{
103+
constfirst=awaitbuildArchive([
104+
awaitzlib.ZipEntry.create('a.txt',Buffer.from('first'),{method: 'store'}),
105+
]);
106+
constsecond=awaitbuildArchive([
107+
awaitzlib.ZipEntry.create('b.txt',Buffer.from('second'),{method: 'store'}),
108+
]);
109+
constarchive=Buffer.concat([first,second,Buffer.from('\0\0')]);
110+
111+
assert.throws(()=>newzlib.ZipBuffer(archive),{
112+
code: 'ERR_ZIP_INVALID_ARCHIVE',
113+
message: /ambiguousendofcentraldirectory/,
114+
});
115+
});
116+
57117
test('a declared-size mismatch is rejected as corrupt',async()=>{
58118
constentry=awaitzlib.ZipEntry.create('f.txt',Buffer.from('hello world'),{method: 'store'});
59119
constarchive=awaitbuildArchive([entry]);
@@ -212,7 +272,7 @@ test('every possible truncation of an archive is rejected, deterministically', a
212272

213273
test('trailing padding after the EOCD is tolerated',async()=>{
214274
// Some streaming writers pad their output to a block size; CPython
215-
// tolerates trailing newlines/NULs and so does the pass-2 EOCD scan.
275+
// tolerates trailing newlines/NULs and so does the EOCD scan.
216276
constarchive=awaitbuildArchive(
217277
[awaitzlib.ZipEntry.create('f.txt',Buffer.from('hi'),{method: 'store'})]);
218278
constpadded=Buffer.concat([archive,Buffer.from('\r\n\0\0\0')]);
@@ -221,6 +281,15 @@ test('trailing padding after the EOCD is tolerated', async () => {
221281
assert.strictEqual((awaitentry.content()).toString(),'hi');
222282
});
223283

284+
test('a maximum-length comment followed by block padding is tolerated',async()=>{
285+
constcomment='x'.repeat(0xffff);
286+
constarchive=awaitbuildArchive([],comment);
287+
constpadded=Buffer.concat([archive,Buffer.alloc(4096)]);
288+
constzip=newzlib.ZipBuffer(padded);
289+
290+
assert.strictEqual(zip.comment,comment);
291+
});
292+
224293
test('junk appended past a declared comment is tolerated and the comment preserved',async()=>{
225294
constarchive=awaitbuildArchive(
226295
[awaitzlib.ZipEntry.create('f.txt',Buffer.from('hi'),{method: 'store'})],
@@ -262,6 +331,10 @@ test('a record count inconsistent with the directory size is rejected', () => {
262331
constarchive=Buffer.concat([Buffer.alloc(46),eocd]);
263332
assert.throws(()=>[...zlib.ZipEntry.read(archive)],
264333
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /inconsistent/});
334+
335+
constzeroRecords=Buffer.concat([Buffer.alloc(46),buildEocd({cdSize: 46})]);
336+
assert.throws(()=>[...zlib.ZipEntry.read(zeroRecords)],
337+
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /inconsistent/});
265338
});
266339

267340
test('a corrupted or overrunning central directory header is rejected',async()=>{

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 8e848d9

Browse files
mcollinaaduh95
authored andcommitted
zlib: reject ambiguous ZIP archive ends
ZIP archives can contain more than one structurally plausible EOCD record. Selecting based on whether a comment reaches EOF can make the chosen central directory depend on trailing padding. Inspect all candidates in the common tail window and reject archives with multiple plausible interpretations. Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #65007 Reviewed-By: Filip Skokan <panva.ip@gmail.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent df48191 commit 8e848d9

2 files changed

Lines changed: 143 additions & 17 deletions

File tree

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

Lines changed: 68 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ const {
2727
MADE_BY_UNIX,
2828
SENTINEL16,
2929
SENTINEL32,
30+
TAIL_LENGTH,
3031
ZIP64_EOCD_MAX_LENGTH,
3132
S_IFLNK,
3233
S_IFMT,
@@ -310,6 +311,51 @@ class LocalFileHeader {
310311
}
311312
}
312313

314+
// Returns whether an EOCD-looking record could describe an archive this
315+
// implementation supports. This is deliberately only a cheap preflight: the
316+
// selected record still receives the complete Zip64 and central-directory
317+
// validation below.
318+
functionisPlausibleArchiveEnd(buffer,eocdPos,scanStart){
319+
constdiskNumber=buffer.readUInt16LE(eocdPos+4);
320+
constcentralDirectoryDiskNumber=buffer.readUInt16LE(eocdPos+6);
321+
constdiskRecords=buffer.readUInt16LE(eocdPos+8);
322+
consttotalRecords=buffer.readUInt16LE(eocdPos+10);
323+
constcentralDirectorySize=buffer.readUInt32LE(eocdPos+12);
324+
constcentralDirectoryOffset=buffer.readUInt32LE(eocdPos+16);
325+
constneedsZip64=
326+
diskNumber===SENTINEL16||
327+
centralDirectoryDiskNumber===SENTINEL16||
328+
diskRecords===SENTINEL16||
329+
totalRecords===SENTINEL16||
330+
centralDirectorySize===SENTINEL32||
331+
centralDirectoryOffset===SENTINEL32;
332+
333+
constlocatorPos=eocdPos-20;
334+
consthasZip64Locator=locatorPos>=0&&
335+
buffer.readUInt32LE(locatorPos)===SIG_ZIP64_EOCD_LOCATOR;
336+
if(needsZip64)returnhasZip64Locator;
337+
// A Zip64 end record may accompany authoritative, non-sentinel classic
338+
// fields. Its central directory does not immediately precede this EOCD.
339+
if(hasZip64Locator)returntrue;
340+
if(
341+
diskNumber!==0||
342+
centralDirectoryDiskNumber!==0||
343+
diskRecords!==totalRecords||
344+
totalRecords*46>centralDirectorySize
345+
){
346+
returnfalse;
347+
}
348+
349+
constcentralDirectoryPos=eocdPos-centralDirectorySize;
350+
if(centralDirectoryPos<scanStart){
351+
// Use the same logical tail window for memory- and file-backed archives.
352+
// The directory is not available for this cheap preflight in either case.
353+
returntrue;
354+
}
355+
if(totalRecords===0)returncentralDirectorySize===0;
356+
returnbuffer.readUInt32LE(centralDirectoryPos)===SIG_CENTRAL_FILE_HEADER;
357+
}
358+
313359
/**
314360
* Locates and validates the end-of-archive structures (EOCD, and the Zip64
315361
* EOCD locator/record when present) in `buffer`. `base` is the absolute
@@ -334,26 +380,30 @@ function findArchiveEnd(buffer, base = 0) {
334380
if(buffer.length<22){
335381
thrownewERR_ZIP_INVALID_ARCHIVE('no end of central directory record found');
336382
}
337-
constmin=MathMax(0,buffer.length-(22+SENTINEL16));
383+
// Use the same tail-sized search window for full buffers and ZipFile's tail
384+
// reads. Besides keeping candidate selection consistent, the extra tail
385+
// slack permits a maximum-length comment followed by modest writer padding.
386+
constmin=MathMax(0,buffer.length-TAIL_LENGTH);
338387
leteocdPos=-1;
339-
// Pass 1: the comment must reach exactly to the end of the buffer (this
340-
// rejects a stray EOCD-looking signature inside an earlier comment).
388+
letfallbackPos=-1;
389+
letexactFallbackPos=-1;
341390
for(letpos=buffer.length-22;pos>=min;pos--){
342391
if(buffer.readUInt32LE(pos)!==SIG_EOCD)continue;
343-
if(pos+22+buffer.readUInt16LE(pos+20)!==buffer.length)continue;
392+
constend=pos+22+buffer.readUInt16LE(pos+20);
393+
if(end>buffer.length)continue;
394+
if(fallbackPos<0)fallbackPos=pos;
395+
if(end===buffer.length&&exactFallbackPos<0)exactFallbackPos=pos;
396+
if(!isPlausibleArchiveEnd(buffer,pos,min))continue;
397+
if(eocdPos>=0){
398+
thrownewERR_ZIP_INVALID_ARCHIVE(
399+
'ambiguous end of central directory records');
400+
}
344401
eocdPos=pos;
345-
break;
346402
}
403+
// Preserve the targeted validation errors for a sole malformed or
404+
// unsupported candidate. Plausible candidates always take precedence.
347405
if(eocdPos<0){
348-
// Pass 2: tolerate trailing padding after the EOCD (some streaming
349-
// writers pad their output to a fixed block size); take the last
350-
// candidate found.
351-
for(letpos=buffer.length-22;pos>=min;pos--){
352-
if(buffer.readUInt32LE(pos)!==SIG_EOCD)continue;
353-
if(pos+22+buffer.readUInt16LE(pos+20)>buffer.length)continue;
354-
eocdPos=pos;
355-
break;
356-
}
406+
eocdPos=exactFallbackPos>=0 ? exactFallbackPos : fallbackPos;
357407
}
358408
if(eocdPos<0){
359409
thrownewERR_ZIP_INVALID_ARCHIVE('no end of central directory record found');
@@ -474,7 +524,10 @@ function findArchiveEnd(buffer, base = 0) {
474524
if(prefix<0){
475525
thrownewERR_ZIP_INVALID_ARCHIVE('central directory does not fit inside the archive');
476526
}
477-
if(totalRecords*46>centralDirectorySize){
527+
if(
528+
(totalRecords===0&&centralDirectorySize!==0)||
529+
totalRecords*46>centralDirectorySize
530+
){
478531
thrownewERR_ZIP_INVALID_ARCHIVE(
479532
'central directory record count is inconsistent with its size');
480533
}

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

Lines changed: 75 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33
require('../common');
44

55
constassert=require('node:assert');
6+
constfs=require('node:fs');
67
constzlib=require('node:zlib');
78
const{ test }=require('node:test');
9+
consttmpdir=require('../common/tmpdir');
810

911
asyncfunctionbuildArchive(entries,comment){
1012
constchunks=[];
@@ -47,13 +49,71 @@ test('an EOCD-looking signature inside a trailing comment is not mistaken for th
4749
// before it reaches the genuine EOCD signature; embedding 4 bytes that
4850
// look like one partway through must not be mistaken for the real record.
4951
constfakeSignature=String.fromCharCode(0x50,0x4b,0x05,0x06);
50-
constarchive=awaitbuildArchive([entry],`before ${fakeSignature} after`);
52+
constarchive=awaitbuildArchive(
53+
[entry],`before ${fakeSignature} this is not a valid EOCD record after`);
5154

5255
constread=[...zlib.ZipEntry.read(archive)];
5356
assert.strictEqual(read.length,1);
5457
assert.strictEqual(read[0].name,'f.txt');
5558
});
5659

60+
test('multiple plausible EOCD records describing different archives are rejected',async()=>{
61+
constfirst=awaitbuildArchive([
62+
awaitzlib.ZipEntry.create('install.sh',Buffer.from('malicious'),{method: 'store'}),
63+
]);
64+
constsecond=awaitbuildArchive([
65+
awaitzlib.ZipEntry.create('install.sh',Buffer.from('benign'),{method: 'store'}),
66+
]);
67+
constarchive=Buffer.concat([first,second,Buffer.from([0])]);
68+
constfirstEocd=first.length-22;
69+
70+
// Make the first EOCD exact-to-EOF by treating the second archive and its
71+
// padding as a comment. The second EOCD remains a plausible archive end for
72+
// readers which tolerate trailing padding and select the rightmost record.
73+
archive.writeUInt16LE(archive.length-firstEocd-22,firstEocd+20);
74+
75+
constexpected={
76+
code: 'ERR_ZIP_INVALID_ARCHIVE',
77+
message: /ambiguousendofcentraldirectory/,
78+
};
79+
assert.throws(()=>[...zlib.ZipEntry.read(archive)],expected);
80+
assert.throws(()=>newzlib.ZipBuffer(archive),expected);
81+
82+
tmpdir.refresh();
83+
constfile=tmpdir.resolve('ambiguous.zip');
84+
fs.writeFileSync(file,archive);
85+
awaitassert.rejects(zlib.ZipFile.open(file),expected);
86+
assert.throws(()=>zlib.ZipFile.openSync(file),expected);
87+
});
88+
89+
test('an exact EOCD embedded in a genuine comment is rejected as ambiguous',async()=>{
90+
constarchive=awaitbuildArchive([
91+
awaitzlib.ZipEntry.create('f.txt',Buffer.from('content'),{method: 'store'}),
92+
]);
93+
constnested=Buffer.concat([archive,buildEocd()]);
94+
nested.writeUInt16LE(22,archive.length-2);
95+
96+
assert.throws(()=>[...zlib.ZipEntry.read(nested)],{
97+
code: 'ERR_ZIP_INVALID_ARCHIVE',
98+
message: /ambiguousendofcentraldirectory/,
99+
});
100+
});
101+
102+
test('multiple padded EOCD records are rejected as ambiguous',async()=>{
103+
constfirst=awaitbuildArchive([
104+
awaitzlib.ZipEntry.create('a.txt',Buffer.from('first'),{method: 'store'}),
105+
]);
106+
constsecond=awaitbuildArchive([
107+
awaitzlib.ZipEntry.create('b.txt',Buffer.from('second'),{method: 'store'}),
108+
]);
109+
constarchive=Buffer.concat([first,second,Buffer.from('\0\0')]);
110+
111+
assert.throws(()=>newzlib.ZipBuffer(archive),{
112+
code: 'ERR_ZIP_INVALID_ARCHIVE',
113+
message: /ambiguousendofcentraldirectory/,
114+
});
115+
});
116+
57117
test('a declared-size mismatch is rejected as corrupt',async()=>{
58118
constentry=awaitzlib.ZipEntry.create('f.txt',Buffer.from('hello world'),{method: 'store'});
59119
constarchive=awaitbuildArchive([entry]);
@@ -212,7 +272,7 @@ test('every possible truncation of an archive is rejected, deterministically', a
212272

213273
test('trailing padding after the EOCD is tolerated',async()=>{
214274
// Some streaming writers pad their output to a block size; CPython
215-
// tolerates trailing newlines/NULs and so does the pass-2 EOCD scan.
275+
// tolerates trailing newlines/NULs and so does the EOCD scan.
216276
constarchive=awaitbuildArchive(
217277
[awaitzlib.ZipEntry.create('f.txt',Buffer.from('hi'),{method: 'store'})]);
218278
constpadded=Buffer.concat([archive,Buffer.from('\r\n\0\0\0')]);
@@ -221,6 +281,15 @@ test('trailing padding after the EOCD is tolerated', async () => {
221281
assert.strictEqual((awaitentry.content()).toString(),'hi');
222282
});
223283

284+
test('a maximum-length comment followed by block padding is tolerated',async()=>{
285+
constcomment='x'.repeat(0xffff);
286+
constarchive=awaitbuildArchive([],comment);
287+
constpadded=Buffer.concat([archive,Buffer.alloc(4096)]);
288+
constzip=newzlib.ZipBuffer(padded);
289+
290+
assert.strictEqual(zip.comment,comment);
291+
});
292+
224293
test('junk appended past a declared comment is tolerated and the comment preserved',async()=>{
225294
constarchive=awaitbuildArchive(
226295
[awaitzlib.ZipEntry.create('f.txt',Buffer.from('hi'),{method: 'store'})],
@@ -262,6 +331,10 @@ test('a record count inconsistent with the directory size is rejected', () => {
262331
constarchive=Buffer.concat([Buffer.alloc(46),eocd]);
263332
assert.throws(()=>[...zlib.ZipEntry.read(archive)],
264333
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /inconsistent/});
334+
335+
constzeroRecords=Buffer.concat([Buffer.alloc(46),buildEocd({cdSize: 46})]);
336+
assert.throws(()=>[...zlib.ZipEntry.read(zeroRecords)],
337+
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /inconsistent/});
265338
});
266339

267340
test('a corrupted or overrunning central directory header is rejected',async()=>{

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 8e848d9

Browse files
mcollinaaduh95
authored andcommitted
zlib: reject ambiguous ZIP archive ends
ZIP archives can contain more than one structurally plausible EOCD record. Selecting based on whether a comment reaches EOF can make the chosen central directory depend on trailing padding. Inspect all candidates in the common tail window and reject archives with multiple plausible interpretations. Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #65007 Reviewed-By: Filip Skokan <panva.ip@gmail.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent df48191 commit 8e848d9

2 files changed

Lines changed: 143 additions & 17 deletions

File tree

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

Lines changed: 68 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ const {
2727
MADE_BY_UNIX,
2828
SENTINEL16,
2929
SENTINEL32,
30+
TAIL_LENGTH,
3031
ZIP64_EOCD_MAX_LENGTH,
3132
S_IFLNK,
3233
S_IFMT,
@@ -310,6 +311,51 @@ class LocalFileHeader {
310311
}
311312
}
312313

314+
// Returns whether an EOCD-looking record could describe an archive this
315+
// implementation supports. This is deliberately only a cheap preflight: the
316+
// selected record still receives the complete Zip64 and central-directory
317+
// validation below.
318+
functionisPlausibleArchiveEnd(buffer,eocdPos,scanStart){
319+
constdiskNumber=buffer.readUInt16LE(eocdPos+4);
320+
constcentralDirectoryDiskNumber=buffer.readUInt16LE(eocdPos+6);
321+
constdiskRecords=buffer.readUInt16LE(eocdPos+8);
322+
consttotalRecords=buffer.readUInt16LE(eocdPos+10);
323+
constcentralDirectorySize=buffer.readUInt32LE(eocdPos+12);
324+
constcentralDirectoryOffset=buffer.readUInt32LE(eocdPos+16);
325+
constneedsZip64=
326+
diskNumber===SENTINEL16||
327+
centralDirectoryDiskNumber===SENTINEL16||
328+
diskRecords===SENTINEL16||
329+
totalRecords===SENTINEL16||
330+
centralDirectorySize===SENTINEL32||
331+
centralDirectoryOffset===SENTINEL32;
332+
333+
constlocatorPos=eocdPos-20;
334+
consthasZip64Locator=locatorPos>=0&&
335+
buffer.readUInt32LE(locatorPos)===SIG_ZIP64_EOCD_LOCATOR;
336+
if(needsZip64)returnhasZip64Locator;
337+
// A Zip64 end record may accompany authoritative, non-sentinel classic
338+
// fields. Its central directory does not immediately precede this EOCD.
339+
if(hasZip64Locator)returntrue;
340+
if(
341+
diskNumber!==0||
342+
centralDirectoryDiskNumber!==0||
343+
diskRecords!==totalRecords||
344+
totalRecords*46>centralDirectorySize
345+
){
346+
returnfalse;
347+
}
348+
349+
constcentralDirectoryPos=eocdPos-centralDirectorySize;
350+
if(centralDirectoryPos<scanStart){
351+
// Use the same logical tail window for memory- and file-backed archives.
352+
// The directory is not available for this cheap preflight in either case.
353+
returntrue;
354+
}
355+
if(totalRecords===0)returncentralDirectorySize===0;
356+
returnbuffer.readUInt32LE(centralDirectoryPos)===SIG_CENTRAL_FILE_HEADER;
357+
}
358+
313359
/**
314360
* Locates and validates the end-of-archive structures (EOCD, and the Zip64
315361
* EOCD locator/record when present) in `buffer`. `base` is the absolute
@@ -334,26 +380,30 @@ function findArchiveEnd(buffer, base = 0) {
334380
if(buffer.length<22){
335381
thrownewERR_ZIP_INVALID_ARCHIVE('no end of central directory record found');
336382
}
337-
constmin=MathMax(0,buffer.length-(22+SENTINEL16));
383+
// Use the same tail-sized search window for full buffers and ZipFile's tail
384+
// reads. Besides keeping candidate selection consistent, the extra tail
385+
// slack permits a maximum-length comment followed by modest writer padding.
386+
constmin=MathMax(0,buffer.length-TAIL_LENGTH);
338387
leteocdPos=-1;
339-
// Pass 1: the comment must reach exactly to the end of the buffer (this
340-
// rejects a stray EOCD-looking signature inside an earlier comment).
388+
letfallbackPos=-1;
389+
letexactFallbackPos=-1;
341390
for(letpos=buffer.length-22;pos>=min;pos--){
342391
if(buffer.readUInt32LE(pos)!==SIG_EOCD)continue;
343-
if(pos+22+buffer.readUInt16LE(pos+20)!==buffer.length)continue;
392+
constend=pos+22+buffer.readUInt16LE(pos+20);
393+
if(end>buffer.length)continue;
394+
if(fallbackPos<0)fallbackPos=pos;
395+
if(end===buffer.length&&exactFallbackPos<0)exactFallbackPos=pos;
396+
if(!isPlausibleArchiveEnd(buffer,pos,min))continue;
397+
if(eocdPos>=0){
398+
thrownewERR_ZIP_INVALID_ARCHIVE(
399+
'ambiguous end of central directory records');
400+
}
344401
eocdPos=pos;
345-
break;
346402
}
403+
// Preserve the targeted validation errors for a sole malformed or
404+
// unsupported candidate. Plausible candidates always take precedence.
347405
if(eocdPos<0){
348-
// Pass 2: tolerate trailing padding after the EOCD (some streaming
349-
// writers pad their output to a fixed block size); take the last
350-
// candidate found.
351-
for(letpos=buffer.length-22;pos>=min;pos--){
352-
if(buffer.readUInt32LE(pos)!==SIG_EOCD)continue;
353-
if(pos+22+buffer.readUInt16LE(pos+20)>buffer.length)continue;
354-
eocdPos=pos;
355-
break;
356-
}
406+
eocdPos=exactFallbackPos>=0 ? exactFallbackPos : fallbackPos;
357407
}
358408
if(eocdPos<0){
359409
thrownewERR_ZIP_INVALID_ARCHIVE('no end of central directory record found');
@@ -474,7 +524,10 @@ function findArchiveEnd(buffer, base = 0) {
474524
if(prefix<0){
475525
thrownewERR_ZIP_INVALID_ARCHIVE('central directory does not fit inside the archive');
476526
}
477-
if(totalRecords*46>centralDirectorySize){
527+
if(
528+
(totalRecords===0&&centralDirectorySize!==0)||
529+
totalRecords*46>centralDirectorySize
530+
){
478531
thrownewERR_ZIP_INVALID_ARCHIVE(
479532
'central directory record count is inconsistent with its size');
480533
}

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

Lines changed: 75 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33
require('../common');
44

55
constassert=require('node:assert');
6+
constfs=require('node:fs');
67
constzlib=require('node:zlib');
78
const{ test }=require('node:test');
9+
consttmpdir=require('../common/tmpdir');
810

911
asyncfunctionbuildArchive(entries,comment){
1012
constchunks=[];
@@ -47,13 +49,71 @@ test('an EOCD-looking signature inside a trailing comment is not mistaken for th
4749
// before it reaches the genuine EOCD signature; embedding 4 bytes that
4850
// look like one partway through must not be mistaken for the real record.
4951
constfakeSignature=String.fromCharCode(0x50,0x4b,0x05,0x06);
50-
constarchive=awaitbuildArchive([entry],`before ${fakeSignature} after`);
52+
constarchive=awaitbuildArchive(
53+
[entry],`before ${fakeSignature} this is not a valid EOCD record after`);
5154

5255
constread=[...zlib.ZipEntry.read(archive)];
5356
assert.strictEqual(read.length,1);
5457
assert.strictEqual(read[0].name,'f.txt');
5558
});
5659

60+
test('multiple plausible EOCD records describing different archives are rejected',async()=>{
61+
constfirst=awaitbuildArchive([
62+
awaitzlib.ZipEntry.create('install.sh',Buffer.from('malicious'),{method: 'store'}),
63+
]);
64+
constsecond=awaitbuildArchive([
65+
awaitzlib.ZipEntry.create('install.sh',Buffer.from('benign'),{method: 'store'}),
66+
]);
67+
constarchive=Buffer.concat([first,second,Buffer.from([0])]);
68+
constfirstEocd=first.length-22;
69+
70+
// Make the first EOCD exact-to-EOF by treating the second archive and its
71+
// padding as a comment. The second EOCD remains a plausible archive end for
72+
// readers which tolerate trailing padding and select the rightmost record.
73+
archive.writeUInt16LE(archive.length-firstEocd-22,firstEocd+20);
74+
75+
constexpected={
76+
code: 'ERR_ZIP_INVALID_ARCHIVE',
77+
message: /ambiguousendofcentraldirectory/,
78+
};
79+
assert.throws(()=>[...zlib.ZipEntry.read(archive)],expected);
80+
assert.throws(()=>newzlib.ZipBuffer(archive),expected);
81+
82+
tmpdir.refresh();
83+
constfile=tmpdir.resolve('ambiguous.zip');
84+
fs.writeFileSync(file,archive);
85+
awaitassert.rejects(zlib.ZipFile.open(file),expected);
86+
assert.throws(()=>zlib.ZipFile.openSync(file),expected);
87+
});
88+
89+
test('an exact EOCD embedded in a genuine comment is rejected as ambiguous',async()=>{
90+
constarchive=awaitbuildArchive([
91+
awaitzlib.ZipEntry.create('f.txt',Buffer.from('content'),{method: 'store'}),
92+
]);
93+
constnested=Buffer.concat([archive,buildEocd()]);
94+
nested.writeUInt16LE(22,archive.length-2);
95+
96+
assert.throws(()=>[...zlib.ZipEntry.read(nested)],{
97+
code: 'ERR_ZIP_INVALID_ARCHIVE',
98+
message: /ambiguousendofcentraldirectory/,
99+
});
100+
});
101+
102+
test('multiple padded EOCD records are rejected as ambiguous',async()=>{
103+
constfirst=awaitbuildArchive([
104+
awaitzlib.ZipEntry.create('a.txt',Buffer.from('first'),{method: 'store'}),
105+
]);
106+
constsecond=awaitbuildArchive([
107+
awaitzlib.ZipEntry.create('b.txt',Buffer.from('second'),{method: 'store'}),
108+
]);
109+
constarchive=Buffer.concat([first,second,Buffer.from('\0\0')]);
110+
111+
assert.throws(()=>newzlib.ZipBuffer(archive),{
112+
code: 'ERR_ZIP_INVALID_ARCHIVE',
113+
message: /ambiguousendofcentraldirectory/,
114+
});
115+
});
116+
57117
test('a declared-size mismatch is rejected as corrupt',async()=>{
58118
constentry=awaitzlib.ZipEntry.create('f.txt',Buffer.from('hello world'),{method: 'store'});
59119
constarchive=awaitbuildArchive([entry]);
@@ -212,7 +272,7 @@ test('every possible truncation of an archive is rejected, deterministically', a
212272

213273
test('trailing padding after the EOCD is tolerated',async()=>{
214274
// Some streaming writers pad their output to a block size; CPython
215-
// tolerates trailing newlines/NULs and so does the pass-2 EOCD scan.
275+
// tolerates trailing newlines/NULs and so does the EOCD scan.
216276
constarchive=awaitbuildArchive(
217277
[awaitzlib.ZipEntry.create('f.txt',Buffer.from('hi'),{method: 'store'})]);
218278
constpadded=Buffer.concat([archive,Buffer.from('\r\n\0\0\0')]);
@@ -221,6 +281,15 @@ test('trailing padding after the EOCD is tolerated', async () => {
221281
assert.strictEqual((awaitentry.content()).toString(),'hi');
222282
});
223283

284+
test('a maximum-length comment followed by block padding is tolerated',async()=>{
285+
constcomment='x'.repeat(0xffff);
286+
constarchive=awaitbuildArchive([],comment);
287+
constpadded=Buffer.concat([archive,Buffer.alloc(4096)]);
288+
constzip=newzlib.ZipBuffer(padded);
289+
290+
assert.strictEqual(zip.comment,comment);
291+
});
292+
224293
test('junk appended past a declared comment is tolerated and the comment preserved',async()=>{
225294
constarchive=awaitbuildArchive(
226295
[awaitzlib.ZipEntry.create('f.txt',Buffer.from('hi'),{method: 'store'})],
@@ -262,6 +331,10 @@ test('a record count inconsistent with the directory size is rejected', () => {
262331
constarchive=Buffer.concat([Buffer.alloc(46),eocd]);
263332
assert.throws(()=>[...zlib.ZipEntry.read(archive)],
264333
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /inconsistent/});
334+
335+
constzeroRecords=Buffer.concat([Buffer.alloc(46),buildEocd({cdSize: 46})]);
336+
assert.throws(()=>[...zlib.ZipEntry.read(zeroRecords)],
337+
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /inconsistent/});
265338
});
266339

267340
test('a corrupted or overrunning central directory header is rejected',async()=>{

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 8e848d9

Browse files
mcollinaaduh95
authored andcommitted
zlib: reject ambiguous ZIP archive ends
ZIP archives can contain more than one structurally plausible EOCD record. Selecting based on whether a comment reaches EOF can make the chosen central directory depend on trailing padding. Inspect all candidates in the common tail window and reject archives with multiple plausible interpretations. Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #65007 Reviewed-By: Filip Skokan <panva.ip@gmail.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent df48191 commit 8e848d9

2 files changed

Lines changed: 143 additions & 17 deletions

File tree

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

Lines changed: 68 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ const {
2727
MADE_BY_UNIX,
2828
SENTINEL16,
2929
SENTINEL32,
30+
TAIL_LENGTH,
3031
ZIP64_EOCD_MAX_LENGTH,
3132
S_IFLNK,
3233
S_IFMT,
@@ -310,6 +311,51 @@ class LocalFileHeader {
310311
}
311312
}
312313

314+
// Returns whether an EOCD-looking record could describe an archive this
315+
// implementation supports. This is deliberately only a cheap preflight: the
316+
// selected record still receives the complete Zip64 and central-directory
317+
// validation below.
318+
functionisPlausibleArchiveEnd(buffer,eocdPos,scanStart){
319+
constdiskNumber=buffer.readUInt16LE(eocdPos+4);
320+
constcentralDirectoryDiskNumber=buffer.readUInt16LE(eocdPos+6);
321+
constdiskRecords=buffer.readUInt16LE(eocdPos+8);
322+
consttotalRecords=buffer.readUInt16LE(eocdPos+10);
323+
constcentralDirectorySize=buffer.readUInt32LE(eocdPos+12);
324+
constcentralDirectoryOffset=buffer.readUInt32LE(eocdPos+16);
325+
constneedsZip64=
326+
diskNumber===SENTINEL16||
327+
centralDirectoryDiskNumber===SENTINEL16||
328+
diskRecords===SENTINEL16||
329+
totalRecords===SENTINEL16||
330+
centralDirectorySize===SENTINEL32||
331+
centralDirectoryOffset===SENTINEL32;
332+
333+
constlocatorPos=eocdPos-20;
334+
consthasZip64Locator=locatorPos>=0&&
335+
buffer.readUInt32LE(locatorPos)===SIG_ZIP64_EOCD_LOCATOR;
336+
if(needsZip64)returnhasZip64Locator;
337+
// A Zip64 end record may accompany authoritative, non-sentinel classic
338+
// fields. Its central directory does not immediately precede this EOCD.
339+
if(hasZip64Locator)returntrue;
340+
if(
341+
diskNumber!==0||
342+
centralDirectoryDiskNumber!==0||
343+
diskRecords!==totalRecords||
344+
totalRecords*46>centralDirectorySize
345+
){
346+
returnfalse;
347+
}
348+
349+
constcentralDirectoryPos=eocdPos-centralDirectorySize;
350+
if(centralDirectoryPos<scanStart){
351+
// Use the same logical tail window for memory- and file-backed archives.
352+
// The directory is not available for this cheap preflight in either case.
353+
returntrue;
354+
}
355+
if(totalRecords===0)returncentralDirectorySize===0;
356+
returnbuffer.readUInt32LE(centralDirectoryPos)===SIG_CENTRAL_FILE_HEADER;
357+
}
358+
313359
/**
314360
* Locates and validates the end-of-archive structures (EOCD, and the Zip64
315361
* EOCD locator/record when present) in `buffer`. `base` is the absolute
@@ -334,26 +380,30 @@ function findArchiveEnd(buffer, base = 0) {
334380
if(buffer.length<22){
335381
thrownewERR_ZIP_INVALID_ARCHIVE('no end of central directory record found');
336382
}
337-
constmin=MathMax(0,buffer.length-(22+SENTINEL16));
383+
// Use the same tail-sized search window for full buffers and ZipFile's tail
384+
// reads. Besides keeping candidate selection consistent, the extra tail
385+
// slack permits a maximum-length comment followed by modest writer padding.
386+
constmin=MathMax(0,buffer.length-TAIL_LENGTH);
338387
leteocdPos=-1;
339-
// Pass 1: the comment must reach exactly to the end of the buffer (this
340-
// rejects a stray EOCD-looking signature inside an earlier comment).
388+
letfallbackPos=-1;
389+
letexactFallbackPos=-1;
341390
for(letpos=buffer.length-22;pos>=min;pos--){
342391
if(buffer.readUInt32LE(pos)!==SIG_EOCD)continue;
343-
if(pos+22+buffer.readUInt16LE(pos+20)!==buffer.length)continue;
392+
constend=pos+22+buffer.readUInt16LE(pos+20);
393+
if(end>buffer.length)continue;
394+
if(fallbackPos<0)fallbackPos=pos;
395+
if(end===buffer.length&&exactFallbackPos<0)exactFallbackPos=pos;
396+
if(!isPlausibleArchiveEnd(buffer,pos,min))continue;
397+
if(eocdPos>=0){
398+
thrownewERR_ZIP_INVALID_ARCHIVE(
399+
'ambiguous end of central directory records');
400+
}
344401
eocdPos=pos;
345-
break;
346402
}
403+
// Preserve the targeted validation errors for a sole malformed or
404+
// unsupported candidate. Plausible candidates always take precedence.
347405
if(eocdPos<0){
348-
// Pass 2: tolerate trailing padding after the EOCD (some streaming
349-
// writers pad their output to a fixed block size); take the last
350-
// candidate found.
351-
for(letpos=buffer.length-22;pos>=min;pos--){
352-
if(buffer.readUInt32LE(pos)!==SIG_EOCD)continue;
353-
if(pos+22+buffer.readUInt16LE(pos+20)>buffer.length)continue;
354-
eocdPos=pos;
355-
break;
356-
}
406+
eocdPos=exactFallbackPos>=0 ? exactFallbackPos : fallbackPos;
357407
}
358408
if(eocdPos<0){
359409
thrownewERR_ZIP_INVALID_ARCHIVE('no end of central directory record found');
@@ -474,7 +524,10 @@ function findArchiveEnd(buffer, base = 0) {
474524
if(prefix<0){
475525
thrownewERR_ZIP_INVALID_ARCHIVE('central directory does not fit inside the archive');
476526
}
477-
if(totalRecords*46>centralDirectorySize){
527+
if(
528+
(totalRecords===0&&centralDirectorySize!==0)||
529+
totalRecords*46>centralDirectorySize
530+
){
478531
thrownewERR_ZIP_INVALID_ARCHIVE(
479532
'central directory record count is inconsistent with its size');
480533
}

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

Lines changed: 75 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33
require('../common');
44

55
constassert=require('node:assert');
6+
constfs=require('node:fs');
67
constzlib=require('node:zlib');
78
const{ test }=require('node:test');
9+
consttmpdir=require('../common/tmpdir');
810

911
asyncfunctionbuildArchive(entries,comment){
1012
constchunks=[];
@@ -47,13 +49,71 @@ test('an EOCD-looking signature inside a trailing comment is not mistaken for th
4749
// before it reaches the genuine EOCD signature; embedding 4 bytes that
4850
// look like one partway through must not be mistaken for the real record.
4951
constfakeSignature=String.fromCharCode(0x50,0x4b,0x05,0x06);
50-
constarchive=awaitbuildArchive([entry],`before ${fakeSignature} after`);
52+
constarchive=awaitbuildArchive(
53+
[entry],`before ${fakeSignature} this is not a valid EOCD record after`);
5154

5255
constread=[...zlib.ZipEntry.read(archive)];
5356
assert.strictEqual(read.length,1);
5457
assert.strictEqual(read[0].name,'f.txt');
5558
});
5659

60+
test('multiple plausible EOCD records describing different archives are rejected',async()=>{
61+
constfirst=awaitbuildArchive([
62+
awaitzlib.ZipEntry.create('install.sh',Buffer.from('malicious'),{method: 'store'}),
63+
]);
64+
constsecond=awaitbuildArchive([
65+
awaitzlib.ZipEntry.create('install.sh',Buffer.from('benign'),{method: 'store'}),
66+
]);
67+
constarchive=Buffer.concat([first,second,Buffer.from([0])]);
68+
constfirstEocd=first.length-22;
69+
70+
// Make the first EOCD exact-to-EOF by treating the second archive and its
71+
// padding as a comment. The second EOCD remains a plausible archive end for
72+
// readers which tolerate trailing padding and select the rightmost record.
73+
archive.writeUInt16LE(archive.length-firstEocd-22,firstEocd+20);
74+
75+
constexpected={
76+
code: 'ERR_ZIP_INVALID_ARCHIVE',
77+
message: /ambiguousendofcentraldirectory/,
78+
};
79+
assert.throws(()=>[...zlib.ZipEntry.read(archive)],expected);
80+
assert.throws(()=>newzlib.ZipBuffer(archive),expected);
81+
82+
tmpdir.refresh();
83+
constfile=tmpdir.resolve('ambiguous.zip');
84+
fs.writeFileSync(file,archive);
85+
awaitassert.rejects(zlib.ZipFile.open(file),expected);
86+
assert.throws(()=>zlib.ZipFile.openSync(file),expected);
87+
});
88+
89+
test('an exact EOCD embedded in a genuine comment is rejected as ambiguous',async()=>{
90+
constarchive=awaitbuildArchive([
91+
awaitzlib.ZipEntry.create('f.txt',Buffer.from('content'),{method: 'store'}),
92+
]);
93+
constnested=Buffer.concat([archive,buildEocd()]);
94+
nested.writeUInt16LE(22,archive.length-2);
95+
96+
assert.throws(()=>[...zlib.ZipEntry.read(nested)],{
97+
code: 'ERR_ZIP_INVALID_ARCHIVE',
98+
message: /ambiguousendofcentraldirectory/,
99+
});
100+
});
101+
102+
test('multiple padded EOCD records are rejected as ambiguous',async()=>{
103+
constfirst=awaitbuildArchive([
104+
awaitzlib.ZipEntry.create('a.txt',Buffer.from('first'),{method: 'store'}),
105+
]);
106+
constsecond=awaitbuildArchive([
107+
awaitzlib.ZipEntry.create('b.txt',Buffer.from('second'),{method: 'store'}),
108+
]);
109+
constarchive=Buffer.concat([first,second,Buffer.from('\0\0')]);
110+
111+
assert.throws(()=>newzlib.ZipBuffer(archive),{
112+
code: 'ERR_ZIP_INVALID_ARCHIVE',
113+
message: /ambiguousendofcentraldirectory/,
114+
});
115+
});
116+
57117
test('a declared-size mismatch is rejected as corrupt',async()=>{
58118
constentry=awaitzlib.ZipEntry.create('f.txt',Buffer.from('hello world'),{method: 'store'});
59119
constarchive=awaitbuildArchive([entry]);
@@ -212,7 +272,7 @@ test('every possible truncation of an archive is rejected, deterministically', a
212272

213273
test('trailing padding after the EOCD is tolerated',async()=>{
214274
// Some streaming writers pad their output to a block size; CPython
215-
// tolerates trailing newlines/NULs and so does the pass-2 EOCD scan.
275+
// tolerates trailing newlines/NULs and so does the EOCD scan.
216276
constarchive=awaitbuildArchive(
217277
[awaitzlib.ZipEntry.create('f.txt',Buffer.from('hi'),{method: 'store'})]);
218278
constpadded=Buffer.concat([archive,Buffer.from('\r\n\0\0\0')]);
@@ -221,6 +281,15 @@ test('trailing padding after the EOCD is tolerated', async () => {
221281
assert.strictEqual((awaitentry.content()).toString(),'hi');
222282
});
223283

284+
test('a maximum-length comment followed by block padding is tolerated',async()=>{
285+
constcomment='x'.repeat(0xffff);
286+
constarchive=awaitbuildArchive([],comment);
287+
constpadded=Buffer.concat([archive,Buffer.alloc(4096)]);
288+
constzip=newzlib.ZipBuffer(padded);
289+
290+
assert.strictEqual(zip.comment,comment);
291+
});
292+
224293
test('junk appended past a declared comment is tolerated and the comment preserved',async()=>{
225294
constarchive=awaitbuildArchive(
226295
[awaitzlib.ZipEntry.create('f.txt',Buffer.from('hi'),{method: 'store'})],
@@ -262,6 +331,10 @@ test('a record count inconsistent with the directory size is rejected', () => {
262331
constarchive=Buffer.concat([Buffer.alloc(46),eocd]);
263332
assert.throws(()=>[...zlib.ZipEntry.read(archive)],
264333
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /inconsistent/});
334+
335+
constzeroRecords=Buffer.concat([Buffer.alloc(46),buildEocd({cdSize: 46})]);
336+
assert.throws(()=>[...zlib.ZipEntry.read(zeroRecords)],
337+
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /inconsistent/});
265338
});
266339

267340
test('a corrupted or overrunning central directory header is rejected',async()=>{

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 8e848d9

Browse files
mcollinaaduh95
authored andcommitted
zlib: reject ambiguous ZIP archive ends
ZIP archives can contain more than one structurally plausible EOCD record. Selecting based on whether a comment reaches EOF can make the chosen central directory depend on trailing padding. Inspect all candidates in the common tail window and reject archives with multiple plausible interpretations. Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: #65007 Reviewed-By: Filip Skokan <panva.ip@gmail.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent df48191 commit 8e848d9

2 files changed

Lines changed: 143 additions & 17 deletions

File tree

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

Lines changed: 68 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ const {
2727
MADE_BY_UNIX,
2828
SENTINEL16,
2929
SENTINEL32,
30+
TAIL_LENGTH,
3031
ZIP64_EOCD_MAX_LENGTH,
3132
S_IFLNK,
3233
S_IFMT,
@@ -310,6 +311,51 @@ class LocalFileHeader {
310311
}
311312
}
312313

314+
// Returns whether an EOCD-looking record could describe an archive this
315+
// implementation supports. This is deliberately only a cheap preflight: the
316+
// selected record still receives the complete Zip64 and central-directory
317+
// validation below.
318+
functionisPlausibleArchiveEnd(buffer,eocdPos,scanStart){
319+
constdiskNumber=buffer.readUInt16LE(eocdPos+4);
320+
constcentralDirectoryDiskNumber=buffer.readUInt16LE(eocdPos+6);
321+
constdiskRecords=buffer.readUInt16LE(eocdPos+8);
322+
consttotalRecords=buffer.readUInt16LE(eocdPos+10);
323+
constcentralDirectorySize=buffer.readUInt32LE(eocdPos+12);
324+
constcentralDirectoryOffset=buffer.readUInt32LE(eocdPos+16);
325+
constneedsZip64=
326+
diskNumber===SENTINEL16||
327+
centralDirectoryDiskNumber===SENTINEL16||
328+
diskRecords===SENTINEL16||
329+
totalRecords===SENTINEL16||
330+
centralDirectorySize===SENTINEL32||
331+
centralDirectoryOffset===SENTINEL32;
332+
333+
constlocatorPos=eocdPos-20;
334+
consthasZip64Locator=locatorPos>=0&&
335+
buffer.readUInt32LE(locatorPos)===SIG_ZIP64_EOCD_LOCATOR;
336+
if(needsZip64)returnhasZip64Locator;
337+
// A Zip64 end record may accompany authoritative, non-sentinel classic
338+
// fields. Its central directory does not immediately precede this EOCD.
339+
if(hasZip64Locator)returntrue;
340+
if(
341+
diskNumber!==0||
342+
centralDirectoryDiskNumber!==0||
343+
diskRecords!==totalRecords||
344+
totalRecords*46>centralDirectorySize
345+
){
346+
returnfalse;
347+
}
348+
349+
constcentralDirectoryPos=eocdPos-centralDirectorySize;
350+
if(centralDirectoryPos<scanStart){
351+
// Use the same logical tail window for memory- and file-backed archives.
352+
// The directory is not available for this cheap preflight in either case.
353+
returntrue;
354+
}
355+
if(totalRecords===0)returncentralDirectorySize===0;
356+
returnbuffer.readUInt32LE(centralDirectoryPos)===SIG_CENTRAL_FILE_HEADER;
357+
}
358+
313359
/**
314360
* Locates and validates the end-of-archive structures (EOCD, and the Zip64
315361
* EOCD locator/record when present) in `buffer`. `base` is the absolute
@@ -334,26 +380,30 @@ function findArchiveEnd(buffer, base = 0) {
334380
if(buffer.length<22){
335381
thrownewERR_ZIP_INVALID_ARCHIVE('no end of central directory record found');
336382
}
337-
constmin=MathMax(0,buffer.length-(22+SENTINEL16));
383+
// Use the same tail-sized search window for full buffers and ZipFile's tail
384+
// reads. Besides keeping candidate selection consistent, the extra tail
385+
// slack permits a maximum-length comment followed by modest writer padding.
386+
constmin=MathMax(0,buffer.length-TAIL_LENGTH);
338387
leteocdPos=-1;
339-
// Pass 1: the comment must reach exactly to the end of the buffer (this
340-
// rejects a stray EOCD-looking signature inside an earlier comment).
388+
letfallbackPos=-1;
389+
letexactFallbackPos=-1;
341390
for(letpos=buffer.length-22;pos>=min;pos--){
342391
if(buffer.readUInt32LE(pos)!==SIG_EOCD)continue;
343-
if(pos+22+buffer.readUInt16LE(pos+20)!==buffer.length)continue;
392+
constend=pos+22+buffer.readUInt16LE(pos+20);
393+
if(end>buffer.length)continue;
394+
if(fallbackPos<0)fallbackPos=pos;
395+
if(end===buffer.length&&exactFallbackPos<0)exactFallbackPos=pos;
396+
if(!isPlausibleArchiveEnd(buffer,pos,min))continue;
397+
if(eocdPos>=0){
398+
thrownewERR_ZIP_INVALID_ARCHIVE(
399+
'ambiguous end of central directory records');
400+
}
344401
eocdPos=pos;
345-
break;
346402
}
403+
// Preserve the targeted validation errors for a sole malformed or
404+
// unsupported candidate. Plausible candidates always take precedence.
347405
if(eocdPos<0){
348-
// Pass 2: tolerate trailing padding after the EOCD (some streaming
349-
// writers pad their output to a fixed block size); take the last
350-
// candidate found.
351-
for(letpos=buffer.length-22;pos>=min;pos--){
352-
if(buffer.readUInt32LE(pos)!==SIG_EOCD)continue;
353-
if(pos+22+buffer.readUInt16LE(pos+20)>buffer.length)continue;
354-
eocdPos=pos;
355-
break;
356-
}
406+
eocdPos=exactFallbackPos>=0 ? exactFallbackPos : fallbackPos;
357407
}
358408
if(eocdPos<0){
359409
thrownewERR_ZIP_INVALID_ARCHIVE('no end of central directory record found');
@@ -474,7 +524,10 @@ function findArchiveEnd(buffer, base = 0) {
474524
if(prefix<0){
475525
thrownewERR_ZIP_INVALID_ARCHIVE('central directory does not fit inside the archive');
476526
}
477-
if(totalRecords*46>centralDirectorySize){
527+
if(
528+
(totalRecords===0&&centralDirectorySize!==0)||
529+
totalRecords*46>centralDirectorySize
530+
){
478531
thrownewERR_ZIP_INVALID_ARCHIVE(
479532
'central directory record count is inconsistent with its size');
480533
}

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

Lines changed: 75 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33
require('../common');
44

55
constassert=require('node:assert');
6+
constfs=require('node:fs');
67
constzlib=require('node:zlib');
78
const{ test }=require('node:test');
9+
consttmpdir=require('../common/tmpdir');
810

911
asyncfunctionbuildArchive(entries,comment){
1012
constchunks=[];
@@ -47,13 +49,71 @@ test('an EOCD-looking signature inside a trailing comment is not mistaken for th
4749
// before it reaches the genuine EOCD signature; embedding 4 bytes that
4850
// look like one partway through must not be mistaken for the real record.
4951
constfakeSignature=String.fromCharCode(0x50,0x4b,0x05,0x06);
50-
constarchive=awaitbuildArchive([entry],`before ${fakeSignature} after`);
52+
constarchive=awaitbuildArchive(
53+
[entry],`before ${fakeSignature} this is not a valid EOCD record after`);
5154

5255
constread=[...zlib.ZipEntry.read(archive)];
5356
assert.strictEqual(read.length,1);
5457
assert.strictEqual(read[0].name,'f.txt');
5558
});
5659

60+
test('multiple plausible EOCD records describing different archives are rejected',async()=>{
61+
constfirst=awaitbuildArchive([
62+
awaitzlib.ZipEntry.create('install.sh',Buffer.from('malicious'),{method: 'store'}),
63+
]);
64+
constsecond=awaitbuildArchive([
65+
awaitzlib.ZipEntry.create('install.sh',Buffer.from('benign'),{method: 'store'}),
66+
]);
67+
constarchive=Buffer.concat([first,second,Buffer.from([0])]);
68+
constfirstEocd=first.length-22;
69+
70+
// Make the first EOCD exact-to-EOF by treating the second archive and its
71+
// padding as a comment. The second EOCD remains a plausible archive end for
72+
// readers which tolerate trailing padding and select the rightmost record.
73+
archive.writeUInt16LE(archive.length-firstEocd-22,firstEocd+20);
74+
75+
constexpected={
76+
code: 'ERR_ZIP_INVALID_ARCHIVE',
77+
message: /ambiguousendofcentraldirectory/,
78+
};
79+
assert.throws(()=>[...zlib.ZipEntry.read(archive)],expected);
80+
assert.throws(()=>newzlib.ZipBuffer(archive),expected);
81+
82+
tmpdir.refresh();
83+
constfile=tmpdir.resolve('ambiguous.zip');
84+
fs.writeFileSync(file,archive);
85+
awaitassert.rejects(zlib.ZipFile.open(file),expected);
86+
assert.throws(()=>zlib.ZipFile.openSync(file),expected);
87+
});
88+
89+
test('an exact EOCD embedded in a genuine comment is rejected as ambiguous',async()=>{
90+
constarchive=awaitbuildArchive([
91+
awaitzlib.ZipEntry.create('f.txt',Buffer.from('content'),{method: 'store'}),
92+
]);
93+
constnested=Buffer.concat([archive,buildEocd()]);
94+
nested.writeUInt16LE(22,archive.length-2);
95+
96+
assert.throws(()=>[...zlib.ZipEntry.read(nested)],{
97+
code: 'ERR_ZIP_INVALID_ARCHIVE',
98+
message: /ambiguousendofcentraldirectory/,
99+
});
100+
});
101+
102+
test('multiple padded EOCD records are rejected as ambiguous',async()=>{
103+
constfirst=awaitbuildArchive([
104+
awaitzlib.ZipEntry.create('a.txt',Buffer.from('first'),{method: 'store'}),
105+
]);
106+
constsecond=awaitbuildArchive([
107+
awaitzlib.ZipEntry.create('b.txt',Buffer.from('second'),{method: 'store'}),
108+
]);
109+
constarchive=Buffer.concat([first,second,Buffer.from('\0\0')]);
110+
111+
assert.throws(()=>newzlib.ZipBuffer(archive),{
112+
code: 'ERR_ZIP_INVALID_ARCHIVE',
113+
message: /ambiguousendofcentraldirectory/,
114+
});
115+
});
116+
57117
test('a declared-size mismatch is rejected as corrupt',async()=>{
58118
constentry=awaitzlib.ZipEntry.create('f.txt',Buffer.from('hello world'),{method: 'store'});
59119
constarchive=awaitbuildArchive([entry]);
@@ -212,7 +272,7 @@ test('every possible truncation of an archive is rejected, deterministically', a
212272

213273
test('trailing padding after the EOCD is tolerated',async()=>{
214274
// Some streaming writers pad their output to a block size; CPython
215-
// tolerates trailing newlines/NULs and so does the pass-2 EOCD scan.
275+
// tolerates trailing newlines/NULs and so does the EOCD scan.
216276
constarchive=awaitbuildArchive(
217277
[awaitzlib.ZipEntry.create('f.txt',Buffer.from('hi'),{method: 'store'})]);
218278
constpadded=Buffer.concat([archive,Buffer.from('\r\n\0\0\0')]);
@@ -221,6 +281,15 @@ test('trailing padding after the EOCD is tolerated', async () => {
221281
assert.strictEqual((awaitentry.content()).toString(),'hi');
222282
});
223283

284+
test('a maximum-length comment followed by block padding is tolerated',async()=>{
285+
constcomment='x'.repeat(0xffff);
286+
constarchive=awaitbuildArchive([],comment);
287+
constpadded=Buffer.concat([archive,Buffer.alloc(4096)]);
288+
constzip=newzlib.ZipBuffer(padded);
289+
290+
assert.strictEqual(zip.comment,comment);
291+
});
292+
224293
test('junk appended past a declared comment is tolerated and the comment preserved',async()=>{
225294
constarchive=awaitbuildArchive(
226295
[awaitzlib.ZipEntry.create('f.txt',Buffer.from('hi'),{method: 'store'})],
@@ -262,6 +331,10 @@ test('a record count inconsistent with the directory size is rejected', () => {
262331
constarchive=Buffer.concat([Buffer.alloc(46),eocd]);
263332
assert.throws(()=>[...zlib.ZipEntry.read(archive)],
264333
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /inconsistent/});
334+
335+
constzeroRecords=Buffer.concat([Buffer.alloc(46),buildEocd({cdSize: 46})]);
336+
assert.throws(()=>[...zlib.ZipEntry.read(zeroRecords)],
337+
{code: 'ERR_ZIP_INVALID_ARCHIVE',message: /inconsistent/});
265338
});
266339

267340
test('a corrupted or overrunning central directory header is rejected',async()=>{

0 commit comments

Comments
Β (0)