Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 4 additions & 0 deletions apps/dav/lib/Connector/Sabre/Directory.php
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,8 @@ public function moveInto($targetName, $fullSourcePath, INode $sourceNode) {
throw new ServiceUnavailable($e->getMessage(), $e->getCode(), $e);
} catch (ForbiddenException $ex) {
throw new Forbidden($ex->getMessage(), $ex->getRetry(), $ex);
} catch (InvalidPathException $ex) {
throw new InvalidPath($ex->getMessage(), false, $ex);
} catch (LockedException $e) {
throw new FileLocked($e->getMessage(), $e->getCode(), $e);
}
Expand Down Expand Up @@ -499,6 +501,8 @@ public function copyInto($targetName, $sourcePath, INode $sourceNode) {
throw new ServiceUnavailable($e->getMessage(), $e->getCode(), $e);
} catch (ForbiddenException $ex) {
throw new Forbidden($ex->getMessage(), $ex->getRetry(), $ex);
} catch (InvalidPathException $ex) {
throw new InvalidPath($ex->getMessage(), false, $ex);
} catch (LockedException $e) {
throw new FileLocked($e->getMessage(), $e->getCode(), $e);
}
Expand Down
2 changes: 2 additions & 0 deletions apps/dav/lib/Connector/Sabre/ObjectTree.php
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,8 @@ public function copy($sourcePath, $destinationPath) {
throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
} catch (ForbiddenException $ex) {
throw new Forbidden($ex->getMessage(), $ex->getRetry());
} catch (InvalidPathException $ex) {
throw new InvalidPath($ex->getMessage(), false, $ex);
} catch (LockedException $e) {
throw new FileLocked($e->getMessage(), $e->getCode(), $e);
}
Expand Down
39 changes: 39 additions & 0 deletions apps/dav/tests/unit/Connector/Sabre/DirectoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -659,4 +659,43 @@ public function testFailingMove(): void {

$targetNode->moveInto(basename($destination), $source, $sourceNode);
}

public function testMoveIntoInvalidPathFromStorage(): void {
$this->expectException(InvalidPath::class);
$this->expectExceptionMessage('Invalid path "b/foo:bar"');

$view = $this->getMockBuilder(TestViewDirectory::class)
->onlyMethods(['rename'])
->setConstructorArgs([['a' => true, 'a/b' => true, 'c' => true], ['a/b' => true]])
->getMock();
$view->method('rename')
->willThrowException(new InvalidPathException('Invalid path "b/foo:bar"'));

$sourceNode = new Directory($view, new FileInfo('a/b', null, null, ['type' => FileInfo::TYPE_FOLDER], null));
$targetNode = $this->getMockBuilder(Directory::class)
->onlyMethods(['childExists'])
->setConstructorArgs([$view, new FileInfo('c', null, null, ['type' => FileInfo::TYPE_FOLDER], null)])
->getMock();
$targetNode->method('childExists')
->willReturn(false);

$targetNode->moveInto('b', 'a/b', $sourceNode);
}

public function testCopyIntoInvalidPathFromStorage(): void {
$this->expectException(InvalidPath::class);
$this->expectExceptionMessage('Invalid path "b/foo:bar"');

$view = $this->getMockBuilder(TestViewDirectory::class)
->onlyMethods(['copy'])
->setConstructorArgs([['c' => true], []])
->getMock();
$view->method('copy')
->willThrowException(new InvalidPathException('Invalid path "b/foo:bar"'));

$sourceNode = new Directory($view, new FileInfo('a/b', null, null, ['type' => FileInfo::TYPE_FOLDER], null));
$targetNode = new Directory($view, new FileInfo('c', null, null, ['type' => FileInfo::TYPE_FOLDER], null));

$targetNode->copyInto('b', 'a/b', $sourceNode);
}
}
29 changes: 29 additions & 0 deletions apps/dav/tests/unit/Connector/Sabre/ObjectTreeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use OCA\DAV\Connector\Sabre\Exception\InvalidPath;
use OCA\DAV\Connector\Sabre\File;
use OCA\DAV\Connector\Sabre\ObjectTree;
use OCP\Files\InvalidPathException;
use OCP\Files\Mount\IMountManager;

/**
Expand Down Expand Up @@ -86,6 +87,34 @@ public function testCopy(string $sourcePath, string $targetPath, string $targetP
$objectTree->copy($sourcePath, $targetPath);
}

public function testCopyInvalidPathFromStorage(): void {
$this->expectException(InvalidPath::class);
$this->expectExceptionMessage('Invalid path "b/foo:bar"');

$view = $this->createMock(View::class);
$view->method('file_exists')
->willReturn(false);
$view->method('copy')
->willThrowException(new InvalidPathException('Invalid path "b/foo:bar"'));

$info = $this->createMock(FileInfo::class);
$info->method('isCreatable')
->willReturn(true);
$view->method('getFileInfo')
->willReturn($info);
$view->method('getRelativePath')
->willReturn('');

$rootDir = new Directory($view, $info);
$objectTree = $this->getMockBuilder(ObjectTree::class)
->onlyMethods(['nodeExists', 'getNodeForPath'])
->setConstructorArgs([$rootDir, $view])
->getMock();

$objectTree->init($rootDir, $view, Filesystem::getMountManager());
$objectTree->copy('a', 'b');
}

#[\PHPUnit\Framework\Attributes\DataProvider(methodName: 'copyDataProvider')]
public function testCopyFailNotCreatable($sourcePath, $targetPath, $targetParent): void {
$this->expectException(\Sabre\DAV\Exception\Forbidden::class);
Expand Down
73 changes: 71 additions & 2 deletions apps/files_external/lib/Lib/Storage/SMB.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Icewind\SMB\Exception\Exception;
use Icewind\SMB\Exception\ForbiddenException;
use Icewind\SMB\Exception\InvalidArgumentException;
use Icewind\SMB\Exception\InvalidPathException;
use Icewind\SMB\Exception\InvalidTypeException;
use Icewind\SMB\Exception\NotFoundException;
use Icewind\SMB\Exception\OutOfSpaceException;
Expand All @@ -32,17 +33,26 @@
use OCP\Cache\CappedMemoryCache;
use OCP\Constants;
use OCP\Files\EntityTooLargeException;
use OCP\Files\FileInfo;
use OCP\Files\IMimeTypeDetector;
use OCP\Files\InvalidCharacterInPathException;
use OCP\Files\Notify\IChange;
use OCP\Files\Notify\IRenameChange;
use OCP\Files\NotPermittedException;
use OCP\Files\Storage\INotifyStorage;
use OCP\Files\Storage\IStorage;
use OCP\Files\StorageAuthException;
use OCP\Files\StorageNotAvailableException;
use OCP\ITempManager;
use OCP\Util;
use Psr\Log\LoggerInterface;

class SMB extends Common implements INotifyStorage {
/**
* Characters icewind/smb rejects in paths, see \Icewind\SMB\AbstractShare
*/
private const FORBIDDEN_CHARACTERS = ['?', '<', '>', ':', '*', '|', '"', "\0", "\n", "\r"];

/**
* @var \Icewind\SMB\IServer
*/
Expand Down Expand Up @@ -72,6 +82,8 @@ class SMB extends Common implements INotifyStorage {
/** @var bool */
protected $checkAcl;

private bool $copyingFromStorage = false;

public function __construct(array $parameters) {
if (!isset($parameters['host'])) {
throw new \Exception('Invalid configuration, no host provided');
Expand Down Expand Up @@ -175,7 +187,7 @@ protected function getFileInfo(string $path): IFileInfo {
$this->throwUnavailable($e);
} catch (InvalidArgumentException $e) {
$this->throwUnavailable($e);
} catch (NotFoundException $e) {
} catch (NotFoundException|InvalidPathException $e) {
throw new \OCP\Files\NotFoundException($e->getMessage(), 0, $e);
} catch (ForbiddenException $e) {
// with php-smbclient, this exception is thrown when the provided password is invalid.
Expand Down Expand Up @@ -289,6 +301,61 @@ protected function formatInfo(IFileInfo $info): array {
return $result;
}

#[\Override]
public function verifyPath(string $path, string $fileName): void {
parent::verifyPath($path, $fileName);
$this->verifyStorableName($fileName);
}

#[\Override]
public function copyFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath, bool $preserveMtime = false): bool {
// Common::copyFromStorage() calls this method again for every entry, the tree only needs to be checked once
if ($this->copyingFromStorage || $sourceStorage->instanceOfStorage(self::class)) {
return parent::copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime);
}

$this->verifyStorableTree($sourceStorage, $sourceInternalPath, basename($targetInternalPath));
$this->copyingFromStorage = true;
try {
return parent::copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime);
} finally {
$this->copyingFromStorage = false;
}
}

/**
* @throws InvalidCharacterInPathException if SMB can't store the name
*/
private function verifyStorableName(string $name, ?string $displayPath = null): void {
foreach (self::FORBIDDEN_CHARACTERS as $char) {
if (str_contains($name, $char)) {
$message = Util::getL10N('lib')->t('"%1$s" is not allowed inside a file or folder name.', [$char]);
throw new InvalidCharacterInPathException($displayPath === null ? $message : $displayPath . ': ' . $message);
}
}
}

/**
* Check all names of a tree before it is copied, so that a name SMB can't store doesn't fail the copy half-way
*
* @throws InvalidCharacterInPathException
*/
private function verifyStorableTree(IStorage $sourceStorage, string $sourcePath, string $displayPath): void {
$this->verifyStorableName(basename($displayPath), $displayPath);
if (!$sourceStorage->is_dir($sourcePath)) {
return;
}
foreach ($sourceStorage->getDirectoryContent($sourcePath) as $entry) {
$childPath = $sourcePath . '/' . $entry['name'];
$childDisplayPath = $displayPath . '/' . $entry['name'];
if ($entry['mimetype'] === FileInfo::MIMETYPE_FOLDER) {
$this->verifyStorableTree($sourceStorage, $childPath, $childDisplayPath);
} else {
$this->verifyStorableName($entry['name'], $childDisplayPath);
}
}
}

/**
* Rename the files. If the source or the target is the root, the rename won't happen.
*
Expand Down Expand Up @@ -405,7 +472,7 @@ public function unlink(string $path): bool {
$this->share->del($path);
return true;
}
} catch (NotFoundException $e) {
} catch (NotFoundException|InvalidPathException $e) {
return false;
} catch (ForbiddenException $e) {
return false;
Expand Down Expand Up @@ -498,6 +565,8 @@ public function fopen(string $path, string $mode) {
} catch (OutOfSpaceException $e) {
$this->logger->warning('Failed to open ' . $path . ' on ' . $this->getId() . ', out of space.', ['exception' => $e]);
throw new EntityTooLargeException('not enough available space to create file', 0, $e);
} catch (InvalidPathException $e) {
throw new \OCP\Files\InvalidPathException($e->getMessage(), 0, $e);
} catch (ConnectException $e) {
$this->logger->error('Error while opening file ' . $path . ' on ' . $this->getId(), ['exception' => $e]);
throw new StorageNotAvailableException($e->getMessage(), (int)$e->getCode(), $e);
Expand Down
64 changes: 64 additions & 0 deletions apps/files_external/tests/Storage/SmbTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,14 @@

namespace OCA\Files_External\Tests\Storage;

use Icewind\SMB\AbstractShare;
use Icewind\SMB\Native\NativeShare;
use OC\Files\Notify\Change;
use OC\Files\Notify\RenameChange;
use OC\Files\Storage\Temporary;
use OCA\Files_External\Lib\Storage\SMB;
use OCP\Files\InvalidCharacterInPathException;
use OCP\Files\InvalidPathException;
use OCP\Files\Notify\IChange;
use PHPUnit\Framework\ExpectationFailedException;

Expand Down Expand Up @@ -172,4 +177,63 @@ public function testRmdirRoot(): void {
// root can't be deleted
$this->assertFalse($this->instance->rmdir(''));
}

public function testInvalidPathDoesNotExist(): void {
$this->assertFalse($this->instance->file_exists('foo:bar.txt'));
$this->assertFalse($this->instance->is_dir('foo:bar'));
$this->assertFalse($this->instance->stat('foo:bar.txt'));
}

public function testForbiddenCharactersMatchIcewind(): void {
$share = (new \ReflectionClass(NativeShare::class))->newInstanceWithoutConstructor();
(new \ReflectionMethod(AbstractShare::class, '__construct'))->invoke($share);
$icewindCharacters = (new \ReflectionProperty(AbstractShare::class, 'forbiddenCharacters'))->getValue($share);

$this->assertEqualsCanonicalizing($icewindCharacters, (new \ReflectionClassConstant(SMB::class, 'FORBIDDEN_CHARACTERS'))->getValue());
}

public function testVerifyPathInvalidCharacter(): void {
$this->expectException(InvalidCharacterInPathException::class);
$this->expectExceptionMessage('":" is not allowed');

$this->instance->verifyPath('', 'foo:bar.txt');
}

public function testUnlinkInvalidPath(): void {
$this->assertFalse($this->instance->unlink('foo:bar.txt'));
}

public function testFopenInvalidPath(): void {
$this->expectException(InvalidPathException::class);
$this->expectExceptionMessage('foo:bar.txt');

$this->instance->fopen('foo:bar.txt', 'w');
}

public function testCopyFromStorageInvalidName(): void {
$source = new Temporary([]);
$source->mkdir('folder');
$source->file_put_contents('folder/a.txt', 'a');
$source->mkdir('folder/sub');
$source->file_put_contents('folder/sub/foo:bar.txt', 'foo');
$source->file_put_contents('folder/z.txt', 'z');

try {
$this->instance->copyFromStorage($source, 'folder', 'target');
$this->fail('Expected InvalidCharacterInPathException');
} catch (InvalidCharacterInPathException $e) {
$this->assertStringStartsWith('target/sub/foo:bar.txt: ', $e->getMessage());
}
$this->assertFalse($this->instance->file_exists('target'));
}

public function testCopyFromStorageValidNames(): void {
$source = new Temporary([]);
$source->mkdir('folder');
$source->mkdir('folder/sub');
$source->file_put_contents('folder/sub/foo bar.txt', 'foo');

$this->assertTrue($this->instance->copyFromStorage($source, 'folder', 'target'));
$this->assertEquals('foo', $this->instance->file_get_contents('target/sub/foo bar.txt'));
}
}
12 changes: 11 additions & 1 deletion lib/private/Files/Storage/Common.php
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,7 @@ public function copyFromStorage(IStorage $sourceStorage, string $sourceInternalP
} else {
$source = $sourceStorage->fopen($sourceInternalPath, 'r');
$result = false;
$writeException = null;
if ($source) {
try {
$this->writeStream($targetInternalPath, $source);
Expand All @@ -552,6 +553,7 @@ public function copyFromStorage(IStorage $sourceStorage, string $sourceInternalP
throw new ForbiddenException($e->getMessage(), false, $e);
} catch (\Exception $e) {
Server::get(LoggerInterface::class)->warning('Failed to copy stream to storage', ['exception' => $e]);
$writeException = $e;
}
}

Expand All @@ -562,9 +564,17 @@ public function copyFromStorage(IStorage $sourceStorage, string $sourceInternalP

if (!$result) {
// delete partially written target file
$this->unlink($targetInternalPath);
try {
$this->unlink($targetInternalPath);
} catch (\Exception $e) {
Server::get(LoggerInterface::class)->warning('Failed to delete partially written target file', ['exception' => $e]);
}
// delete cache entry that was created by fopen
$this->getCache()->remove($targetInternalPath);

if ($writeException instanceof InvalidPathException) {
throw $writeException;
}
}
}
return (bool)$result;
Expand Down
Loading