Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
5359e3c
test: add supervised decoder runner and isolated regressions
vitormattos Nov 22, 2026
9a0719f
fix: supervise 7za and RAR CLI extraction against resource budgets
vitormattos Nov 22, 2026
b77dc31
test: use safe RAR5 fixture and reject staged symlinks
vitormattos Nov 22, 2026
3c00a61
docs: state proc_open requirement for supervised extraction
vitormattos Nov 22, 2026
10b7129
fix: bound archive listing output and drain verbose decoders
vitormattos Nov 22, 2026
c319333
fix: bound seven-zip preflight and reject link metadata
vitormattos Nov 22, 2026
8d0c037
fix: validate RAR entry types before extraction and test unsafe metadata
vitormattos Nov 22, 2026
6e02191
test: accept empty link metadata emitted for regular archives
vitormattos Nov 22, 2026
a4806ef
fix: enforce streaming quotas and CRC checks for PHP RAR extraction
vitormattos Nov 22, 2026
6925972
fix: terminate isolated decoder process groups on timeout
vitormattos Nov 22, 2026
0123b55
fix: initialize process group state and count RAR entries safely
vitormattos Nov 22, 2026
cf5c019
fix: terminate remaining decoder descendants and preserve exit status
vitormattos Nov 22, 2026
cee8ebb
test: ensure timed-out decoder children stop and document isolation l…
vitormattos Nov 22, 2026
9ffb10a
refactor: separate decoder process lifecycle from staging budget checks
vitormattos Nov 22, 2026
402f96d
test: exercise staging budget checks without launching decoders
vitormattos Nov 22, 2026
9e17c28
style: format decoder process constructor
vitormattos Nov 22, 2026
74f7e31
refactor: isolate archive safety rules and extraction limit configura…
vitormattos Nov 22, 2026
5e05bed
fix: preserve CLI preflight methods during service extraction
vitormattos Nov 22, 2026
36f228a
refactor: consolidate bounded ZIP and RAR streaming into tested copier
vitormattos Nov 22, 2026
2138f96
refactor: move ZIP extraction into independently testable extractor
vitormattos Nov 22, 2026
1706403
refactor: isolate bounded PHP RAR extraction in dedicated service
vitormattos Nov 22, 2026
0359c69
refactor: isolate CLI archive preflight and extraction behind service
vitormattos Nov 22, 2026
040d58d
test: target extracted validator and fix expected PHP file warnings
vitormattos Nov 22, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion lib/Controller/ExtractionController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
51 changes: 51 additions & 0 deletions lib/Service/ArchiveSafetyValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

/**
* SPDX-FileCopyrightText: 2012-2022 Paul Lereverend <paulereverend@gmail.com>
* SPDX-FileCopyrightText: 2022 Claus-Justus Heine <himself@claus-justus-heine.de>
* 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')];
}
}
77 changes: 77 additions & 0 deletions lib/Service/BoundedStreamCopier.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

/**
* SPDX-FileCopyrightText: 2012-2022 Paul Lereverend <paulereverend@gmail.com>
* SPDX-FileCopyrightText: 2022 Claus-Justus Heine <himself@claus-justus-heine.de>
* 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));
}
}
199 changes: 199 additions & 0 deletions lib/Service/CliArchiveExtractor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
<?php

/**
* SPDX-FileCopyrightText: 2012-2022 Paul Lereverend <paulereverend@gmail.com>
* SPDX-FileCopyrightText: 2022 Claus-Justus Heine <himself@claus-justus-heine.de>
* 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;
}
}
Loading
Loading