From 5359e3cd78ff3e52fa78f6331cdc057eaabe18ff Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:03:31 +0000 Subject: [PATCH 01/23] test: add supervised decoder runner and isolated regressions Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/ResourceLimitedProcess.php | 131 ++++++++++++++++++++++ tests/unit/ResourceLimitedProcessTest.php | 76 +++++++++++++ 2 files changed, 207 insertions(+) create mode 100644 lib/Service/ResourceLimitedProcess.php create mode 100644 tests/unit/ResourceLimitedProcessTest.php diff --git a/lib/Service/ResourceLimitedProcess.php b/lib/Service/ResourceLimitedProcess.php new file mode 100644 index 0000000..2c1068f --- /dev/null +++ b/lib/Service/ResourceLimitedProcess.php @@ -0,0 +1,131 @@ + $command Fixed executable and argument vector, never a shell command + * @return array{success: bool, reason: string} + */ + public static function run(array $command, string $directory, int $maxBytes, int $maxEntries, int $timeoutSeconds): array { + if ($maxBytes < 0 || $maxEntries < 1 || $timeoutSeconds < 1 || !function_exists('proc_open')) { + return ['success' => false, 'reason' => 'unavailable']; + } + + try { + $process = proc_open($command, [ + 0 => ['pipe', 'r'], + 1 => ['pipe', 'w'], + 2 => ['pipe', 'w'], + ], $pipes, null, null, ['bypass_shell' => true]); + } catch (\Throwable) { + return ['success' => false, 'reason' => 'unavailable']; + } + if (!is_resource($process)) { + return ['success' => false, 'reason' => 'unavailable']; + } + + fclose($pipes[0]); + stream_set_blocking($pipes[1], false); + stream_set_blocking($pipes[2], false); + $reason = null; + $exitCode = null; + $deadline = microtime(true) + $timeoutSeconds; + try { + while (true) { + // Drain bounded chunks so verbose decoders cannot block on full pipes. + foreach ([1, 2] as $index) { + fread($pipes[$index], 8192); + } + $reason = self::inspect($directory, $maxBytes, $maxEntries); + if ($reason !== null) { + break; + } + if (microtime(true) >= $deadline) { + $reason = 'timeout'; + break; + } + $status = proc_get_status($process); + if (!$status['running']) { + $exitCode = $status['exitcode']; + break; + } + usleep(self::POLL_INTERVAL_US); + } + } catch (\Throwable) { + $reason = 'inspection'; + } finally { + if ($reason !== null) { + proc_terminate($process); + usleep(self::POLL_INTERVAL_US); + if (proc_get_status($process)['running']) { + proc_terminate($process, 9); + } + } + fclose($pipes[1]); + fclose($pipes[2]); + $closedCode = proc_close($process); + if ($exitCode === null && $closedCode >= 0) { + $exitCode = $closedCode; + } + } + if ($reason !== null) { + return ['success' => false, 'reason' => $reason]; + } + try { + $reason = self::inspect($directory, $maxBytes, $maxEntries); + } catch (\Throwable) { + $reason = 'inspection'; + } + if ($reason !== null) { + return ['success' => false, 'reason' => $reason]; + } + if ($exitCode !== 0) { + return ['success' => false, 'reason' => 'exit']; + } + return ['success' => true, 'reason' => '']; + } + + private static function inspect(string $directory, int $maxBytes, int $maxEntries): ?string { + if (!is_dir($directory)) { + return null; + } + clearstatcache(true); + $bytes = 0; + $entries = 0; + $iterator = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS), + \RecursiveIteratorIterator::SELF_FIRST, + ); + foreach ($iterator as $entry) { + if ($entry->isLink()) { + return 'symlink'; + } + if (++$entries > $maxEntries) { + return 'entries'; + } + if (!$entry->isDir()) { + $size = $entry->getSize(); + if ($size < 0 || $size > $maxBytes - $bytes) { + return 'size'; + } + $bytes += $size; + } + } + return null; + } +} diff --git a/tests/unit/ResourceLimitedProcessTest.php b/tests/unit/ResourceLimitedProcessTest.php new file mode 100644 index 0000000..b757e3e --- /dev/null +++ b/tests/unit/ResourceLimitedProcessTest.php @@ -0,0 +1,76 @@ +directory = sys_get_temp_dir() . '/extract-bounded-' . bin2hex(random_bytes(8)); + self::assertTrue(mkdir($this->directory, 0700)); + } + + protected function tearDown(): void { + if (isset($this->directory) && is_dir($this->directory)) { + $iterator = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($this->directory, \FilesystemIterator::SKIP_DOTS), + \RecursiveIteratorIterator::CHILD_FIRST, + ); + foreach ($iterator as $entry) { + $entry->isDir() ? rmdir($entry->getPathname()) : unlink($entry->getPathname()); + } + rmdir($this->directory); + } + parent::tearDown(); + } + + public function testAcceptsExtractionBelowLimits(): void { + $result = ResourceLimitedProcess::run([ + PHP_BINARY, '-r', 'file_put_contents($argv[1] . "/ok.txt", "safe");', $this->directory, + ], $this->directory, 16, 2, 3); + self::assertSame(['success' => true, 'reason' => ''], $result); + self::assertSame('safe', file_get_contents($this->directory . '/ok.txt')); + } + + public function testRejectsTooManyBytesEvenWhenProcessExitsSuccessfully(): void { + $result = ResourceLimitedProcess::run([ + PHP_BINARY, '-r', 'file_put_contents($argv[1] . "/large.txt", str_repeat("x", 256));', $this->directory, + ], $this->directory, 64, 3, 3); + self::assertSame(['success' => false, 'reason' => 'size'], $result); + } + + public function testRejectsTooManyEntries(): void { + $result = ResourceLimitedProcess::run([ + PHP_BINARY, '-r', 'foreach(range(1, 4) as $i){ file_put_contents($argv[1] . "/" . $i, "a"); }', $this->directory, + ], $this->directory, 50, 2, 3); + self::assertSame(['success' => false, 'reason' => 'entries'], $result); + } + + public function testStopsDecoderThatRunsBeyondDeadline(): void { + $result = ResourceLimitedProcess::run([ + PHP_BINARY, '-r', 'while (true) { usleep(200000); }', + ], $this->directory, 50, 2, 1); + self::assertSame(['success' => false, 'reason' => 'timeout'], $result); + } + + public function testDoesNotAcceptNonZeroExit(): void { + $result = ResourceLimitedProcess::run([ + PHP_BINARY, '-r', 'exit(9);', + ], $this->directory, 50, 2, 3); + self::assertSame(['success' => false, 'reason' => 'exit'], $result); + } +} From 9a0719f5639ebe3254712d4c1974b8a28472ded2 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:03:53 +0000 Subject: [PATCH 02/23] fix: supervise 7za and RAR CLI extraction against resource budgets Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- README.md | 11 +++- lib/Controller/ExtractionController.php | 2 +- lib/Service/ExtractionService.php | 79 ++++++++++++++----------- 3 files changed, 55 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index 9b96a3d..c449c5f 100644 --- a/README.md +++ b/README.md @@ -60,8 +60,15 @@ The same configured limits and destination-space estimates are now checked against the *declared* contents of archives handled by `7za` (7z, tar, Gzip, Bzip2 and Deb) **before** launching their extraction. Unlike the ZIP streaming path, an external decoder may expand beyond dishonest archive -metadata before the app can stop it; this is a preflight safeguard and not -a process-level disk quota. RAR decoding still needs separate resource bounds. +metadata before the app can stop it. Command-line decoders now run under a +best-effort supervisor that periodically measures the staging directory, +interrupts processes that exceed the configured size or entry budget, and +enforces a default **300-second** timeout. Administrators can change it with +`occ config:app:set extract max_extraction_seconds --value=600`. +Checks are periodic and can be exceeded briefly; this is **not** a strict +filesystem quota. High-risk deployments should isolate temporary storage +with an operating-system-enforced limit. PHP `rar` extension extraction is +not yet covered by the subprocess supervisor. The `zip` PHP extension is required for Zip files. Rar needs either the PHP `rar` extension or the `unrar` binary; every other format is handled by the diff --git a/lib/Controller/ExtractionController.php b/lib/Controller/ExtractionController.php index 2a1673d..210f95a 100644 --- a/lib/Controller/ExtractionController.php +++ b/lib/Controller/ExtractionController.php @@ -534,7 +534,7 @@ public function execute( $response = $this->extractionService->extractZip($file, $extractTo, $destinationParent->getFreeSpace()); break; case 'rar': - $response = $this->extractionService->extractRar($file, $extractTo); + $response = $this->extractionService->extractRar($file, $extractTo, $destinationParent->getFreeSpace()); break; default: if (self::isWrappedTarball($nameOfFile) === true) { diff --git a/lib/Service/ExtractionService.php b/lib/Service/ExtractionService.php index bddbc29..326f393 100644 --- a/lib/Service/ExtractionService.php +++ b/lib/Service/ExtractionService.php @@ -262,23 +262,56 @@ public function extractZip(string $file, string $extractTo, ?int $availableBytes * * @psalm-return array{code: 0|1, desc?: string} */ - public function extractRar(string $file, string $extractTo): array { + /** + * Run a command-line decoder with periodic staging checks and a time limit. + * This is best-effort supervision, not a kernel-enforced filesystem quota. + * + * @param non-empty-list $command + * @return array{code: 0|1, desc?: string} + */ + private function runExternalDecoder(array $command, string $extractTo, ?int $availableBytes = null): array { + $limit = $this->configuredLimit('max_extracted_bytes', self::DEFAULT_MAX_EXTRACTED_BYTES); + if ($availableBytes !== null && $availableBytes >= 0) { + $limit = min($limit, $availableBytes); + } + $stagingSpace = disk_free_space(dirname($extractTo)); + if ($stagingSpace !== false) { + $limit = min($limit, (int)$stagingSpace); + } + $result = ResourceLimitedProcess::run( + $command, + $extractTo, + $limit, + $this->configuredLimit('max_archive_entries', self::DEFAULT_MAX_ARCHIVE_ENTRIES), + $this->configuredLimit('max_extraction_seconds', 300), + ); + if (!$result['success']) { + $this->logger->warning('Archive decoder stopped: ' . $result['reason']); + $message = match ($result['reason']) { + 'size' => 'Archive exceeds the allowed extraction size', + 'entries' => 'Archive contains too many files', + 'timeout' => 'Archive extraction timed out', + 'symlink' => 'Symbolic links are not supported in extracted archives', + default => 'Could not extract archive', + }; + return ['code' => 0, 'desc' => $this->l->t($message)]; + } + return ['code' => 1]; + } + + public function extractRar(string $file, string $extractTo, ?int $availableBytes = null): array { $response = []; if (!extension_loaded('rar')) { if (!$this->isCommandAvailable('unrar')) { - return $this->extractRarWithSevenZip($file, $extractTo); + return $this->extractRarWithSevenZip($file, $extractTo, $availableBytes); } if ($error = $this->assertSafeRarShell($file)) { return $error; } - $output = []; - $return = 0; - exec('unrar x ' . escapeshellarg($file) . ' -R ' . escapeshellarg($extractTo) . '/ -o+', $output, $return); - if ($return !== 0) { - $response = array_merge($response, ['code' => 0, 'desc' => $this->l->t('Oops something went wrong. Check that you have rar extension or unrar installed')]); - $this->logger->error('unrar failed with exit code ' . $return . '. Output: ' . print_r($output, true)); - return $response; + $result = $this->runExternalDecoder(['unrar', 'x', $file, '-R', $extractTo . '/', '-o+'], $extractTo, $availableBytes); + if ($result['code'] !== 1) { + return $result; } } else { $rar_file = rar_open($file); @@ -322,7 +355,6 @@ public function extractRar(string $file, string $extractTo): array { * @psalm-return array{code: 0|1, desc?: string} */ public function extractOther(string $file, string $extractTo, ?int $availableBytes = null): array { - $response = []; $temporarySpace = disk_free_space(dirname($extractTo)); if ($error = $this->assertSafe7z( @@ -332,21 +364,7 @@ public function extractOther(string $file, string $extractTo, ?int $availableByt )) { return $error; } - $output = []; - $return = 0; - exec('7za -y x ' . escapeshellarg($file) . ' -o' . escapeshellarg($extractTo), $output, $return); - - // 7za reports failure through its exit code: 0 on success, 2 on a fatal - // error such as a corrupt archive or a missing file, 127 when the - // binary itself is absent. The output line count is not a usable signal - // because failures print more lines than successes. - if ($return !== 0) { - $response = array_merge($response, ['code' => 0, 'desc' => $this->l->t('Oops something went wrong.')]); - $this->logger->error('7za failed with exit code ' . $return . '. Is 7-Zip installed? Output: ' . print_r($output, true)); - return $response; - } - $response = array_merge($response, ['code' => 1]); - return $response; + return $this->runExternalDecoder(['7za', '-y', 'x', $file, '-o' . $extractTo], $extractTo, $availableBytes); } /** @@ -378,21 +396,14 @@ private function assertSafeRarSevenZip(string $file): ?array { * Use the full 7z binary as an alternate RAR decoder on distributions that * cannot install the unrar command or the PHP rar extension. */ - private function extractRarWithSevenZip(string $file, string $extractTo): array { + private function extractRarWithSevenZip(string $file, string $extractTo, ?int $availableBytes = null): array { if (!$this->isCommandAvailable('7z')) { return ['code' => 0, 'desc' => $this->l->t('RAR extraction requires unrar, the PHP rar extension, or the full 7z binary')]; } if ($error = $this->assertSafeRarSevenZip($file)) { return $error; } - $output = []; - $return = 0; - exec('7z -y x ' . escapeshellarg($file) . ' -o' . escapeshellarg($extractTo) . ' 2>&1', $output, $return); - if ($return !== 0) { - $this->logger->error('RAR extraction via 7z failed (rc=' . $return . '): ' . implode("\n", $output)); - return ['code' => 0, 'desc' => $this->l->t('Could not extract RAR archive')]; - } - return ['code' => 1]; + return $this->runExternalDecoder(['7z', '-y', 'x', $file, '-o' . $extractTo], $extractTo, $availableBytes); } /** From b77dc31564ae58e0ce3de4db611ba58e64dcb11b Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:05:58 +0000 Subject: [PATCH 03/23] test: use safe RAR5 fixture and reject staged symlinks Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- tests/unit/RarFallbackTest.php | 9 ++++----- tests/unit/ResourceLimitedProcessTest.php | 11 +++++++++++ 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/tests/unit/RarFallbackTest.php b/tests/unit/RarFallbackTest.php index 8bb8b34..a121023 100644 --- a/tests/unit/RarFallbackTest.php +++ b/tests/unit/RarFallbackTest.php @@ -16,10 +16,10 @@ final class RarFallbackTest extends TestCase { /** - * Small RAR 2 fixture adapted from libarchive's freely distributed - * test_read_format_rar.rar.uu (libarchive/test), unmodified contents. + * Small RAR5 stored-file fixture adapted from libarchive's freely distributed + * test_read_format_rar5_stored.rar.uu (libarchive/test), unmodified contents. */ - private const RAR_FIXTURE = 'UmFyIRoHAM+QcwAADQAAAAAAAACEUnQgkDIAFAAAABQAAAADQqLIvrd22j4UMAgApIEAAHRlc3QudHh0gAi3dto+t3baPnRlc3QgdGV4dCBkb2N1bWVudA0KnS90IJAyAAgAAAAIAAAAA3tEybbRTNg+FDAIAP+hAAB0ZXN0bGlua8AI0UzYPlBf2j50ZXN0LnR4dM3gdCCQOgAUAAAAFAAAAANCosi+Y3faPhQwEACkgQAAdGVzdGRpclx0ZXN0LnR4dMDMY3faPmN32j50ZXN0IHRleHQgZG9jdW1lbnQNCqHIdOCQMQAAAAAAAAAAAAMAAAAAY3faPhQwBwDtQQAAdGVzdGRpcsDMY3faPmR32j7m53TgkDYAAAAAAAAAAAADAAAAAJ2r1T4UMAwA7UEAAHRlc3RlbXB0eWRpcoDMnavVPsVd2j7EPXsAQAcA'; + private const RAR_FIXTURE = 'UmFyIRoHAQAzkrXlCgEFBgAFAQGAgAA4MAZjLAIDC50ABJ0ApIMCtEOglYAAAQ5oZWxsb3dvcmxkLnR4dAoDE34Oq1tW6Q4aaGVsbG8gbGliYXJjaGl2ZSB0ZXN0IHN1aXRlIQodd1ZRAwUEAA=='; public function testRarUsesFullSevenZipWhenUnrarIsUnavailable(): void { if (extension_loaded('rar') || trim((string)shell_exec('command -v unrar 2>/dev/null')) !== '') { @@ -41,8 +41,7 @@ public function testRarUsesFullSevenZipWhenUnrarIsUnavailable(): void { try { $result = $service->extractRar($archive, $destination); self::assertSame(['code' => 1], $result); - self::assertSame("test text document\r\n", file_get_contents($destination . '/test.txt')); - self::assertSame("test text document\r\n", file_get_contents($destination . '/testdir/test.txt')); + self::assertSame("hello libarchive test suite!\n", file_get_contents($destination . '/helloworld.txt')); } finally { if (is_dir($destination)) { $files = new \RecursiveIteratorIterator( diff --git a/tests/unit/ResourceLimitedProcessTest.php b/tests/unit/ResourceLimitedProcessTest.php index b757e3e..de9c626 100644 --- a/tests/unit/ResourceLimitedProcessTest.php +++ b/tests/unit/ResourceLimitedProcessTest.php @@ -67,6 +67,17 @@ public function testStopsDecoderThatRunsBeyondDeadline(): void { self::assertSame(['success' => false, 'reason' => 'timeout'], $result); } + + public function testRejectsStagedSymbolicLinks(): void { + if (!function_exists('symlink')) { + self::markTestSkipped('Symbolic links are unavailable on this platform'); + } + $result = ResourceLimitedProcess::run([ + PHP_BINARY, '-r', 'symlink("somewhere-outside", $argv[1] . "/link");', $this->directory, + ], $this->directory, 50, 2, 3); + self::assertSame(['success' => false, 'reason' => 'symlink'], $result); + } + public function testDoesNotAcceptNonZeroExit(): void { $result = ResourceLimitedProcess::run([ PHP_BINARY, '-r', 'exit(9);', From 3c00a611c12a58e8712d1159de5fb0c7dfebf6a3 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:08:02 +0000 Subject: [PATCH 04/23] docs: state proc_open requirement for supervised extraction Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index c449c5f..a722291 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,8 @@ the archive directory. Extraction needs enough free space in the server's temporary directory for the uncompressed archive. Symbolic links in archives are not supported. +External decoders require PHP `proc_open` to be enabled; if it is disabled, +extraction fails closed rather than falling back to unsupervised `exec()`. ZIP extraction enforces the destination's available Nextcloud quota, staging disk free space, and two configurable safety limits (defaults: **2 GiB** total uncompressed bytes and **10,000** entries). The limits apply before extraction From 10b7129e31aeebd4d2e14903883fd1e56fc076be Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:22:27 +0000 Subject: [PATCH 05/23] fix: bound archive listing output and drain verbose decoders Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/ResourceLimitedProcess.php | 118 +++++++++++++++++++++- tests/unit/ResourceLimitedProcessTest.php | 42 ++++++++ 2 files changed, 157 insertions(+), 3 deletions(-) diff --git a/lib/Service/ResourceLimitedProcess.php b/lib/Service/ResourceLimitedProcess.php index 2c1068f..7471b3f 100644 --- a/lib/Service/ResourceLimitedProcess.php +++ b/lib/Service/ResourceLimitedProcess.php @@ -15,7 +15,8 @@ * staging filesystem when they need a strict, kernel-enforced disk quota. */ final class ResourceLimitedProcess { - private const POLL_INTERVAL_US = 100000; + private const POLL_INTERVAL_US = 50000; + private const MAX_DRAIN_PER_POLL = 524288; /** * @param non-empty-list $command Fixed executable and argument vector, never a shell command @@ -47,9 +48,24 @@ public static function run(array $command, string $directory, int $maxBytes, int $deadline = microtime(true) + $timeoutSeconds; try { while (true) { - // Drain bounded chunks so verbose decoders cannot block on full pipes. + // Drain sufficient output to keep verbose decoders running, + // without starving deadline and staging-space inspections. + $remaining = self::MAX_DRAIN_PER_POLL; foreach ([1, 2] as $index) { - fread($pipes[$index], 8192); + while ($remaining > 0) { + $chunk = fread($pipes[$index], min(65536, $remaining)); + if ($chunk === false) { + $reason = 'io'; + break 2; + } + if ($chunk === '') { + break; + } + $remaining -= strlen($chunk); + } + } + if ($reason !== null) { + break; } $reason = self::inspect($directory, $maxBytes, $maxEntries); if ($reason !== null) { @@ -100,6 +116,102 @@ public static function run(array $command, string $directory, int $maxBytes, int return ['success' => true, 'reason' => '']; } + /** + * Inspect archive listing output with bounded memory and execution time. + * Never run listing commands through exec(), which buffers all output + * without imposing a timeout or a memory limit. + * + * @param non-empty-list $command + * @return array{success: bool, reason: string, output: string} + */ + public static function capture(array $command, int $maxOutputBytes, int $timeoutSeconds): array { + if ($maxOutputBytes < 1 || $timeoutSeconds < 1 || !function_exists('proc_open')) { + return ['success' => false, 'reason' => 'unavailable', 'output' => '']; + } + try { + $process = proc_open($command, [ + 0 => ['pipe', 'r'], + 1 => ['pipe', 'w'], + 2 => ['pipe', 'w'], + ], $pipes, null, null, ['bypass_shell' => true]); + } catch (\Throwable) { + return ['success' => false, 'reason' => 'unavailable', 'output' => '']; + } + if (!is_resource($process)) { + return ['success' => false, 'reason' => 'unavailable', 'output' => '']; + } + + fclose($pipes[0]); + stream_set_blocking($pipes[1], false); + stream_set_blocking($pipes[2], false); + $output = ''; + $capturedBytes = 0; + $reason = null; + $exitCode = null; + $deadline = hrtime(true) + (int)min($timeoutSeconds, 3600) * 1000000000; + try { + while (true) { + $remaining = self::MAX_DRAIN_PER_POLL; + foreach ([1, 2] as $index) { + while ($remaining > 0) { + $chunk = fread($pipes[$index], min(65536, $remaining)); + if ($chunk === false) { + $reason = 'io'; + break 2; + } + if ($chunk === '') { + break; + } + if (strlen($chunk) > $maxOutputBytes - $capturedBytes) { + $reason = 'output'; + break 2; + } + $capturedBytes += strlen($chunk); + $remaining -= strlen($chunk); + if ($index === 1) { + $output .= $chunk; + } + } + } + if ($reason !== null) { + break; + } + if (hrtime(true) >= $deadline) { + $reason = 'timeout'; + break; + } + $status = proc_get_status($process); + if (!$status['running']) { + $exitCode = $status['exitcode']; + if (feof($pipes[1]) && feof($pipes[2])) { + break; + } + } + usleep(self::POLL_INTERVAL_US); + } + } catch (\Throwable) { + $reason = 'inspection'; + } finally { + if ($reason !== null) { + proc_terminate($process); + usleep(self::POLL_INTERVAL_US); + if (proc_get_status($process)['running']) { + proc_terminate($process, 9); + } + } + fclose($pipes[1]); + fclose($pipes[2]); + $closedCode = proc_close($process); + if (($exitCode === null || $exitCode < 0) && $closedCode >= 0) { + $exitCode = $closedCode; + } + } + if ($reason === null && $exitCode !== 0) { + $reason = 'exit'; + } + return ['success' => $reason === null, 'reason' => $reason ?? '', 'output' => $output]; + } + private static function inspect(string $directory, int $maxBytes, int $maxEntries): ?string { if (!is_dir($directory)) { return null; diff --git a/tests/unit/ResourceLimitedProcessTest.php b/tests/unit/ResourceLimitedProcessTest.php index de9c626..45e1a27 100644 --- a/tests/unit/ResourceLimitedProcessTest.php +++ b/tests/unit/ResourceLimitedProcessTest.php @@ -78,6 +78,48 @@ public function testRejectsStagedSymbolicLinks(): void { self::assertSame(['success' => false, 'reason' => 'symlink'], $result); } + + public function testLargeStdoutDoesNotBlockAValidDecoder(): void { + $result = ResourceLimitedProcess::run( + [PHP_BINARY, '-r', 'echo str_repeat("x", 1000000);'], + $this->directory, + 100, + 10, + 3, + ); + self::assertSame(['success' => true, 'reason' => ''], $result); + } + + public function testListingRejectsExcessOutput(): void { + $result = ResourceLimitedProcess::capture( + [PHP_BINARY, '-r', 'echo str_repeat("x", 1000000);'], + 1024, + 3, + ); + self::assertFalse($result['success']); + self::assertSame('output', $result['reason']); + self::assertLessThanOrEqual(1024, strlen($result['output'])); + } + + public function testListingHasDeadline(): void { + $result = ResourceLimitedProcess::capture( + [PHP_BINARY, '-r', 'sleep(10);'], + 1024, + 1, + ); + self::assertFalse($result['success']); + self::assertSame('timeout', $result['reason']); + } + + public function testListingAcceptsNormalOutput(): void { + $result = ResourceLimitedProcess::capture( + [PHP_BINARY, '-r', 'echo "Path = normal.txt\nSize = 5\n";'], + 1024, + 3, + ); + self::assertSame(['success' => true, 'reason' => '', 'output' => "Path = normal.txt\nSize = 5\n"], $result); + } + public function testDoesNotAcceptNonZeroExit(): void { $result = ResourceLimitedProcess::run([ PHP_BINARY, '-r', 'exit(9);', From c31933380caf59128af9983d68a5208045c023e4 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:23:27 +0000 Subject: [PATCH 06/23] fix: bound seven-zip preflight and reject link metadata Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/ExtractionService.php | 59 +++++++++++++++++++++++++------ 1 file changed, 49 insertions(+), 10 deletions(-) diff --git a/lib/Service/ExtractionService.php b/lib/Service/ExtractionService.php index 326f393..8e3ac43 100644 --- a/lib/Service/ExtractionService.php +++ b/lib/Service/ExtractionService.php @@ -16,6 +16,8 @@ final class ExtractionService { private const DEFAULT_MAX_EXTRACTED_BYTES = 2147483648; // 2 GiB private const DEFAULT_MAX_ARCHIVE_ENTRIES = 10000; + private const MAX_ARCHIVE_LISTING_BYTES = 16777216; + private const ARCHIVE_LIST_TIMEOUT_SECONDS = 20; public function __construct( private IL10N $l, @@ -62,6 +64,41 @@ private function assertSafeZip(ZipArchive $zip): ?array { return null; } + /** + * Run archive listing with a bounded output size and an execution deadline. + * + * @param non-empty-list $command + * @return ?list + */ + private function listWithLimits(array $command): ?array { + $result = ResourceLimitedProcess::capture( + $command, + self::MAX_ARCHIVE_LISTING_BYTES, + self::ARCHIVE_LIST_TIMEOUT_SECONDS, + ); + if (!$result['success']) { + $this->logger->warning('Archive listing rejected: ' . $result['reason']); + return null; + } + return explode("\n", $result['output']); + } + + /** + * Refuse archive links and special nodes before starting any extractor. + * A periodic filesystem scan does not prevent intermediate unsafe writes. + * + * @return null|array{code: 0, desc: string} + */ + private function rejectUnsafeMetadata(string $line): ?array { + if (preg_match('/^(?:Symbolic Link|Hard Link|Junction|Reparse Point)\s*=/i', $line) !== 1 + && !(str_starts_with($line, 'Attributes = ') + && preg_match('/(?:^|\s)[lbpcs][-rwxstST]{9}(?:\s|$)/', $line) === 1)) { + return null; + } + $this->logger->warning('Refusing archive with links or special files'); + return ['code' => 0, 'desc' => $this->l->t('Archive contains links or unsupported special files')]; + } + /** @return null|array{code: 0, desc: string} */ private function assertSafeRarShell(string $file): ?array { $output = []; @@ -88,11 +125,8 @@ private function assertSafeRarShell(string $file): ?array { * @return null|array{code: 0, desc: string} */ private function assertSafe7z(string $file, ?int $availableBytes, ?int $temporarySpace): ?array { - $output = []; - $return = 0; - exec('7za l -ba -slt ' . escapeshellarg($file) . ' 2>&1', $output, $return); - if ($return !== 0) { - $this->logger->error('7za list failed (rc=' . $return . '): ' . implode("\n", $output)); + $output = $this->listWithLimits(['7za', 'l', '-ba', '-slt', $file]); + if ($output === null) { return ['code' => 0, 'desc' => $this->l->t('Failed to inspect archive contents')]; } $budget = $this->configuredLimit('max_extracted_bytes', self::DEFAULT_MAX_EXTRACTED_BYTES); @@ -106,6 +140,10 @@ private function assertSafe7z(string $file, ?int $availableBytes, ?int $temporar $entries = 0; $size = 0; foreach ($output as $line) { + $line = rtrim($line, "\r"); + if ($error = $this->rejectUnsafeMetadata($line)) { + return $error; + } if (str_starts_with($line, 'Path = ')) { if ($error = $this->rejectUnsafe(substr($line, 7))) { return $error; @@ -375,14 +413,15 @@ public function extractOther(string $file, string $extractTo, ?int $availableByt * @return null|array{code: 0, desc: string} */ private function assertSafeRarSevenZip(string $file): ?array { - $output = []; - $return = 0; - exec('7z l -ba -slt ' . escapeshellarg($file) . ' 2>&1', $output, $return); - if ($return !== 0) { - $this->logger->error('7z RAR listing failed (rc=' . $return . '): ' . implode("\n", $output)); + $output = $this->listWithLimits(['7z', 'l', '-ba', '-slt', $file]); + if ($output === null) { return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; } foreach ($output as $line) { + $line = rtrim($line, "\r"); + if ($error = $this->rejectUnsafeMetadata($line)) { + return $error; + } if (str_starts_with($line, 'Path = ')) { if ($error = $this->rejectUnsafe(substr($line, 7))) { return $error; From 8d0c0374d84c7b9fd2b73e21a1be2b3f83961a8f Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:23:55 +0000 Subject: [PATCH 07/23] fix: validate RAR entry types before extraction and test unsafe metadata Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/ExtractionService.php | 29 +++++++++++++++++++++++----- tests/unit/ExtractionServiceTest.php | 27 ++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 5 deletions(-) diff --git a/lib/Service/ExtractionService.php b/lib/Service/ExtractionService.php index 8e3ac43..5ed013e 100644 --- a/lib/Service/ExtractionService.php +++ b/lib/Service/ExtractionService.php @@ -101,18 +101,37 @@ private function rejectUnsafeMetadata(string $line): ?array { /** @return null|array{code: 0, desc: string} */ private function assertSafeRarShell(string $file): ?array { - $output = []; - $return = 0; - exec('unrar lb ' . escapeshellarg($file) . ' 2>&1', $output, $return); - if ($return !== 0) { - $this->logger->error('unrar list failed (rc=' . $return . '): ' . implode("\n", $output)); + $output = $this->listWithLimits(['unrar', 'lb', $file]); + if ($output === null) { return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; } foreach ($output as $entry) { + $entry = rtrim($entry, "\r"); if ($entry !== '' && ($error = $this->rejectUnsafe($entry))) { return $error; } } + // The plain filename list does not reveal links. Inspect entry types + // before extraction, using 7z technical metadata when available. + if ($this->isCommandAvailable('7z')) { + return $this->assertSafeRarSevenZip($file); + } + $details = $this->listWithLimits(['unrar', 'lt', $file]); + if ($details === null) { + return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; + } + $types = 0; + foreach ($details as $line) { + if (preg_match('/^\s*Type\s*:\s*(.+)$/i', $line, $match) === 1) { + $types++; + if (preg_match('/^(?:File|Directory)$/i', trim($match[1])) !== 1) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains links or unsupported special files')]; + } + } + } + if ($types === 0) { + return ['code' => 0, 'desc' => $this->l->t('Could not verify RAR entry types')]; + } return null; } diff --git a/tests/unit/ExtractionServiceTest.php b/tests/unit/ExtractionServiceTest.php index 3077c67..19ed2e7 100644 --- a/tests/unit/ExtractionServiceTest.php +++ b/tests/unit/ExtractionServiceTest.php @@ -235,6 +235,33 @@ public function testTarArchiveRespectsDestinationQuota(): void { self::assertSame(str_repeat('x', 256), file_get_contents($allowed . '/payload.txt')); } + + public function testRefusesArchiveLinkMetadataBeforeExtraction(): void { + $method = new \ReflectionMethod(ExtractionService::class, 'rejectUnsafeMetadata'); + foreach ([ + 'Attributes = A lrwxrwxrwx', + 'Hard Link = file.txt', + 'Symbolic Link = ../../outside', + 'Junction = ../outside', + 'Attributes = A brw-rw----', + ] as $line) { + $response = $method->invoke($this->service, $line); + self::assertSame(0, $response['code'], $line); + } + } + + public function testAllowsOrdinaryArchiveMetadata(): void { + $method = new \ReflectionMethod(ExtractionService::class, 'rejectUnsafeMetadata'); + foreach ([ + 'Attributes = D drwxr-xr-x', + 'Attributes = A -rw-r--r--', + 'Attributes = RA', + 'Size = 1024', + ] as $line) { + self::assertNull($method->invoke($this->service, $line), $line); + } + } + /** * A decompression bomb must be refused before staging any files when the * total uncompressed content cannot fit the user's Nextcloud quota. From 6e02191a386615d50e62401a6923d137abb57b71 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:25:03 +0000 Subject: [PATCH 08/23] test: accept empty link metadata emitted for regular archives Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/ExtractionService.php | 2 +- tests/unit/ExtractionServiceTest.php | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/Service/ExtractionService.php b/lib/Service/ExtractionService.php index 5ed013e..dd55168 100644 --- a/lib/Service/ExtractionService.php +++ b/lib/Service/ExtractionService.php @@ -90,7 +90,7 @@ private function listWithLimits(array $command): ?array { * @return null|array{code: 0, desc: string} */ private function rejectUnsafeMetadata(string $line): ?array { - if (preg_match('/^(?:Symbolic Link|Hard Link|Junction|Reparse Point)\s*=/i', $line) !== 1 + if (preg_match('/^(?:Symbolic Link|Hard Link|Junction|Reparse Point)\s*=\s*\S/i', $line) !== 1 && !(str_starts_with($line, 'Attributes = ') && preg_match('/(?:^|\s)[lbpcs][-rwxstST]{9}(?:\s|$)/', $line) === 1)) { return null; diff --git a/tests/unit/ExtractionServiceTest.php b/tests/unit/ExtractionServiceTest.php index 19ed2e7..094c8bf 100644 --- a/tests/unit/ExtractionServiceTest.php +++ b/tests/unit/ExtractionServiceTest.php @@ -256,6 +256,8 @@ public function testAllowsOrdinaryArchiveMetadata(): void { 'Attributes = D drwxr-xr-x', 'Attributes = A -rw-r--r--', 'Attributes = RA', + 'Symbolic Link = ', + 'Hard Link = ', 'Size = 1024', ] as $line) { self::assertNull($method->invoke($this->service, $line), $line); From a4806ef97354a6e6c2b110907e492b921fba8f3c Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:26:04 +0000 Subject: [PATCH 09/23] fix: enforce streaming quotas and CRC checks for PHP RAR extraction Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/ExtractionService.php | 177 ++++++++++++++++++++++----- tests/unit/ExtractionServiceTest.php | 46 +++++++ 2 files changed, 194 insertions(+), 29 deletions(-) diff --git a/lib/Service/ExtractionService.php b/lib/Service/ExtractionService.php index dd55168..1402d6e 100644 --- a/lib/Service/ExtractionService.php +++ b/lib/Service/ExtractionService.php @@ -371,35 +371,7 @@ public function extractRar(string $file, string $extractTo, ?int $availableBytes return $result; } } else { - $rar_file = rar_open($file); - if ($rar_file === false) { - $response = array_merge($response, ['code' => 0, 'desc' => $this->l->t('Cannot open Rar file')]); - return $response; - } - $list = rar_list($rar_file); - if ($list === false) { - rar_close($rar_file); - return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; - } - foreach ($list as $archive_file) { - if ($error = $this->rejectUnsafe($archive_file->getName())) { - rar_close($rar_file); - return $error; - } - } - foreach ($list as $archive_file) { - $entry = rar_entry_get($rar_file, $archive_file->getName()); - if ($entry->extract($extractTo) === false) { - // A password-protected or damaged entry fails here; without this - // check the method reported success and the caller published a - // partial result. - rar_close($rar_file); - $response = array_merge($response, ['code' => 0, 'desc' => $this->l->t('Oops something went wrong.')]); - $this->logger->error('rar_entry::extract failed for ' . $archive_file->getName()); - return $response; - } - } - rar_close($rar_file); + return $this->extractRarWithPhpExtension($file, $extractTo, $availableBytes); } $response = array_merge($response, ['code' => 1]); @@ -411,6 +383,153 @@ public function extractRar(string $file, string $extractTo, ?int $availableBytes * * @psalm-return array{code: 0|1, desc?: string} */ + /** + * Stream a RAR entry into staging with strict per-entry and total-byte + * limits. Unlike RarEntry::extract(), PHP controls every output path. + * + * @param resource $input + */ + private function copyRarStream($input, string $target, int $expectedBytes, string $expectedCrc, int &$written, int $budget, int $deadline): bool { + $output = fopen($target, 'xb'); + if ($output === false) { + return false; + } + $size = 0; + $hash = hash_init('crc32b'); + try { + while (!feof($input)) { + if (hrtime(true) >= $deadline) { + return false; + } + $chunk = fread($input, 65536); + if ($chunk === false || ($chunk === '' && !feof($input))) { + return false; + } + $length = strlen($chunk); + if ($length > $budget - $written || $length > $expectedBytes - $size) { + return false; + } + $offset = 0; + while ($offset < $length) { + if (hrtime(true) >= $deadline) { + return false; + } + $count = fwrite($output, substr($chunk, $offset)); + if ($count === false || $count === 0) { + return false; + } + $offset += $count; + } + hash_update($hash, $chunk); + $size += $length; + $written += $length; + } + } finally { + fclose($output); + } + return $size === $expectedBytes && hash_equals(strtolower($expectedCrc), hash_final($hash)); + } + + /** + * The PHP RAR extension must not bypass quota checks or create archive + * links using RarEntry::extract(). Stream only regular files and folders + * with a cumulative size budget and CRC verification. + * + * @return array{code: 0|1, desc?: string} + */ + private function extractRarWithPhpExtension(string $file, string $extractTo, ?int $availableBytes): array { + $archive = rar_open($file); + if ($archive === false) { + return ['code' => 0, 'desc' => $this->l->t('Cannot open Rar file')]; + } + try { + $entries = rar_list($archive); + if ($entries === false) { + return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; + } + if (count($entries) > $this->configuredLimit('max_archive_entries', self::DEFAULT_MAX_ARCHIVE_ENTRIES)) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains too many files')]; + } + $budget = $this->configuredLimit('max_extracted_bytes', self::DEFAULT_MAX_EXTRACTED_BYTES); + if ($availableBytes !== null && $availableBytes >= 0) { + $budget = min($budget, $availableBytes); + } + $space = disk_free_space(dirname($extractTo)); + if ($space !== false) { + $budget = min($budget, (int)$space); + } + $declared = 0; + $paths = []; + foreach ($entries as $entry) { + $name = str_replace('\\', '/', $entry->getName()); + $relative = rtrim($name, '/'); + if ($relative === '' || preg_match('//u', $relative) !== 1 || isset($paths[$relative])) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains an invalid filename')]; + } + if ($error = $this->rejectUnsafe($name)) { + return $error; + } + $paths[$relative] = true; + if ($entry->isEncrypted()) { + return ['code' => 0, 'desc' => $this->l->t('Encrypted RAR archives are not supported')]; + } + // Unix RAR4 entries can encode links and devices as native + // filesystem types. RAR5 redirects are never materialized: + // getStream() writes regular file bytes under PHP control. + if (defined('RAR_HOST_UNIX') && $entry->getHostOs() === constant('RAR_HOST_UNIX')) { + $type = $entry->getAttr() & 0xf000; + if ($type !== 0x8000 && $type !== 0x4000) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains links or unsupported special files')]; + } + } + $size = $entry->getUnpackedSize(); + if ($size === false || $size < 0 || $size > $budget - $declared) { + return ['code' => 0, 'desc' => $this->l->t('Archive exceeds the allowed extraction size')]; + } + $declared += $size; + } + if (!is_dir($extractTo) && !mkdir($extractTo, 0700, true)) { + return ['code' => 0, 'desc' => $this->l->t('Could not prepare extraction directory')]; + } + $written = 0; + $deadline = hrtime(true) + min($this->configuredLimit('max_extraction_seconds', 300), 3600) * 1000000000; + foreach ($entries as $entry) { + $name = rtrim(str_replace('\\', '/', $entry->getName()), '/'); + $target = $extractTo . '/' . $name; + if ($entry->isDirectory()) { + if (!is_dir($target) && !mkdir($target, 0700, true)) { + return ['code' => 0, 'desc' => $this->l->t('Could not extract RAR archive')]; + } + continue; + } + if (!is_dir(dirname($target)) && !mkdir(dirname($target), 0700, true)) { + return ['code' => 0, 'desc' => $this->l->t('Could not extract RAR archive')]; + } + $crc = $entry->getCrc(); + if (!is_string($crc) || preg_match('/^[0-9a-fA-F]{8}$/', $crc) !== 1) { + return ['code' => 0, 'desc' => $this->l->t('Could not verify RAR entry integrity')]; + } + $input = $entry->getStream(); + if ($input === false) { + return ['code' => 0, 'desc' => $this->l->t('Could not read RAR entry')]; + } + try { + if (!$this->copyRarStream($input, $target, $entry->getUnpackedSize(), $crc, $written, $budget, $deadline)) { + return ['code' => 0, 'desc' => $this->l->t('RAR extraction exceeded limits or failed integrity verification')]; + } + } finally { + fclose($input); + } + } + return ['code' => 1]; + } catch (\Throwable $e) { + $this->logger->warning('RAR stream extraction failed: ' . $e->getMessage()); + return ['code' => 0, 'desc' => $this->l->t('Could not extract RAR archive')]; + } finally { + rar_close($archive); + } + } + public function extractOther(string $file, string $extractTo, ?int $availableBytes = null): array { $temporarySpace = disk_free_space(dirname($extractTo)); diff --git a/tests/unit/ExtractionServiceTest.php b/tests/unit/ExtractionServiceTest.php index 094c8bf..f392e93 100644 --- a/tests/unit/ExtractionServiceTest.php +++ b/tests/unit/ExtractionServiceTest.php @@ -264,6 +264,52 @@ public function testAllowsOrdinaryArchiveMetadata(): void { } } + /** + * The PHP RAR extraction path must enforce limits on actual stream bytes + * and check CRC, not trust only the archive's advertised size. + */ + public function testBoundedRarStreamPreservesDataAndRefusesInvalidCrc(): void { + $method = new \ReflectionMethod(ExtractionService::class, 'copyRarStream'); + $payload = 'hello world'; + $stream = fopen('php://temp', 'w+b'); + self::assertIsResource($stream); + fwrite($stream, $payload); + rewind($stream); + $written = 0; + try { + $arguments = [$stream, $this->tmpDir . '/good.txt', strlen($payload), hash('crc32b', $payload), &$written, strlen($payload), hrtime(true) + 2000000000]; + self::assertTrue($method->invokeArgs($this->service, $arguments)); + self::assertSame($payload, file_get_contents($this->tmpDir . '/good.txt')); + self::assertSame(strlen($payload), $written); + } finally { + fclose($stream); + } + + $stream = fopen('php://temp', 'w+b'); + self::assertIsResource($stream); + fwrite($stream, $payload); + rewind($stream); + $written = 0; + try { + $arguments = [$stream, $this->tmpDir . '/limited.txt', strlen($payload), hash('crc32b', $payload), &$written, strlen($payload) - 1, hrtime(true) + 2000000000]; + self::assertFalse($method->invokeArgs($this->service, $arguments)); + } finally { + fclose($stream); + } + + $stream = fopen('php://temp', 'w+b'); + self::assertIsResource($stream); + fwrite($stream, $payload); + rewind($stream); + $written = 0; + try { + $arguments = [$stream, $this->tmpDir . '/corrupt.txt', strlen($payload), '00000000', &$written, strlen($payload), hrtime(true) + 2000000000]; + self::assertFalse($method->invokeArgs($this->service, $arguments)); + } finally { + fclose($stream); + } + } + /** * A decompression bomb must be refused before staging any files when the * total uncompressed content cannot fit the user's Nextcloud quota. From 69259728cc8d78716d521691923bf15b831d94bd Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:27:15 +0000 Subject: [PATCH 10/23] fix: terminate isolated decoder process groups on timeout Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/ResourceLimitedProcess.php | 78 ++++++++++++++++++++++---- 1 file changed, 68 insertions(+), 10 deletions(-) diff --git a/lib/Service/ResourceLimitedProcess.php b/lib/Service/ResourceLimitedProcess.php index 7471b3f..37e0c63 100644 --- a/lib/Service/ResourceLimitedProcess.php +++ b/lib/Service/ResourceLimitedProcess.php @@ -27,6 +27,7 @@ public static function run(array $command, string $directory, int $maxBytes, int return ['success' => false, 'reason' => 'unavailable']; } + $command = self::isolatedCommand($command, $isolated); try { $process = proc_open($command, [ 0 => ['pipe', 'r'], @@ -45,6 +46,7 @@ public static function run(array $command, string $directory, int $maxBytes, int stream_set_blocking($pipes[2], false); $reason = null; $exitCode = null; + $groupId = null; $deadline = microtime(true) + $timeoutSeconds; try { while (true) { @@ -76,6 +78,9 @@ public static function run(array $command, string $directory, int $maxBytes, int break; } $status = proc_get_status($process); + if ($isolated && $groupId === null) { + $groupId = self::processGroupId($status); + } if (!$status['running']) { $exitCode = $status['exitcode']; break; @@ -86,11 +91,7 @@ public static function run(array $command, string $directory, int $maxBytes, int $reason = 'inspection'; } finally { if ($reason !== null) { - proc_terminate($process); - usleep(self::POLL_INTERVAL_US); - if (proc_get_status($process)['running']) { - proc_terminate($process, 9); - } + self::stopProcess($process, $groupId, $isolated); } fclose($pipes[1]); fclose($pipes[2]); @@ -128,6 +129,7 @@ public static function capture(array $command, int $maxOutputBytes, int $timeout if ($maxOutputBytes < 1 || $timeoutSeconds < 1 || !function_exists('proc_open')) { return ['success' => false, 'reason' => 'unavailable', 'output' => '']; } + $command = self::isolatedCommand($command, $isolated); try { $process = proc_open($command, [ 0 => ['pipe', 'r'], @@ -148,6 +150,7 @@ public static function capture(array $command, int $maxOutputBytes, int $timeout $capturedBytes = 0; $reason = null; $exitCode = null; + $groupId = null; $deadline = hrtime(true) + (int)min($timeoutSeconds, 3600) * 1000000000; try { while (true) { @@ -181,6 +184,9 @@ public static function capture(array $command, int $maxOutputBytes, int $timeout break; } $status = proc_get_status($process); + if ($isolated && $groupId === null) { + $groupId = self::processGroupId($status); + } if (!$status['running']) { $exitCode = $status['exitcode']; if (feof($pipes[1]) && feof($pipes[2])) { @@ -193,11 +199,7 @@ public static function capture(array $command, int $maxOutputBytes, int $timeout $reason = 'inspection'; } finally { if ($reason !== null) { - proc_terminate($process); - usleep(self::POLL_INTERVAL_US); - if (proc_get_status($process)['running']) { - proc_terminate($process, 9); - } + self::stopProcess($process, $groupId, $isolated); } fclose($pipes[1]); fclose($pipes[2]); @@ -212,6 +214,62 @@ public static function capture(array $command, int $maxOutputBytes, int $timeout return ['success' => $reason === null, 'reason' => $reason ?? '', 'output' => $output]; } + /** + * Prefer a separate process session on Unix so timed-out decoders cannot + * leave inherited child processes writing after the parent is terminated. + * + * @param non-empty-list $command + * @return non-empty-list + */ + private static function isolatedCommand(array $command, bool &$isolated): array { + $isolated = false; + if (DIRECTORY_SEPARATOR !== '/' || !function_exists('posix_kill') || !function_exists('posix_getpgid')) { + return $command; + } + foreach (['/usr/bin/setsid', '/bin/setsid'] as $binary) { + if (is_executable($binary)) { + $isolated = true; + return [$binary, ...$command]; + } + } + return $command; + } + + /** @param array{pid: int, running: bool} $status */ + private static function processGroupId(array $status): ?int { + $pid = $status['pid']; + if ($pid <= 1 || $pid === posix_getpgrp()) { + return null; + } + return @posix_getpgid($pid) === $pid ? $pid : null; + } + + /** + * Terminate the decoder session when available, then stop its direct child + * as a fallback. Only signal a verified, distinct POSIX process group. + * + * @param resource $process + */ + private static function stopProcess($process, ?int $groupId, bool $isolated): void { + if ($isolated && $groupId === null) { + $groupId = self::processGroupId(proc_get_status($process)); + } + if ($groupId !== null) { + @posix_kill(-$groupId, 15); + usleep(self::POLL_INTERVAL_US); + if (@posix_kill(-$groupId, 0)) { + @posix_kill(-$groupId, 9); + } + } + if (proc_get_status($process)['running']) { + proc_terminate($process); + usleep(self::POLL_INTERVAL_US); + if (proc_get_status($process)['running']) { + proc_terminate($process, 9); + } + } + } + private static function inspect(string $directory, int $maxBytes, int $maxEntries): ?string { if (!is_dir($directory)) { return null; From 0123b559df24fce7dd5e94354288bace0f1f0993 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:28:44 +0000 Subject: [PATCH 11/23] fix: initialize process group state and count RAR entries safely Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/ExtractionService.php | 8 +++++--- lib/Service/ResourceLimitedProcess.php | 4 +++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/Service/ExtractionService.php b/lib/Service/ExtractionService.php index 1402d6e..0d19d11 100644 --- a/lib/Service/ExtractionService.php +++ b/lib/Service/ExtractionService.php @@ -447,9 +447,8 @@ private function extractRarWithPhpExtension(string $file, string $extractTo, ?in if ($entries === false) { return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; } - if (count($entries) > $this->configuredLimit('max_archive_entries', self::DEFAULT_MAX_ARCHIVE_ENTRIES)) { - return ['code' => 0, 'desc' => $this->l->t('Archive contains too many files')]; - } + $entryLimit = $this->configuredLimit('max_archive_entries', self::DEFAULT_MAX_ARCHIVE_ENTRIES); + $entryCount = 0; $budget = $this->configuredLimit('max_extracted_bytes', self::DEFAULT_MAX_EXTRACTED_BYTES); if ($availableBytes !== null && $availableBytes >= 0) { $budget = min($budget, $availableBytes); @@ -461,6 +460,9 @@ private function extractRarWithPhpExtension(string $file, string $extractTo, ?in $declared = 0; $paths = []; foreach ($entries as $entry) { + if (++$entryCount > $entryLimit) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains too many files')]; + } $name = str_replace('\\', '/', $entry->getName()); $relative = rtrim($name, '/'); if ($relative === '' || preg_match('//u', $relative) !== 1 || isset($paths[$relative])) { diff --git a/lib/Service/ResourceLimitedProcess.php b/lib/Service/ResourceLimitedProcess.php index 37e0c63..6f441e9 100644 --- a/lib/Service/ResourceLimitedProcess.php +++ b/lib/Service/ResourceLimitedProcess.php @@ -27,6 +27,7 @@ public static function run(array $command, string $directory, int $maxBytes, int return ['success' => false, 'reason' => 'unavailable']; } + $isolated = false; $command = self::isolatedCommand($command, $isolated); try { $process = proc_open($command, [ @@ -129,6 +130,7 @@ public static function capture(array $command, int $maxOutputBytes, int $timeout if ($maxOutputBytes < 1 || $timeoutSeconds < 1 || !function_exists('proc_open')) { return ['success' => false, 'reason' => 'unavailable', 'output' => '']; } + $isolated = false; $command = self::isolatedCommand($command, $isolated); try { $process = proc_open($command, [ @@ -235,7 +237,7 @@ private static function isolatedCommand(array $command, bool &$isolated): array return $command; } - /** @param array{pid: int, running: bool} $status */ + /** @param array{pid: int, running: bool, command: string, exitcode: int, signaled: bool, stopped: bool, stopsig: int, termsig: int} $status */ private static function processGroupId(array $status): ?int { $pid = $status['pid']; if ($pid <= 1 || $pid === posix_getpgrp()) { From cf5c0196d9bee84e8bd506322dc5ab03320ec411 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:29:33 +0000 Subject: [PATCH 12/23] fix: terminate remaining decoder descendants and preserve exit status Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/ResourceLimitedProcess.php | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/lib/Service/ResourceLimitedProcess.php b/lib/Service/ResourceLimitedProcess.php index 6f441e9..a3b08c6 100644 --- a/lib/Service/ResourceLimitedProcess.php +++ b/lib/Service/ResourceLimitedProcess.php @@ -91,9 +91,9 @@ public static function run(array $command, string $directory, int $maxBytes, int } catch (\Throwable) { $reason = 'inspection'; } finally { - if ($reason !== null) { - self::stopProcess($process, $groupId, $isolated); - } + // Clean up any descendants in the isolated session even when the + // direct decoder process has already exited successfully. + self::stopProcess($process, $groupId, $isolated); fclose($pipes[1]); fclose($pipes[2]); $closedCode = proc_close($process); @@ -190,7 +190,11 @@ public static function capture(array $command, int $maxOutputBytes, int $timeout $groupId = self::processGroupId($status); } if (!$status['running']) { - $exitCode = $status['exitcode']; + // proc_get_status may return -1 on repeated queries; preserve + // the first valid exit code until the pipes reach EOF. + if ($exitCode === null || $exitCode < 0) { + $exitCode = $status['exitcode']; + } if (feof($pipes[1]) && feof($pipes[2])) { break; } @@ -200,9 +204,9 @@ public static function capture(array $command, int $maxOutputBytes, int $timeout } catch (\Throwable) { $reason = 'inspection'; } finally { - if ($reason !== null) { - self::stopProcess($process, $groupId, $isolated); - } + // Clean up any descendants in the isolated session even when the + // direct decoder process has already exited successfully. + self::stopProcess($process, $groupId, $isolated); fclose($pipes[1]); fclose($pipes[2]); $closedCode = proc_close($process); From cee8ebbc629d3c88d6443299222e293a9ccc4911 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:30:14 +0000 Subject: [PATCH 13/23] test: ensure timed-out decoder children stop and document isolation limits Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- README.md | 7 ++- tests/unit/ResourceLimitedProcessTest.php | 53 +++++++++++++++++++++++ 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a722291..963a916 100644 --- a/README.md +++ b/README.md @@ -69,8 +69,11 @@ enforces a default **300-second** timeout. Administrators can change it with `occ config:app:set extract max_extraction_seconds --value=600`. Checks are periodic and can be exceeded briefly; this is **not** a strict filesystem quota. High-risk deployments should isolate temporary storage -with an operating-system-enforced limit. PHP `rar` extension extraction is -not yet covered by the subprocess supervisor. +with an operating-system-enforced limit. When available, the supervisor +runs command-line decoders in their own POSIX session and terminates remaining +child processes on completion or failure. The PHP `rar` extension follows a +separate bounded streaming path with CRC checks rather than spawning a decoder, +but it still cannot provide an operating-system-enforced CPU or disk quota. The `zip` PHP extension is required for Zip files. Rar needs either the PHP `rar` extension or the `unrar` binary; every other format is handled by the diff --git a/tests/unit/ResourceLimitedProcessTest.php b/tests/unit/ResourceLimitedProcessTest.php index 45e1a27..2e588f6 100644 --- a/tests/unit/ResourceLimitedProcessTest.php +++ b/tests/unit/ResourceLimitedProcessTest.php @@ -120,6 +120,59 @@ public function testListingAcceptsNormalOutput(): void { self::assertSame(['success' => true, 'reason' => '', 'output' => "Path = normal.txt\nSize = 5\n"], $result); } + + public function testTimeoutStopsChildProcessInIsolatedSession(): void { + if (!function_exists('posix_kill') || !is_executable('/usr/bin/setsid')) { + $result = ResourceLimitedProcess::run( + [PHP_BINARY, '-r', 'sleep(5);'], + $this->directory, + 128, + 5, + 1, + ); + self::assertSame('timeout', $result['reason']); + return; + } + + $marker = $this->directory . '/child-survived.txt'; + $pidFile = $this->directory . '/child.pid'; + $script = <<<'PHP' +$child = proc_open( + [PHP_BINARY, '-r', 'usleep(1800000); file_put_contents($argv[1], "survived");', $argv[1]], + [ + 0 => ['file', '/dev/null', 'r'], + 1 => ['file', '/dev/null', 'w'], + 2 => ['file', '/dev/null', 'w'], + ], + $pipes, +); +if (is_resource($child)) { + file_put_contents($argv[2], (string)proc_get_status($child)['pid']); +} +sleep(5); +PHP; + try { + $result = ResourceLimitedProcess::run( + [PHP_BINARY, '-r', $script, $marker, $pidFile], + $this->directory, + 128, + 5, + 1, + ); + self::assertSame('timeout', $result['reason']); + self::assertFileExists($pidFile); + usleep(1100000); + self::assertFileDoesNotExist($marker, 'Timed-out decoder descendants must not continue writing'); + } finally { + if (is_file($pidFile)) { + $pid = (int)file_get_contents($pidFile); + if ($pid > 1) { + @posix_kill($pid, 9); + } + } + } + } + public function testDoesNotAcceptNonZeroExit(): void { $result = ResourceLimitedProcess::run([ PHP_BINARY, '-r', 'exit(9);', From 9ffb10a9cc2c6d2ef5c6ad5154f1b90c619b93e2 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:55:52 +0000 Subject: [PATCH 14/23] refactor: separate decoder process lifecycle from staging budget checks Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/DecoderProcess.php | 175 +++++++++++++++ lib/Service/ResourceLimitedProcess.php | 288 ++++--------------------- lib/Service/StagingBudgetInspector.php | 60 ++++++ 3 files changed, 275 insertions(+), 248 deletions(-) create mode 100644 lib/Service/DecoderProcess.php create mode 100644 lib/Service/StagingBudgetInspector.php diff --git a/lib/Service/DecoderProcess.php b/lib/Service/DecoderProcess.php new file mode 100644 index 0000000..9f310c1 --- /dev/null +++ b/lib/Service/DecoderProcess.php @@ -0,0 +1,175 @@ + */ + private array $pipes; + private ?int $exitCode = null; + private ?int $groupId = null; + private int $outputBytes = 0; + private string $output = ''; + + /** + * @param resource $process + * @param array $pipes + */ + private function __construct($process, array $pipes, private readonly bool $isolated) { + $this->process = $process; + $this->pipes = $pipes; + } + + /** + * @param non-empty-list $command A fixed argument vector, not a shell command + */ + public static function start(array $command): ?self { + if (!function_exists('proc_open')) { + return null; + } + $isolated = false; + $command = self::isolatedCommand($command, $isolated); + try { + $process = proc_open($command, [ + 0 => ['pipe', 'r'], + 1 => ['pipe', 'w'], + 2 => ['pipe', 'w'], + ], $pipes, null, null, ['bypass_shell' => true]); + } catch (\Throwable) { + return null; + } + if (!is_resource($process)) { + return null; + } + fclose($pipes[0]); + stream_set_blocking($pipes[1], false); + stream_set_blocking($pipes[2], false); + return new self($process, $pipes, $isolated); + } + + /** + * Drain stdout and stderr without buffering extraction output. For archive + * listings, limit the combined bytes while only retaining stdout. + */ + public function drain(?int $outputLimit): ?string { + $remaining = self::MAX_DRAIN_PER_POLL; + foreach ([1, 2] as $index) { + while ($remaining > 0) { + $chunk = fread($this->pipes[$index], min(65536, $remaining)); + if ($chunk === false) { + return 'io'; + } + if ($chunk === '') { + break; + } + $length = strlen($chunk); + $remaining -= $length; + if ($outputLimit !== null) { + if ($length > $outputLimit - $this->outputBytes) { + return 'output'; + } + $this->outputBytes += $length; + if ($index === 1) { + $this->output .= $chunk; + } + } + } + } + return null; + } + + public function hasExited(): bool { + $status = proc_get_status($this->process); + if ($this->isolated && $this->groupId === null) { + $this->groupId = self::processGroupId($status); + } + if (!$status['running'] && ($this->exitCode === null || $this->exitCode < 0)) { + $this->exitCode = $status['exitcode']; + } + return !$status['running']; + } + + public function outputComplete(): bool { + return feof($this->pipes[1]) && feof($this->pipes[2]); + } + + public function output(): string { + return $this->output; + } + + /** Always tear down the process group and release every pipe. */ + public function close(): int { + $this->stopProcess(); + fclose($this->pipes[1]); + fclose($this->pipes[2]); + $closedCode = proc_close($this->process); + if (($this->exitCode === null || $this->exitCode < 0) && $closedCode >= 0) { + $this->exitCode = $closedCode; + } + return $this->exitCode ?? -1; + } + + /** + * @param non-empty-list $command + * @return non-empty-list + */ + private static function isolatedCommand(array $command, bool &$isolated): array { + $isolated = false; + if (DIRECTORY_SEPARATOR !== '/' || !function_exists('posix_kill') || !function_exists('posix_getpgid') || !function_exists('posix_getpgrp')) { + return $command; + } + foreach (['/usr/bin/setsid', '/bin/setsid'] as $binary) { + if (is_executable($binary)) { + $isolated = true; + return [$binary, ...$command]; + } + } + return $command; + } + + /** + * @param array{pid: int, running: bool, command: string, exitcode: int, signaled: bool, stopped: bool, stopsig: int, termsig: int} $status + */ + private static function processGroupId(array $status): ?int { + $pid = $status['pid']; + if ($pid <= 1 || $pid === posix_getpgrp()) { + return null; + } + return @posix_getpgid($pid) === $pid ? $pid : null; + } + + private function stopProcess(): void { + if ($this->isolated && $this->groupId === null) { + $this->groupId = self::processGroupId(proc_get_status($this->process)); + } + if ($this->groupId !== null) { + @posix_kill(-$this->groupId, 15); + usleep(self::TERMINATION_WAIT_US); + if (@posix_kill(-$this->groupId, 0)) { + @posix_kill(-$this->groupId, 9); + } + } + if (proc_get_status($this->process)['running']) { + proc_terminate($this->process); + usleep(self::TERMINATION_WAIT_US); + if (proc_get_status($this->process)['running']) { + proc_terminate($this->process, 9); + } + } + } +} diff --git a/lib/Service/ResourceLimitedProcess.php b/lib/Service/ResourceLimitedProcess.php index a3b08c6..443f2a5 100644 --- a/lib/Service/ResourceLimitedProcess.php +++ b/lib/Service/ResourceLimitedProcess.php @@ -10,298 +10,90 @@ namespace OCA\Extract\Service; /** - * Supervise an external archive decoder while it writes to a private staging - * directory. Checks are periodic, so administrators must still isolate the - * staging filesystem when they need a strict, kernel-enforced disk quota. + * Coordinate bounded extraction and listing through the same process loop. + * The process lifecycle and staging checks are independently testable. + * Polling is not a kernel-enforced resource quota. */ final class ResourceLimitedProcess { private const POLL_INTERVAL_US = 50000; - private const MAX_DRAIN_PER_POLL = 524288; /** - * @param non-empty-list $command Fixed executable and argument vector, never a shell command + * @param non-empty-list $command Fixed executable and argument vector * @return array{success: bool, reason: string} */ public static function run(array $command, string $directory, int $maxBytes, int $maxEntries, int $timeoutSeconds): array { - if ($maxBytes < 0 || $maxEntries < 1 || $timeoutSeconds < 1 || !function_exists('proc_open')) { - return ['success' => false, 'reason' => 'unavailable']; - } - - $isolated = false; - $command = self::isolatedCommand($command, $isolated); - try { - $process = proc_open($command, [ - 0 => ['pipe', 'r'], - 1 => ['pipe', 'w'], - 2 => ['pipe', 'w'], - ], $pipes, null, null, ['bypass_shell' => true]); - } catch (\Throwable) { - return ['success' => false, 'reason' => 'unavailable']; - } - if (!is_resource($process)) { + if ($maxBytes < 0 || $maxEntries < 1) { return ['success' => false, 'reason' => 'unavailable']; } + $result = self::execute($command, $timeoutSeconds, new StagingBudgetInspector($directory, $maxBytes, $maxEntries), null); + return ['success' => $result['success'], 'reason' => $result['reason']]; + } - fclose($pipes[0]); - stream_set_blocking($pipes[1], false); - stream_set_blocking($pipes[2], false); - $reason = null; - $exitCode = null; - $groupId = null; - $deadline = microtime(true) + $timeoutSeconds; - try { - while (true) { - // Drain sufficient output to keep verbose decoders running, - // without starving deadline and staging-space inspections. - $remaining = self::MAX_DRAIN_PER_POLL; - foreach ([1, 2] as $index) { - while ($remaining > 0) { - $chunk = fread($pipes[$index], min(65536, $remaining)); - if ($chunk === false) { - $reason = 'io'; - break 2; - } - if ($chunk === '') { - break; - } - $remaining -= strlen($chunk); - } - } - if ($reason !== null) { - break; - } - $reason = self::inspect($directory, $maxBytes, $maxEntries); - if ($reason !== null) { - break; - } - if (microtime(true) >= $deadline) { - $reason = 'timeout'; - break; - } - $status = proc_get_status($process); - if ($isolated && $groupId === null) { - $groupId = self::processGroupId($status); - } - if (!$status['running']) { - $exitCode = $status['exitcode']; - break; - } - usleep(self::POLL_INTERVAL_US); - } - } catch (\Throwable) { - $reason = 'inspection'; - } finally { - // Clean up any descendants in the isolated session even when the - // direct decoder process has already exited successfully. - self::stopProcess($process, $groupId, $isolated); - fclose($pipes[1]); - fclose($pipes[2]); - $closedCode = proc_close($process); - if ($exitCode === null && $closedCode >= 0) { - $exitCode = $closedCode; - } - } - if ($reason !== null) { - return ['success' => false, 'reason' => $reason]; - } - try { - $reason = self::inspect($directory, $maxBytes, $maxEntries); - } catch (\Throwable) { - $reason = 'inspection'; - } - if ($reason !== null) { - return ['success' => false, 'reason' => $reason]; - } - if ($exitCode !== 0) { - return ['success' => false, 'reason' => 'exit']; + /** + * @param non-empty-list $command Fixed executable and argument vector + * @return array{success: bool, reason: string, output: string} + */ + public static function capture(array $command, int $maxOutputBytes, int $timeoutSeconds): array { + if ($maxOutputBytes < 1) { + return ['success' => false, 'reason' => 'unavailable', 'output' => '']; } - return ['success' => true, 'reason' => '']; + return self::execute($command, $timeoutSeconds, null, $maxOutputBytes); } /** - * Inspect archive listing output with bounded memory and execution time. - * Never run listing commands through exec(), which buffers all output - * without imposing a timeout or a memory limit. + * Share one supervision loop for archive extraction and metadata listing. + * Only extraction needs filesystem scans; only listing retains stdout. * * @param non-empty-list $command * @return array{success: bool, reason: string, output: string} */ - public static function capture(array $command, int $maxOutputBytes, int $timeoutSeconds): array { - if ($maxOutputBytes < 1 || $timeoutSeconds < 1 || !function_exists('proc_open')) { - return ['success' => false, 'reason' => 'unavailable', 'output' => '']; - } - $isolated = false; - $command = self::isolatedCommand($command, $isolated); - try { - $process = proc_open($command, [ - 0 => ['pipe', 'r'], - 1 => ['pipe', 'w'], - 2 => ['pipe', 'w'], - ], $pipes, null, null, ['bypass_shell' => true]); - } catch (\Throwable) { + private static function execute(array $command, int $timeoutSeconds, ?StagingBudgetInspector $inspector, ?int $maxOutputBytes): array { + if ($timeoutSeconds < 1) { return ['success' => false, 'reason' => 'unavailable', 'output' => '']; } - if (!is_resource($process)) { + $process = DecoderProcess::start($command); + if ($process === null) { return ['success' => false, 'reason' => 'unavailable', 'output' => '']; } - fclose($pipes[0]); - stream_set_blocking($pipes[1], false); - stream_set_blocking($pipes[2], false); - $output = ''; - $capturedBytes = 0; $reason = null; - $exitCode = null; - $groupId = null; - $deadline = hrtime(true) + (int)min($timeoutSeconds, 3600) * 1000000000; + // Preserve the configured extraction timeout; limit listing to one hour. + $deadline = microtime(true) + ($maxOutputBytes === null ? $timeoutSeconds : min($timeoutSeconds, 3600)); try { while (true) { - $remaining = self::MAX_DRAIN_PER_POLL; - foreach ([1, 2] as $index) { - while ($remaining > 0) { - $chunk = fread($pipes[$index], min(65536, $remaining)); - if ($chunk === false) { - $reason = 'io'; - break 2; - } - if ($chunk === '') { - break; - } - if (strlen($chunk) > $maxOutputBytes - $capturedBytes) { - $reason = 'output'; - break 2; - } - $capturedBytes += strlen($chunk); - $remaining -= strlen($chunk); - if ($index === 1) { - $output .= $chunk; - } - } + $reason = $process->drain($maxOutputBytes); + if ($reason !== null) { + break; } + $reason = $inspector?->inspect(); if ($reason !== null) { break; } - if (hrtime(true) >= $deadline) { + if (microtime(true) >= $deadline) { $reason = 'timeout'; break; } - $status = proc_get_status($process); - if ($isolated && $groupId === null) { - $groupId = self::processGroupId($status); - } - if (!$status['running']) { - // proc_get_status may return -1 on repeated queries; preserve - // the first valid exit code until the pipes reach EOF. - if ($exitCode === null || $exitCode < 0) { - $exitCode = $status['exitcode']; - } - if (feof($pipes[1]) && feof($pipes[2])) { - break; - } + if ($process->hasExited() && ($maxOutputBytes === null || $process->outputComplete())) { + break; } usleep(self::POLL_INTERVAL_US); } } catch (\Throwable) { $reason = 'inspection'; } finally { - // Clean up any descendants in the isolated session even when the - // direct decoder process has already exited successfully. - self::stopProcess($process, $groupId, $isolated); - fclose($pipes[1]); - fclose($pipes[2]); - $closedCode = proc_close($process); - if (($exitCode === null || $exitCode < 0) && $closedCode >= 0) { - $exitCode = $closedCode; - } - } - if ($reason === null && $exitCode !== 0) { - $reason = 'exit'; - } - return ['success' => $reason === null, 'reason' => $reason ?? '', 'output' => $output]; - } - - /** - * Prefer a separate process session on Unix so timed-out decoders cannot - * leave inherited child processes writing after the parent is terminated. - * - * @param non-empty-list $command - * @return non-empty-list - */ - private static function isolatedCommand(array $command, bool &$isolated): array { - $isolated = false; - if (DIRECTORY_SEPARATOR !== '/' || !function_exists('posix_kill') || !function_exists('posix_getpgid')) { - return $command; + $exitCode = $process->close(); } - foreach (['/usr/bin/setsid', '/bin/setsid'] as $binary) { - if (is_executable($binary)) { - $isolated = true; - return [$binary, ...$command]; - } - } - return $command; - } - - /** @param array{pid: int, running: bool, command: string, exitcode: int, signaled: bool, stopped: bool, stopsig: int, termsig: int} $status */ - private static function processGroupId(array $status): ?int { - $pid = $status['pid']; - if ($pid <= 1 || $pid === posix_getpgrp()) { - return null; - } - return @posix_getpgid($pid) === $pid ? $pid : null; - } - /** - * Terminate the decoder session when available, then stop its direct child - * as a fallback. Only signal a verified, distinct POSIX process group. - * - * @param resource $process - */ - private static function stopProcess($process, ?int $groupId, bool $isolated): void { - if ($isolated && $groupId === null) { - $groupId = self::processGroupId(proc_get_status($process)); - } - if ($groupId !== null) { - @posix_kill(-$groupId, 15); - usleep(self::POLL_INTERVAL_US); - if (@posix_kill(-$groupId, 0)) { - @posix_kill(-$groupId, 9); + if ($reason === null) { + try { + $reason = $inspector?->inspect(); + } catch (\Throwable) { + $reason = 'inspection'; } } - if (proc_get_status($process)['running']) { - proc_terminate($process); - usleep(self::POLL_INTERVAL_US); - if (proc_get_status($process)['running']) { - proc_terminate($process, 9); - } - } - } - - private static function inspect(string $directory, int $maxBytes, int $maxEntries): ?string { - if (!is_dir($directory)) { - return null; - } - clearstatcache(true); - $bytes = 0; - $entries = 0; - $iterator = new \RecursiveIteratorIterator( - new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS), - \RecursiveIteratorIterator::SELF_FIRST, - ); - foreach ($iterator as $entry) { - if ($entry->isLink()) { - return 'symlink'; - } - if (++$entries > $maxEntries) { - return 'entries'; - } - if (!$entry->isDir()) { - $size = $entry->getSize(); - if ($size < 0 || $size > $maxBytes - $bytes) { - return 'size'; - } - $bytes += $size; - } + if ($reason === null && $exitCode !== 0) { + $reason = 'exit'; } - return null; + return ['success' => $reason === null, 'reason' => $reason ?? '', 'output' => $process->output()]; } } diff --git a/lib/Service/StagingBudgetInspector.php b/lib/Service/StagingBudgetInspector.php new file mode 100644 index 0000000..679a9e6 --- /dev/null +++ b/lib/Service/StagingBudgetInspector.php @@ -0,0 +1,60 @@ +directory)) { + return 'symlink'; + } + if (!is_dir($this->directory)) { + return file_exists($this->directory) ? 'inspection' : null; + } + $bytes = 0; + $entries = 0; + $iterator = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($this->directory, \FilesystemIterator::SKIP_DOTS), + \RecursiveIteratorIterator::SELF_FIRST, + ); + foreach ($iterator as $entry) { + if ($entry->isLink()) { + return 'symlink'; + } + if (++$entries > $this->maxEntries) { + return 'entries'; + } + if (!$entry->isDir()) { + // Fail closed for device nodes, pipes and sockets in staging. + if (!$entry->isFile()) { + return 'inspection'; + } + $size = $entry->getSize(); + if ($size < 0 || $size > $this->maxBytes - $bytes) { + return 'size'; + } + $bytes += $size; + } + } + return null; + } +} From 402f96d02451de915ab2f0a5c6ed8cfd18678c14 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:56:09 +0000 Subject: [PATCH 15/23] test: exercise staging budget checks without launching decoders Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- tests/unit/StagingBudgetInspectorTest.php | 79 +++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 tests/unit/StagingBudgetInspectorTest.php diff --git a/tests/unit/StagingBudgetInspectorTest.php b/tests/unit/StagingBudgetInspectorTest.php new file mode 100644 index 0000000..62ef333 --- /dev/null +++ b/tests/unit/StagingBudgetInspectorTest.php @@ -0,0 +1,79 @@ +directory = sys_get_temp_dir() . '/extract-inspector-' . bin2hex(random_bytes(8)); + self::assertTrue(mkdir($this->directory, 0700)); + } + + protected function tearDown(): void { + if (isset($this->directory) && is_dir($this->directory)) { + $iterator = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($this->directory, \FilesystemIterator::SKIP_DOTS), + \RecursiveIteratorIterator::CHILD_FIRST, + ); + foreach ($iterator as $entry) { + if ($entry->isDir() && !$entry->isLink()) { + rmdir($entry->getPathname()); + } else { + unlink($entry->getPathname()); + } + } + rmdir($this->directory); + } + parent::tearDown(); + } + + public function testAcceptsNestedContentWithinLimits(): void { + self::assertTrue(mkdir($this->directory . '/nested', 0700)); + self::assertSame(5, file_put_contents($this->directory . '/nested/file', 'hello')); + self::assertNull((new StagingBudgetInspector($this->directory, 5, 2))->inspect()); + } + + public function testRejectsExcessBytes(): void { + self::assertSame(6, file_put_contents($this->directory . '/file', '123456')); + self::assertSame('size', (new StagingBudgetInspector($this->directory, 5, 1))->inspect()); + } + + public function testRejectsExcessEntriesIncludingDirectories(): void { + self::assertTrue(mkdir($this->directory . '/nested', 0700)); + self::assertSame(1, file_put_contents($this->directory . '/nested/file', 'x')); + self::assertSame('entries', (new StagingBudgetInspector($this->directory, 100, 1))->inspect()); + } + + public function testRejectsSymlinkWithoutFollowingIt(): void { + if (!function_exists('symlink')) { + self::markTestSkipped('Symlinks are not available'); + } + self::assertTrue(symlink('/etc/passwd', $this->directory . '/link')); + self::assertSame('symlink', (new StagingBudgetInspector($this->directory, 100, 10))->inspect()); + } + + public function testAbsentOutputDirectoryHasNoContent(): void { + self::assertNull((new StagingBudgetInspector($this->directory . '/not-yet-created', 100, 5))->inspect()); + } + + public function testRejectsSymlinkUsedAsOutputDirectory(): void { + if (!function_exists('symlink')) { + self::markTestSkipped('Symlinks are not available'); + } + $alias = $this->directory . '/alias'; + self::assertTrue(symlink('/tmp', $alias)); + self::assertSame('symlink', (new StagingBudgetInspector($alias, 100, 10))->inspect()); + } +} From 9e17c286fbc2333e220a5751681a087cb0565607 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:57:08 +0000 Subject: [PATCH 16/23] style: format decoder process constructor Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/DecoderProcess.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/Service/DecoderProcess.php b/lib/Service/DecoderProcess.php index 9f310c1..70b7b07 100644 --- a/lib/Service/DecoderProcess.php +++ b/lib/Service/DecoderProcess.php @@ -30,7 +30,11 @@ final class DecoderProcess { * @param resource $process * @param array $pipes */ - private function __construct($process, array $pipes, private readonly bool $isolated) { + private function __construct( + $process, + array $pipes, + private readonly bool $isolated, + ) { $this->process = $process; $this->pipes = $pipes; } From 74f7e319f4f28ff532144be264fe29c5bbd2f47f Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:11:48 +0000 Subject: [PATCH 17/23] refactor: isolate archive safety rules and extraction limit configuration Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/ArchiveSafetyValidator.php | 48 ++++++ lib/Service/ExtractionLimits.php | 47 ++++++ lib/Service/ExtractionService.php | 190 ++-------------------- tests/unit/ArchiveSafetyValidatorTest.php | 46 ++++++ tests/unit/ExtractionLimitsTest.php | 31 ++++ 5 files changed, 188 insertions(+), 174 deletions(-) create mode 100644 lib/Service/ArchiveSafetyValidator.php create mode 100644 lib/Service/ExtractionLimits.php create mode 100644 tests/unit/ArchiveSafetyValidatorTest.php create mode 100644 tests/unit/ExtractionLimitsTest.php diff --git a/lib/Service/ArchiveSafetyValidator.php b/lib/Service/ArchiveSafetyValidator.php new file mode 100644 index 0000000..72424da --- /dev/null +++ b/lib/Service/ArchiveSafetyValidator.php @@ -0,0 +1,48 @@ + + * SPDX-FileCopyrightText: 2022 Claus-Justus Heine + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace OCA\Extract\Service; + +use OCP\IL10N; +use Psr\Log\LoggerInterface; + +/** Validate entry names and archive metadata independently from decoders. */ +final class ArchiveSafetyValidator { + public function __construct(private IL10N $l, private LoggerInterface $logger) { + } + + private function isUnsafePath(string $entry): bool { + $path = str_replace('\\', '/', $entry); + if (preg_match('/[\x00-\x1f\x7f]/', $entry) === 1) { + return true; + } + if (str_starts_with($path, '/') || preg_match('/^[a-zA-Z]:/', $path) === 1) { + return true; + } + return preg_match('#(^|/)\.\.($|/)#', $path) === 1; + } + + public function rejectUnsafe(string $entry): ?array { + if (!$this->isUnsafePath($entry)) { + return null; + } + $this->logger->warning('Refusing archive with unsafe entry'); + return ['code' => 0, 'desc' => $this->l->t('Archive contains an unsafe path and was not extracted')]; + } + + public function rejectUnsafeMetadata(string $line): ?array { + if (preg_match('/^(?:Symbolic Link|Hard Link|Junction|Reparse Point)\s*=\s*\S/i', $line) !== 1 + && !(str_starts_with($line, 'Attributes = ') + && preg_match('/(?:^|\s)[lbpcs][-rwxstST]{9}(?:\s|$)/', $line) === 1)) { + return null; + } + $this->logger->warning('Refusing archive with links or special files'); + return ['code' => 0, 'desc' => $this->l->t('Archive contains links or unsupported special files')]; + } +} diff --git a/lib/Service/ExtractionLimits.php b/lib/Service/ExtractionLimits.php new file mode 100644 index 0000000..e7586e6 --- /dev/null +++ b/lib/Service/ExtractionLimits.php @@ -0,0 +1,47 @@ + + * SPDX-FileCopyrightText: 2022 Claus-Justus Heine + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace OCA\Extract\Service; + +use OCP\IConfig; + +/** Resolve positive application limits without exposing configuration parsing. */ +final class ExtractionLimits { + public function __construct(private IConfig $config) { + } + + public function configuredLimit(string $key, int $default): int { + $value = $this->config->getAppValue('extract', $key, (string)$default); + if (!is_string($value) || filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) === false) { + return $default; + } + return (int)$value; + } + + /** Calculate the staging budget consistently across ZIP, RAR and CLI. */ + public function byteBudget(string $extractTo, ?int $availableBytes): int { + $limit = $this->configuredLimit('max_extracted_bytes', 2147483648); + if ($availableBytes !== null && $availableBytes >= 0) { + $limit = min($limit, $availableBytes); + } + $space = disk_free_space(dirname($extractTo)); + if ($space !== false) { + $limit = min($limit, (int)$space); + } + return $limit; + } + + public function entryLimit(): int { + return $this->configuredLimit('max_archive_entries', 10000); + } + + public function timeout(): int { + return $this->configuredLimit('max_extraction_seconds', 300); + } +} diff --git a/lib/Service/ExtractionService.php b/lib/Service/ExtractionService.php index 0d19d11..1f1e79b 100644 --- a/lib/Service/ExtractionService.php +++ b/lib/Service/ExtractionService.php @@ -19,183 +19,25 @@ final class ExtractionService { private const MAX_ARCHIVE_LISTING_BYTES = 16777216; private const ARCHIVE_LIST_TIMEOUT_SECONDS = 20; + private ArchiveSafetyValidator $safety; + private ExtractionLimits $limits; + public function __construct( private IL10N $l, private LoggerInterface $logger, private IConfig $config, ) { + $this->safety = new ArchiveSafetyValidator($l, $logger); + $this->limits = new ExtractionLimits($config); } - /** - * Reject archive names that may escape the extraction staging directory, - * including absolute, Windows drive and traversal paths. - */ - private function isUnsafePath(string $entry): bool { - $path = str_replace('\\', '/', $entry); - if (preg_match('/[\x00-\x1f\x7f]/', $entry) === 1) { - return true; - } - if (str_starts_with($path, '/') || preg_match('/^[a-zA-Z]:/', $path) === 1) { - return true; - } - return preg_match('#(^|/)\.\.($|/)#', $path) === 1; - } - /** @return null|array{code: 0, desc: string} */ - private function rejectUnsafe(string $entry): ?array { - if (!$this->isUnsafePath($entry)) { - return null; - } - $this->logger->warning('Refusing archive with unsafe entry'); - return ['code' => 0, 'desc' => $this->l->t('Archive contains an unsafe path and was not extracted')]; - } - /** @return null|array{code: 0, desc: string} */ - private function assertSafeZip(ZipArchive $zip): ?array { - for ($i = 0; $i < $zip->numFiles; $i++) { - $name = $zip->getNameIndex($i); - if ($name === false) { - return ['code' => 0, 'desc' => $this->l->t('Failed to read archive index')]; - } - if ($error = $this->rejectUnsafe($name)) { - return $error; - } - } - return null; - } - /** - * Run archive listing with a bounded output size and an execution deadline. - * - * @param non-empty-list $command - * @return ?list - */ - private function listWithLimits(array $command): ?array { - $result = ResourceLimitedProcess::capture( - $command, - self::MAX_ARCHIVE_LISTING_BYTES, - self::ARCHIVE_LIST_TIMEOUT_SECONDS, - ); - if (!$result['success']) { - $this->logger->warning('Archive listing rejected: ' . $result['reason']); - return null; - } - return explode("\n", $result['output']); - } - /** - * Refuse archive links and special nodes before starting any extractor. - * A periodic filesystem scan does not prevent intermediate unsafe writes. - * - * @return null|array{code: 0, desc: string} - */ - private function rejectUnsafeMetadata(string $line): ?array { - if (preg_match('/^(?:Symbolic Link|Hard Link|Junction|Reparse Point)\s*=\s*\S/i', $line) !== 1 - && !(str_starts_with($line, 'Attributes = ') - && preg_match('/(?:^|\s)[lbpcs][-rwxstST]{9}(?:\s|$)/', $line) === 1)) { - return null; - } - $this->logger->warning('Refusing archive with links or special files'); - return ['code' => 0, 'desc' => $this->l->t('Archive contains links or unsupported special files')]; - } - /** @return null|array{code: 0, desc: string} */ - private function assertSafeRarShell(string $file): ?array { - $output = $this->listWithLimits(['unrar', 'lb', $file]); - if ($output === null) { - return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; - } - foreach ($output as $entry) { - $entry = rtrim($entry, "\r"); - if ($entry !== '' && ($error = $this->rejectUnsafe($entry))) { - return $error; - } - } - // The plain filename list does not reveal links. Inspect entry types - // before extraction, using 7z technical metadata when available. - if ($this->isCommandAvailable('7z')) { - return $this->assertSafeRarSevenZip($file); - } - $details = $this->listWithLimits(['unrar', 'lt', $file]); - if ($details === null) { - return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; - } - $types = 0; - foreach ($details as $line) { - if (preg_match('/^\s*Type\s*:\s*(.+)$/i', $line, $match) === 1) { - $types++; - if (preg_match('/^(?:File|Directory)$/i', trim($match[1])) !== 1) { - return ['code' => 0, 'desc' => $this->l->t('Archive contains links or unsupported special files')]; - } - } - } - if ($types === 0) { - return ['code' => 0, 'desc' => $this->l->t('Could not verify RAR entry types')]; - } - return null; - } - /** - * Validate 7za archive paths and reject metadata announcing extraction - * beyond the available quota, staging space, or configured resource caps. - * The external decoder may still misreport sizes; this is a preflight, - * not a substitute for process-level disk isolation. - * - * @return null|array{code: 0, desc: string} - */ - private function assertSafe7z(string $file, ?int $availableBytes, ?int $temporarySpace): ?array { - $output = $this->listWithLimits(['7za', 'l', '-ba', '-slt', $file]); - if ($output === null) { - return ['code' => 0, 'desc' => $this->l->t('Failed to inspect archive contents')]; - } - $budget = $this->configuredLimit('max_extracted_bytes', self::DEFAULT_MAX_EXTRACTED_BYTES); - if ($availableBytes !== null && $availableBytes >= 0) { - $budget = min($budget, $availableBytes); - } - if ($temporarySpace !== null && $temporarySpace >= 0) { - $budget = min($budget, $temporarySpace); - } - $entryLimit = $this->configuredLimit('max_archive_entries', self::DEFAULT_MAX_ARCHIVE_ENTRIES); - $entries = 0; - $size = 0; - foreach ($output as $line) { - $line = rtrim($line, "\r"); - if ($error = $this->rejectUnsafeMetadata($line)) { - return $error; - } - if (str_starts_with($line, 'Path = ')) { - if ($error = $this->rejectUnsafe(substr($line, 7))) { - return $error; - } - $entries++; - if ($entries > $entryLimit) { - return ['code' => 0, 'desc' => $this->l->t('Archive contains too many files')]; - } - } elseif (str_starts_with($line, 'Size = ')) { - $declaredSize = filter_var(trim(substr($line, 7)), FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]]); - if ($declaredSize === false) { - return ['code' => 0, 'desc' => $this->l->t('Failed to inspect archive contents')]; - } - if ($declaredSize > $budget - $size) { - return ['code' => 0, 'desc' => $this->l->t('Archive exceeds the allowed extraction size')]; - } - $size += $declaredSize; - } - } - return null; - } - /** - * Read a positive integer resource limit from application configuration. - * Invalid or overflowing values are ignored instead of disabling protection. - */ - private function configuredLimit(string $key, int $default): int { - $value = $this->config->getAppValue('extract', $key, (string)$default); - if (!is_string($value) || filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) === false) { - return $default; - } - return (int)$value; - } /** * Extract ZIP entries through bounded streams, never via an unbounded @@ -221,7 +63,7 @@ public function extractZip(string $file, string $extractTo, ?int $availableBytes return $error; } - $limit = $this->configuredLimit('max_extracted_bytes', self::DEFAULT_MAX_EXTRACTED_BYTES); + $limit = $this->limits->configuredLimit('max_extracted_bytes', self::DEFAULT_MAX_EXTRACTED_BYTES); if ($availableBytes !== null && $availableBytes >= 0) { $limit = min($limit, $availableBytes); } @@ -229,7 +71,7 @@ public function extractZip(string $file, string $extractTo, ?int $availableBytes if ($temporarySpace !== false) { $limit = min($limit, (int)$temporarySpace); } - if ($zip->numFiles > $this->configuredLimit('max_archive_entries', self::DEFAULT_MAX_ARCHIVE_ENTRIES)) { + if ($zip->numFiles > $this->limits->configuredLimit('max_archive_entries', self::DEFAULT_MAX_ARCHIVE_ENTRIES)) { return ['code' => 0, 'desc' => $this->l->t('Archive contains too many files')]; } @@ -327,7 +169,7 @@ public function extractZip(string $file, string $extractTo, ?int $availableBytes * @return array{code: 0|1, desc?: string} */ private function runExternalDecoder(array $command, string $extractTo, ?int $availableBytes = null): array { - $limit = $this->configuredLimit('max_extracted_bytes', self::DEFAULT_MAX_EXTRACTED_BYTES); + $limit = $this->limits->configuredLimit('max_extracted_bytes', self::DEFAULT_MAX_EXTRACTED_BYTES); if ($availableBytes !== null && $availableBytes >= 0) { $limit = min($limit, $availableBytes); } @@ -339,8 +181,8 @@ private function runExternalDecoder(array $command, string $extractTo, ?int $ava $command, $extractTo, $limit, - $this->configuredLimit('max_archive_entries', self::DEFAULT_MAX_ARCHIVE_ENTRIES), - $this->configuredLimit('max_extraction_seconds', 300), + $this->limits->configuredLimit('max_archive_entries', self::DEFAULT_MAX_ARCHIVE_ENTRIES), + $this->limits->configuredLimit('max_extraction_seconds', 300), ); if (!$result['success']) { $this->logger->warning('Archive decoder stopped: ' . $result['reason']); @@ -447,9 +289,9 @@ private function extractRarWithPhpExtension(string $file, string $extractTo, ?in if ($entries === false) { return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; } - $entryLimit = $this->configuredLimit('max_archive_entries', self::DEFAULT_MAX_ARCHIVE_ENTRIES); + $entryLimit = $this->limits->configuredLimit('max_archive_entries', self::DEFAULT_MAX_ARCHIVE_ENTRIES); $entryCount = 0; - $budget = $this->configuredLimit('max_extracted_bytes', self::DEFAULT_MAX_EXTRACTED_BYTES); + $budget = $this->limits->configuredLimit('max_extracted_bytes', self::DEFAULT_MAX_EXTRACTED_BYTES); if ($availableBytes !== null && $availableBytes >= 0) { $budget = min($budget, $availableBytes); } @@ -468,7 +310,7 @@ private function extractRarWithPhpExtension(string $file, string $extractTo, ?in if ($relative === '' || preg_match('//u', $relative) !== 1 || isset($paths[$relative])) { return ['code' => 0, 'desc' => $this->l->t('Archive contains an invalid filename')]; } - if ($error = $this->rejectUnsafe($name)) { + if ($error = $this->safety->rejectUnsafe($name)) { return $error; } $paths[$relative] = true; @@ -494,7 +336,7 @@ private function extractRarWithPhpExtension(string $file, string $extractTo, ?in return ['code' => 0, 'desc' => $this->l->t('Could not prepare extraction directory')]; } $written = 0; - $deadline = hrtime(true) + min($this->configuredLimit('max_extraction_seconds', 300), 3600) * 1000000000; + $deadline = hrtime(true) + min($this->limits->configuredLimit('max_extraction_seconds', 300), 3600) * 1000000000; foreach ($entries as $entry) { $name = rtrim(str_replace('\\', '/', $entry->getName()), '/'); $target = $extractTo . '/' . $name; @@ -559,11 +401,11 @@ private function assertSafeRarSevenZip(string $file): ?array { } foreach ($output as $line) { $line = rtrim($line, "\r"); - if ($error = $this->rejectUnsafeMetadata($line)) { + if ($error = $this->safety->rejectUnsafeMetadata($line)) { return $error; } if (str_starts_with($line, 'Path = ')) { - if ($error = $this->rejectUnsafe(substr($line, 7))) { + if ($error = $this->safety->rejectUnsafe(substr($line, 7))) { return $error; } } diff --git a/tests/unit/ArchiveSafetyValidatorTest.php b/tests/unit/ArchiveSafetyValidatorTest.php new file mode 100644 index 0000000..5a5a012 --- /dev/null +++ b/tests/unit/ArchiveSafetyValidatorTest.php @@ -0,0 +1,46 @@ + + * SPDX-FileCopyrightText: 2022 Claus-Justus Heine + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace OCA\Extract\Tests\unit; + +use OCA\Extract\Service\ArchiveSafetyValidator; +use OCP\IL10N; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +final class ArchiveSafetyValidatorTest extends TestCase { + private ArchiveSafetyValidator $validator; + + protected function setUp(): void { + $l10n = $this->createStub(IL10N::class); + $l10n->method('t')->willReturnCallback(static fn (string $s): string => $s); + $this->validator = new ArchiveSafetyValidator($l10n, $this->createStub(LoggerInterface::class)); + } + + public function testRejectsTraversalAndAbsoluteNames(): void { + foreach (['../outside', 'a/../../outside', '/etc/passwd', 'C:\\\\Windows\\\\secret', 'some/..\\\\outside', "bad\\0name"] as $name) { + self::assertSame(0, $this->validator->rejectUnsafe($name)['code'], $name); + } + } + + public function testAcceptsValidUnicodeAndNestedNames(): void { + foreach (['Café.txt', '한국어/전자책.txt', 'dir/sub/file.txt'] as $name) { + self::assertNull($this->validator->rejectUnsafe($name), $name); + } + } + + public function testRejectsActualLinksButNotEmptyLinkFields(): void { + foreach (['Symbolic Link = ../out', 'Hard Link = file', 'Attributes = A lrwxrwxrwx'] as $line) { + self::assertSame(0, $this->validator->rejectUnsafeMetadata($line)['code']); + } + foreach (['Symbolic Link = ', 'Hard Link = ', 'Attributes = RA', 'Attributes = A -rw-r--r--'] as $line) { + self::assertNull($this->validator->rejectUnsafeMetadata($line)); + } + } +} diff --git a/tests/unit/ExtractionLimitsTest.php b/tests/unit/ExtractionLimitsTest.php new file mode 100644 index 0000000..fb8d7a5 --- /dev/null +++ b/tests/unit/ExtractionLimitsTest.php @@ -0,0 +1,31 @@ + + * SPDX-FileCopyrightText: 2022 Claus-Justus Heine + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace OCA\Extract\Tests\unit; + +use OCA\Extract\Service\ExtractionLimits; +use OCP\IConfig; +use PHPUnit\Framework\TestCase; + +final class ExtractionLimitsTest extends TestCase { + public function testInvalidLimitsFallBackToSafeDefaults(): void { + $config = $this->createStub(IConfig::class); + $config->method('getAppValue')->willReturnCallback(static fn (string $app, string $key, string $default): string => 'not-an-int'); + $limits = new ExtractionLimits($config); + self::assertSame(10000, $limits->entryLimit()); + self::assertSame(300, $limits->timeout()); + } + + public function testQuotaCanOnlyReduceTheBudget(): void { + $config = $this->createStub(IConfig::class); + $config->method('getAppValue')->willReturnCallback(static fn (string $app, string $key, string $default): string => $default); + $limits = new ExtractionLimits($config); + self::assertSame(15, $limits->byteBudget(sys_get_temp_dir() . '/extract-limits-destination', 15)); + } +} From 5e05bedff9f962742ac88d601b259f5de8ea88f4 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:12:14 +0000 Subject: [PATCH 18/23] fix: preserve CLI preflight methods during service extraction Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/ExtractionService.php | 119 ++++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) diff --git a/lib/Service/ExtractionService.php b/lib/Service/ExtractionService.php index 1f1e79b..a1e4729 100644 --- a/lib/Service/ExtractionService.php +++ b/lib/Service/ExtractionService.php @@ -35,7 +35,126 @@ public function __construct( + /** @return null|array{code: 0, desc: string} */ + private function assertSafeZip(ZipArchive $zip): ?array { + for ($i = 0; $i < $zip->numFiles; $i++) { + $name = $zip->getNameIndex($i); + if ($name === false) { + return ['code' => 0, 'desc' => $this->l->t('Failed to read archive index')]; + } + if ($error = $this->safety->rejectUnsafe($name)) { + return $error; + } + } + return null; + } + + /** + * Run archive listing with a bounded output size and an execution deadline. + * + * @param non-empty-list $command + * @return ?list + */ + private function listWithLimits(array $command): ?array { + $result = ResourceLimitedProcess::capture( + $command, + self::MAX_ARCHIVE_LISTING_BYTES, + self::ARCHIVE_LIST_TIMEOUT_SECONDS, + ); + if (!$result['success']) { + $this->logger->warning('Archive listing rejected: ' . $result['reason']); + return null; + } + return explode("\n", $result['output']); + } + + + + /** @return null|array{code: 0, desc: string} */ + private function assertSafeRarShell(string $file): ?array { + $output = $this->listWithLimits(['unrar', 'lb', $file]); + if ($output === null) { + return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; + } + foreach ($output as $entry) { + $entry = rtrim($entry, "\r"); + if ($entry !== '' && ($error = $this->safety->rejectUnsafe($entry))) { + return $error; + } + } + // The plain filename list does not reveal links. Inspect entry types + // before extraction, using 7z technical metadata when available. + if ($this->isCommandAvailable('7z')) { + return $this->assertSafeRarSevenZip($file); + } + $details = $this->listWithLimits(['unrar', 'lt', $file]); + if ($details === null) { + return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; + } + $types = 0; + foreach ($details as $line) { + if (preg_match('/^\s*Type\s*:\s*(.+)$/i', $line, $match) === 1) { + $types++; + if (preg_match('/^(?:File|Directory)$/i', trim($match[1])) !== 1) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains links or unsupported special files')]; + } + } + } + if ($types === 0) { + return ['code' => 0, 'desc' => $this->l->t('Could not verify RAR entry types')]; + } + return null; + } + /** + * Validate 7za archive paths and reject metadata announcing extraction + * beyond the available quota, staging space, or configured resource caps. + * The external decoder may still misreport sizes; this is a preflight, + * not a substitute for process-level disk isolation. + * + * @return null|array{code: 0, desc: string} + */ + private function assertSafe7z(string $file, ?int $availableBytes, ?int $temporarySpace): ?array { + $output = $this->listWithLimits(['7za', 'l', '-ba', '-slt', $file]); + if ($output === null) { + return ['code' => 0, 'desc' => $this->l->t('Failed to inspect archive contents')]; + } + $budget = $this->limits->configuredLimit('max_extracted_bytes', self::DEFAULT_MAX_EXTRACTED_BYTES); + if ($availableBytes !== null && $availableBytes >= 0) { + $budget = min($budget, $availableBytes); + } + if ($temporarySpace !== null && $temporarySpace >= 0) { + $budget = min($budget, $temporarySpace); + } + $entryLimit = $this->limits->configuredLimit('max_archive_entries', self::DEFAULT_MAX_ARCHIVE_ENTRIES); + $entries = 0; + $size = 0; + foreach ($output as $line) { + $line = rtrim($line, "\r"); + if ($error = $this->safety->rejectUnsafeMetadata($line)) { + return $error; + } + if (str_starts_with($line, 'Path = ')) { + if ($error = $this->safety->rejectUnsafe(substr($line, 7))) { + return $error; + } + $entries++; + if ($entries > $entryLimit) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains too many files')]; + } + } elseif (str_starts_with($line, 'Size = ')) { + $declaredSize = filter_var(trim(substr($line, 7)), FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]]); + if ($declaredSize === false) { + return ['code' => 0, 'desc' => $this->l->t('Failed to inspect archive contents')]; + } + if ($declaredSize > $budget - $size) { + return ['code' => 0, 'desc' => $this->l->t('Archive exceeds the allowed extraction size')]; + } + $size += $declaredSize; + } + } + return null; + } From 36f228ac5a54903d0149bc9a2bbf70c625feb8b0 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:12:57 +0000 Subject: [PATCH 19/23] refactor: consolidate bounded ZIP and RAR streaming into tested copier Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/BoundedStreamCopier.php | 77 ++++++++++++++++++++ lib/Service/ExtractionService.php | 76 ++------------------ tests/unit/ArchiveSafetyValidatorTest.php | 2 +- tests/unit/BoundedStreamCopierTest.php | 87 +++++++++++++++++++++++ tests/unit/ExtractionServiceTest.php | 44 ------------ 5 files changed, 170 insertions(+), 116 deletions(-) create mode 100644 lib/Service/BoundedStreamCopier.php create mode 100644 tests/unit/BoundedStreamCopierTest.php diff --git a/lib/Service/BoundedStreamCopier.php b/lib/Service/BoundedStreamCopier.php new file mode 100644 index 0000000..512792c --- /dev/null +++ b/lib/Service/BoundedStreamCopier.php @@ -0,0 +1,77 @@ + + * SPDX-FileCopyrightText: 2022 Claus-Justus Heine + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace OCA\Extract\Service; + +/** + * Copy decoded bytes with one cumulative budget and optional size, deadline + * and CRC requirements. Input ownership remains with the calling extractor. + */ +final class BoundedStreamCopier { + /** + * @param resource $input + */ + public function copy( + $input, + string $target, + int &$written, + int $budget, + ?int $expectedBytes = null, + ?string $expectedCrc = null, + ?int $deadline = null, + ): bool { + if ($budget < 0 || $written < 0 || $written > $budget || ($expectedBytes !== null && $expectedBytes < 0)) { + return false; + } + // Preserve ZIP overwrite semantics; RAR entries must never overwrite. + $output = fopen($target, $expectedBytes === null ? 'wb' : 'xb'); + if ($output === false) { + return false; + } + $entryBytes = 0; + $hash = $expectedCrc !== null ? hash_init('crc32b') : null; + try { + while (!feof($input)) { + if ($deadline !== null && hrtime(true) >= $deadline) { + return false; + } + $chunk = fread($input, 65536); + if ($chunk === false || ($chunk === '' && !feof($input))) { + return false; + } + $length = strlen($chunk); + if ($length > $budget - $written || ($expectedBytes !== null && $length > $expectedBytes - $entryBytes)) { + return false; + } + $offset = 0; + while ($offset < $length) { + if ($deadline !== null && hrtime(true) >= $deadline) { + return false; + } + $count = fwrite($output, substr($chunk, $offset)); + if ($count === false || $count === 0) { + return false; + } + $offset += $count; + } + if ($hash !== null) { + hash_update($hash, $chunk); + } + $entryBytes += $length; + $written += $length; + } + } finally { + fclose($output); + } + if ($expectedBytes !== null && $entryBytes !== $expectedBytes) { + return false; + } + return $hash === null || hash_equals(strtolower($expectedCrc), hash_final($hash)); + } +} diff --git a/lib/Service/ExtractionService.php b/lib/Service/ExtractionService.php index a1e4729..c1550a2 100644 --- a/lib/Service/ExtractionService.php +++ b/lib/Service/ExtractionService.php @@ -21,6 +21,7 @@ final class ExtractionService { private ArchiveSafetyValidator $safety; private ExtractionLimits $limits; + private BoundedStreamCopier $copier; public function __construct( private IL10N $l, @@ -29,6 +30,7 @@ public function __construct( ) { $this->safety = new ArchiveSafetyValidator($l, $logger); $this->limits = new ExtractionLimits($config); + $this->copier = new BoundedStreamCopier(); } @@ -239,32 +241,9 @@ public function extractZip(string $file, string $extractTo, ?int $availableBytes return ['code' => 0, 'desc' => $this->l->t('Could not extract Zip archive')]; } try { - $output = fopen($path, 'wb'); - if ($output === false) { + if (!$this->copier->copy($input, $path, $written, $limit)) { return ['code' => 0, 'desc' => $this->l->t('Could not extract Zip archive')]; } - try { - while (!feof($input)) { - $chunk = fread($input, 65536); - if ($chunk === false || ($chunk === '' && !feof($input))) { - return ['code' => 0, 'desc' => $this->l->t('Could not extract Zip archive')]; - } - if (strlen($chunk) > $limit - $written) { - return ['code' => 0, 'desc' => $this->l->t('Archive exceeds the allowed extraction size')]; - } - $written += strlen($chunk); - $offset = 0; - while ($offset < strlen($chunk)) { - $count = fwrite($output, substr($chunk, $offset)); - if ($count === false || $count === 0) { - return ['code' => 0, 'desc' => $this->l->t('Could not extract Zip archive')]; - } - $offset += $count; - } - } - } finally { - fclose($output); - } } finally { fclose($input); } @@ -344,52 +323,7 @@ public function extractRar(string $file, string $extractTo, ?int $availableBytes * * @psalm-return array{code: 0|1, desc?: string} */ - /** - * Stream a RAR entry into staging with strict per-entry and total-byte - * limits. Unlike RarEntry::extract(), PHP controls every output path. - * - * @param resource $input - */ - private function copyRarStream($input, string $target, int $expectedBytes, string $expectedCrc, int &$written, int $budget, int $deadline): bool { - $output = fopen($target, 'xb'); - if ($output === false) { - return false; - } - $size = 0; - $hash = hash_init('crc32b'); - try { - while (!feof($input)) { - if (hrtime(true) >= $deadline) { - return false; - } - $chunk = fread($input, 65536); - if ($chunk === false || ($chunk === '' && !feof($input))) { - return false; - } - $length = strlen($chunk); - if ($length > $budget - $written || $length > $expectedBytes - $size) { - return false; - } - $offset = 0; - while ($offset < $length) { - if (hrtime(true) >= $deadline) { - return false; - } - $count = fwrite($output, substr($chunk, $offset)); - if ($count === false || $count === 0) { - return false; - } - $offset += $count; - } - hash_update($hash, $chunk); - $size += $length; - $written += $length; - } - } finally { - fclose($output); - } - return $size === $expectedBytes && hash_equals(strtolower($expectedCrc), hash_final($hash)); - } + /** * The PHP RAR extension must not bypass quota checks or create archive @@ -477,7 +411,7 @@ private function extractRarWithPhpExtension(string $file, string $extractTo, ?in return ['code' => 0, 'desc' => $this->l->t('Could not read RAR entry')]; } try { - if (!$this->copyRarStream($input, $target, $entry->getUnpackedSize(), $crc, $written, $budget, $deadline)) { + if (!$this->copier->copy($input, $target, $written, $budget, $entry->getUnpackedSize(), $crc, $deadline)) { return ['code' => 0, 'desc' => $this->l->t('RAR extraction exceeded limits or failed integrity verification')]; } } finally { diff --git a/tests/unit/ArchiveSafetyValidatorTest.php b/tests/unit/ArchiveSafetyValidatorTest.php index 5a5a012..4c60458 100644 --- a/tests/unit/ArchiveSafetyValidatorTest.php +++ b/tests/unit/ArchiveSafetyValidatorTest.php @@ -24,7 +24,7 @@ protected function setUp(): void { } public function testRejectsTraversalAndAbsoluteNames(): void { - foreach (['../outside', 'a/../../outside', '/etc/passwd', 'C:\\\\Windows\\\\secret', 'some/..\\\\outside', "bad\\0name"] as $name) { + foreach (['../outside', 'a/../../outside', '/etc/passwd', 'C:\\\\Windows\\\\secret', 'some/..\\\\outside', "bad\0name"] as $name) { self::assertSame(0, $this->validator->rejectUnsafe($name)['code'], $name); } } diff --git a/tests/unit/BoundedStreamCopierTest.php b/tests/unit/BoundedStreamCopierTest.php new file mode 100644 index 0000000..7d9d6aa --- /dev/null +++ b/tests/unit/BoundedStreamCopierTest.php @@ -0,0 +1,87 @@ +directory = sys_get_temp_dir() . '/extract-copy-' . bin2hex(random_bytes(8)); + self::assertTrue(mkdir($this->directory, 0700)); + } + + protected function tearDown(): void { + foreach (glob($this->directory . '/*') ?: [] as $path) { + unlink($path); + } + rmdir($this->directory); + } + + private function stream(string $contents) { + $stream = fopen('php://temp', 'w+b'); + self::assertIsResource($stream); + fwrite($stream, $contents); + rewind($stream); + return $stream; + } + + public function testCopiesWithinBudgetAndVerifiesCrc(): void { + $stream = $this->stream('hello world'); + $written = 0; + try { + self::assertTrue((new BoundedStreamCopier())->copy($stream, $this->directory . '/good.txt', $written, 11, 11, hash('crc32b', 'hello world'))); + self::assertSame(11, $written); + self::assertSame('hello world', file_get_contents($this->directory . '/good.txt')); + } finally { + fclose($stream); + } + } + + public function testRejectsSizeOverflowAndWrongCrc(): void { + $stream = $this->stream('1234567890'); + $written = 0; + try { + self::assertFalse((new BoundedStreamCopier())->copy($stream, $this->directory . '/over.txt', $written, 9, 10, hash('crc32b', '1234567890'))); + self::assertSame(0, $written); + } finally { + fclose($stream); + } + $stream = $this->stream('hello'); + try { + self::assertFalse((new BoundedStreamCopier())->copy($stream, $this->directory . '/crc.txt', $written, 10, 5, 'deadbeef')); + } finally { + fclose($stream); + } + } + + public function testDoesNotOverwriteRarDestination(): void { + file_put_contents($this->directory . '/exists.txt', 'original'); + $stream = $this->stream('new'); + $written = 0; + try { + self::assertFalse((new BoundedStreamCopier())->copy($stream, $this->directory . '/exists.txt', $written, 100, 3, hash('crc32b', 'new'))); + self::assertSame('original', file_get_contents($this->directory . '/exists.txt')); + } finally { + fclose($stream); + } + } + + public function testCopyWithoutDeclaredSizeUsesZipSemantics(): void { + $stream = $this->stream('payload'); + $written = 0; + try { + self::assertTrue((new BoundedStreamCopier())->copy($stream, $this->directory . '/zip.txt', $written, 7)); + self::assertSame('payload', file_get_contents($this->directory . '/zip.txt')); + } finally { + fclose($stream); + } + } +} diff --git a/tests/unit/ExtractionServiceTest.php b/tests/unit/ExtractionServiceTest.php index f392e93..e04102d 100644 --- a/tests/unit/ExtractionServiceTest.php +++ b/tests/unit/ExtractionServiceTest.php @@ -264,51 +264,7 @@ public function testAllowsOrdinaryArchiveMetadata(): void { } } - /** - * The PHP RAR extraction path must enforce limits on actual stream bytes - * and check CRC, not trust only the archive's advertised size. - */ - public function testBoundedRarStreamPreservesDataAndRefusesInvalidCrc(): void { - $method = new \ReflectionMethod(ExtractionService::class, 'copyRarStream'); - $payload = 'hello world'; - $stream = fopen('php://temp', 'w+b'); - self::assertIsResource($stream); - fwrite($stream, $payload); - rewind($stream); - $written = 0; - try { - $arguments = [$stream, $this->tmpDir . '/good.txt', strlen($payload), hash('crc32b', $payload), &$written, strlen($payload), hrtime(true) + 2000000000]; - self::assertTrue($method->invokeArgs($this->service, $arguments)); - self::assertSame($payload, file_get_contents($this->tmpDir . '/good.txt')); - self::assertSame(strlen($payload), $written); - } finally { - fclose($stream); - } - $stream = fopen('php://temp', 'w+b'); - self::assertIsResource($stream); - fwrite($stream, $payload); - rewind($stream); - $written = 0; - try { - $arguments = [$stream, $this->tmpDir . '/limited.txt', strlen($payload), hash('crc32b', $payload), &$written, strlen($payload) - 1, hrtime(true) + 2000000000]; - self::assertFalse($method->invokeArgs($this->service, $arguments)); - } finally { - fclose($stream); - } - - $stream = fopen('php://temp', 'w+b'); - self::assertIsResource($stream); - fwrite($stream, $payload); - rewind($stream); - $written = 0; - try { - $arguments = [$stream, $this->tmpDir . '/corrupt.txt', strlen($payload), '00000000', &$written, strlen($payload), hrtime(true) + 2000000000]; - self::assertFalse($method->invokeArgs($this->service, $arguments)); - } finally { - fclose($stream); - } - } /** * A decompression bomb must be refused before staging any files when the From 2138f96641ed644d984094814b25c31e2d9425e8 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:13:26 +0000 Subject: [PATCH 20/23] refactor: move ZIP extraction into independently testable extractor Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/ExtractionService.php | 100 ++------------------------ lib/Service/ZipExtractor.php | 115 ++++++++++++++++++++++++++++++ tests/unit/ZipExtractorTest.php | 45 ++++++++++++ 3 files changed, 164 insertions(+), 96 deletions(-) create mode 100644 lib/Service/ZipExtractor.php create mode 100644 tests/unit/ZipExtractorTest.php diff --git a/lib/Service/ExtractionService.php b/lib/Service/ExtractionService.php index c1550a2..d7eb0b7 100644 --- a/lib/Service/ExtractionService.php +++ b/lib/Service/ExtractionService.php @@ -11,7 +11,6 @@ use OCP\IConfig; use OCP\IL10N; use Psr\Log\LoggerInterface; -use ZipArchive; final class ExtractionService { private const DEFAULT_MAX_EXTRACTED_BYTES = 2147483648; // 2 GiB @@ -22,6 +21,7 @@ final class ExtractionService { private ArchiveSafetyValidator $safety; private ExtractionLimits $limits; private BoundedStreamCopier $copier; + private ZipExtractor $zip; public function __construct( private IL10N $l, @@ -31,25 +31,14 @@ public function __construct( $this->safety = new ArchiveSafetyValidator($l, $logger); $this->limits = new ExtractionLimits($config); $this->copier = new BoundedStreamCopier(); + $this->zip = new ZipExtractor($l, $this->safety, $this->limits, $this->copier); } - /** @return null|array{code: 0, desc: string} */ - private function assertSafeZip(ZipArchive $zip): ?array { - for ($i = 0; $i < $zip->numFiles; $i++) { - $name = $zip->getNameIndex($i); - if ($name === false) { - return ['code' => 0, 'desc' => $this->l->t('Failed to read archive index')]; - } - if ($error = $this->safety->rejectUnsafe($name)) { - return $error; - } - } - return null; - } + /** * Run archive listing with a bounded output size and an execution deadline. @@ -170,88 +159,7 @@ private function assertSafe7z(string $file, ?int $availableBytes, ?int $temporar * @return array{code: 0|1, desc?: string} */ public function extractZip(string $file, string $extractTo, ?int $availableBytes = null): array { - if (!extension_loaded('zip')) { - return ['code' => 0, 'desc' => $this->l->t('Zip extension is not available')]; - } - - $zip = new ZipArchive(); - if ($zip->open($file) !== true) { - return ['code' => 0, 'desc' => $this->l->t('Cannot open Zip file')]; - } - - try { - if ($error = $this->assertSafeZip($zip)) { - return $error; - } - - $limit = $this->limits->configuredLimit('max_extracted_bytes', self::DEFAULT_MAX_EXTRACTED_BYTES); - if ($availableBytes !== null && $availableBytes >= 0) { - $limit = min($limit, $availableBytes); - } - $temporarySpace = disk_free_space(dirname($extractTo)); - if ($temporarySpace !== false) { - $limit = min($limit, (int)$temporarySpace); - } - if ($zip->numFiles > $this->limits->configuredLimit('max_archive_entries', self::DEFAULT_MAX_ARCHIVE_ENTRIES)) { - return ['code' => 0, 'desc' => $this->l->t('Archive contains too many files')]; - } - - // Check declared sizes before creating any staging content. Streaming - // below also enforces the actual size if metadata is dishonest. - $declared = 0; - for ($i = 0; $i < $zip->numFiles; $i++) { - $stat = $zip->statIndex($i); - if ($stat === false || !isset($stat['size']) || !is_int($stat['size']) || $stat['size'] < 0) { - return ['code' => 0, 'desc' => $this->l->t('Failed to inspect Zip contents')]; - } - if ($stat['size'] > $limit - $declared) { - return ['code' => 0, 'desc' => $this->l->t('Archive exceeds the allowed extraction size')]; - } - $declared += $stat['size']; - } - - if (!is_dir($extractTo) && !mkdir($extractTo, 0700, true)) { - return ['code' => 0, 'desc' => $this->l->t('Could not prepare extraction directory')]; - } - - $written = 0; - $seen = []; - for ($i = 0; $i < $zip->numFiles; $i++) { - $name = $zip->getNameIndex($i); - if ($name === false || $name === '' || preg_match('//u', $name) !== 1) { - return ['code' => 0, 'desc' => $this->l->t('Archive contains an invalid filename')]; - } - $relative = rtrim($name, '/'); - if (isset($seen[$relative])) { - return ['code' => 0, 'desc' => $this->l->t('Archive contains duplicate filenames')]; - } - $seen[$relative] = true; - $path = $extractTo . '/' . $relative; - if (str_ends_with($name, '/')) { - if (!is_dir($path) && !mkdir($path, 0700, true)) { - return ['code' => 0, 'desc' => $this->l->t('Could not extract Zip archive')]; - } - continue; - } - if (!is_dir(dirname($path)) && !mkdir(dirname($path), 0700, true)) { - return ['code' => 0, 'desc' => $this->l->t('Could not extract Zip archive')]; - } - $input = $zip->getStreamIndex($i); - if ($input === false) { - return ['code' => 0, 'desc' => $this->l->t('Could not extract Zip archive')]; - } - try { - if (!$this->copier->copy($input, $path, $written, $limit)) { - return ['code' => 0, 'desc' => $this->l->t('Could not extract Zip archive')]; - } - } finally { - fclose($input); - } - } - return ['code' => 1]; - } finally { - $zip->close(); - } + return $this->zip->extract($file, $extractTo, $availableBytes); } /** diff --git a/lib/Service/ZipExtractor.php b/lib/Service/ZipExtractor.php new file mode 100644 index 0000000..c3c1a79 --- /dev/null +++ b/lib/Service/ZipExtractor.php @@ -0,0 +1,115 @@ + + * SPDX-FileCopyrightText: 2022 Claus-Justus Heine + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace OCA\Extract\Service; + +use OCP\IL10N; +use ZipArchive; + +/** ZIP-specific archive inspection and bounded extraction. */ +final class ZipExtractor { + public function __construct( + private IL10N $l, + private ArchiveSafetyValidator $safety, + private ExtractionLimits $limits, + private BoundedStreamCopier $copier, + ) { + } + + private function assertSafeZip(ZipArchive $zip): ?array { + for ($i = 0; $i < $zip->numFiles; $i++) { + $name = $zip->getNameIndex($i); + if ($name === false) { + return ['code' => 0, 'desc' => $this->l->t('Failed to read archive index')]; + } + if ($error = $this->safety->rejectUnsafe($name)) { + return $error; + } + } + return null; + } + + public function extract(string $file, string $extractTo, ?int $availableBytes = null): array { + if (!extension_loaded('zip')) { + return ['code' => 0, 'desc' => $this->l->t('Zip extension is not available')]; + } + + $zip = new ZipArchive(); + if ($zip->open($file) !== true) { + return ['code' => 0, 'desc' => $this->l->t('Cannot open Zip file')]; + } + + try { + if ($error = $this->assertSafeZip($zip)) { + return $error; + } + + $limit = $this->limits->byteBudget($extractTo, $availableBytes); + if ($zip->numFiles > $this->limits->entryLimit()) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains too many files')]; + } + + // Check declared sizes before creating any staging content. Streaming + // below also enforces the actual size if metadata is dishonest. + $declared = 0; + for ($i = 0; $i < $zip->numFiles; $i++) { + $stat = $zip->statIndex($i); + if ($stat === false || !isset($stat['size']) || !is_int($stat['size']) || $stat['size'] < 0) { + return ['code' => 0, 'desc' => $this->l->t('Failed to inspect Zip contents')]; + } + if ($stat['size'] > $limit - $declared) { + return ['code' => 0, 'desc' => $this->l->t('Archive exceeds the allowed extraction size')]; + } + $declared += $stat['size']; + } + + if (!is_dir($extractTo) && !mkdir($extractTo, 0700, true)) { + return ['code' => 0, 'desc' => $this->l->t('Could not prepare extraction directory')]; + } + + $written = 0; + $seen = []; + for ($i = 0; $i < $zip->numFiles; $i++) { + $name = $zip->getNameIndex($i); + if ($name === false || $name === '' || preg_match('//u', $name) !== 1) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains an invalid filename')]; + } + $relative = rtrim($name, '/'); + if (isset($seen[$relative])) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains duplicate filenames')]; + } + $seen[$relative] = true; + $path = $extractTo . '/' . $relative; + if (str_ends_with($name, '/')) { + if (!is_dir($path) && !mkdir($path, 0700, true)) { + return ['code' => 0, 'desc' => $this->l->t('Could not extract Zip archive')]; + } + continue; + } + if (!is_dir(dirname($path)) && !mkdir(dirname($path), 0700, true)) { + return ['code' => 0, 'desc' => $this->l->t('Could not extract Zip archive')]; + } + $input = $zip->getStreamIndex($i); + if ($input === false) { + return ['code' => 0, 'desc' => $this->l->t('Could not extract Zip archive')]; + } + try { + if (!$this->copier->copy($input, $path, $written, $limit)) { + return ['code' => 0, 'desc' => $this->l->t('Could not extract Zip archive')]; + } + } finally { + fclose($input); + } + } + return ['code' => 1]; + } finally { + $zip->close(); + } + } +} diff --git a/tests/unit/ZipExtractorTest.php b/tests/unit/ZipExtractorTest.php new file mode 100644 index 0000000..46ccec3 --- /dev/null +++ b/tests/unit/ZipExtractorTest.php @@ -0,0 +1,45 @@ +open($archive, ZipArchive::CREATE | ZipArchive::OVERWRITE)); + self::assertTrue($zip->addFromString('../outside.txt', 'unsafe')); + $zip->close(); + + $l10n = $this->createStub(IL10N::class); + $l10n->method('t')->willReturnCallback(static fn (string $s): string => $s); + $validator = new ArchiveSafetyValidator($l10n, $this->createStub(LoggerInterface::class)); + $extractor = new ZipExtractor($l10n, $validator, new ExtractionLimits($this->createStub(IConfig::class)), new BoundedStreamCopier()); + $out = $directory . '/result'; + try { + $response = $extractor->extract($archive, $out); + self::assertSame(0, $response['code']); + self::assertDirectoryDoesNotExist($out); + self::assertFileDoesNotExist($directory . '/outside.txt'); + } finally { + unlink($archive); + rmdir($directory); + } + } +} From 170640371e50ce6b31eb1946eb6621e96a95de6a Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:14:08 +0000 Subject: [PATCH 21/23] refactor: isolate bounded PHP RAR extraction in dedicated service Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/ExtractionService.php | 98 +------------------------- lib/Service/PhpRarExtractor.php | 113 ++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+), 95 deletions(-) create mode 100644 lib/Service/PhpRarExtractor.php diff --git a/lib/Service/ExtractionService.php b/lib/Service/ExtractionService.php index d7eb0b7..a1a0bfd 100644 --- a/lib/Service/ExtractionService.php +++ b/lib/Service/ExtractionService.php @@ -22,6 +22,7 @@ final class ExtractionService { private ExtractionLimits $limits; private BoundedStreamCopier $copier; private ZipExtractor $zip; + private PhpRarExtractor $phpRar; public function __construct( private IL10N $l, @@ -32,6 +33,7 @@ public function __construct( $this->limits = new ExtractionLimits($config); $this->copier = new BoundedStreamCopier(); $this->zip = new ZipExtractor($l, $this->safety, $this->limits, $this->copier); + $this->phpRar = new PhpRarExtractor($l, $logger, $this->safety, $this->limits, $this->copier); } @@ -219,7 +221,7 @@ public function extractRar(string $file, string $extractTo, ?int $availableBytes return $result; } } else { - return $this->extractRarWithPhpExtension($file, $extractTo, $availableBytes); + return $this->phpRar->extract($file, $extractTo, $availableBytes); } $response = array_merge($response, ['code' => 1]); @@ -240,100 +242,6 @@ public function extractRar(string $file, string $extractTo, ?int $availableBytes * * @return array{code: 0|1, desc?: string} */ - private function extractRarWithPhpExtension(string $file, string $extractTo, ?int $availableBytes): array { - $archive = rar_open($file); - if ($archive === false) { - return ['code' => 0, 'desc' => $this->l->t('Cannot open Rar file')]; - } - try { - $entries = rar_list($archive); - if ($entries === false) { - return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; - } - $entryLimit = $this->limits->configuredLimit('max_archive_entries', self::DEFAULT_MAX_ARCHIVE_ENTRIES); - $entryCount = 0; - $budget = $this->limits->configuredLimit('max_extracted_bytes', self::DEFAULT_MAX_EXTRACTED_BYTES); - if ($availableBytes !== null && $availableBytes >= 0) { - $budget = min($budget, $availableBytes); - } - $space = disk_free_space(dirname($extractTo)); - if ($space !== false) { - $budget = min($budget, (int)$space); - } - $declared = 0; - $paths = []; - foreach ($entries as $entry) { - if (++$entryCount > $entryLimit) { - return ['code' => 0, 'desc' => $this->l->t('Archive contains too many files')]; - } - $name = str_replace('\\', '/', $entry->getName()); - $relative = rtrim($name, '/'); - if ($relative === '' || preg_match('//u', $relative) !== 1 || isset($paths[$relative])) { - return ['code' => 0, 'desc' => $this->l->t('Archive contains an invalid filename')]; - } - if ($error = $this->safety->rejectUnsafe($name)) { - return $error; - } - $paths[$relative] = true; - if ($entry->isEncrypted()) { - return ['code' => 0, 'desc' => $this->l->t('Encrypted RAR archives are not supported')]; - } - // Unix RAR4 entries can encode links and devices as native - // filesystem types. RAR5 redirects are never materialized: - // getStream() writes regular file bytes under PHP control. - if (defined('RAR_HOST_UNIX') && $entry->getHostOs() === constant('RAR_HOST_UNIX')) { - $type = $entry->getAttr() & 0xf000; - if ($type !== 0x8000 && $type !== 0x4000) { - return ['code' => 0, 'desc' => $this->l->t('Archive contains links or unsupported special files')]; - } - } - $size = $entry->getUnpackedSize(); - if ($size === false || $size < 0 || $size > $budget - $declared) { - return ['code' => 0, 'desc' => $this->l->t('Archive exceeds the allowed extraction size')]; - } - $declared += $size; - } - if (!is_dir($extractTo) && !mkdir($extractTo, 0700, true)) { - return ['code' => 0, 'desc' => $this->l->t('Could not prepare extraction directory')]; - } - $written = 0; - $deadline = hrtime(true) + min($this->limits->configuredLimit('max_extraction_seconds', 300), 3600) * 1000000000; - foreach ($entries as $entry) { - $name = rtrim(str_replace('\\', '/', $entry->getName()), '/'); - $target = $extractTo . '/' . $name; - if ($entry->isDirectory()) { - if (!is_dir($target) && !mkdir($target, 0700, true)) { - return ['code' => 0, 'desc' => $this->l->t('Could not extract RAR archive')]; - } - continue; - } - if (!is_dir(dirname($target)) && !mkdir(dirname($target), 0700, true)) { - return ['code' => 0, 'desc' => $this->l->t('Could not extract RAR archive')]; - } - $crc = $entry->getCrc(); - if (!is_string($crc) || preg_match('/^[0-9a-fA-F]{8}$/', $crc) !== 1) { - return ['code' => 0, 'desc' => $this->l->t('Could not verify RAR entry integrity')]; - } - $input = $entry->getStream(); - if ($input === false) { - return ['code' => 0, 'desc' => $this->l->t('Could not read RAR entry')]; - } - try { - if (!$this->copier->copy($input, $target, $written, $budget, $entry->getUnpackedSize(), $crc, $deadline)) { - return ['code' => 0, 'desc' => $this->l->t('RAR extraction exceeded limits or failed integrity verification')]; - } - } finally { - fclose($input); - } - } - return ['code' => 1]; - } catch (\Throwable $e) { - $this->logger->warning('RAR stream extraction failed: ' . $e->getMessage()); - return ['code' => 0, 'desc' => $this->l->t('Could not extract RAR archive')]; - } finally { - rar_close($archive); - } - } public function extractOther(string $file, string $extractTo, ?int $availableBytes = null): array { diff --git a/lib/Service/PhpRarExtractor.php b/lib/Service/PhpRarExtractor.php new file mode 100644 index 0000000..a83b53b --- /dev/null +++ b/lib/Service/PhpRarExtractor.php @@ -0,0 +1,113 @@ + + * SPDX-FileCopyrightText: 2022 Claus-Justus Heine + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace OCA\Extract\Service; + +use OCP\IL10N; +use Psr\Log\LoggerInterface; + +/** Extract via the optional PHP rar extension, with bounded streaming. */ +final class PhpRarExtractor { + public function __construct( + private IL10N $l, + private LoggerInterface $logger, + private ArchiveSafetyValidator $safety, + private ExtractionLimits $limits, + private BoundedStreamCopier $copier, + ) { + } + + public function extract(string $file, string $extractTo, ?int $availableBytes): array { + $archive = rar_open($file); + if ($archive === false) { + return ['code' => 0, 'desc' => $this->l->t('Cannot open Rar file')]; + } + try { + $entries = rar_list($archive); + if ($entries === false) { + return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; + } + $entryLimit = $this->limits->entryLimit(); + $entryCount = 0; + $budget = $this->limits->byteBudget($extractTo, $availableBytes); + $declared = 0; + $paths = []; + foreach ($entries as $entry) { + if (++$entryCount > $entryLimit) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains too many files')]; + } + $name = str_replace('\\', '/', $entry->getName()); + $relative = rtrim($name, '/'); + if ($relative === '' || preg_match('//u', $relative) !== 1 || isset($paths[$relative])) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains an invalid filename')]; + } + if ($error = $this->safety->rejectUnsafe($name)) { + return $error; + } + $paths[$relative] = true; + if ($entry->isEncrypted()) { + return ['code' => 0, 'desc' => $this->l->t('Encrypted RAR archives are not supported')]; + } + // Unix RAR4 entries can encode links and devices as native + // filesystem types. RAR5 redirects are never materialized: + // getStream() writes regular file bytes under PHP control. + if (defined('RAR_HOST_UNIX') && $entry->getHostOs() === constant('RAR_HOST_UNIX')) { + $type = $entry->getAttr() & 0xf000; + if ($type !== 0x8000 && $type !== 0x4000) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains links or unsupported special files')]; + } + } + $size = $entry->getUnpackedSize(); + if ($size === false || $size < 0 || $size > $budget - $declared) { + return ['code' => 0, 'desc' => $this->l->t('Archive exceeds the allowed extraction size')]; + } + $declared += $size; + } + if (!is_dir($extractTo) && !mkdir($extractTo, 0700, true)) { + return ['code' => 0, 'desc' => $this->l->t('Could not prepare extraction directory')]; + } + $written = 0; + $deadline = hrtime(true) + min($this->limits->timeout(), 3600) * 1000000000; + foreach ($entries as $entry) { + $name = rtrim(str_replace('\\', '/', $entry->getName()), '/'); + $target = $extractTo . '/' . $name; + if ($entry->isDirectory()) { + if (!is_dir($target) && !mkdir($target, 0700, true)) { + return ['code' => 0, 'desc' => $this->l->t('Could not extract RAR archive')]; + } + continue; + } + if (!is_dir(dirname($target)) && !mkdir(dirname($target), 0700, true)) { + return ['code' => 0, 'desc' => $this->l->t('Could not extract RAR archive')]; + } + $crc = $entry->getCrc(); + if (!is_string($crc) || preg_match('/^[0-9a-fA-F]{8}$/', $crc) !== 1) { + return ['code' => 0, 'desc' => $this->l->t('Could not verify RAR entry integrity')]; + } + $input = $entry->getStream(); + if ($input === false) { + return ['code' => 0, 'desc' => $this->l->t('Could not read RAR entry')]; + } + try { + if (!$this->copier->copy($input, $target, $written, $budget, $entry->getUnpackedSize(), $crc, $deadline)) { + return ['code' => 0, 'desc' => $this->l->t('RAR extraction exceeded limits or failed integrity verification')]; + } + } finally { + fclose($input); + } + } + return ['code' => 1]; + } catch (\Throwable $e) { + $this->logger->warning('RAR stream extraction failed: ' . $e->getMessage()); + return ['code' => 0, 'desc' => $this->l->t('Could not extract RAR archive')]; + } finally { + rar_close($archive); + } + } +} From 0359c6939af8b9fbc997dd74db6e27d21635ddf7 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:15:18 +0000 Subject: [PATCH 22/23] refactor: isolate CLI archive preflight and extraction behind service Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/CliArchiveExtractor.php | 198 ++++++++++++++++++ lib/Service/ExtractionService.php | 295 ++------------------------- tests/unit/ExtractionServiceTest.php | 28 +-- 3 files changed, 216 insertions(+), 305 deletions(-) create mode 100644 lib/Service/CliArchiveExtractor.php diff --git a/lib/Service/CliArchiveExtractor.php b/lib/Service/CliArchiveExtractor.php new file mode 100644 index 0000000..7888c0c --- /dev/null +++ b/lib/Service/CliArchiveExtractor.php @@ -0,0 +1,198 @@ + + * SPDX-FileCopyrightText: 2022 Claus-Justus Heine + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +namespace OCA\Extract\Service; + +use OCP\IL10N; +use Psr\Log\LoggerInterface; + +/** Preflight and supervise external archive formats through 7za, 7z and unrar. */ +final class CliArchiveExtractor { + private const DEFAULT_MAX_EXTRACTED_BYTES = 2147483648; + private const DEFAULT_MAX_ARCHIVE_ENTRIES = 10000; + private const MAX_ARCHIVE_LISTING_BYTES = 16777216; + private const ARCHIVE_LIST_TIMEOUT_SECONDS = 20; + public function __construct( + private IL10N $l, + private LoggerInterface $logger, + private ArchiveSafetyValidator $safety, + private ExtractionLimits $limits, + ) { + } + + private function listWithLimits(array $command): ?array { + $result = ResourceLimitedProcess::capture( + $command, + self::MAX_ARCHIVE_LISTING_BYTES, + self::ARCHIVE_LIST_TIMEOUT_SECONDS, + ); + if (!$result['success']) { + $this->logger->warning('Archive listing rejected: ' . $result['reason']); + return null; + } + return explode("\n", $result['output']); + } + + private function assertSafeRarShell(string $file): ?array { + $output = $this->listWithLimits(['unrar', 'lb', $file]); + if ($output === null) { + return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; + } + foreach ($output as $entry) { + $entry = rtrim($entry, "\r"); + if ($entry !== '' && ($error = $this->safety->rejectUnsafe($entry))) { + return $error; + } + } + // The plain filename list does not reveal links. Inspect entry types + // before extraction, using 7z technical metadata when available. + if ($this->isCommandAvailable('7z')) { + return $this->assertSafeRarSevenZip($file); + } + $details = $this->listWithLimits(['unrar', 'lt', $file]); + if ($details === null) { + return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; + } + $types = 0; + foreach ($details as $line) { + if (preg_match('/^\s*Type\s*:\s*(.+)$/i', $line, $match) === 1) { + $types++; + if (preg_match('/^(?:File|Directory)$/i', trim($match[1])) !== 1) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains links or unsupported special files')]; + } + } + } + if ($types === 0) { + return ['code' => 0, 'desc' => $this->l->t('Could not verify RAR entry types')]; + } + return null; + } + + private function assertSafe7z(string $file, ?int $availableBytes, ?int $temporarySpace): ?array { + $output = $this->listWithLimits(['7za', 'l', '-ba', '-slt', $file]); + if ($output === null) { + return ['code' => 0, 'desc' => $this->l->t('Failed to inspect archive contents')]; + } + $budget = $this->limits->configuredLimit('max_extracted_bytes', self::DEFAULT_MAX_EXTRACTED_BYTES); + if ($availableBytes !== null && $availableBytes >= 0) { + $budget = min($budget, $availableBytes); + } + if ($temporarySpace !== null && $temporarySpace >= 0) { + $budget = min($budget, $temporarySpace); + } + $entryLimit = $this->limits->entryLimit(); + $entries = 0; + $size = 0; + foreach ($output as $line) { + $line = rtrim($line, "\r"); + if ($error = $this->safety->rejectUnsafeMetadata($line)) { + return $error; + } + if (str_starts_with($line, 'Path = ')) { + if ($error = $this->safety->rejectUnsafe(substr($line, 7))) { + return $error; + } + $entries++; + if ($entries > $entryLimit) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains too many files')]; + } + } elseif (str_starts_with($line, 'Size = ')) { + $declaredSize = filter_var(trim(substr($line, 7)), FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]]); + if ($declaredSize === false) { + return ['code' => 0, 'desc' => $this->l->t('Failed to inspect archive contents')]; + } + if ($declaredSize > $budget - $size) { + return ['code' => 0, 'desc' => $this->l->t('Archive exceeds the allowed extraction size')]; + } + $size += $declaredSize; + } + } + return null; + } + + private function runExternalDecoder(array $command, string $extractTo, ?int $availableBytes = null): array { + $limit = $this->limits->byteBudget($extractTo, $availableBytes); + $result = ResourceLimitedProcess::run( + $command, + $extractTo, + $limit, + $this->limits->entryLimit(), + $this->limits->timeout(), + ); + if (!$result['success']) { + $this->logger->warning('Archive decoder stopped: ' . $result['reason']); + $message = match ($result['reason']) { + 'size' => 'Archive exceeds the allowed extraction size', + 'entries' => 'Archive contains too many files', + 'timeout' => 'Archive extraction timed out', + 'symlink' => 'Symbolic links are not supported in extracted archives', + default => 'Could not extract archive', + }; + return ['code' => 0, 'desc' => $this->l->t($message)]; + } + return ['code' => 1]; + } + + public function extractRar(string $file, string $extractTo, ?int $availableBytes = null): array { + if (!$this->isCommandAvailable('unrar')) { + return $this->extractRarWithSevenZip($file, $extractTo, $availableBytes); + } + if ($error = $this->assertSafeRarShell($file)) { + return $error; + } + return $this->runExternalDecoder(['unrar', 'x', $file, '-R', $extractTo . '/', '-o+'], $extractTo, $availableBytes); + } + + public function extractOther(string $file, string $extractTo, ?int $availableBytes = null): array { + + $temporarySpace = disk_free_space(dirname($extractTo)); + if ($error = $this->assertSafe7z( + $file, + $availableBytes, + $temporarySpace === false ? null : (int)$temporarySpace, + )) { + return $error; + } + return $this->runExternalDecoder(['7za', '-y', 'x', $file, '-o' . $extractTo], $extractTo, $availableBytes); + } + + private function assertSafeRarSevenZip(string $file): ?array { + $output = $this->listWithLimits(['7z', 'l', '-ba', '-slt', $file]); + if ($output === null) { + return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; + } + foreach ($output as $line) { + $line = rtrim($line, "\r"); + if ($error = $this->safety->rejectUnsafeMetadata($line)) { + return $error; + } + if (str_starts_with($line, 'Path = ')) { + if ($error = $this->safety->rejectUnsafe(substr($line, 7))) { + return $error; + } + } + } + return null; + } + + private function extractRarWithSevenZip(string $file, string $extractTo, ?int $availableBytes = null): array { + if (!$this->isCommandAvailable('7z')) { + return ['code' => 0, 'desc' => $this->l->t('RAR extraction requires unrar, the PHP rar extension, or the full 7z binary')]; + } + if ($error = $this->assertSafeRarSevenZip($file)) { + return $error; + } + return $this->runExternalDecoder(['7z', '-y', 'x', $file, '-o' . $extractTo], $extractTo, $availableBytes); + } + + private function isCommandAvailable(string $binary): bool { + $return = 0; + $output = []; + exec('command -v ' . escapeshellarg($binary) . ' >/dev/null 2>&1', $output, $return); + return $return === 0; + } +} diff --git a/lib/Service/ExtractionService.php b/lib/Service/ExtractionService.php index a1a0bfd..dba6b20 100644 --- a/lib/Service/ExtractionService.php +++ b/lib/Service/ExtractionService.php @@ -1,309 +1,46 @@ * SPDX-FileCopyrightText: 2022 Claus-Justus Heine + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ - namespace OCA\Extract\Service; use OCP\IConfig; use OCP\IL10N; use Psr\Log\LoggerInterface; +/** Stable entry point for the Nextcloud extraction controller. */ final class ExtractionService { - private const DEFAULT_MAX_EXTRACTED_BYTES = 2147483648; // 2 GiB - private const DEFAULT_MAX_ARCHIVE_ENTRIES = 10000; - private const MAX_ARCHIVE_LISTING_BYTES = 16777216; - private const ARCHIVE_LIST_TIMEOUT_SECONDS = 20; - - private ArchiveSafetyValidator $safety; - private ExtractionLimits $limits; - private BoundedStreamCopier $copier; private ZipExtractor $zip; private PhpRarExtractor $phpRar; + private CliArchiveExtractor $cli; - public function __construct( - private IL10N $l, - private LoggerInterface $logger, - private IConfig $config, - ) { - $this->safety = new ArchiveSafetyValidator($l, $logger); - $this->limits = new ExtractionLimits($config); - $this->copier = new BoundedStreamCopier(); - $this->zip = new ZipExtractor($l, $this->safety, $this->limits, $this->copier); - $this->phpRar = new PhpRarExtractor($l, $logger, $this->safety, $this->limits, $this->copier); - } - - - - - - - - /** - * Run archive listing with a bounded output size and an execution deadline. - * - * @param non-empty-list $command - * @return ?list - */ - private function listWithLimits(array $command): ?array { - $result = ResourceLimitedProcess::capture( - $command, - self::MAX_ARCHIVE_LISTING_BYTES, - self::ARCHIVE_LIST_TIMEOUT_SECONDS, - ); - if (!$result['success']) { - $this->logger->warning('Archive listing rejected: ' . $result['reason']); - return null; - } - return explode("\n", $result['output']); + public function __construct(IL10N $l, LoggerInterface $logger, IConfig $config) { + $safety = new ArchiveSafetyValidator($l, $logger); + $limits = new ExtractionLimits($config); + $copier = new BoundedStreamCopier(); + $this->zip = new ZipExtractor($l, $safety, $limits, $copier); + $this->phpRar = new PhpRarExtractor($l, $logger, $safety, $limits, $copier); + $this->cli = new CliArchiveExtractor($l, $logger, $safety, $limits); } - - - /** @return null|array{code: 0, desc: string} */ - private function assertSafeRarShell(string $file): ?array { - $output = $this->listWithLimits(['unrar', 'lb', $file]); - if ($output === null) { - return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; - } - foreach ($output as $entry) { - $entry = rtrim($entry, "\r"); - if ($entry !== '' && ($error = $this->safety->rejectUnsafe($entry))) { - return $error; - } - } - // The plain filename list does not reveal links. Inspect entry types - // before extraction, using 7z technical metadata when available. - if ($this->isCommandAvailable('7z')) { - return $this->assertSafeRarSevenZip($file); - } - $details = $this->listWithLimits(['unrar', 'lt', $file]); - if ($details === null) { - return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; - } - $types = 0; - foreach ($details as $line) { - if (preg_match('/^\s*Type\s*:\s*(.+)$/i', $line, $match) === 1) { - $types++; - if (preg_match('/^(?:File|Directory)$/i', trim($match[1])) !== 1) { - return ['code' => 0, 'desc' => $this->l->t('Archive contains links or unsupported special files')]; - } - } - } - if ($types === 0) { - return ['code' => 0, 'desc' => $this->l->t('Could not verify RAR entry types')]; - } - return null; - } - - /** - * Validate 7za archive paths and reject metadata announcing extraction - * beyond the available quota, staging space, or configured resource caps. - * The external decoder may still misreport sizes; this is a preflight, - * not a substitute for process-level disk isolation. - * - * @return null|array{code: 0, desc: string} - */ - private function assertSafe7z(string $file, ?int $availableBytes, ?int $temporarySpace): ?array { - $output = $this->listWithLimits(['7za', 'l', '-ba', '-slt', $file]); - if ($output === null) { - return ['code' => 0, 'desc' => $this->l->t('Failed to inspect archive contents')]; - } - $budget = $this->limits->configuredLimit('max_extracted_bytes', self::DEFAULT_MAX_EXTRACTED_BYTES); - if ($availableBytes !== null && $availableBytes >= 0) { - $budget = min($budget, $availableBytes); - } - if ($temporarySpace !== null && $temporarySpace >= 0) { - $budget = min($budget, $temporarySpace); - } - $entryLimit = $this->limits->configuredLimit('max_archive_entries', self::DEFAULT_MAX_ARCHIVE_ENTRIES); - $entries = 0; - $size = 0; - foreach ($output as $line) { - $line = rtrim($line, "\r"); - if ($error = $this->safety->rejectUnsafeMetadata($line)) { - return $error; - } - if (str_starts_with($line, 'Path = ')) { - if ($error = $this->safety->rejectUnsafe(substr($line, 7))) { - return $error; - } - $entries++; - if ($entries > $entryLimit) { - return ['code' => 0, 'desc' => $this->l->t('Archive contains too many files')]; - } - } elseif (str_starts_with($line, 'Size = ')) { - $declaredSize = filter_var(trim(substr($line, 7)), FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]]); - if ($declaredSize === false) { - return ['code' => 0, 'desc' => $this->l->t('Failed to inspect archive contents')]; - } - if ($declaredSize > $budget - $size) { - return ['code' => 0, 'desc' => $this->l->t('Archive exceeds the allowed extraction size')]; - } - $size += $declaredSize; - } - } - return null; - } - - - - /** - * Extract ZIP entries through bounded streams, never via an unbounded - * ZipArchive::extractTo(). The quota estimate is checked before opening a - * stream and the actual byte count is enforced while writing to staging. - * - * @param ?int $availableBytes Remaining destination quota, or negative if - * Nextcloud reports unlimited/unknown space. - * @return array{code: 0|1, desc?: string} - */ + /** @return array{code: 0|1, desc?: string} */ public function extractZip(string $file, string $extractTo, ?int $availableBytes = null): array { return $this->zip->extract($file, $extractTo, $availableBytes); } - /** - * @return (int|mixed)[] - * - * @psalm-return array{code: 0|1, desc?: string} - */ - /** - * Run a command-line decoder with periodic staging checks and a time limit. - * This is best-effort supervision, not a kernel-enforced filesystem quota. - * - * @param non-empty-list $command - * @return array{code: 0|1, desc?: string} - */ - private function runExternalDecoder(array $command, string $extractTo, ?int $availableBytes = null): array { - $limit = $this->limits->configuredLimit('max_extracted_bytes', self::DEFAULT_MAX_EXTRACTED_BYTES); - if ($availableBytes !== null && $availableBytes >= 0) { - $limit = min($limit, $availableBytes); - } - $stagingSpace = disk_free_space(dirname($extractTo)); - if ($stagingSpace !== false) { - $limit = min($limit, (int)$stagingSpace); - } - $result = ResourceLimitedProcess::run( - $command, - $extractTo, - $limit, - $this->limits->configuredLimit('max_archive_entries', self::DEFAULT_MAX_ARCHIVE_ENTRIES), - $this->limits->configuredLimit('max_extraction_seconds', 300), - ); - if (!$result['success']) { - $this->logger->warning('Archive decoder stopped: ' . $result['reason']); - $message = match ($result['reason']) { - 'size' => 'Archive exceeds the allowed extraction size', - 'entries' => 'Archive contains too many files', - 'timeout' => 'Archive extraction timed out', - 'symlink' => 'Symbolic links are not supported in extracted archives', - default => 'Could not extract archive', - }; - return ['code' => 0, 'desc' => $this->l->t($message)]; - } - return ['code' => 1]; - } - + /** @return array{code: 0|1, desc?: string} */ public function extractRar(string $file, string $extractTo, ?int $availableBytes = null): array { - $response = []; - - if (!extension_loaded('rar')) { - if (!$this->isCommandAvailable('unrar')) { - return $this->extractRarWithSevenZip($file, $extractTo, $availableBytes); - } - if ($error = $this->assertSafeRarShell($file)) { - return $error; - } - $result = $this->runExternalDecoder(['unrar', 'x', $file, '-R', $extractTo . '/', '-o+'], $extractTo, $availableBytes); - if ($result['code'] !== 1) { - return $result; - } - } else { + if (extension_loaded('rar')) { return $this->phpRar->extract($file, $extractTo, $availableBytes); } - - $response = array_merge($response, ['code' => 1]); - return $response; + return $this->cli->extractRar($file, $extractTo, $availableBytes); } - /** - * @return (int|mixed)[] - * - * @psalm-return array{code: 0|1, desc?: string} - */ - - - /** - * The PHP RAR extension must not bypass quota checks or create archive - * links using RarEntry::extract(). Stream only regular files and folders - * with a cumulative size budget and CRC verification. - * - * @return array{code: 0|1, desc?: string} - */ - + /** @return array{code: 0|1, desc?: string} */ public function extractOther(string $file, string $extractTo, ?int $availableBytes = null): array { - - $temporarySpace = disk_free_space(dirname($extractTo)); - if ($error = $this->assertSafe7z( - $file, - $availableBytes, - $temporarySpace === false ? null : (int)$temporarySpace, - )) { - return $error; - } - return $this->runExternalDecoder(['7za', '-y', 'x', $file, '-o' . $extractTo], $extractTo, $availableBytes); + return $this->cli->extractOther($file, $extractTo, $availableBytes); } - - /** - * Inspect RAR paths with the full 7z binary before extraction. Keeping the - * RAR listing separate from 7za allows the two formats to use different - * capabilities, and keeps additional 7za metadata checks independent. - * - * @return null|array{code: 0, desc: string} - */ - private function assertSafeRarSevenZip(string $file): ?array { - $output = $this->listWithLimits(['7z', 'l', '-ba', '-slt', $file]); - if ($output === null) { - return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; - } - foreach ($output as $line) { - $line = rtrim($line, "\r"); - if ($error = $this->safety->rejectUnsafeMetadata($line)) { - return $error; - } - if (str_starts_with($line, 'Path = ')) { - if ($error = $this->safety->rejectUnsafe(substr($line, 7))) { - return $error; - } - } - } - return null; - } - - /** - * Use the full 7z binary as an alternate RAR decoder on distributions that - * cannot install the unrar command or the PHP rar extension. - */ - private function extractRarWithSevenZip(string $file, string $extractTo, ?int $availableBytes = null): array { - if (!$this->isCommandAvailable('7z')) { - return ['code' => 0, 'desc' => $this->l->t('RAR extraction requires unrar, the PHP rar extension, or the full 7z binary')]; - } - if ($error = $this->assertSafeRarSevenZip($file)) { - return $error; - } - return $this->runExternalDecoder(['7z', '-y', 'x', $file, '-o' . $extractTo], $extractTo, $availableBytes); - } - - /** - * Check for a fixed, known external archive utility before invocation. - */ - private function isCommandAvailable(string $binary): bool { - $return = 0; - $output = []; - exec('command -v ' . escapeshellarg($binary) . ' >/dev/null 2>&1', $output, $return); - return $return === 0; - } - } diff --git a/tests/unit/ExtractionServiceTest.php b/tests/unit/ExtractionServiceTest.php index e04102d..d905be6 100644 --- a/tests/unit/ExtractionServiceTest.php +++ b/tests/unit/ExtractionServiceTest.php @@ -236,33 +236,9 @@ public function testTarArchiveRespectsDestinationQuota(): void { } - public function testRefusesArchiveLinkMetadataBeforeExtraction(): void { - $method = new \ReflectionMethod(ExtractionService::class, 'rejectUnsafeMetadata'); - foreach ([ - 'Attributes = A lrwxrwxrwx', - 'Hard Link = file.txt', - 'Symbolic Link = ../../outside', - 'Junction = ../outside', - 'Attributes = A brw-rw----', - ] as $line) { - $response = $method->invoke($this->service, $line); - self::assertSame(0, $response['code'], $line); - } - } - public function testAllowsOrdinaryArchiveMetadata(): void { - $method = new \ReflectionMethod(ExtractionService::class, 'rejectUnsafeMetadata'); - foreach ([ - 'Attributes = D drwxr-xr-x', - 'Attributes = A -rw-r--r--', - 'Attributes = RA', - 'Symbolic Link = ', - 'Hard Link = ', - 'Size = 1024', - ] as $line) { - self::assertNull($method->invoke($this->service, $line), $line); - } - } + + From 040d58d896e1d1accfab80a69e613dd0c2df2af3 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:16:35 +0000 Subject: [PATCH 23/23] test: target extracted validator and fix expected PHP file warnings Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/ArchiveSafetyValidator.php | 5 ++++- lib/Service/BoundedStreamCopier.php | 2 +- lib/Service/CliArchiveExtractor.php | 1 + lib/Service/ExtractionLimits.php | 4 +++- lib/Service/ExtractionService.php | 1 + tests/unit/ExtractionPathSafetyTest.php | 10 ++++++---- 6 files changed, 16 insertions(+), 7 deletions(-) diff --git a/lib/Service/ArchiveSafetyValidator.php b/lib/Service/ArchiveSafetyValidator.php index 72424da..a2aa76d 100644 --- a/lib/Service/ArchiveSafetyValidator.php +++ b/lib/Service/ArchiveSafetyValidator.php @@ -14,7 +14,10 @@ /** Validate entry names and archive metadata independently from decoders. */ final class ArchiveSafetyValidator { - public function __construct(private IL10N $l, private LoggerInterface $logger) { + public function __construct( + private IL10N $l, + private LoggerInterface $logger, + ) { } private function isUnsafePath(string $entry): bool { diff --git a/lib/Service/BoundedStreamCopier.php b/lib/Service/BoundedStreamCopier.php index 512792c..d9dfb49 100644 --- a/lib/Service/BoundedStreamCopier.php +++ b/lib/Service/BoundedStreamCopier.php @@ -30,7 +30,7 @@ public function copy( return false; } // Preserve ZIP overwrite semantics; RAR entries must never overwrite. - $output = fopen($target, $expectedBytes === null ? 'wb' : 'xb'); + $output = @fopen($target, $expectedBytes === null ? 'wb' : 'xb'); if ($output === false) { return false; } diff --git a/lib/Service/CliArchiveExtractor.php b/lib/Service/CliArchiveExtractor.php index 7888c0c..9a87670 100644 --- a/lib/Service/CliArchiveExtractor.php +++ b/lib/Service/CliArchiveExtractor.php @@ -1,4 +1,5 @@ * SPDX-FileCopyrightText: 2022 Claus-Justus Heine diff --git a/lib/Service/ExtractionLimits.php b/lib/Service/ExtractionLimits.php index e7586e6..11b291a 100644 --- a/lib/Service/ExtractionLimits.php +++ b/lib/Service/ExtractionLimits.php @@ -13,7 +13,9 @@ /** Resolve positive application limits without exposing configuration parsing. */ final class ExtractionLimits { - public function __construct(private IConfig $config) { + public function __construct( + private IConfig $config, + ) { } public function configuredLimit(string $key, int $default): int { diff --git a/lib/Service/ExtractionService.php b/lib/Service/ExtractionService.php index dba6b20..9cd1a23 100644 --- a/lib/Service/ExtractionService.php +++ b/lib/Service/ExtractionService.php @@ -1,4 +1,5 @@ * SPDX-FileCopyrightText: 2022 Claus-Justus Heine diff --git a/tests/unit/ExtractionPathSafetyTest.php b/tests/unit/ExtractionPathSafetyTest.php index 838f650..ffe96a8 100644 --- a/tests/unit/ExtractionPathSafetyTest.php +++ b/tests/unit/ExtractionPathSafetyTest.php @@ -9,6 +9,7 @@ namespace OCA\Extract\Tests\unit; +use OCA\Extract\Service\ArchiveSafetyValidator; use OCA\Extract\Service\ExtractionService; use OCP\IL10N; use PHPUnit\Framework\TestCase; @@ -23,14 +24,15 @@ private function service(): ExtractionService { } public function testUnsafeArchiveEntryNamesAreRejected(): void { - $method = new \ReflectionMethod(ExtractionService::class, 'isUnsafePath'); - $service = $this->service(); + $l10n = $this->createStub(IL10N::class); + $l10n->method('t')->willReturnCallback(static fn (string $s): string => $s); + $validator = new ArchiveSafetyValidator($l10n, $this->createStub(LoggerInterface::class)); foreach (['../escape.txt', 'a/../../escape.txt', '..\\escape.txt', '/etc/passwd', '\\\\server\\share', 'C:\\outside.txt', 'C:relative.txt', "a\x00b"] as $entry) { - self::assertTrue($method->invoke($service, $entry), 'Unsafe path accepted: ' . bin2hex($entry)); + self::assertSame(0, $validator->rejectUnsafe($entry)['code'], 'Unsafe path accepted: ' . bin2hex($entry)); } foreach (['safe.txt', 'nested/file.txt', 'nested\\file.txt', 'a/..name.txt', './inside.txt'] as $entry) { - self::assertFalse($method->invoke($service, $entry), 'Safe path rejected: ' . $entry); + self::assertNull($validator->rejectUnsafe($entry), 'Safe path rejected: ' . $entry); } }