diff --git a/README.md b/README.md index 9b96a3d..963a916 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 @@ -60,8 +62,18 @@ 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. 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/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/ArchiveSafetyValidator.php b/lib/Service/ArchiveSafetyValidator.php new file mode 100644 index 0000000..a2aa76d --- /dev/null +++ b/lib/Service/ArchiveSafetyValidator.php @@ -0,0 +1,51 @@ + + * 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/BoundedStreamCopier.php b/lib/Service/BoundedStreamCopier.php new file mode 100644 index 0000000..d9dfb49 --- /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/CliArchiveExtractor.php b/lib/Service/CliArchiveExtractor.php new file mode 100644 index 0000000..9a87670 --- /dev/null +++ b/lib/Service/CliArchiveExtractor.php @@ -0,0 +1,199 @@ + + * 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/DecoderProcess.php b/lib/Service/DecoderProcess.php new file mode 100644 index 0000000..70b7b07 --- /dev/null +++ b/lib/Service/DecoderProcess.php @@ -0,0 +1,179 @@ + */ + 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/ExtractionLimits.php b/lib/Service/ExtractionLimits.php new file mode 100644 index 0000000..11b291a --- /dev/null +++ b/lib/Service/ExtractionLimits.php @@ -0,0 +1,49 @@ + + * 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 bddbc29..9cd1a23 100644 --- a/lib/Service/ExtractionService.php +++ b/lib/Service/ExtractionService.php @@ -3,406 +3,45 @@ /** * SPDX-FileCopyrightText: 2012-2022 Paul Lereverend * 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; -use ZipArchive; +/** 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; - - public function __construct( - private IL10N $l, - private LoggerInterface $logger, - private IConfig $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; - } + private ZipExtractor $zip; + private PhpRarExtractor $phpRar; + private CliArchiveExtractor $cli; - /** @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)); - return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; - } - foreach ($output as $entry) { - if ($entry !== '' && ($error = $this->rejectUnsafe($entry))) { - return $error; - } - } - return null; + 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); } - /** - * 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 = []; - $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)); - 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) { - 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 - * 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 { - 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->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->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 { - $output = fopen($path, 'wb'); - if ($output === false) { - 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); - } - } - return ['code' => 1]; - } finally { - $zip->close(); - } + return $this->zip->extract($file, $extractTo, $availableBytes); } - /** - * @return (int|mixed)[] - * - * @psalm-return array{code: 0|1, desc?: string} - */ - public function extractRar(string $file, string $extractTo): array { - $response = []; - - if (!extension_loaded('rar')) { - if (!$this->isCommandAvailable('unrar')) { - return $this->extractRarWithSevenZip($file, $extractTo); - } - 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; - } - } 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 array{code: 0|1, desc?: string} */ + public function extractRar(string $file, string $extractTo, ?int $availableBytes = null): array { + 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} - */ + /** @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( - $file, - $availableBytes, - $temporarySpace === false ? null : (int)$temporarySpace, - )) { - 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->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 = []; - $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)); - return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; - } - foreach ($output as $line) { - if (str_starts_with($line, 'Path = ')) { - if ($error = $this->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): 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]; - } - - /** - * 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/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); + } + } +} diff --git a/lib/Service/ResourceLimitedProcess.php b/lib/Service/ResourceLimitedProcess.php new file mode 100644 index 0000000..443f2a5 --- /dev/null +++ b/lib/Service/ResourceLimitedProcess.php @@ -0,0 +1,99 @@ + $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) { + return ['success' => false, 'reason' => 'unavailable']; + } + $result = self::execute($command, $timeoutSeconds, new StagingBudgetInspector($directory, $maxBytes, $maxEntries), null); + return ['success' => $result['success'], 'reason' => $result['reason']]; + } + + /** + * @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 self::execute($command, $timeoutSeconds, null, $maxOutputBytes); + } + + /** + * 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} + */ + private static function execute(array $command, int $timeoutSeconds, ?StagingBudgetInspector $inspector, ?int $maxOutputBytes): array { + if ($timeoutSeconds < 1) { + return ['success' => false, 'reason' => 'unavailable', 'output' => '']; + } + $process = DecoderProcess::start($command); + if ($process === null) { + return ['success' => false, 'reason' => 'unavailable', 'output' => '']; + } + + $reason = null; + // Preserve the configured extraction timeout; limit listing to one hour. + $deadline = microtime(true) + ($maxOutputBytes === null ? $timeoutSeconds : min($timeoutSeconds, 3600)); + try { + while (true) { + $reason = $process->drain($maxOutputBytes); + if ($reason !== null) { + break; + } + $reason = $inspector?->inspect(); + if ($reason !== null) { + break; + } + if (microtime(true) >= $deadline) { + $reason = 'timeout'; + break; + } + if ($process->hasExited() && ($maxOutputBytes === null || $process->outputComplete())) { + break; + } + usleep(self::POLL_INTERVAL_US); + } + } catch (\Throwable) { + $reason = 'inspection'; + } finally { + $exitCode = $process->close(); + } + + if ($reason === null) { + try { + $reason = $inspector?->inspect(); + } catch (\Throwable) { + $reason = 'inspection'; + } + } + if ($reason === null && $exitCode !== 0) { + $reason = 'exit'; + } + 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; + } +} 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/ArchiveSafetyValidatorTest.php b/tests/unit/ArchiveSafetyValidatorTest.php new file mode 100644 index 0000000..4c60458 --- /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/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/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)); + } +} 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); } } diff --git a/tests/unit/ExtractionServiceTest.php b/tests/unit/ExtractionServiceTest.php index 3077c67..d905be6 100644 --- a/tests/unit/ExtractionServiceTest.php +++ b/tests/unit/ExtractionServiceTest.php @@ -235,6 +235,13 @@ public function testTarArchiveRespectsDestinationQuota(): void { self::assertSame(str_repeat('x', 256), file_get_contents($allowed . '/payload.txt')); } + + + + + + + /** * A decompression bomb must be refused before staging any files when the * total uncompressed content cannot fit the user's Nextcloud quota. 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 new file mode 100644 index 0000000..2e588f6 --- /dev/null +++ b/tests/unit/ResourceLimitedProcessTest.php @@ -0,0 +1,182 @@ +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 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 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 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);', + ], $this->directory, 50, 2, 3); + self::assertSame(['success' => false, 'reason' => 'exit'], $result); + } +} 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()); + } +} 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); + } + } +}