Blame view

sources/apps/files_encryption/lib/util.php 44.7 KB
03e52840d   Kload   Init
1
2
3
4
  <?php
  /**
   * ownCloud
   *
a293d369c   Kload   Update sources to...
5
   * @author Sam Tuke, Frank Karlitschek, Bjoern Schiessle
03e52840d   Kload   Init
6
   * @copyright 2012 Sam Tuke <samtuke@owncloud.com>,
a293d369c   Kload   Update sources to...
7
8
   * Frank Karlitschek <frank@owncloud.org>,
   * Bjoern Schiessle <schiessle@owncloud.com>
03e52840d   Kload   Init
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
   *
   * This library is free software; you can redistribute it and/or
   * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
   * License as published by the Free Software Foundation; either
   * version 3 of the License, or any later version.
   *
   * This library 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 library.  If not, see <http://www.gnu.org/licenses/>.
   *
   */
03e52840d   Kload   Init
24
25
26
  namespace OCA\Encryption;
  
  /**
6d9380f96   Cédric Dupont   Update sources OC...
27
28
   * Class for utilities relating to encrypted file storage system
   * @param \OC\Files\View $view expected to have OC '/' as root path
03e52840d   Kload   Init
29
30
31
32
33
34
   * @param string $userId ID of the logged in user
   * @param int $client indicating status of client side encryption. Currently
   * unused, likely to become obsolete shortly
   */
  
  class Util {
03e52840d   Kload   Init
35
36
37
  	const MIGRATION_COMPLETED = 1;    // migration to new encryption completed
  	const MIGRATION_IN_PROGRESS = -1; // migration is running
  	const MIGRATION_OPEN = 0;         // user still needs to be migrated
6d9380f96   Cédric Dupont   Update sources OC...
38
  	private $view; // OC\Files\View object for filesystem operations
31b7f2792   Kload   Upgrade to ownclo...
39
40
  	private $userId; // ID of the user we use to encrypt/decrypt files
  	private $keyId; // ID of the key we want to manipulate
03e52840d   Kload   Init
41
42
43
44
45
46
47
48
49
50
51
52
  	private $client; // Client side encryption mode flag
  	private $publicKeyDir; // Dir containing all public user keys
  	private $encryptionDir; // Dir containing user's files_encryption
  	private $keyfilesPath; // Dir containing user's keyfiles
  	private $shareKeysPath; // Dir containing env keys for shared files
  	private $publicKeyPath; // Path to user's public key
  	private $privateKeyPath; // Path to user's private key
  	private $publicShareKeyId;
  	private $recoveryKeyId;
  	private $isPublic;
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
53
54
  	 * @param \OC\Files\View $view
  	 * @param string $userId
03e52840d   Kload   Init
55
56
  	 * @param bool $client
  	 */
a293d369c   Kload   Update sources to...
57
  	public function __construct($view, $userId, $client = false) {
03e52840d   Kload   Init
58
59
  
  		$this->view = $view;
03e52840d   Kload   Init
60
  		$this->client = $client;
31b7f2792   Kload   Upgrade to ownclo...
61
  		$this->userId = $userId;
03e52840d   Kload   Init
62

6d9380f96   Cédric Dupont   Update sources OC...
63
64
65
66
  		$appConfig = \OC::$server->getAppConfig();
  
  		$this->publicShareKeyId = $appConfig->getValue('files_encryption', 'publicShareKeyId');
  		$this->recoveryKeyId = $appConfig->getValue('files_encryption', 'recoveryKeyId');
03e52840d   Kload   Init
67

31b7f2792   Kload   Upgrade to ownclo...
68
69
70
71
72
73
74
75
76
  		$this->userDir = '/' . $this->userId;
  		$this->fileFolderName = 'files';
  		$this->userFilesDir =
  				'/' . $userId . '/' . $this->fileFolderName; // TODO: Does this need to be user configurable?
  		$this->publicKeyDir = '/' . 'public-keys';
  		$this->encryptionDir = '/' . $this->userId . '/' . 'files_encryption';
  		$this->keyfilesPath = $this->encryptionDir . '/' . 'keyfiles';
  		$this->shareKeysPath = $this->encryptionDir . '/' . 'share-keys';
  		$this->publicKeyPath =
03e52840d   Kload   Init
77
  				$this->publicKeyDir . '/' . $this->userId . '.public.key'; // e.g. data/public-keys/admin.public.key
31b7f2792   Kload   Upgrade to ownclo...
78
  		$this->privateKeyPath =
03e52840d   Kload   Init
79
  				$this->encryptionDir . '/' . $this->userId . '.private.key'; // e.g. data/admin/admin.private.key
31b7f2792   Kload   Upgrade to ownclo...
80
81
82
83
84
85
86
87
88
  		// make sure that the owners home is mounted
  		\OC\Files\Filesystem::initMountPoints($userId);
  
  		if (\OCA\Encryption\Helper::isPublicAccess()) {
  			$this->keyId = $this->publicShareKeyId;
  			$this->isPublic = true;
  		} else {
  			$this->keyId = $this->userId;
  			$this->isPublic = false;
03e52840d   Kload   Init
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
  		}
  	}
  
  	/**
  	 * @return bool
  	 */
  	public function ready() {
  
  		if (
  			!$this->view->file_exists($this->encryptionDir)
  			or !$this->view->file_exists($this->keyfilesPath)
  			or !$this->view->file_exists($this->shareKeysPath)
  			or !$this->view->file_exists($this->publicKeyPath)
  			or !$this->view->file_exists($this->privateKeyPath)
  		) {
03e52840d   Kload   Init
104
  			return false;
03e52840d   Kload   Init
105
  		} else {
03e52840d   Kload   Init
106
  			return true;
03e52840d   Kload   Init
107
  		}
31b7f2792   Kload   Upgrade to ownclo...
108
  	}
03e52840d   Kload   Init
109

31b7f2792   Kload   Upgrade to ownclo...
110
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
111
  	 * check if the users private & public key exists
31b7f2792   Kload   Upgrade to ownclo...
112
113
114
115
116
117
118
119
120
121
  	 * @return boolean
  	 */
  	public function userKeysExists() {
  		if (
  				$this->view->file_exists($this->privateKeyPath) &&
  				$this->view->file_exists($this->publicKeyPath)) {
  			return true;
  		} else {
  			return false;
  		}
03e52840d   Kload   Init
122
123
124
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
125
  	 * Sets up user folders and keys for serverside encryption
03e52840d   Kload   Init
126
127
128
129
130
131
132
133
134
  	 *
  	 * @param string $passphrase to encrypt server-stored private key with
  	 * @return bool
  	 */
  	public function setupServerSide($passphrase = null) {
  
  		// Set directories to check / create
  		$setUpDirs = array(
  			$this->userDir,
03e52840d   Kload   Init
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
  			$this->publicKeyDir,
  			$this->encryptionDir,
  			$this->keyfilesPath,
  			$this->shareKeysPath
  		);
  
  		// Check / create all necessary dirs
  		foreach ($setUpDirs as $dirPath) {
  
  			if (!$this->view->file_exists($dirPath)) {
  
  				$this->view->mkdir($dirPath);
  
  			}
  
  		}
  
  		// Create user keypair
  		// we should never override a keyfile
  		if (
  			!$this->view->file_exists($this->publicKeyPath)
  			&& !$this->view->file_exists($this->privateKeyPath)
  		) {
  
  			// Generate keypair
  			$keypair = Crypt::createKeypair();
  
  			if ($keypair) {
  
  				\OC_FileProxy::$enabled = false;
  
  				// Encrypt private key with user pwd as passphrase
f7d878ff1   kload   [enh] Update to 7...
167
  				$encryptedPrivateKey = Crypt::symmetricEncryptFileContent($keypair['privateKey'], $passphrase, Helper::getCipher());
03e52840d   Kload   Init
168
169
170
  
  				// Save key-pair
  				if ($encryptedPrivateKey) {
f7d878ff1   kload   [enh] Update to 7...
171
172
  					$header = crypt::generateHeader();
  					$this->view->file_put_contents($this->privateKeyPath, $header . $encryptedPrivateKey);
03e52840d   Kload   Init
173
174
175
176
177
178
179
180
181
182
  					$this->view->file_put_contents($this->publicKeyPath, $keypair['publicKey']);
  				}
  
  				\OC_FileProxy::$enabled = true;
  			}
  
  		} else {
  			// check if public-key exists but private-key is missing
  			if ($this->view->file_exists($this->publicKeyPath) && !$this->view->file_exists($this->privateKeyPath)) {
  				\OCP\Util::writeLog('Encryption library',
31b7f2792   Kload   Upgrade to ownclo...
183
  					'public key exists but private key is missing for "' . $this->keyId . '"', \OCP\Util::FATAL);
03e52840d   Kload   Init
184
185
186
187
188
  				return false;
  			} else {
  				if (!$this->view->file_exists($this->publicKeyPath) && $this->view->file_exists($this->privateKeyPath)
  				) {
  					\OCP\Util::writeLog('Encryption library',
31b7f2792   Kload   Upgrade to ownclo...
189
  						'private key exists but public key is missing for "' . $this->keyId . '"', \OCP\Util::FATAL);
03e52840d   Kload   Init
190
191
192
193
  					return false;
  				}
  			}
  		}
03e52840d   Kload   Init
194
195
196
197
198
199
200
201
202
203
204
205
  		return true;
  
  	}
  
  	/**
  	 * @return string
  	 */
  	public function getPublicShareKeyId() {
  		return $this->publicShareKeyId;
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
206
  	 * Check whether pwd recovery is enabled for a given user
03e52840d   Kload   Init
207
208
209
210
211
212
  	 * @return bool 1 = yes, 0 = no, false = no record
  	 *
  	 * @note If records are not being returned, check for a hidden space
  	 *       at the start of the uid in db
  	 */
  	public function recoveryEnabledForUser() {
6d9380f96   Cédric Dupont   Update sources OC...
213
  		$recoveryMode = \OC_Preferences::getValue($this->userId, 'files_encryption', 'recovery_enabled', '0');
03e52840d   Kload   Init
214

6d9380f96   Cédric Dupont   Update sources OC...
215
  		return ($recoveryMode === '1') ? true : false;
03e52840d   Kload   Init
216
217
218
219
  
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
220
  	 * Enable / disable pwd recovery for a given user
03e52840d   Kload   Init
221
222
223
224
  	 * @param bool $enabled Whether to enable or disable recovery
  	 * @return bool
  	 */
  	public function setRecoveryForUser($enabled) {
6d9380f96   Cédric Dupont   Update sources OC...
225
226
  		$value = $enabled ? '1' : '0';
  		return \OC_Preferences::setValue($this->userId, 'files_encryption', 'recovery_enabled', $value);
03e52840d   Kload   Init
227
228
229
230
  
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
231
  	 * Find all files and their encryption status within a directory
03e52840d   Kload   Init
232
233
  	 * @param string $directory The path of the parent directory to search
  	 * @param bool $found the founded files if called again
6d9380f96   Cédric Dupont   Update sources OC...
234
  	 * @return array keys: plain, encrypted, legacy, broken
03e52840d   Kload   Init
235
236
237
238
239
240
241
242
243
244
245
246
247
  	 * @note $directory needs to be a path relative to OC data dir. e.g.
  	 *       /admin/files NOT /backup OR /home/www/oc/data/admin/files
  	 */
  	public function findEncFiles($directory, &$found = false) {
  
  		// Disable proxy - we don't want files to be decrypted before
  		// we handle them
  		\OC_FileProxy::$enabled = false;
  
  		if ($found === false) {
  			$found = array(
  				'plain' => array(),
  				'encrypted' => array(),
a293d369c   Kload   Update sources to...
248
249
  				'legacy' => array(),
  				'broken' => array(),
03e52840d   Kload   Init
250
251
  			);
  		}
6d9380f96   Cédric Dupont   Update sources OC...
252
253
  		if ($this->view->is_dir($directory) && $handle = $this->view->opendir($directory)){
  			if (is_resource($handle)) {
31b7f2792   Kload   Upgrade to ownclo...
254
  				while (false !== ($file = readdir($handle))) {
a293d369c   Kload   Update sources to...
255
  					if ($file !== "." && $file !== "..") {
31b7f2792   Kload   Upgrade to ownclo...
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
  
  						$filePath = $directory . '/' . $this->view->getRelativePath('/' . $file);
  						$relPath = \OCA\Encryption\Helper::stripUserFilesPath($filePath);
  
  						// If the path is a directory, search
  						// its contents
  						if ($this->view->is_dir($filePath)) {
  
  							$this->findEncFiles($filePath, $found);
  
  							// If the path is a file, determine
  							// its encryption status
  						} elseif ($this->view->is_file($filePath)) {
  
  							// Disable proxies again, some-
  							// where they got re-enabled :/
  							\OC_FileProxy::$enabled = false;
  
  							$isEncryptedPath = $this->isEncryptedPath($filePath);
  							// If the file is encrypted
  							// NOTE: If the userId is
  							// empty or not set, file will
  							// detected as plain
  							// NOTE: This is inefficient;
  							// scanning every file like this
  							// will eat server resources :(
a293d369c   Kload   Update sources to...
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
  							if ($isEncryptedPath) {
  
  								$fileKey = Keymanager::getFileKey($this->view, $this, $relPath);
  								$shareKey = Keymanager::getShareKey($this->view, $this->userId, $this, $relPath);
  								// if file is encrypted but now file key is available, throw exception
  								if ($fileKey === false || $shareKey === false) {
  									\OCP\Util::writeLog('encryption library', 'No keys available to decrypt the file: ' . $filePath, \OCP\Util::ERROR);
  									$found['broken'][] = array(
  										'name' => $file,
  										'path' => $filePath,
  									);
  								} else {
  									$found['encrypted'][] = array(
  										'name' => $file,
  										'path' => $filePath,
  									);
  								}
31b7f2792   Kload   Upgrade to ownclo...
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
  
  								// If the file uses old
  								// encryption system
  							} elseif (Crypt::isLegacyEncryptedContent($isEncryptedPath, $relPath)) {
  
  								$found['legacy'][] = array(
  									'name' => $file,
  									'path' => $filePath
  								);
  
  								// If the file is not encrypted
  							} else {
  
  								$found['plain'][] = array(
  									'name' => $file,
  									'path' => $relPath
  								);
31b7f2792   Kload   Upgrade to ownclo...
316
  							}
03e52840d   Kload   Init
317
  						}
03e52840d   Kload   Init
318
  					}
03e52840d   Kload   Init
319
  				}
03e52840d   Kload   Init
320
  			}
03e52840d   Kload   Init
321
  		}
03e52840d   Kload   Init
322
  		\OC_FileProxy::$enabled = true;
6d9380f96   Cédric Dupont   Update sources OC...
323
  		return $found;
03e52840d   Kload   Init
324
325
326
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
327
  	 * Check if a given path identifies an encrypted file
03e52840d   Kload   Init
328
329
330
331
  	 * @param string $path
  	 * @return boolean
  	 */
  	public function isEncryptedPath($path) {
a293d369c   Kload   Update sources to...
332
333
334
335
  		// Disable encryption proxy so data retrieved is in its
  		// original form
  		$proxyStatus = \OC_FileProxy::$enabled;
  		\OC_FileProxy::$enabled = false;
03e52840d   Kload   Init
336

a293d369c   Kload   Update sources to...
337
  		$data = '';
6d9380f96   Cédric Dupont   Update sources OC...
338
339
340
341
342
343
344
345
  
  		// we only need 24 byte from the last chunk
  		if ($this->view->file_exists($path)) {
  			$handle = $this->view->fopen($path, 'r');
  			if (is_resource($handle)) {
  				// suppress fseek warining, we handle the case that fseek doesn't
  				// work in the else branch
  				if (@fseek($handle, -24, SEEK_END) === 0) {
837968727   Kload   [enh] Upgrade to ...
346
  					$data = fgets($handle);
6d9380f96   Cédric Dupont   Update sources OC...
347
348
349
350
351
352
353
354
355
  				} else {
  					// if fseek failed on the storage we create a local copy from the file
  					// and read this one
  					fclose($handle);
  					$localFile = $this->view->getLocalFile($path);
  					$handle = fopen($localFile, 'r');
  					if (is_resource($handle) && fseek($handle, -24, SEEK_END) === 0) {
  						$data = fgets($handle);
  					}
837968727   Kload   [enh] Upgrade to ...
356
  				}
6d9380f96   Cédric Dupont   Update sources OC...
357
  				fclose($handle);
837968727   Kload   [enh] Upgrade to ...
358
  			}
03e52840d   Kload   Init
359
  		}
a293d369c   Kload   Update sources to...
360
361
  		// re-enable proxy
  		\OC_FileProxy::$enabled = $proxyStatus;
03e52840d   Kload   Init
362

a293d369c   Kload   Update sources to...
363
  		return Crypt::isCatfileContent($data);
03e52840d   Kload   Init
364
365
366
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
367
  	 * get the file size of the unencrypted file
03e52840d   Kload   Init
368
369
370
371
372
373
374
375
376
377
378
379
380
  	 * @param string $path absolute path
  	 * @return bool
  	 */
  	public function getFileSize($path) {
  
  		$result = 0;
  
  		// Disable encryption proxy to prevent recursive calls
  		$proxyStatus = \OC_FileProxy::$enabled;
  		\OC_FileProxy::$enabled = false;
  
  		// split the path parts
  		$pathParts = explode('/', $path);
03e52840d   Kload   Init
381
382
383
  		if (isset($pathParts[2]) && $pathParts[2] === 'files' && $this->view->file_exists($path)
  			&& $this->isEncryptedPath($path)
  		) {
f7d878ff1   kload   [enh] Update to 7...
384
385
386
387
388
389
390
391
  			$offset = 0;
  			if ($this->containHeader($path)) {
  				$offset = Crypt::BLOCKSIZE;
  			}
  
  			// get the size from filesystem if the file contains a encryption header we
  			// we substract it
  			$size = $this->view->filesize($path) - $offset;
03e52840d   Kload   Init
392
393
394
395
396
397
398
399
400
401
  
  			// fast path, else the calculation for $lastChunkNr is bogus
  			if ($size === 0) {
  				\OC_FileProxy::$enabled = $proxyStatus;
  				return 0;
  			}
  
  			// calculate last chunk nr
  			// next highest is end of chunks, one subtracted is last one
  			// we have to read the last chunk, we can't just calculate it (because of padding etc)
f7d878ff1   kload   [enh] Update to 7...
402
403
  			$lastChunkNr = ceil($size/ Crypt::BLOCKSIZE) - 1;
  			$lastChunkSize = $size - ($lastChunkNr * Crypt::BLOCKSIZE);
03e52840d   Kload   Init
404
405
  
  			// open stream
31b7f2792   Kload   Upgrade to ownclo...
406
  			$stream = fopen('crypt://' . $path, "r");
03e52840d   Kload   Init
407
408
409
  
  			if (is_resource($stream)) {
  				// calculate last chunk position
f7d878ff1   kload   [enh] Update to 7...
410
  				$lastChunckPos = ($lastChunkNr * Crypt::BLOCKSIZE);
03e52840d   Kload   Init
411
412
  
  				// seek to end
837968727   Kload   [enh] Upgrade to ...
413
414
415
416
417
418
419
420
421
422
423
424
425
426
  				if (@fseek($stream, $lastChunckPos) === -1) {
  					// storage doesn't support fseek, we need a local copy
  					fclose($stream);
  					$localFile = $this->view->getLocalFile($path);
  					Helper::addTmpFileToMapper($localFile, $path);
  					$stream = fopen('crypt://' . $localFile, "r");
  					if (fseek($stream, $lastChunckPos) === -1) {
  						// if fseek also fails on the local storage, than
  						// there is nothing we can do
  						fclose($stream);
  						\OCP\Util::writeLog('Encryption library', 'couldn\'t determine size of "' . $path, \OCP\Util::ERROR);
  						return $result;
  					}
  				}
03e52840d   Kload   Init
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
  
  				// get the content of the last chunk
  				$lastChunkContent = fread($stream, $lastChunkSize);
  
  				// calc the real file size with the size of the last chunk
  				$realSize = (($lastChunkNr * 6126) + strlen($lastChunkContent));
  
  				// store file size
  				$result = $realSize;
  			}
  		}
  
  		\OC_FileProxy::$enabled = $proxyStatus;
  
  		return $result;
  	}
  
  	/**
f7d878ff1   kload   [enh] Update to 7...
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
  	 * check if encrypted file contain a encryption header
  	 *
  	 * @param string $path
  	 * @return boolean
  	 */
  	private function containHeader($path) {
  		// Disable encryption proxy to read the raw data
  		$proxyStatus = \OC_FileProxy::$enabled;
  		\OC_FileProxy::$enabled = false;
  
  		$isHeader = false;
  		$handle = $this->view->fopen($path, 'r');
  
  		if (is_resource($handle)) {
  			$firstBlock = fread($handle, Crypt::BLOCKSIZE);
  			$isHeader =  Crypt::isHeader($firstBlock);
  		}
  
  		\OC_FileProxy::$enabled = $proxyStatus;
  
  		return $isHeader;
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
469
  	 * fix the file size of the encrypted file
03e52840d   Kload   Init
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
  	 * @param string $path absolute path
  	 * @return boolean true / false if file is encrypted
  	 */
  	public function fixFileSize($path) {
  
  		$result = false;
  
  		// Disable encryption proxy to prevent recursive calls
  		$proxyStatus = \OC_FileProxy::$enabled;
  		\OC_FileProxy::$enabled = false;
  
  		$realSize = $this->getFileSize($path);
  
  		if ($realSize > 0) {
  
  			$cached = $this->view->getFileInfo($path);
  			$cached['encrypted'] = true;
  
  			// set the size
  			$cached['unencrypted_size'] = $realSize;
  
  			// put file info
  			$this->view->putFileInfo($path, $cached);
  
  			$result = true;
  
  		}
  
  		\OC_FileProxy::$enabled = $proxyStatus;
  
  		return $result;
  	}
03e52840d   Kload   Init
502
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
503
  	 * encrypt versions from given file
31b7f2792   Kload   Upgrade to ownclo...
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
  	 * @param array $filelist list of encrypted files, relative to data/user/files
  	 * @return boolean
  	 */
  	private function encryptVersions($filelist) {
  
  		$successful = true;
  
  		if (\OCP\App::isEnabled('files_versions')) {
  
  			foreach ($filelist as $filename) {
  
  				$versions = \OCA\Files_Versions\Storage::getVersions($this->userId, $filename);
  				foreach ($versions as $version) {
  
  					$path = '/' . $this->userId . '/files_versions/' . $version['path'] . '.v' . $version['version'];
  
  					$encHandle = fopen('crypt://' . $path . '.part', 'wb');
  
  					if ($encHandle === false) {
  						\OCP\Util::writeLog('Encryption library', 'couldn\'t open "' . $path . '", decryption failed!', \OCP\Util::FATAL);
  						$successful = false;
  						continue;
  					}
  
  					$plainHandle = $this->view->fopen($path, 'rb');
  					if ($plainHandle === false) {
  						\OCP\Util::writeLog('Encryption library', 'couldn\'t open "' . $path . '.part", decryption failed!', \OCP\Util::FATAL);
  						$successful = false;
  						continue;
  					}
  
  					stream_copy_to_stream($plainHandle, $encHandle);
  
  					fclose($encHandle);
  					fclose($plainHandle);
  
  					$this->view->rename($path . '.part', $path);
  				}
  			}
  		}
  
  		return $successful;
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
549
  	 * decrypt versions from given file
31b7f2792   Kload   Upgrade to ownclo...
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
  	 * @param string $filelist list of decrypted files, relative to data/user/files
  	 * @return boolean
  	 */
  	private function decryptVersions($filelist) {
  
  		$successful = true;
  
  		if (\OCP\App::isEnabled('files_versions')) {
  
  			foreach ($filelist as $filename) {
  
  				$versions = \OCA\Files_Versions\Storage::getVersions($this->userId, $filename);
  				foreach ($versions as $version) {
  
  					$path = '/' . $this->userId . '/files_versions/' . $version['path'] . '.v' . $version['version'];
  
  					$encHandle = fopen('crypt://' . $path, 'rb');
  
  					if ($encHandle === false) {
  						\OCP\Util::writeLog('Encryption library', 'couldn\'t open "' . $path . '", decryption failed!', \OCP\Util::FATAL);
  						$successful = false;
  						continue;
  					}
  
  					$plainHandle = $this->view->fopen($path . '.part', 'wb');
  					if ($plainHandle === false) {
  						\OCP\Util::writeLog('Encryption library', 'couldn\'t open "' . $path . '.part", decryption failed!', \OCP\Util::FATAL);
  						$successful = false;
  						continue;
  					}
  
  					stream_copy_to_stream($encHandle, $plainHandle);
  
  					fclose($encHandle);
  					fclose($plainHandle);
  
  					$this->view->rename($path . '.part', $path);
  				}
  			}
  		}
  
  		return $successful;
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
595
  	 * Decrypt all files
31b7f2792   Kload   Upgrade to ownclo...
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
  	 * @return bool
  	 */
  	public function decryptAll() {
  
  		$found = $this->findEncFiles($this->userId . '/files');
  
  		$successful = true;
  
  		if ($found) {
  
  			$versionStatus = \OCP\App::isEnabled('files_versions');
  			\OC_App::disable('files_versions');
  
  			$decryptedFiles = array();
  
  			// Encrypt unencrypted files
  			foreach ($found['encrypted'] as $encryptedFile) {
  
  				//relative to data/<user>/file
  				$relPath = Helper::stripUserFilesPath($encryptedFile['path']);
  
  				//get file info
  				$fileInfo = \OC\Files\Filesystem::getFileInfo($relPath);
  
  				//relative to /data
  				$rawPath = $encryptedFile['path'];
  
  				//get timestamp
  				$timestamp = $fileInfo['mtime'];
  
  				//enable proxy to use OC\Files\View to access the original file
  				\OC_FileProxy::$enabled = true;
  
  				// Open enc file handle for binary reading
  				$encHandle = $this->view->fopen($rawPath, 'rb');
  
  				// Disable proxy to prevent file being encrypted again
  				\OC_FileProxy::$enabled = false;
  
  				if ($encHandle === false) {
  					\OCP\Util::writeLog('Encryption library', 'couldn\'t open "' . $rawPath . '", decryption failed!', \OCP\Util::FATAL);
  					$successful = false;
  					continue;
  				}
  
  				// Open plain file handle for binary writing, with same filename as original plain file
  				$plainHandle = $this->view->fopen($rawPath . '.part', 'wb');
  				if ($plainHandle === false) {
  					\OCP\Util::writeLog('Encryption library', 'couldn\'t open "' . $rawPath . '.part", decryption failed!', \OCP\Util::FATAL);
  					$successful = false;
  					continue;
  				}
  
  				// Move plain file to a temporary location
  				$size = stream_copy_to_stream($encHandle, $plainHandle);
  				if ($size === 0) {
  					\OCP\Util::writeLog('Encryption library', 'Zero bytes copied of "' . $rawPath . '", decryption failed!', \OCP\Util::FATAL);
  					$successful = false;
  					continue;
  				}
  
  				fclose($encHandle);
  				fclose($plainHandle);
  
  				$fakeRoot = $this->view->getRoot();
  				$this->view->chroot('/' . $this->userId . '/files');
  
  				$this->view->rename($relPath . '.part', $relPath);
  
  				//set timestamp
  				$this->view->touch($relPath, $timestamp);
  
  				$this->view->chroot($fakeRoot);
  
  				// Add the file to the cache
  				\OC\Files\Filesystem::putFileInfo($relPath, array(
  					'encrypted' => false,
  					'size' => $size,
  					'unencrypted_size' => 0,
  					'etag' => $fileInfo['etag']
  				));
  
  				$decryptedFiles[] = $relPath;
  
  			}
  
  			if ($versionStatus) {
  				\OC_App::enable('files_versions');
  			}
  
  			if (!$this->decryptVersions($decryptedFiles)) {
  				$successful = false;
  			}
a293d369c   Kload   Update sources to...
689
690
691
692
693
  			// if there are broken encrypted files than the complete decryption
  			// was not successful
  			if (!empty($found['broken'])) {
  				$successful = false;
  			}
31b7f2792   Kload   Upgrade to ownclo...
694
  			if ($successful) {
6d9380f96   Cédric Dupont   Update sources OC...
695
696
  				$this->view->rename($this->keyfilesPath, $this->keyfilesPath . '.backup');
  				$this->view->rename($this->shareKeysPath, $this->shareKeysPath . '.backup');
31b7f2792   Kload   Upgrade to ownclo...
697
698
699
700
701
702
703
704
705
  			}
  
  			\OC_FileProxy::$enabled = true;
  		}
  
  		return $successful;
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
706
  	 * Encrypt all files in a directory
03e52840d   Kload   Init
707
708
709
710
711
712
713
  	 * @param string $dirPath the directory whose files will be encrypted
  	 * @param null $legacyPassphrase
  	 * @param null $newPassphrase
  	 * @return bool
  	 * @note Encryption is recursive
  	 */
  	public function encryptAll($dirPath, $legacyPassphrase = null, $newPassphrase = null) {
6d9380f96   Cédric Dupont   Update sources OC...
714
  		$result = true;
31b7f2792   Kload   Upgrade to ownclo...
715

6d9380f96   Cédric Dupont   Update sources OC...
716
  		$found = $this->findEncFiles($dirPath);
03e52840d   Kload   Init
717

6d9380f96   Cédric Dupont   Update sources OC...
718
719
  		// Disable proxy to prevent file being encrypted twice
  		\OC_FileProxy::$enabled = false;
03e52840d   Kload   Init
720

6d9380f96   Cédric Dupont   Update sources OC...
721
722
  		$versionStatus = \OCP\App::isEnabled('files_versions');
  		\OC_App::disable('files_versions');
31b7f2792   Kload   Upgrade to ownclo...
723

6d9380f96   Cédric Dupont   Update sources OC...
724
  		$encryptedFiles = array();
31b7f2792   Kload   Upgrade to ownclo...
725

6d9380f96   Cédric Dupont   Update sources OC...
726
727
  		// Encrypt unencrypted files
  		foreach ($found['plain'] as $plainFile) {
03e52840d   Kload   Init
728

6d9380f96   Cédric Dupont   Update sources OC...
729
730
  			//get file info
  			$fileInfo = \OC\Files\Filesystem::getFileInfo($plainFile['path']);
03e52840d   Kload   Init
731

6d9380f96   Cédric Dupont   Update sources OC...
732
733
  			//relative to data/<user>/file
  			$relPath = $plainFile['path'];
31b7f2792   Kload   Upgrade to ownclo...
734

6d9380f96   Cédric Dupont   Update sources OC...
735
736
  			//relative to /data
  			$rawPath = '/' . $this->userId . '/files/' . $plainFile['path'];
03e52840d   Kload   Init
737

6d9380f96   Cédric Dupont   Update sources OC...
738
739
  			// keep timestamp
  			$timestamp = $fileInfo['mtime'];
31b7f2792   Kload   Upgrade to ownclo...
740

6d9380f96   Cédric Dupont   Update sources OC...
741
742
  			// Open plain file handle for binary reading
  			$plainHandle = $this->view->fopen($rawPath, 'rb');
03e52840d   Kload   Init
743

6d9380f96   Cédric Dupont   Update sources OC...
744
745
  			// Open enc file handle for binary writing, with same filename as original plain file
  			$encHandle = fopen('crypt://' . $rawPath . '.part', 'wb');
03e52840d   Kload   Init
746

6d9380f96   Cédric Dupont   Update sources OC...
747
748
749
  			if (is_resource($encHandle) && is_resource($plainHandle)) {
  				// Move plain file to a temporary location
  				$size = stream_copy_to_stream($plainHandle, $encHandle);
03e52840d   Kload   Init
750

6d9380f96   Cédric Dupont   Update sources OC...
751
752
  				fclose($encHandle);
  				fclose($plainHandle);
03e52840d   Kload   Init
753

6d9380f96   Cédric Dupont   Update sources OC...
754
755
  				$fakeRoot = $this->view->getRoot();
  				$this->view->chroot('/' . $this->userId . '/files');
03e52840d   Kload   Init
756

6d9380f96   Cédric Dupont   Update sources OC...
757
  				$this->view->rename($relPath . '.part', $relPath);
03e52840d   Kload   Init
758

6d9380f96   Cédric Dupont   Update sources OC...
759
760
  				// set timestamp
  				$this->view->touch($relPath, $timestamp);
03e52840d   Kload   Init
761

6d9380f96   Cédric Dupont   Update sources OC...
762
  				$encSize = $this->view->filesize($relPath);
31b7f2792   Kload   Upgrade to ownclo...
763

6d9380f96   Cédric Dupont   Update sources OC...
764
  				$this->view->chroot($fakeRoot);
31b7f2792   Kload   Upgrade to ownclo...
765

6d9380f96   Cédric Dupont   Update sources OC...
766
767
768
769
770
771
772
  				// Add the file to the cache
  				\OC\Files\Filesystem::putFileInfo($relPath, array(
  					'encrypted' => true,
  					'size' => $encSize,
  					'unencrypted_size' => $size,
  					'etag' => $fileInfo['etag']
  				));
31b7f2792   Kload   Upgrade to ownclo...
773

6d9380f96   Cédric Dupont   Update sources OC...
774
775
776
777
  				$encryptedFiles[] = $relPath;
  			} else {
  				\OCP\Util::writeLog('files_encryption', 'initial encryption: could not encrypt ' . $rawPath, \OCP\Util::FATAL);
  				$result = false;
03e52840d   Kload   Init
778
  			}
6d9380f96   Cédric Dupont   Update sources OC...
779
  		}
03e52840d   Kload   Init
780

6d9380f96   Cédric Dupont   Update sources OC...
781
782
  		// Encrypt legacy encrypted files
  		if (!empty($legacyPassphrase) && !empty($newPassphrase)) {
03e52840d   Kload   Init
783

6d9380f96   Cédric Dupont   Update sources OC...
784
  			foreach ($found['legacy'] as $legacyFile) {
03e52840d   Kload   Init
785

6d9380f96   Cédric Dupont   Update sources OC...
786
787
  				// Fetch data from file
  				$legacyData = $this->view->file_get_contents($legacyFile['path']);
03e52840d   Kload   Init
788

6d9380f96   Cédric Dupont   Update sources OC...
789
790
  				// decrypt data, generate catfile
  				$decrypted = Crypt::legacyBlockDecrypt($legacyData, $legacyPassphrase);
03e52840d   Kload   Init
791

6d9380f96   Cédric Dupont   Update sources OC...
792
  				$rawPath = $legacyFile['path'];
03e52840d   Kload   Init
793

6d9380f96   Cédric Dupont   Update sources OC...
794
795
  				// enable proxy the ensure encryption is handled
  				\OC_FileProxy::$enabled = true;
03e52840d   Kload   Init
796

6d9380f96   Cédric Dupont   Update sources OC...
797
798
  				// Open enc file handle for binary writing, with same filename as original plain file
  				$encHandle = $this->view->fopen($rawPath, 'wb');
03e52840d   Kload   Init
799

6d9380f96   Cédric Dupont   Update sources OC...
800
  				if (is_resource($encHandle)) {
03e52840d   Kload   Init
801

6d9380f96   Cédric Dupont   Update sources OC...
802
803
  					// write data to stream
  					fwrite($encHandle, $decrypted);
03e52840d   Kload   Init
804

6d9380f96   Cédric Dupont   Update sources OC...
805
806
807
808
809
  					// close stream
  					fclose($encHandle);
  				} else {
  					\OCP\Util::writeLog('files_encryption', 'initial encryption: could not encrypt legacy file ' . $rawPath, \OCP\Util::FATAL);
  					$result = false;
03e52840d   Kload   Init
810
  				}
6d9380f96   Cédric Dupont   Update sources OC...
811
812
813
  
  				// disable proxy to prevent file being encrypted twice
  				\OC_FileProxy::$enabled = false;
03e52840d   Kload   Init
814
  			}
6d9380f96   Cédric Dupont   Update sources OC...
815
  		}
03e52840d   Kload   Init
816

6d9380f96   Cédric Dupont   Update sources OC...
817
  		\OC_FileProxy::$enabled = true;
03e52840d   Kload   Init
818

6d9380f96   Cédric Dupont   Update sources OC...
819
820
821
  		if ($versionStatus) {
  			\OC_App::enable('files_versions');
  		}
31b7f2792   Kload   Upgrade to ownclo...
822

6d9380f96   Cédric Dupont   Update sources OC...
823
  		$result = $result && $this->encryptVersions($encryptedFiles);
31b7f2792   Kload   Upgrade to ownclo...
824

6d9380f96   Cédric Dupont   Update sources OC...
825
  		return $result;
03e52840d   Kload   Init
826

03e52840d   Kload   Init
827
828
829
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
830
  	 * Return important encryption related paths
03e52840d   Kload   Init
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
  	 * @param string $pathName Name of the directory to return the path of
  	 * @return string path
  	 */
  	public function getPath($pathName) {
  
  		switch ($pathName) {
  
  			case 'publicKeyDir':
  
  				return $this->publicKeyDir;
  
  				break;
  
  			case 'encryptionDir':
  
  				return $this->encryptionDir;
  
  				break;
  
  			case 'keyfilesPath':
  
  				return $this->keyfilesPath;
  
  				break;
  
  			case 'publicKeyPath':
  
  				return $this->publicKeyPath;
  
  				break;
  
  			case 'privateKeyPath':
  
  				return $this->privateKeyPath;
  
  				break;
  		}
  
  		return false;
  
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
874
  	 * Filter an array of UIDs to return only ones ready for sharing
03e52840d   Kload   Init
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
  	 * @param array $unfilteredUsers users to be checked for sharing readiness
  	 * @return array as multi-dimensional array. keys: ready, unready
  	 */
  	public function filterShareReadyUsers($unfilteredUsers) {
  
  		// This array will collect the filtered IDs
  		$readyIds = $unreadyIds = array();
  
  		// Loop through users and create array of UIDs that need new keyfiles
  		foreach ($unfilteredUsers as $user) {
  
  			$util = new Util($this->view, $user);
  
  			// Check that the user is encryption capable, or is the
  			// public system user 'ownCloud' (for public shares)
  			if (
  				$user === $this->publicShareKeyId
  				or $user === $this->recoveryKeyId
  				or $util->ready()
  			) {
  
  				// Construct array of ready UIDs for Keymanager{}
  				$readyIds[] = $user;
  
  			} else {
  
  				// Construct array of unready UIDs for Keymanager{}
  				$unreadyIds[] = $user;
  
  				// Log warning; we can't do necessary setup here
  				// because we don't have the user passphrase
  				\OCP\Util::writeLog('Encryption library',
  					'"' . $user . '" is not setup for encryption', \OCP\Util::WARN);
  
  			}
  
  		}
  
  		return array(
  			'ready' => $readyIds,
  			'unready' => $unreadyIds
  		);
  
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
921
  	 * Decrypt a keyfile
03e52840d   Kload   Init
922
  	 * @param string $filePath
03e52840d   Kload   Init
923
  	 * @param string $privateKey
6d9380f96   Cédric Dupont   Update sources OC...
924
  	 * @return false|string
03e52840d   Kload   Init
925
  	 */
31b7f2792   Kload   Upgrade to ownclo...
926
  	private function decryptKeyfile($filePath, $privateKey) {
03e52840d   Kload   Init
927
928
  
  		// Get the encrypted keyfile
31b7f2792   Kload   Upgrade to ownclo...
929
  		$encKeyfile = Keymanager::getFileKey($this->view, $this, $filePath);
03e52840d   Kload   Init
930

31b7f2792   Kload   Upgrade to ownclo...
931
932
  		// The file has a shareKey and must use it for decryption
  		$shareKey = Keymanager::getShareKey($this->view, $this->keyId, $this, $filePath);
03e52840d   Kload   Init
933

31b7f2792   Kload   Upgrade to ownclo...
934
  		$plainKeyfile = Crypt::multiKeyDecrypt($encKeyfile, $shareKey, $privateKey);
03e52840d   Kload   Init
935
936
  
  		return $plainKeyfile;
03e52840d   Kload   Init
937
938
939
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
940
  	 * Encrypt keyfile to multiple users
03e52840d   Kload   Init
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
  	 * @param Session $session
  	 * @param array $users list of users which should be able to access the file
  	 * @param string $filePath path of the file to be shared
  	 * @return bool
  	 */
  	public function setSharedFileKeyfiles(Session $session, array $users, $filePath) {
  
  		// Make sure users are capable of sharing
  		$filteredUids = $this->filterShareReadyUsers($users);
  
  		// If we're attempting to share to unready users
  		if (!empty($filteredUids['unready'])) {
  
  			\OCP\Util::writeLog('Encryption library',
  				'Sharing to these user(s) failed as they are unready for encryption:"'
  				. print_r($filteredUids['unready'], 1), \OCP\Util::WARN);
  
  			return false;
  
  		}
  
  		// Get public keys for each user, ready for generating sharekeys
  		$userPubKeys = Keymanager::getPublicKeys($this->view, $filteredUids['ready']);
  
  		// Note proxy status then disable it
  		$proxyStatus = \OC_FileProxy::$enabled;
  		\OC_FileProxy::$enabled = false;
  
  		// Get the current users's private key for decrypting existing keyfile
  		$privateKey = $session->getPrivateKey();
6d9380f96   Cédric Dupont   Update sources OC...
971
972
973
974
975
976
977
978
979
980
981
982
983
984
  		try {
  			// Decrypt keyfile
  			$plainKeyfile = $this->decryptKeyfile($filePath, $privateKey);
  			// Re-enc keyfile to (additional) sharekeys
  			$multiEncKey = Crypt::multiKeyEncrypt($plainKeyfile, $userPubKeys);
  		} catch (Exceptions\EncryptionException $e) {
  			$msg = 'set shareFileKeyFailed (code: ' . $e->getCode() . '): ' . $e->getMessage();
  			\OCP\Util::writeLog('files_encryption', $msg, \OCP\Util::FATAL);
  			return false;
  		} catch (\Exception $e) {
  			$msg = 'set shareFileKeyFailed (unknown error): ' . $e->getMessage();
  			\OCP\Util::writeLog('files_encryption', $msg, \OCP\Util::FATAL);
  			return false;
  		}
03e52840d   Kload   Init
985
986
987
988
  
  		// Save the recrypted key to it's owner's keyfiles directory
  		// Save new sharekeys to all necessary user directory
  		if (
6d9380f96   Cédric Dupont   Update sources OC...
989
990
  				!Keymanager::setFileKey($this->view, $this, $filePath, $multiEncKey['data'])
  				|| !Keymanager::setShareKeys($this->view, $this, $filePath, $multiEncKey['keys'])
03e52840d   Kload   Init
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
  		) {
  
  			\OCP\Util::writeLog('Encryption library',
  				'Keyfiles could not be saved for users sharing ' . $filePath, \OCP\Util::ERROR);
  
  			return false;
  
  		}
  
  		// Return proxy to original status
  		\OC_FileProxy::$enabled = $proxyStatus;
  
  		return true;
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
1007
  	 * Find, sanitise and format users sharing a file
03e52840d   Kload   Init
1008
  	 * @note This wraps other methods into a portable bundle
6d9380f96   Cédric Dupont   Update sources OC...
1009
1010
  	 * @param boolean $sharingEnabled
  	 * @param string $filePath path relativ to current users files folder
03e52840d   Kload   Init
1011
  	 */
6d9380f96   Cédric Dupont   Update sources OC...
1012
1013
1014
  	public function getSharingUsersArray($sharingEnabled, $filePath) {
  
  		$appConfig = \OC::$server->getAppConfig();
03e52840d   Kload   Init
1015
1016
1017
  
  		// Check if key recovery is enabled
  		if (
6d9380f96   Cédric Dupont   Update sources OC...
1018
  			$appConfig->getValue('files_encryption', 'recoveryAdminEnabled')
03e52840d   Kload   Init
1019
1020
1021
1022
1023
1024
1025
1026
1027
  			&& $this->recoveryEnabledForUser()
  		) {
  			$recoveryEnabled = true;
  		} else {
  			$recoveryEnabled = false;
  		}
  
  		// Make sure that a share key is generated for the owner too
  		list($owner, $ownerPath) = $this->getUidAndFilename($filePath);
31b7f2792   Kload   Upgrade to ownclo...
1028
  		$ownerPath = \OCA\Encryption\Helper::stripPartialFileExtension($ownerPath);
03e52840d   Kload   Init
1029

6d9380f96   Cédric Dupont   Update sources OC...
1030
1031
  		// always add owner to the list of users with access to the file
  		$userIds = array($owner);
03e52840d   Kload   Init
1032
1033
1034
  		if ($sharingEnabled) {
  
  			// Find out who, if anyone, is sharing the file
6d9380f96   Cédric Dupont   Update sources OC...
1035
1036
  			$result = \OCP\Share::getUsersSharingFile($ownerPath, $owner);
  			$userIds = \array_merge($userIds, $result['users']);
03e52840d   Kload   Init
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
  			if ($result['public']) {
  				$userIds[] = $this->publicShareKeyId;
  			}
  
  		}
  
  		// If recovery is enabled, add the
  		// Admin UID to list of users to share to
  		if ($recoveryEnabled) {
  			// Find recoveryAdmin user ID
6d9380f96   Cédric Dupont   Update sources OC...
1047
  			$recoveryKeyId = $appConfig->getValue('files_encryption', 'recoveryKeyId');
03e52840d   Kload   Init
1048
1049
1050
  			// Add recoveryAdmin to list of users sharing
  			$userIds[] = $recoveryKeyId;
  		}
03e52840d   Kload   Init
1051
1052
  		// check if it is a group mount
  		if (\OCP\App::isEnabled("files_external")) {
f7d878ff1   kload   [enh] Update to 7...
1053
1054
1055
1056
  			$mounts = \OC_Mount_Config::getSystemMountPoints();
  			foreach ($mounts as $mount) {
  				if ($mount['mountpoint'] == substr($ownerPath, 1, strlen($mount['mountpoint']))) {
  					$userIds = array_merge($userIds, $this->getUserWithAccessToMountPoint($mount['applicable']['users'], $mount['applicable']['groups']));
03e52840d   Kload   Init
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
  				}
  			}
  		}
  
  		// Remove duplicate UIDs
  		$uniqueUserIds = array_unique($userIds);
  
  		return $uniqueUserIds;
  
  	}
  
  	private function getUserWithAccessToMountPoint($users, $groups) {
  		$result = array();
  		if (in_array('all', $users)) {
  			$result = \OCP\User::getUsers();
  		} else {
  			$result = array_merge($result, $users);
  			foreach ($groups as $group) {
  				$result = array_merge($result, \OC_Group::usersInGroup($group));
  			}
  		}
  
  		return $result;
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
1083
  	 * set migration status
a293d369c   Kload   Update sources to...
1084
  	 * @param int $status
6d9380f96   Cédric Dupont   Update sources OC...
1085
  	 * @param int $preCondition only update migration status if the previous value equals $preCondition
03e52840d   Kload   Init
1086
1087
  	 * @return boolean
  	 */
6d9380f96   Cédric Dupont   Update sources OC...
1088
  	private function setMigrationStatus($status, $preCondition = null) {
03e52840d   Kload   Init
1089

6d9380f96   Cédric Dupont   Update sources OC...
1090
1091
  		// convert to string if preCondition is set
  		$preCondition = ($preCondition === null) ? null : (string)$preCondition;
03e52840d   Kload   Init
1092

6d9380f96   Cédric Dupont   Update sources OC...
1093
  		return \OC_Preferences::setValue($this->userId, 'files_encryption', 'migration_status', (string)$status, $preCondition);
a293d369c   Kload   Update sources to...
1094

a293d369c   Kload   Update sources to...
1095
1096
1097
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
1098
  	 * start migration mode to initially encrypt users data
a293d369c   Kload   Update sources to...
1099
1100
1101
  	 * @return boolean
  	 */
  	public function beginMigration() {
6d9380f96   Cédric Dupont   Update sources OC...
1102
  		$result = $this->setMigrationStatus(self::MIGRATION_IN_PROGRESS, self::MIGRATION_OPEN);
a293d369c   Kload   Update sources to...
1103
1104
  
  		if ($result) {
03e52840d   Kload   Init
1105
1106
1107
1108
  			\OCP\Util::writeLog('Encryption library', "Start migration to encryption mode for " . $this->userId, \OCP\Util::INFO);
  		} else {
  			\OCP\Util::writeLog('Encryption library', "Could not activate migration mode for " . $this->userId . ". Probably another process already started the initial encryption", \OCP\Util::WARN);
  		}
a293d369c   Kload   Update sources to...
1109
1110
1111
1112
1113
  		return $result;
  	}
  
  	public function resetMigrationStatus() {
  		return $this->setMigrationStatus(self::MIGRATION_OPEN);
03e52840d   Kload   Init
1114
1115
1116
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
1117
  	 * close migration mode after users data has been encrypted successfully
03e52840d   Kload   Init
1118
1119
1120
  	 * @return boolean
  	 */
  	public function finishMigration() {
a293d369c   Kload   Update sources to...
1121
  		$result = $this->setMigrationStatus(self::MIGRATION_COMPLETED);
03e52840d   Kload   Init
1122

a293d369c   Kload   Update sources to...
1123
  		if ($result) {
03e52840d   Kload   Init
1124
1125
1126
1127
  			\OCP\Util::writeLog('Encryption library', "Finish migration successfully for " . $this->userId, \OCP\Util::INFO);
  		} else {
  			\OCP\Util::writeLog('Encryption library', "Could not deactivate migration mode for " . $this->userId, \OCP\Util::WARN);
  		}
a293d369c   Kload   Update sources to...
1128
  		return $result;
03e52840d   Kload   Init
1129
1130
1131
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
1132
1133
  	 * check if files are already migrated to the encryption system
  	 * @return int|false migration status, false = in case of no record
03e52840d   Kload   Init
1134
1135
1136
1137
  	 * @note If records are not being returned, check for a hidden space
  	 *       at the start of the uid in db
  	 */
  	public function getMigrationStatus() {
6d9380f96   Cédric Dupont   Update sources OC...
1138
1139
1140
1141
1142
1143
  		$migrationStatus = false;
  		if (\OCP\User::userExists($this->userId)) {
  			$migrationStatus = \OC_Preferences::getValue($this->userId, 'files_encryption', 'migration_status');
  			if ($migrationStatus === null) {
  				\OC_Preferences::setValue($this->userId, 'files_encryption', 'migration_status', (string)self::MIGRATION_OPEN);
  				$migrationStatus = self::MIGRATION_OPEN;
03e52840d   Kload   Init
1144
1145
  			}
  		}
6d9380f96   Cédric Dupont   Update sources OC...
1146
  		return (int)$migrationStatus;
03e52840d   Kload   Init
1147
1148
1149
1150
  
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
1151
  	 * get uid of the owners of the file and the path to the file
03e52840d   Kload   Init
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
  	 * @param string $path Path of the file to check
  	 * @throws \Exception
  	 * @note $shareFilePath must be relative to data/UID/files. Files
  	 *       relative to /Shared are also acceptable
  	 * @return array
  	 */
  	public function getUidAndFilename($path) {
  
  		$pathinfo = pathinfo($path);
  		$partfile = false;
  		$parentFolder = false;
  		if (array_key_exists('extension', $pathinfo) && $pathinfo['extension'] === 'part') {
  			// if the real file exists we check this file
  			$filePath = $this->userFilesDir . '/' .$pathinfo['dirname'] . '/' . $pathinfo['filename'];
  			if ($this->view->file_exists($filePath)) {
  				$pathToCheck = $pathinfo['dirname'] . '/' . $pathinfo['filename'];
  			} else { // otherwise we look for the parent
  				$pathToCheck = $pathinfo['dirname'];
  				$parentFolder = true;
  			}
  			$partfile = true;
  		} else {
  			$pathToCheck = $path;
  		}
  
  		$view = new \OC\Files\View($this->userFilesDir);
  		$fileOwnerUid = $view->getOwner($pathToCheck);
  
  		// handle public access
  		if ($this->isPublic) {
  			$filename = $path;
31b7f2792   Kload   Upgrade to ownclo...
1183
  			$fileOwnerUid = $this->userId;
03e52840d   Kload   Init
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
  
  			return array(
  				$fileOwnerUid,
  				$filename
  			);
  		} else {
  
  			// Check that UID is valid
  			if (!\OCP\User::userExists($fileOwnerUid)) {
  				throw new \Exception(
  					'Could not find owner (UID = "' . var_export($fileOwnerUid, 1) . '") of file "' . $path . '"');
  			}
  
  			// NOTE: Bah, this dependency should be elsewhere
  			\OC\Files\Filesystem::initMountPoints($fileOwnerUid);
  
  			// If the file owner is the currently logged in user
  			if ($fileOwnerUid === $this->userId) {
  
  				// Assume the path supplied is correct
  				$filename = $path;
  
  			} else {
  				$info = $view->getFileInfo($pathToCheck);
  				$ownerView = new \OC\Files\View('/' . $fileOwnerUid . '/files');
  
  				// Fetch real file path from DB
  				$filename = $ownerView->getPath($info['fileid']);
  				if ($parentFolder) {
  					$filename = $filename . '/'. $pathinfo['filename'];
  				}
  
  				if ($partfile) {
  					$filename = $filename . '.' . $pathinfo['extension'];
  				}
  
  			}
  
  			return array(
  				$fileOwnerUid,
6d9380f96   Cédric Dupont   Update sources OC...
1224
  				\OC\Files\Filesystem::normalizePath($filename)
03e52840d   Kload   Init
1225
1226
1227
  			);
  		}
  	}
03e52840d   Kload   Init
1228
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
1229
  	 * go recursively through a dir and collect all files and sub files.
03e52840d   Kload   Init
1230
1231
1232
  	 * @param string $dir relative to the users files folder
  	 * @return array with list of files relative to the users files folder
  	 */
6d9380f96   Cédric Dupont   Update sources OC...
1233
  	public function getAllFiles($dir, $mountPoint = '') {
03e52840d   Kload   Init
1234
  		$result = array();
a293d369c   Kload   Update sources to...
1235
  		$dirList = array($dir);
03e52840d   Kload   Init
1236

a293d369c   Kload   Update sources to...
1237
1238
1239
1240
  		while ($dirList) {
  			$dir = array_pop($dirList);
  			$content = $this->view->getDirectoryContent(\OC\Files\Filesystem::normalizePath(
  					$this->userFilesDir . '/' . $dir));
03e52840d   Kload   Init
1241

a293d369c   Kload   Update sources to...
1242
  			foreach ($content as $c) {
6d9380f96   Cédric Dupont   Update sources OC...
1243
1244
1245
1246
  				// getDirectoryContent() returns the paths relative to the mount points, so we need
  				// to re-construct the complete path
  				$path = ($mountPoint !== '') ? $mountPoint . '/' .  $c['path'] : $c['path'];
  				$path = \OC\Files\Filesystem::normalizePath($path);
a293d369c   Kload   Update sources to...
1247
  				if ($c['type'] === 'dir') {
6d9380f96   Cédric Dupont   Update sources OC...
1248
  					$dirList[] = substr($path, strlen('/' . \OCP\User::getUser() . "/files"));
03e52840d   Kload   Init
1249
  				} else {
6d9380f96   Cédric Dupont   Update sources OC...
1250
  					$result[] = substr($path, strlen('/' . \OCP\User::getUser() . "/files"));
03e52840d   Kload   Init
1251
  				}
03e52840d   Kload   Init
1252
  			}
03e52840d   Kload   Init
1253
1254
1255
  		}
  
  		return $result;
03e52840d   Kload   Init
1256
1257
1258
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
1259
1260
  	 * get owner of the shared files.
  	 * @param int $id ID of a share
03e52840d   Kload   Init
1261
1262
1263
1264
1265
1266
1267
  	 * @return string owner
  	 */
  	public function getOwnerFromSharedFile($id) {
  
  		$query = \OCP\DB::prepare('SELECT `parent`, `uid_owner` FROM `*PREFIX*share` WHERE `id` = ?', 1);
  
  		$result = $query->execute(array($id));
a293d369c   Kload   Update sources to...
1268
  		$source = null;
03e52840d   Kload   Init
1269
1270
1271
  		if (\OCP\DB::isError($result)) {
  			\OCP\Util::writeLog('Encryption library', \OC_DB::getErrorMessage($result), \OCP\Util::ERROR);
  		} else {
a293d369c   Kload   Update sources to...
1272
  			$source = $result->fetchRow();
03e52840d   Kload   Init
1273
1274
1275
  		}
  
  		$fileOwner = false;
a293d369c   Kload   Update sources to...
1276
  		if ($source && isset($source['parent'])) {
03e52840d   Kload   Init
1277
1278
1279
1280
1281
1282
1283
1284
  
  			$parent = $source['parent'];
  
  			while (isset($parent)) {
  
  				$query = \OCP\DB::prepare('SELECT `parent`, `uid_owner` FROM `*PREFIX*share` WHERE `id` = ?', 1);
  
  				$result = $query->execute(array($parent));
a293d369c   Kload   Update sources to...
1285
  				$item = null;
03e52840d   Kload   Init
1286
1287
1288
  				if (\OCP\DB::isError($result)) {
  					\OCP\Util::writeLog('Encryption library', \OC_DB::getErrorMessage($result), \OCP\Util::ERROR);
  				} else {
a293d369c   Kload   Update sources to...
1289
  					$item = $result->fetchRow();
03e52840d   Kload   Init
1290
  				}
a293d369c   Kload   Update sources to...
1291
  				if ($item && isset($item['parent'])) {
03e52840d   Kload   Init
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
  
  					$parent = $item['parent'];
  
  				} else {
  
  					$fileOwner = $item['uid_owner'];
  
  					break;
  
  				}
  			}
  
  		} else {
  
  			$fileOwner = $source['uid_owner'];
  
  		}
  
  		return $fileOwner;
  
  	}
  
  	/**
  	 * @return string
  	 */
  	public function getUserId() {
  		return $this->userId;
  	}
  
  	/**
  	 * @return string
  	 */
31b7f2792   Kload   Upgrade to ownclo...
1324
1325
1326
1327
1328
1329
1330
  	public function getKeyId() {
  		return $this->keyId;
  	}
  
  	/**
  	 * @return string
  	 */
03e52840d   Kload   Init
1331
1332
1333
1334
1335
  	public function getUserFilesDir() {
  		return $this->userFilesDir;
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
1336
  	 * @param string $password
03e52840d   Kload   Init
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
  	 * @return bool
  	 */
  	public function checkRecoveryPassword($password) {
  
  		$result = false;
  		$pathKey = '/owncloud_private_key/' . $this->recoveryKeyId . ".private.key";
  
  		$proxyStatus = \OC_FileProxy::$enabled;
  		\OC_FileProxy::$enabled = false;
  
  		$recoveryKey = $this->view->file_get_contents($pathKey);
  
  		$decryptedRecoveryKey = Crypt::decryptPrivateKey($recoveryKey, $password);
  
  		if ($decryptedRecoveryKey) {
  			$result = true;
  		}
  
  		\OC_FileProxy::$enabled = $proxyStatus;
  
  
  		return $result;
  	}
  
  	/**
  	 * @return string
  	 */
  	public function getRecoveryKeyId() {
  		return $this->recoveryKeyId;
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
1369
  	 * add recovery key to all encrypted files
03e52840d   Kload   Init
1370
1371
1372
1373
1374
1375
1376
1377
1378
  	 */
  	public function addRecoveryKeys($path = '/') {
  		$dirContent = $this->view->getDirectoryContent($this->keyfilesPath . $path);
  		foreach ($dirContent as $item) {
  			// get relative path from files_encryption/keyfiles/
  			$filePath = substr($item['path'], strlen('files_encryption/keyfiles'));
  			if ($item['type'] === 'dir') {
  				$this->addRecoveryKeys($filePath . '/');
  			} else {
6d9380f96   Cédric Dupont   Update sources OC...
1379
  				$session = new \OCA\Encryption\Session(new \OC\Files\View('/'));
03e52840d   Kload   Init
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
  				$sharingEnabled = \OCP\Share::isEnabled();
  				// remove '.key' extension from path e.g. 'file.txt.key' to 'file.txt'
  				$file = substr($filePath, 0, -4);
  				$usersSharing = $this->getSharingUsersArray($sharingEnabled, $file);
  				$this->setSharedFileKeyfiles($session, $usersSharing, $file);
  			}
  		}
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
1390
  	 * remove recovery key to all encrypted files
03e52840d   Kload   Init
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
  	 */
  	public function removeRecoveryKeys($path = '/') {
  		$dirContent = $this->view->getDirectoryContent($this->keyfilesPath . $path);
  		foreach ($dirContent as $item) {
  			// get relative path from files_encryption/keyfiles
  			$filePath = substr($item['path'], strlen('files_encryption/keyfiles'));
  			if ($item['type'] === 'dir') {
  				$this->removeRecoveryKeys($filePath . '/');
  			} else {
  				// remove '.key' extension from path e.g. 'file.txt.key' to 'file.txt'
  				$file = substr($filePath, 0, -4);
  				$this->view->unlink($this->shareKeysPath . '/' . $file . '.' . $this->recoveryKeyId . '.shareKey');
  			}
  		}
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
1408
  	 * decrypt given file with recovery key and encrypt it again to the owner and his new key
03e52840d   Kload   Init
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
  	 * @param string $file
  	 * @param string $privateKey recovery key to decrypt the file
  	 */
  	private function recoverFile($file, $privateKey) {
  
  		$sharingEnabled = \OCP\Share::isEnabled();
  
  		// Find out who, if anyone, is sharing the file
  		if ($sharingEnabled) {
  			$result = \OCP\Share::getUsersSharingFile($file, $this->userId, true);
  			$userIds = $result['users'];
  			$userIds[] = $this->recoveryKeyId;
  			if ($result['public']) {
  				$userIds[] = $this->publicShareKeyId;
  			}
  		} else {
  			$userIds = array(
  				$this->userId,
  				$this->recoveryKeyId
  			);
  		}
  		$filteredUids = $this->filterShareReadyUsers($userIds);
  
  		$proxyStatus = \OC_FileProxy::$enabled;
  		\OC_FileProxy::$enabled = false;
  
  		//decrypt file key
  		$encKeyfile = $this->view->file_get_contents($this->keyfilesPath . $file . ".key");
  		$shareKey = $this->view->file_get_contents(
  			$this->shareKeysPath . $file . "." . $this->recoveryKeyId . ".shareKey");
  		$plainKeyfile = Crypt::multiKeyDecrypt($encKeyfile, $shareKey, $privateKey);
  		// encrypt file key again to all users, this time with the new public key for the recovered use
  		$userPubKeys = Keymanager::getPublicKeys($this->view, $filteredUids['ready']);
  		$multiEncKey = Crypt::multiKeyEncrypt($plainKeyfile, $userPubKeys);
  
  		// write new keys to filesystem TDOO!
  		$this->view->file_put_contents($this->keyfilesPath . $file . '.key', $multiEncKey['data']);
  		foreach ($multiEncKey['keys'] as $userId => $shareKey) {
  			$shareKeyPath = $this->shareKeysPath . $file . '.' . $userId . '.shareKey';
  			$this->view->file_put_contents($shareKeyPath, $shareKey);
  		}
  
  		// Return proxy to original status
  		\OC_FileProxy::$enabled = $proxyStatus;
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
1456
  	 * collect all files and recover them one by one
03e52840d   Kload   Init
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
  	 * @param string $path to look for files keys
  	 * @param string $privateKey private recovery key which is used to decrypt the files
  	 */
  	private function recoverAllFiles($path, $privateKey) {
  		$dirContent = $this->view->getDirectoryContent($this->keyfilesPath . $path);
  		foreach ($dirContent as $item) {
  			// get relative path from files_encryption/keyfiles
  			$filePath = substr($item['path'], strlen('files_encryption/keyfiles'));
  			if ($item['type'] === 'dir') {
  				$this->recoverAllFiles($filePath . '/', $privateKey);
  			} else {
  				// remove '.key' extension from path e.g. 'file.txt.key' to 'file.txt'
  				$file = substr($filePath, 0, -4);
  				$this->recoverFile($file, $privateKey);
  			}
  		}
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
1476
  	 * recover users files in case of password lost
03e52840d   Kload   Init
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
  	 * @param string $recoveryPassword
  	 */
  	public function recoverUsersFiles($recoveryPassword) {
  
  		// Disable encryption proxy to prevent recursive calls
  		$proxyStatus = \OC_FileProxy::$enabled;
  		\OC_FileProxy::$enabled = false;
  
  		$encryptedKey = $this->view->file_get_contents(
  			'/owncloud_private_key/' . $this->recoveryKeyId . '.private.key');
  		$privateKey = Crypt::decryptPrivateKey($encryptedKey, $recoveryPassword);
  
  		\OC_FileProxy::$enabled = $proxyStatus;
  
  		$this->recoverAllFiles('/', $privateKey);
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
1495
1496
  	 * check if the file is stored on a system wide mount point
  	 * @param string $path relative to /data/user with leading '/'
03e52840d   Kload   Init
1497
1498
1499
  	 * @return boolean
  	 */
  	public function isSystemWideMountPoint($path) {
6d9380f96   Cédric Dupont   Update sources OC...
1500
  		$normalizedPath = ltrim($path, '/');
03e52840d   Kload   Init
1501
  		if (\OCP\App::isEnabled("files_external")) {
f7d878ff1   kload   [enh] Update to 7...
1502
1503
1504
1505
1506
1507
  			$mounts = \OC_Mount_Config::getSystemMountPoints();
  			foreach ($mounts as $mount) {
  				if ($mount['mountpoint'] == substr($normalizedPath, 0, strlen($mount['mountpoint']))) {
  					if ($this->isMountPointApplicableToUser($mount)) {
  						return true;
  					}
03e52840d   Kload   Init
1508
1509
1510
1511
1512
  				}
  			}
  		}
  		return false;
  	}
31b7f2792   Kload   Upgrade to ownclo...
1513
  	/**
f7d878ff1   kload   [enh] Update to 7...
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
  	 * check if mount point is applicable to user
  	 *
  	 * @param array $mount contains $mount['applicable']['users'], $mount['applicable']['groups']
  	 * @return boolean
  	 */
  	protected function isMountPointApplicableToUser($mount) {
  		$uid = \OCP\User::getUser();
  		$acceptedUids = array('all', $uid);
  		// check if mount point is applicable for the user
  		$intersection = array_intersect($acceptedUids, $mount['applicable']['users']);
  		if (!empty($intersection)) {
  			return true;
  		}
  		// check if mount point is applicable for group where the user is a member
  		foreach ($mount['applicable']['groups'] as $gid) {
  			if (\OC_Group::inGroup($uid, $gid)) {
  				return true;
  			}
  		}
  		return false;
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
1537
  	 * decrypt private key and add it to the current session
31b7f2792   Kload   Upgrade to ownclo...
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
  	 * @param array $params with 'uid' and 'password'
  	 * @return mixed session or false
  	 */
  	public function initEncryption($params) {
  
  		$session = new \OCA\Encryption\Session($this->view);
  
  		// we tried to initialize the encryption app for this session
  		$session->setInitialized(\OCA\Encryption\Session::INIT_EXECUTED);
  
  		$encryptedKey = Keymanager::getPrivateKey($this->view, $params['uid']);
  
  		$privateKey = Crypt::decryptPrivateKey($encryptedKey, $params['password']);
  
  		if ($privateKey === false) {
  			\OCP\Util::writeLog('Encryption library', 'Private key for user "' . $params['uid']
  					. '" is not valid! Maybe the user password was changed from outside if so please change it back to gain access', \OCP\Util::ERROR);
  			return false;
  		}
  
  		$session->setPrivateKey($privateKey);
  		$session->setInitialized(\OCA\Encryption\Session::INIT_SUCCESSFUL);
  
  		return $session;
  	}
a293d369c   Kload   Update sources to...
1563
  	/*
6d9380f96   Cédric Dupont   Update sources OC...
1564
  	 * remove encryption related keys from the session
a293d369c   Kload   Update sources to...
1565
1566
1567
1568
1569
  	 */
  	public function closeEncryptionSession() {
  		$session = new \OCA\Encryption\Session($this->view);
  		$session->closeSession();
  	}
03e52840d   Kload   Init
1570
  }