Passed
Push — master ( bf1943...bfd61d )
by Blizzz
09:37
created

OC_Mount_Config::encryptPasswords()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Andreas Fischer <[email protected]>
6
 * @author Arthur Schiwon <[email protected]>
7
 * @author Bart Visscher <[email protected]>
8
 * @author Björn Schießle <[email protected]>
9
 * @author Frank Karlitschek <[email protected]>
10
 * @author Jesús Macias <[email protected]>
11
 * @author Joas Schilling <[email protected]>
12
 * @author Juan Pablo Villafáñez <[email protected]>
13
 * @author Lukas Reschke <[email protected]>
14
 * @author Michael Gapczynski <[email protected]>
15
 * @author Morris Jobke <[email protected]>
16
 * @author Philipp Kapfer <[email protected]>
17
 * @author Robin Appelman <[email protected]>
18
 * @author Robin McCorkell <[email protected]>
19
 * @author Roeland Jago Douma <[email protected]>
20
 * @author Thomas Müller <[email protected]>
21
 * @author Vincent Petry <[email protected]>
22
 *
23
 * @license AGPL-3.0
24
 *
25
 * This code is free software: you can redistribute it and/or modify
26
 * it under the terms of the GNU Affero General Public License, version 3,
27
 * as published by the Free Software Foundation.
28
 *
29
 * This program is distributed in the hope that it will be useful,
30
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
31
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
32
 * GNU Affero General Public License for more details.
33
 *
34
 * You should have received a copy of the GNU Affero General Public License, version 3,
35
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
36
 *
37
 */
38
39
use OCA\Files_External\Config\IConfigHandler;
40
use OCA\Files_External\Config\UserPlaceholderHandler;
41
use phpseclib\Crypt\AES;
42
use \OCA\Files_External\AppInfo\Application;
43
use \OCA\Files_External\Lib\Backend\LegacyBackend;
44
use \OCA\Files_External\Lib\StorageConfig;
45
use \OCA\Files_External\Lib\Backend\Backend;
46
use \OCP\Files\StorageNotAvailableException;
47
use OCA\Files_External\Service\BackendService;
48
use OCA\Files_External\Lib\Auth\Builtin;
49
use OCA\Files_External\Service\UserGlobalStoragesService;
50
use OCP\IUserManager;
51
use OCA\Files_External\Service\GlobalStoragesService;
52
use OCA\Files_External\Service\UserStoragesService;
53
54
/**
55
 * Class to configure mount.json globally and for users
56
 */
57
class OC_Mount_Config {
58
	// TODO: make this class non-static and give it a proper namespace
59
60
	const MOUNT_TYPE_GLOBAL = 'global';
61
	const MOUNT_TYPE_GROUP = 'group';
62
	const MOUNT_TYPE_USER = 'user';
63
	const MOUNT_TYPE_PERSONAL = 'personal';
64
65
	// whether to skip backend test (for unit tests, as this static class is not mockable)
66
	public static $skipTest = false;
67
68
	/** @var Application */
69
	public static $app;
70
71
	/**
72
	 * @param string $class
73
	 * @param array $definition
74
	 * @return bool
75
	 * @deprecated 8.2.0 use \OCA\Files_External\Service\BackendService::registerBackend()
76
	 */
77
	public static function registerBackend($class, $definition) {
78
		$backendService = self::$app->getContainer()->query(BackendService::class);
79
		$auth = self::$app->getContainer()->query(Builtin::class);
80
81
		$backendService->registerBackend(new LegacyBackend($class, $definition, $auth));
82
83
		return true;
84
	}
85
86
	/**
87
	 * Returns the mount points for the given user.
88
	 * The mount point is relative to the data directory.
89
	 *
90
	 * @param string $uid user
91
	 * @return array of mount point string as key, mountpoint config as value
92
	 *
93
	 * @deprecated 8.2.0 use UserGlobalStoragesService::getStorages() and UserStoragesService::getStorages()
94
	 */
95
	public static function getAbsoluteMountPoints($uid) {
96
		$mountPoints = array();
97
98
		$userGlobalStoragesService = self::$app->getContainer()->query(UserGlobalStoragesService::class);
99
		$userStoragesService = self::$app->getContainer()->query(UserStoragesService::class);
100
		$user = self::$app->getContainer()->query(IUserManager::class)->get($uid);
101
102
		$userGlobalStoragesService->setUser($user);
103
		$userStoragesService->setUser($user);
104
105
		foreach ($userGlobalStoragesService->getStorages() as $storage) {
106
			/** @var \OCA\Files_External\Lib\StorageConfig $storage */
107
			$mountPoint = '/'.$uid.'/files'.$storage->getMountPoint();
108
			$mountEntry = self::prepareMountPointEntry($storage, false);
109
			foreach ($mountEntry['options'] as &$option) {
110
				$option = self::substitutePlaceholdersInConfig($option);
111
			}
112
			$mountPoints[$mountPoint] = $mountEntry;
113
		}
114
115
		foreach ($userStoragesService->getStorages() as $storage) {
116
			$mountPoint = '/'.$uid.'/files'.$storage->getMountPoint();
117
			$mountEntry = self::prepareMountPointEntry($storage, true);
118
			foreach ($mountEntry['options'] as &$option) {
119
				$option = self::substitutePlaceholdersInConfig($uid, $option);
0 ignored issues
show
Unused Code introduced by
The call to OC_Mount_Config::substitutePlaceholdersInConfig() has too many arguments starting with $option. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

119
				/** @scrutinizer ignore-call */ 
120
    $option = self::substitutePlaceholdersInConfig($uid, $option);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
120
			}
121
			$mountPoints[$mountPoint] = $mountEntry;
122
		}
123
124
		$userGlobalStoragesService->resetUser();
125
		$userStoragesService->resetUser();
126
127
		return $mountPoints;
128
	}
129
130
	/**
131
	 * Get the system mount points
132
	 *
133
	 * @return array
134
	 *
135
	 * @deprecated 8.2.0 use GlobalStoragesService::getStorages()
136
	 */
137
	public static function getSystemMountPoints() {
138
		$mountPoints = [];
139
		$service = self::$app->getContainer()->query(GlobalStoragesService::class);
140
141
		foreach ($service->getStorages() as $storage) {
142
			$mountPoints[] = self::prepareMountPointEntry($storage, false);
143
		}
144
145
		return $mountPoints;
146
	}
147
148
	/**
149
	 * Get the personal mount points of the current user
150
	 *
151
	 * @return array
152
	 *
153
	 * @deprecated 8.2.0 use UserStoragesService::getStorages()
154
	 */
155
	public static function getPersonalMountPoints() {
156
		$mountPoints = [];
157
		$service = self::$app->getContainer()->query(UserStoragesService::class);
158
159
		foreach ($service->getStorages() as $storage) {
160
			$mountPoints[] = self::prepareMountPointEntry($storage, true);
161
		}
162
163
		return $mountPoints;
164
	}
165
166
	/**
167
	 * Convert a StorageConfig to the legacy mountPoints array format
168
	 * There's a lot of extra information in here, to satisfy all of the legacy functions
169
	 *
170
	 * @param StorageConfig $storage
171
	 * @param bool $isPersonal
172
	 * @return array
173
	 */
174
	private static function prepareMountPointEntry(StorageConfig $storage, $isPersonal) {
175
		$mountEntry = [];
176
177
		$mountEntry['mountpoint'] = substr($storage->getMountPoint(), 1); // remove leading slash
178
		$mountEntry['class'] = $storage->getBackend()->getIdentifier();
179
		$mountEntry['backend'] = $storage->getBackend()->getText();
180
		$mountEntry['authMechanism'] = $storage->getAuthMechanism()->getIdentifier();
181
		$mountEntry['personal'] = $isPersonal;
182
		$mountEntry['options'] = self::decryptPasswords($storage->getBackendOptions());
183
		$mountEntry['mountOptions'] = $storage->getMountOptions();
184
		$mountEntry['priority'] = $storage->getPriority();
185
		$mountEntry['applicable'] = [
186
			'groups' => $storage->getApplicableGroups(),
187
			'users' => $storage->getApplicableUsers(),
188
		];
189
		// if mountpoint is applicable to all users the old API expects ['all']
190
		if (empty($mountEntry['applicable']['groups']) && empty($mountEntry['applicable']['users'])) {
191
			$mountEntry['applicable']['users'] = ['all'];
192
		}
193
194
		$mountEntry['id'] = $storage->getId();
195
196
		return $mountEntry;
197
	}
198
199
	/**
200
	 * fill in the correct values for $user
201
	 *
202
	 * @param string $user user value
203
	 * @param string|array $input
204
	 * @return string
205
	 * @deprecated use self::substitutePlaceholdersInConfig($input)
206
	 */
207
	public static function setUserVars($user, $input) {
0 ignored issues
show
Unused Code introduced by
The parameter $user is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

207
	public static function setUserVars(/** @scrutinizer ignore-unused */ $user, $input) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
208
		$handler = self::$app->getContainer()->query(UserPlaceholderHandler::class);
209
		return $handler->handle($input);
210
	}
211
212
	/**
213
	 * @param mixed $input
214
	 * @return mixed
215
	 * @throws \OCP\AppFramework\QueryException
216
	 * @since 16.0.0
217
	 */
218
	public static function substitutePlaceholdersInConfig($input) {
219
		/** @var BackendService $backendService */
220
		$backendService = self::$app->getContainer()->query(BackendService::class);
221
		/** @var IConfigHandler[] $handlers */
222
		$handlers = $backendService->getConfigHandlers();
223
		foreach ($handlers as $handler) {
224
			$input = $handler->handle($input);
225
		}
226
		return $input;
227
	}
228
229
	/**
230
	 * Test connecting using the given backend configuration
231
	 *
232
	 * @param string $class backend class name
233
	 * @param array $options backend configuration options
234
	 * @param boolean $isPersonal
235
	 * @return int see self::STATUS_*
236
	 * @throws Exception
237
	 */
238
	public static function getBackendStatus($class, $options, $isPersonal, $testOnly = true) {
239
		if (self::$skipTest) {
240
			return StorageNotAvailableException::STATUS_SUCCESS;
241
		}
242
		foreach ($options as &$option) {
243
			$option = self::substitutePlaceholdersInConfig($option);
244
			if(!self::arePlaceholdersSubstituted($option)) {
245
				\OC::$server->getLogger()->error(
246
					'A placeholder was not substituted: {option} for mount type {class}',
247
					[
248
						'app' => 'files_external',
249
						'option' => $option,
250
						'class' => $class,
251
					]
252
				);
253
				throw new StorageNotAvailableException(
254
					'Mount configuration incomplete',
255
					StorageNotAvailableException::STATUS_INCOMPLETE_CONF
256
				);
257
			}
258
		}
259
		if (class_exists($class)) {
260
			try {
261
				/** @var \OC\Files\Storage\Common $storage */
262
				$storage = new $class($options);
263
264
				try {
265
					$result = $storage->test($isPersonal, $testOnly);
0 ignored issues
show
Unused Code introduced by
The call to OC\Files\Storage\Common::test() has too many arguments starting with $isPersonal. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

265
					/** @scrutinizer ignore-call */ 
266
     $result = $storage->test($isPersonal, $testOnly);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
266
					$storage->setAvailability($result);
267
					if ($result) {
268
						return StorageNotAvailableException::STATUS_SUCCESS;
269
					}
270
				} catch (\Exception $e) {
271
					$storage->setAvailability(false);
272
					throw $e;
273
				}
274
			} catch (Exception $exception) {
275
				\OC::$server->getLogger()->logException($exception, ['app' => 'files_external']);
276
				throw $exception;
277
			}
278
		}
279
		return StorageNotAvailableException::STATUS_ERROR;
280
	}
281
282
	public static function arePlaceholdersSubstituted($option):bool {
283
		$result = true;
284
		if(is_array($option)) {
285
			foreach ($option as $optionItem) {
286
				if(is_array($optionItem)) {
287
					$result = $result && self::arePlaceholdersSubstituted($option);
288
				}
289
			}
290
		} else if (is_string($option)) {
291
			if (strpos($option, '$') !== false) {
292
				$result = false;
293
			}
294
		}
295
		return $result;
296
	}
297
298
	/**
299
	 * Read the mount points in the config file into an array
300
	 *
301
	 * @param string|null $user If not null, personal for $user, otherwise system
302
	 * @return array
303
	 */
304
	public static function readData($user = null) {
305
		if (isset($user)) {
306
			$jsonFile = \OC::$server->getUserManager()->get($user)->getHome() . '/mount.json';
307
		} else {
308
			$config = \OC::$server->getConfig();
309
			$datadir = $config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/');
310
			$jsonFile = $config->getSystemValue('mount_file', $datadir . '/mount.json');
311
		}
312
		if (is_file($jsonFile)) {
313
			$mountPoints = json_decode(file_get_contents($jsonFile), true);
314
			if (is_array($mountPoints)) {
315
				return $mountPoints;
316
			}
317
		}
318
		return array();
319
	}
320
321
	/**
322
	 * Get backend dependency message
323
	 * TODO: move into AppFramework along with templates
324
	 *
325
	 * @param Backend[] $backends
326
	 * @return string
327
	 */
328
	public static function dependencyMessage($backends) {
329
		$l = \OC::$server->getL10N('files_external');
330
		$message = '';
331
		$dependencyGroups = [];
332
333
		foreach ($backends as $backend) {
334
			foreach ($backend->checkDependencies() as $dependency) {
335
				if ($message = $dependency->getMessage()) {
336
					$message .= '<p>' . $message . '</p>';
337
				} else {
338
					$dependencyGroups[$dependency->getDependency()][] = $backend;
339
				}
340
			}
341
		}
342
343
		foreach ($dependencyGroups as $module => $dependants) {
344
			$backends = implode(', ', array_map(function($backend) {
345
				return '"' . $backend->getText() . '"';
346
			}, $dependants));
347
			$message .= '<p>' . OC_Mount_Config::getSingleDependencyMessage($l, $module, $backends) . '</p>';
348
		}
349
350
		return $message;
351
	}
352
353
	/**
354
	 * Returns a dependency missing message
355
	 *
356
	 * @param \OCP\IL10N $l
357
	 * @param string $module
358
	 * @param string $backend
359
	 * @return string
360
	 */
361
	private static function getSingleDependencyMessage(\OCP\IL10N $l, $module, $backend) {
362
		switch (strtolower($module)) {
363
			case 'curl':
364
				return (string)$l->t('The cURL support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it.', [$backend]);
365
			case 'ftp':
366
				return (string)$l->t('The FTP support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it.', [$backend]);
367
			default:
368
				return (string)$l->t('"%1$s" is not installed. Mounting of %2$s is not possible. Please ask your system administrator to install it.', [$module, $backend]);
369
		}
370
	}
371
372
	/**
373
	 * Encrypt passwords in the given config options
374
	 *
375
	 * @param array $options mount options
376
	 * @return array updated options
377
	 */
378
	public static function encryptPasswords($options) {
379
		if (isset($options['password'])) {
380
			$options['password_encrypted'] = self::encryptPassword($options['password']);
381
			// do not unset the password, we want to keep the keys order
382
			// on load... because that's how the UI currently works
383
			$options['password'] = '';
384
		}
385
		return $options;
386
	}
387
388
	/**
389
	 * Decrypt passwords in the given config options
390
	 *
391
	 * @param array $options mount options
392
	 * @return array updated options
393
	 */
394
	public static function decryptPasswords($options) {
395
		// note: legacy options might still have the unencrypted password in the "password" field
396
		if (isset($options['password_encrypted'])) {
397
			$options['password'] = self::decryptPassword($options['password_encrypted']);
398
			unset($options['password_encrypted']);
399
		}
400
		return $options;
401
	}
402
403
	/**
404
	 * Encrypt a single password
405
	 *
406
	 * @param string $password plain text password
407
	 * @return string encrypted password
408
	 */
409
	private static function encryptPassword($password) {
410
		$cipher = self::getCipher();
411
		$iv = \OC::$server->getSecureRandom()->generate(16);
412
		$cipher->setIV($iv);
413
		return base64_encode($iv . $cipher->encrypt($password));
414
	}
415
416
	/**
417
	 * Decrypts a single password
418
	 *
419
	 * @param string $encryptedPassword encrypted password
420
	 * @return string plain text password
421
	 */
422
	private static function decryptPassword($encryptedPassword) {
423
		$cipher = self::getCipher();
424
		$binaryPassword = base64_decode($encryptedPassword);
425
		$iv = substr($binaryPassword, 0, 16);
426
		$cipher->setIV($iv);
427
		$binaryPassword = substr($binaryPassword, 16);
428
		return $cipher->decrypt($binaryPassword);
429
	}
430
431
	/**
432
	 * Returns the encryption cipher
433
	 *
434
	 * @return AES
435
	 */
436
	private static function getCipher() {
437
		$cipher = new AES(AES::MODE_CBC);
438
		$cipher->setKey(\OC::$server->getConfig()->getSystemValue('passwordsalt', null));
439
		return $cipher;
440
	}
441
442
	/**
443
	 * Computes a hash based on the given configuration.
444
	 * This is mostly used to find out whether configurations
445
	 * are the same.
446
	 *
447
	 * @param array $config
448
	 * @return string
449
	 */
450
	public static function makeConfigHash($config) {
451
		$data = json_encode(
452
			array(
453
				'c' => $config['backend'],
454
				'a' => $config['authMechanism'],
455
				'm' => $config['mountpoint'],
456
				'o' => $config['options'],
457
				'p' => isset($config['priority']) ? $config['priority'] : -1,
458
				'mo' => isset($config['mountOptions']) ? $config['mountOptions'] : [],
459
			)
460
		);
461
		return hash('md5', $data);
462
	}
463
}
464