瀏覽代碼

fix: harden extraction against Zip Slip and escaping symlinks (#100, #101)

Issue #100: FilesUtil::normalizeZipPath() only split entry names on '/',
so a Windows-style traversal entry like '..\..\evil.txt' survived
sanitization and escaped the extraction directory via backslash
separators. Split on both separators and reject drive-relative, UNC and
stream-wrapper style names with a ZipException.

Issue #101: extractTo() passed raw symlink targets to symlink() without
any containment check when ZipOptions::EXTRACT_SYMLINKS was enabled,
letting an archive plant links that resolve outside the destination
(same bug class as CVE-2024-12718 in CPython). Validate the resolved
target lexically and via realpath of the first existing ancestor, and
skip unsafe links instead of creating them.

Adds regression tests for backslash traversals, unsafe names, escaping
and absolute symlink targets, and the legitimate inside-root case.
Ne-Lexa 3 周之前
父節點
當前提交
40f4c3b89f
共有 4 個文件被更改,包括 328 次插入 和 1 次删除
  1. 96 1
      src/Util/FilesUtil.php
  2. 14 0
      src/ZipFile.php
  3. 107 0
      tests/SymlinkTest.php
  4. 111 0
      tests/ZipSlipVulnerabilityTest.php

+ 96 - 1
src/Util/FilesUtil.php

@@ -11,6 +11,7 @@ declare(strict_types=1);
 
 namespace PhpZip\Util;
 
+use PhpZip\Exception\ZipException;
 use PhpZip\Util\Iterator\IgnoreFilesFilterIterator;
 use PhpZip\Util\Iterator\IgnoreFilesRecursiveFilterIterator;
 
@@ -250,14 +251,34 @@ final class FilesUtil
     /**
      * Normalizes zip path.
      *
+     * Treats both "/" and "\" as path separators, removes "." and ".."
+     * components and rejects absolute, drive-relative, UNC and stream-wrapper
+     * style names, so that a crafted archive cannot escape the extraction
+     * directory (Zip Slip). See issues #39, #100.
+     *
      * @param string $path Zip path
+     *
+     * @throws ZipException if the entry name is unsafe
      */
     public static function normalizeZipPath(string $path): string
     {
+        if (strpos($path, "\0") !== false) {
+            throw new ZipException(sprintf('Invalid zip entry name "%s": contains NUL byte', $path));
+        }
+
+        // A Windows drive-relative name ("C:evil.txt", "C:\dir\file.txt"),
+        // a UNC path ("\\server\share\file") or a stream-wrapper-like name
+        // would bypass the extraction directory when joined with it.
+        if (preg_match('#^([A-Za-z]:|\\\\\\\\|[A-Za-z0-9+.-]+://)#', $path) === 1) {
+            throw new ZipException(sprintf('Invalid zip entry name "%s": absolute or unsafe path', $path));
+        }
+
+        $parts = preg_split('#[/\\\\]#', $path);
+
         return implode(
             \DIRECTORY_SEPARATOR,
             array_filter(
-                explode('/', $path),
+                $parts === false ? [] : $parts,
                 static fn ($part) => $part !== '.' && $part !== '..'
             )
         );
@@ -290,6 +311,80 @@ final class FilesUtil
         return symlink($target, $path);
     }
 
+    /**
+     * Checks that a symlink target, resolved against the link location,
+     * stays inside the given extraction root. See issue #101.
+     *
+     * @param string $target       the raw symlink target stored in the zip entry
+     * @param string $linkPath     the filesystem path of the link being created
+     * @param string $rootRealPath the realpath of the extraction directory
+     */
+    public static function isSymlinkTargetInsideRoot(string $target, string $linkPath, string $rootRealPath): bool
+    {
+        $rootRealPath = rtrim($rootRealPath, '/');
+
+        if ($rootRealPath === ''
+            || $target === ''
+            || strpos($target, "\0") !== false
+            || self::isAbsolutePath($target)
+        ) {
+            return false;
+        }
+
+        $baseRealPath = realpath(\dirname($linkPath));
+
+        if ($baseRealPath === false) {
+            return false;
+        }
+
+        // Lexically resolve the relative target against the link's parent
+        // directory (the link itself does not exist yet).
+        $stack = explode('/', $baseRealPath);
+        $targetParts = preg_split('#[/\\\\]#', $target);
+
+        foreach ($targetParts === false ? [] : $targetParts as $targetPart) {
+            if ($targetPart === '' || $targetPart === '.') {
+                continue;
+            }
+            if ($targetPart === '..') {
+                array_pop($stack);
+                continue;
+            }
+            $stack[] = $targetPart;
+        }
+
+        $resolvedPath = implode('/', $stack);
+
+        if ($resolvedPath !== $rootRealPath
+            && strpos($resolvedPath, $rootRealPath . '/') !== 0
+        ) {
+            return false;
+        }
+
+        // The resolved path must not traverse through a directory symlink
+        // planted by an earlier entry pointing outside the root. Find the
+        // first existing ancestor and verify its real location.
+        $prefix = $resolvedPath;
+
+        while (strpos($prefix, $rootRealPath) === 0) {
+            if (file_exists($prefix)) {
+                $prefixRealPath = realpath($prefix);
+
+                return $prefixRealPath !== false
+                    && ($prefixRealPath === $rootRealPath
+                        || strpos($prefixRealPath, $rootRealPath . '/') === 0);
+            }
+            $parentPath = \dirname($prefix);
+
+            if ($parentPath === $prefix || strpos($parentPath, $rootRealPath) !== 0) {
+                break;
+            }
+            $prefix = $parentPath;
+        }
+
+        return false;
+    }
+
     public static function isBadCompressionFile(string $file): bool
     {
         $badCompressFileExt = [

+ 14 - 0
src/ZipFile.php

@@ -464,8 +464,22 @@ class ZipFile implements \Countable, \ArrayAccess, \Iterator
         }
 
         $allowSymlink = (bool) $options[ZipOptions::EXTRACT_SYMLINKS];
+        $destDirRealPath = realpath($destDir);
 
         foreach ($symlinks as $linkPath => $target) {
+            if (
+                $allowSymlink
+                && \DIRECTORY_SEPARATOR !== '\\'
+                && ($destDirRealPath === false
+                    || !FilesUtil::isSymlinkTargetInsideRoot($target, $linkPath, $destDirRealPath))
+            ) {
+                // A symlink target that resolves outside the extraction
+                // directory is rejected (issue #101). The entry is skipped
+                // the same way as a failed symlink.
+                unset($extractedEntries[$linkPath]);
+                continue;
+            }
+
             if (!FilesUtil::symlink($target, $linkPath, $allowSymlink)) {
                 unset($extractedEntries[$linkPath]);
             }

+ 107 - 0
tests/SymlinkTest.php

@@ -77,4 +77,111 @@ final class SymlinkTest extends ZipTestCase
         yield 'allow' => [true];
         yield 'deny' => [false];
     }
+
+    /**
+     * A symlink entry whose target resolves outside the extraction directory
+     * must be skipped instead of created. See issue #101.
+     *
+     * @throws \Exception
+     */
+    public function testExtractSkipsSymlinkTargetOutsideRoot(): void
+    {
+        self::skipTestForWindows();
+
+        $root = $this->outputDirname;
+        $payloadDirname = $root . '/payload';
+        $dest = $root . '/extract-root/a/b';
+
+        self::assertTrue(mkdir($payloadDirname, 0755, true));
+        self::assertTrue(mkdir($dest, 0755, true));
+        self::assertNotFalse(file_put_contents($root . '/outside.txt', 'outside'));
+        // When extracted into $dest, "link" resolves to
+        // "extract-root/a/outside.txt", which is outside $dest.
+        self::assertTrue(symlink('../outside.txt', $payloadDirname . '/link'));
+
+        $zipFile = new ZipFile();
+        $zipFile->addFromFinder((new Finder())->in($payloadDirname));
+        $zipFile->saveAsFile($this->outputFilename);
+        $zipFile->close();
+
+        $zipFile->openFile($this->outputFilename);
+        $zipFile->extractTo($dest, null, [
+            ZipOptions::EXTRACT_SYMLINKS => true,
+        ], $extractedEntries);
+        $zipFile->close();
+
+        self::assertArrayNotHasKey($dest . '/link', $extractedEntries);
+        self::assertFalse(is_link($dest . '/link'));
+        self::assertFileDoesNotExist($root . '/extract-root/a/outside.txt');
+    }
+
+    /**
+     * A symlink entry with an absolute target must be skipped.
+     * See issue #101.
+     *
+     * @throws \Exception
+     */
+    public function testExtractSkipsSymlinkWithAbsoluteTarget(): void
+    {
+        self::skipTestForWindows();
+
+        $root = $this->outputDirname;
+        $payloadDirname = $root . '/payload';
+        $dest = $root . '/extract-root';
+
+        self::assertTrue(mkdir($payloadDirname, 0755, true));
+        self::assertTrue(mkdir($dest, 0755, true));
+        self::assertNotFalse(file_put_contents($payloadDirname . '/file.txt', 'contents'));
+        self::assertTrue(symlink($payloadDirname . '/file.txt', $payloadDirname . '/abslink'));
+
+        $zipFile = new ZipFile();
+        $zipFile->addFromFinder((new Finder())->in($payloadDirname));
+        $zipFile->saveAsFile($this->outputFilename);
+        $zipFile->close();
+
+        $zipFile->openFile($this->outputFilename);
+        $zipFile->extractTo($dest, null, [
+            ZipOptions::EXTRACT_SYMLINKS => true,
+        ], $extractedEntries);
+        $zipFile->close();
+
+        self::assertArrayNotHasKey($dest . '/abslink', $extractedEntries);
+        self::assertFalse(is_link($dest . '/abslink'));
+    }
+
+    /**
+     * A symlink entry whose target resolves inside the extraction directory
+     * is still created. See issue #101.
+     *
+     * @throws \Exception
+     */
+    public function testExtractCreatesSymlinkTargetInsideRoot(): void
+    {
+        self::skipTestForWindows();
+
+        $root = $this->outputDirname;
+        $payloadDirname = $root . '/payload';
+        $dest = $root . '/extract-root';
+
+        self::assertTrue(mkdir($payloadDirname . '/sub', 0755, true));
+        self::assertTrue(mkdir($dest, 0755, true));
+        self::assertNotFalse(file_put_contents($payloadDirname . '/sub/file.txt', 'contents'));
+        // "sub/link" resolves to "extract-root/sub/file.txt" - inside $dest.
+        self::assertTrue(symlink('file.txt', $payloadDirname . '/sub/link'));
+
+        $zipFile = new ZipFile();
+        $zipFile->addFromFinder((new Finder())->in($payloadDirname));
+        $zipFile->saveAsFile($this->outputFilename);
+        $zipFile->close();
+
+        $zipFile->openFile($this->outputFilename);
+        $zipFile->extractTo($dest, null, [
+            ZipOptions::EXTRACT_SYMLINKS => true,
+        ], $extractedEntries);
+        $zipFile->close();
+
+        self::assertArrayHasKey($dest . '/sub/link', $extractedEntries);
+        self::assertTrue(is_link($dest . '/sub/link'));
+        self::assertSame('file.txt', (string) (new \SplFileInfo($dest . '/sub/link'))->getLinkTarget());
+    }
 }

+ 111 - 0
tests/ZipSlipVulnerabilityTest.php

@@ -12,6 +12,7 @@ declare(strict_types=1);
 namespace PhpZip\Tests;
 
 use PhpZip\Exception\ZipException;
+use PhpZip\Util\FilesUtil;
 use PhpZip\ZipFile;
 
 /**
@@ -53,4 +54,114 @@ class ZipSlipVulnerabilityTest extends ZipTestCase
         $expectedExtractedFile = $this->outputDirname . '/dir/file.txt';
         static::assertTrue(is_file($expectedExtractedFile));
     }
+
+    /**
+     * Backslash traversal entry names must not escape the extraction
+     * directory, on any platform. See issue #100.
+     *
+     * @dataProvider provideBackslashTraversalEntryNames
+     *
+     * @throws ZipException
+     */
+    public function testUnpackBackslashTraversalIsSanitized(string $entryName, string $expectedEntryPath): void
+    {
+        $root = $this->outputDirname . '/root';
+        $dest = $root . '/a/b';
+        static::assertTrue(mkdir($dest, 0755, true));
+
+        $zipFile = new ZipFile();
+        $zipFile->addFromString($entryName, 'contents');
+        $zipFile->extractTo($dest);
+        $zipFile->close();
+
+        static::assertFileExists($dest . '/' . $expectedEntryPath);
+        // Nothing may be written outside the extraction directory.
+        static::assertFileDoesNotExist($root . '/evil.txt');
+    }
+
+    /**
+     * @return \Generator<string, array{string, string}>
+     */
+    public function provideBackslashTraversalEntryNames(): \Generator
+    {
+        yield 'plain backslash traversal' => ['..\\..\\evil.txt', 'evil.txt'];
+        yield 'mixed separators traversal' => ['safe/..\\..\\evil.txt', 'safe/evil.txt'];
+        yield 'backslash dot segments' => ['.\\..\\evil.txt', 'evil.txt'];
+        yield 'backslash as directory separator' => ['dir\\sub\\evil.txt', 'dir/sub/evil.txt'];
+    }
+
+    /**
+     * Drive-relative and stream-wrapper entry names are rejected outright.
+     * See issue #100.
+     *
+     * @dataProvider provideUnsafeEntryNames
+     *
+     * @throws ZipException
+     */
+    public function testUnpackUnsafeEntryNameThrows(string $entryName): void
+    {
+        static::assertTrue(mkdir($this->outputDirname, 0755, true));
+
+        $zipFile = new ZipFile();
+        $zipFile->addFromString($entryName, 'contents');
+
+        $this->expectException(ZipException::class);
+        $this->expectExceptionMessage('Invalid zip entry name');
+        $zipFile->extractTo($this->outputDirname);
+    }
+
+    /**
+     * @return \Generator<string, array{string}>
+     */
+    public function provideUnsafeEntryNames(): \Generator
+    {
+        yield 'drive absolute path' => ['C:\\evil.txt'];
+        yield 'drive relative path' => ['C:evil.txt'];
+        yield 'stream wrapper path' => ['phar://evil.phar/evil.txt'];
+    }
+
+    /**
+     * Unsafe entry names are rejected directly, including names that cannot
+     * pass through addFromString because it trims leading separators
+     * (UNC paths). See issue #100.
+     *
+     * @dataProvider provideUnsafeEntryNamesForNormalizer
+     */
+    public function testNormalizeZipPathRejectsUnsafeNames(string $entryName): void
+    {
+        $this->expectException(ZipException::class);
+        $this->expectExceptionMessage('Invalid zip entry name');
+        FilesUtil::normalizeZipPath($entryName);
+    }
+
+    /**
+     * @return \Generator<string, array{string}>
+     */
+    public function provideUnsafeEntryNamesForNormalizer(): \Generator
+    {
+        yield 'unc path' => ['\\\\server\\share\\evil.txt'];
+        yield 'nul byte' => ["evil\0.txt"];
+        yield 'drive absolute path' => ['C:\\evil.txt'];
+        yield 'stream wrapper path' => ['phar://evil.phar/evil.txt'];
+    }
+
+    /**
+     * @dataProvider provideSanitizedEntryNames
+     */
+    public function testNormalizeZipPathSanitizes(string $entryName, string $expectedPath): void
+    {
+        static::assertSame($expectedPath, FilesUtil::normalizeZipPath($entryName));
+    }
+
+    /**
+     * @return \Generator<string, array{string, string}>
+     */
+    public function provideSanitizedEntryNames(): \Generator
+    {
+        yield 'unix traversal' => ['../dir/./../../file.txt', 'dir/file.txt'];
+        yield 'backslash traversal' => ['..\\..\\evil.txt', 'evil.txt'];
+        yield 'mixed separators' => ['safe/..\\..\\evil.txt', 'safe/evil.txt'];
+        yield 'double slashes kept for BC' => ['a//b.txt', 'a//b.txt'];
+        yield 'plain name' => ['file.txt', 'file.txt'];
+    }
 }