* @author Ilja Neumann * * @copyright Copyright (c) 2019, ownCloud GmbH * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see * */ namespace OCA\Encryption\Command; use OC\Files\View; use OC\ServerNotAvailableException; use OCA\Encryption\Util; use OCP\Files\IRootFolder; use OCP\HintException; use OCP\IConfig; use OCP\ILogger; use OCP\IUserManager; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class FixEncryptedVersion extends Command { /** @var IConfig */ private $config; /** @var ILogger */ private $logger; /** @var IRootFolder */ private $rootFolder; /** @var IUserManager */ private $userManager; /** @var Util */ private $util; /** @var View */ private $view; /** @var bool */ private $supportLegacy; public function __construct( IConfig $config, ILogger $logger, IRootFolder $rootFolder, IUserManager $userManager, Util $util, View $view ) { $this->config = $config; $this->logger = $logger; $this->rootFolder = $rootFolder; $this->userManager = $userManager; $this->util = $util; $this->view = $view; $this->supportLegacy = false; parent::__construct(); } protected function configure(): void { parent::configure(); $this ->setName('encryption:fix-encrypted-version') ->setDescription('Fix the encrypted version if the encrypted file(s) are not downloadable.') ->addArgument( 'user', InputArgument::REQUIRED, 'The id of the user whose files need fixing' )->addOption( 'path', 'p', InputArgument::OPTIONAL, 'Limit files to fix with path, e.g., --path="/Music/Artist". If path indicates a directory, all the files inside directory will be fixed.' ); } /** * @param InputInterface $input * @param OutputInterface $output * @return int */ protected function execute(InputInterface $input, OutputInterface $output): int { $skipSignatureCheck = $this->config->getSystemValue('encryption_skip_signature_check', false); $this->supportLegacy = $this->config->getSystemValueBool('encryption.legacy_format_support', false); if ($skipSignatureCheck) { $output->writeln("Repairing is not possible when \"encryption_skip_signature_check\" is set. Please disable this flag in the configuration.\n"); return 1; } if (!$this->util->isMasterKeyEnabled()) { $output->writeln("Repairing only works with master key encryption.\n"); return 1; } $user = (string)$input->getArgument('user'); $pathToWalk = "/$user/files"; $pathOption = \trim(($input->getOption('path') ?? ''), '/'); if ($pathOption !== "") { $pathToWalk = "$pathToWalk/$pathOption"; } if ($user === null) { $output->writeln("No user id provided.\n"); return 1; } if ($this->userManager->get($user) === null) { $output->writeln("User id $user does not exist. Please provide a valid user id"); return 1; } return $this->walkPathOfUser($user, $pathToWalk, $output); } /** * @param string $user * @param string $path * @param OutputInterface $output * @return int 0 for success, 1 for error */ private function walkPathOfUser($user, $path, OutputInterface $output): int { $this->setupUserFs($user); if (!$this->view->file_exists($path)) { $output->writeln("Path \"$path\" does not exist. Please provide a valid path."); return 1; } if ($this->view->is_file($path)) { $output->writeln("Verifying the content of file \"$path\""); $this->verifyFileContent($path, $output); return 0; } $directories = []; $directories[] = $path; while ($root = \array_pop($directories)) { $directoryContent = $this->view->getDirectoryContent($root); foreach ($directoryContent as $file) { $path = $root . '/' . $file['name']; if ($this->view->is_dir($path)) { $directories[] = $path; } else { $output->writeln("Verifying the content of file \"$path\""); $this->verifyFileContent($path, $output); } } } return 0; } /** * @param string $path * @param OutputInterface $output * @param bool $ignoreCorrectEncVersionCall, setting this variable to false avoids recursion */ private function verifyFileContent($path, OutputInterface $output, $ignoreCorrectEncVersionCall = true): bool { try { /** * In encryption, the files are read in a block size of 8192 bytes * Read block size of 8192 and a bit more (808 bytes) * If there is any problem, the first block should throw the signature * mismatch error. Which as of now, is enough to proceed ahead to * correct the encrypted version. */ $handle = $this->view->fopen($path, 'rb'); if (\fread($handle, 9001) !== false) { $output->writeln("The file \"$path\" is: OK"); } \fclose($handle); return true; } catch (ServerNotAvailableException $e) { // not a "bad signature" error and likely "legacy cipher" exception // this could mean that the file is maybe not encrypted but the encrypted version is set if (!$this->supportLegacy && $ignoreCorrectEncVersionCall === true) { $output->writeln("Attempting to fix the path: \"$path\""); return $this->correctEncryptedVersion($path, $output, true); } return false; } catch (HintException $e) { $this->logger->warning("Issue: " . $e->getMessage()); //If allowOnce is set to false, this becomes recursive. if ($ignoreCorrectEncVersionCall === true) { //Lets rectify the file by correcting encrypted version $output->writeln("Attempting to fix the path: \"$path\""); return $this->correctEncryptedVersion($path, $output); } return false; } } /** * @param string $path * @param OutputInterface $output * @param bool $includeZero whether to try zero version for unencrypted file * @return bool */ private function correctEncryptedVersion($path, OutputInterface $output, bool $includeZero = false): bool { $fileInfo = $this->view->getFileInfo($path); if (!$fileInfo) { $output->writeln("File info not found for file: \"$path\""); return true; } $fileId = $fileInfo->getId(); $encryptedVersion = $fileInfo->getEncryptedVersion(); $wrongEncryptedVersion = $encryptedVersion; $storage = $fileInfo->getStorage(); $cache = $storage->getCache(); $fileCache = $cache->get($fileId); if (!$fileCache) { $output->writeln("File cache entry not found for file: \"$path\""); return true; } if ($storage->instanceOfStorage('OCA\Files_Sharing\ISharedStorage')) { $output->writeln("The file: \"$path\" is a share. Please also run the script for the owner of the share"); return true; } // Save original encrypted version so we can restore it if decryption fails with all version $originalEncryptedVersion = $encryptedVersion; if ($encryptedVersion >= 0) { if ($includeZero) { // try with zero first $cacheInfo = ['encryptedVersion' => 0, 'encrypted' => 0]; $cache->put($fileCache->getPath(), $cacheInfo); $output->writeln("Set the encrypted version to 0 (unencrypted)"); if ($this->verifyFileContent($path, $output, false) === true) { $output->writeln("Fixed the file: \"$path\" with version 0 (unencrypted)"); return true; } } //test by decrementing the value till 1 and if nothing works try incrementing $encryptedVersion--; while ($encryptedVersion > 0) { $cacheInfo = ['encryptedVersion' => $encryptedVersion, 'encrypted' => $encryptedVersion]; $cache->put($fileCache->getPath(), $cacheInfo); $output->writeln("Decrement the encrypted version to $encryptedVersion"); if ($this->verifyFileContent($path, $output, false) === true) { $output->writeln("Fixed the file: \"$path\" with version " . $encryptedVersion . ""); return true; } $encryptedVersion--; } //So decrementing did not work. Now lets increment. Max increment is till 5 $increment = 1; while ($increment <= 5) { /** * The wrongEncryptedVersion would not be incremented so nothing to worry about here. * Only the newEncryptedVersion is incremented. * For example if the wrong encrypted version is 4 then * cycle1 -> newEncryptedVersion = 5 ( 4 + 1) * cycle2 -> newEncryptedVersion = 6 ( 4 + 2) * cycle3 -> newEncryptedVersion = 7 ( 4 + 3) */ $newEncryptedVersion = $wrongEncryptedVersion + $increment; $cacheInfo = ['encryptedVersion' => $newEncryptedVersion, 'encrypted' => $newEncryptedVersion]; $cache->put($fileCache->getPath(), $cacheInfo); $output->writeln("Increment the encrypted version to $newEncryptedVersion"); if ($this->verifyFileContent($path, $output, false) === true) { $output->writeln("Fixed the file: \"$path\" with version " . $newEncryptedVersion . ""); return true; } $increment++; } } $cacheInfo = ['encryptedVersion' => $originalEncryptedVersion, 'encrypted' => $originalEncryptedVersion]; $cache->put($fileCache->getPath(), $cacheInfo); $output->writeln("No fix found for \"$path\", restored version to original: $originalEncryptedVersion"); return false; } /** * Setup user file system * @param string $uid */ private function setupUserFs($uid): void { \OC_Util::tearDownFS(); \OC_Util::setupFS($uid); } } _full_warning Nextcloud server, a safe home for all your data: https://github.com/nextcloud/serverwww-data
aboutsummaryrefslogtreecommitdiffstats
blob: a3557d7cda6a7aac2bc34a12a1d40b52c76c5ef9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
<?php

/**
 * @copyright 2017 Christoph Wurst <christoph@winzerhof-wurst.at>
 *
 * @author 2017 Christoph Wurst <christoph@winzerhof-wurst.at>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

namespace Tests\Contacts\ContactsMenu;

use OC\App\AppManager;
use OC\Contacts\ContactsMenu\ActionProviderStore;
use OC\Contacts\ContactsMenu\Providers\EMailProvider;
use OC\Contacts\ContactsMenu\Providers\ProfileProvider;
use OCP\App\IAppManager;
use OCP\AppFramework\QueryException;
use OCP\Contacts\ContactsMenu\IProvider;
use OCP\IServerContainer;
use OCP\IUser;
use Psr\Log\LoggerInterface;
use Test\TestCase;

class ActionProviderStoreTest extends TestCase {

	/** @var IServerContainer|\PHPUnit\Framework\MockObject\MockObject */
	private $serverContainer;

	/** @var IAppManager|\PHPUnit\Framework\MockObject\MockObject */
	private $appManager;

	/** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */
	private $logger;

	/** @var ActionProviderStore */
	private $actionProviderStore;

	protected function setUp(): void {
		parent::setUp();

		$this->serverContainer = $this->createMock(IServerContainer::class);
		$this->appManager = $this->createMock(AppManager::class);
		$this->logger = $this->createMock(LoggerInterface::class);

		$this->actionProviderStore = new ActionProviderStore($this->serverContainer, $this->appManager, $this->logger);
	}

	public function testGetProviders() {
		$user = $this->createMock(IUser::class);
		$provider1 = $this->createMock(ProfileProvider::class);
		$provider2 = $this->createMock(EMailProvider::class);
		$provider3 = $this->createMock(IProvider::class);

		$this->appManager->expects($this->once())
			->method('getEnabledAppsForUser')
			->with($user)
			->willReturn(['contacts']);
		$this->appManager->expects($this->once())
			->method('getAppInfo')
			->with('contacts')
			->willReturn([
				'contactsmenu' => [
					'OCA\Contacts\Provider1',
				],
			]);
		$this->serverContainer->expects($this->exactly(3))
			->method('query')
			->willReturnMap([
				[ProfileProvider::class, true, $provider1],
				[EMailProvider::class, true, $provider2],
				['OCA\Contacts\Provider1', true, $provider3]
			]);

		$providers = $this->actionProviderStore->getProviders($user);

		$this->assertCount(3, $providers);
		$this->assertInstanceOf(ProfileProvider::class, $providers[0]);
		$this->assertInstanceOf(EMailProvider::class, $providers[1]);
	}

	public function testGetProvidersOfAppWithIncompleInfo() {
		$user = $this->createMock(IUser::class);
		$provider1 = $this->createMock(ProfileProvider::class);
		$provider2 = $this->createMock(EMailProvider::class);

		$this->appManager->expects($this->once())
			->method('getEnabledAppsForUser')
			->with($user)
			->willReturn(['contacts']);
		$this->appManager->expects($this->once())
			->method('getAppInfo')
			->with('contacts')
			->willReturn([/* Empty info.xml */]);
		$this->serverContainer->expects($this->exactly(2))
			->method('query')
			->willReturnMap([
				[ProfileProvider::class, true, $provider1],
				[EMailProvider::class, true, $provider2],
			]);

		$providers = $this->actionProviderStore->getProviders($user);

		$this->assertCount(2, $providers);
		$this->assertInstanceOf(ProfileProvider::class, $providers[0]);
		$this->assertInstanceOf(EMailProvider::class, $providers[1]);
	}


	public function testGetProvidersWithQueryException() {
		$this->expectException(\Exception::class);

		$user = $this->createMock(IUser::class);
		$this->appManager->expects($this->once())
			->method('getEnabledAppsForUser')
			->with($user)
			->willReturn([]);
		$this->serverContainer->expects($this->once())
			->method('query')
			->willThrowException(new QueryException());

		$this->actionProviderStore->getProviders($user);
	}
}