Blame view

sources/apps/files_encryption/hooks/hooks.php 22.3 KB
03e52840d   Kload   Init
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
  <?php
  
  /**
   * ownCloud
   *
   * @author Sam Tuke
   * @copyright 2012 Sam Tuke samtuke@owncloud.org
   *
   * 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/>.
   *
   */
  
  namespace OCA\Encryption;
  
  use OC\Files\Filesystem;
  
  /**
   * Class for hook specific logic
   */
  class Hooks {
  
a293d369c   Kload   Update sources to...
33
34
35
36
  	// file for which we want to rename the keys after the rename operation was successful
  	private static $renamedFiles = array();
  	// file for which we want to delete the keys after the delete operation was successful
  	private static $deleteFiles = array();
6d9380f96   Cédric Dupont   Update sources OC...
37
38
  	// file for which we want to delete the keys after the delete operation was successful
  	private static $umountedFiles = array();
a293d369c   Kload   Update sources to...
39
  
03e52840d   Kload   Init
40
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
41
  	 * Startup encryption backend upon user login
03e52840d   Kload   Init
42
43
44
45
46
47
48
49
  	 * @note This method should never be called for users using client side encryption
  	 */
  	public static function login($params) {
  
  		if (\OCP\App::isEnabled('files_encryption') === false) {
  			return true;
  		}
  
31b7f2792   Kload   Upgrade to ownclo...
50
  
03e52840d   Kload   Init
51
52
  		$l = new \OC_L10N('files_encryption');
  
6d9380f96   Cédric Dupont   Update sources OC...
53
  		$view = new \OC\Files\View('/');
31b7f2792   Kload   Upgrade to ownclo...
54
55
  
  		// ensure filesystem is loaded
6d9380f96   Cédric Dupont   Update sources OC...
56
  		if (!\OC\Files\Filesystem::$loaded) {
31b7f2792   Kload   Upgrade to ownclo...
57
58
59
  			\OC_Util::setupFS($params['uid']);
  		}
  
03e52840d   Kload   Init
60
61
62
  		$privateKey = \OCA\Encryption\Keymanager::getPrivateKey($view, $params['uid']);
  
  		// if no private key exists, check server configuration
6d9380f96   Cédric Dupont   Update sources OC...
63
  		if (!$privateKey) {
31b7f2792   Kload   Upgrade to ownclo...
64
  			//check if all requirements are met
6d9380f96   Cédric Dupont   Update sources OC...
65
  			if (!Helper::checkRequirements() || !Helper::checkConfiguration()) {
03e52840d   Kload   Init
66
67
68
69
70
71
72
73
  				$error_msg = $l->t("Missing requirements.");
  				$hint = $l->t('Please make sure that PHP 5.3.3 or newer is installed and that OpenSSL together with the PHP extension is enabled and configured properly. For now, the encryption app has been disabled.');
  				\OC_App::disable('files_encryption');
  				\OCP\Util::writeLog('Encryption library', $error_msg . ' ' . $hint, \OCP\Util::ERROR);
  				\OCP\Template::printErrorPage($error_msg, $hint);
  			}
  		}
  
03e52840d   Kload   Init
74
75
76
77
78
79
80
  		$util = new Util($view, $params['uid']);
  
  		// setup user, if user not ready force relogin
  		if (Helper::setupUser($util, $params['password']) === false) {
  			return false;
  		}
  
31b7f2792   Kload   Upgrade to ownclo...
81
  		$session = $util->initEncryption($params);
03e52840d   Kload   Init
82
83
84
  
  		// Check if first-run file migration has already been performed
  		$ready = false;
a293d369c   Kload   Update sources to...
85
  		$migrationStatus = $util->getMigrationStatus();
6d9380f96   Cédric Dupont   Update sources OC...
86
  		if ($migrationStatus === Util::MIGRATION_OPEN && $session !== false) {
03e52840d   Kload   Init
87
  			$ready = $util->beginMigration();
a293d369c   Kload   Update sources to...
88
89
90
91
92
  		} elseif ($migrationStatus === Util::MIGRATION_IN_PROGRESS) {
  			// refuse login as long as the initial encryption is running
  			sleep(5);
  			\OCP\User::logout();
  			return false;
03e52840d   Kload   Init
93
94
  		}
  
6d9380f96   Cédric Dupont   Update sources OC...
95
96
  		$result = true;
  
03e52840d   Kload   Init
97
98
99
  		// If migration not yet done
  		if ($ready) {
  
6d9380f96   Cédric Dupont   Update sources OC...
100
  			$userView = new \OC\Files\View('/' . $params['uid']);
03e52840d   Kload   Init
101
102
103
  
  			// Set legacy encryption key if it exists, to support
  			// depreciated encryption system
6d9380f96   Cédric Dupont   Update sources OC...
104
105
106
  			if ($userView->file_exists('encryption.key')) {
  				$encLegacyKey = $userView->file_get_contents('encryption.key');
  				if ($encLegacyKey) {
03e52840d   Kload   Init
107
  
6d9380f96   Cédric Dupont   Update sources OC...
108
  					$plainLegacyKey = Crypt::legacyDecrypt($encLegacyKey, $params['password']);
03e52840d   Kload   Init
109
  
6d9380f96   Cédric Dupont   Update sources OC...
110
111
  					$session->setLegacyKey($plainLegacyKey);
  				}
03e52840d   Kload   Init
112
113
  			}
  
a293d369c   Kload   Update sources to...
114
115
116
117
118
  			// Encrypt existing user files
  			try {
  				$result = $util->encryptAll('/' . $params['uid'] . '/' . 'files', $session->getLegacyKey(), $params['password']);
  			} catch (\Exception $ex) {
  				\OCP\Util::writeLog('Encryption library', 'Initial encryption failed! Error: ' . $ex->getMessage(), \OCP\Util::FATAL);
a293d369c   Kload   Update sources to...
119
120
121
122
  				$result = false;
  			}
  
  			if ($result) {
03e52840d   Kload   Init
123
  				\OC_Log::write(
6d9380f96   Cédric Dupont   Update sources OC...
124
125
126
  						'Encryption library', 'Encryption of existing files belonging to "' . $params['uid'] . '" completed'
  						, \OC_Log::INFO
  					);
a293d369c   Kload   Update sources to...
127
128
  				// Register successful migration in DB
  				$util->finishMigration();
6d9380f96   Cédric Dupont   Update sources OC...
129
130
131
132
  			} else  {
  				\OCP\Util::writeLog('Encryption library', 'Initial encryption failed!', \OCP\Util::FATAL);
  				$util->resetMigrationStatus();
  				\OCP\User::logout();
a293d369c   Kload   Update sources to...
133
  			}
03e52840d   Kload   Init
134
135
  		}
  
6d9380f96   Cédric Dupont   Update sources OC...
136
  		return $result;
03e52840d   Kload   Init
137
138
139
  	}
  
  	/**
f7d878ff1   kload   [enh] Update to 7...
140
141
142
143
144
145
146
147
  	 * remove keys from session during logout
  	 */
  	public static function logout() {
  		$session = new \OCA\Encryption\Session(new \OC\Files\View());
  		$session->removeKeys();
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
148
  	 * setup encryption backend upon user created
03e52840d   Kload   Init
149
150
151
152
153
  	 * @note This method should never be called for users using client side encryption
  	 */
  	public static function postCreateUser($params) {
  
  		if (\OCP\App::isEnabled('files_encryption')) {
6d9380f96   Cédric Dupont   Update sources OC...
154
  			$view = new \OC\Files\View('/');
03e52840d   Kload   Init
155
156
157
158
159
160
  			$util = new Util($view, $params['uid']);
  			Helper::setupUser($util, $params['password']);
  		}
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
161
  	 * cleanup encryption backend upon user deleted
03e52840d   Kload   Init
162
163
164
165
166
  	 * @note This method should never be called for users using client side encryption
  	 */
  	public static function postDeleteUser($params) {
  
  		if (\OCP\App::isEnabled('files_encryption')) {
6d9380f96   Cédric Dupont   Update sources OC...
167
  			$view = new \OC\Files\View('/');
03e52840d   Kload   Init
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
  
  			// cleanup public key
  			$publicKey = '/public-keys/' . $params['uid'] . '.public.key';
  
  			// Disable encryption proxy to prevent recursive calls
  			$proxyStatus = \OC_FileProxy::$enabled;
  			\OC_FileProxy::$enabled = false;
  
  			$view->unlink($publicKey);
  
  			\OC_FileProxy::$enabled = $proxyStatus;
  		}
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
183
  	 * If the password can't be changed within ownCloud, than update the key password in advance.
03e52840d   Kload   Init
184
185
186
187
188
189
190
191
192
193
  	 */
  	public static function preSetPassphrase($params) {
  		if (\OCP\App::isEnabled('files_encryption')) {
  			if ( ! \OC_User::canUserChangePassword($params['uid']) ) {
  				self::setPassphrase($params);
  			}
  		}
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
194
  	 * Change a user's encryption passphrase
03e52840d   Kload   Init
195
196
197
  	 * @param array $params keys: uid, password
  	 */
  	public static function setPassphrase($params) {
03e52840d   Kload   Init
198
199
200
201
202
203
204
205
206
  		if (\OCP\App::isEnabled('files_encryption') === false) {
  			return true;
  		}
  
  		// Only attempt to change passphrase if server-side encryption
  		// is in use (client-side encryption does not have access to
  		// the necessary keys)
  		if (Crypt::mode() === 'server') {
  
6d9380f96   Cédric Dupont   Update sources OC...
207
  			$view = new \OC\Files\View('/');
03e52840d   Kload   Init
208
  
31b7f2792   Kload   Upgrade to ownclo...
209
  			if ($params['uid'] === \OCP\User::getUser()) {
03e52840d   Kload   Init
210
211
212
213
214
215
216
  
  				$session = new \OCA\Encryption\Session($view);
  
  				// Get existing decrypted private key
  				$privateKey = $session->getPrivateKey();
  
  				// Encrypt private key with new user pwd as passphrase
f7d878ff1   kload   [enh] Update to 7...
217
  				$encryptedPrivateKey = Crypt::symmetricEncryptFileContent($privateKey, $params['password'], Helper::getCipher());
03e52840d   Kload   Init
218
219
  
  				// Save private key
f7d878ff1   kload   [enh] Update to 7...
220
221
222
223
224
  				if ($encryptedPrivateKey) {
  					Keymanager::setPrivateKey($encryptedPrivateKey, \OCP\User::getUser());
  				} else {
  					\OCP\Util::writeLog('files_encryption', 'Could not update users encryption password', \OCP\Util::ERROR);
  				}
03e52840d   Kload   Init
225
226
227
228
229
230
231
232
233
  
  				// NOTE: Session does not need to be updated as the
  				// private key has not changed, only the passphrase
  				// used to decrypt it has changed
  
  
  			} else { // admin changed the password for a different user, create new keys and reencrypt file keys
  
  				$user = $params['uid'];
31b7f2792   Kload   Upgrade to ownclo...
234
235
  				$util = new Util($view, $user);
  				$recoveryPassword = isset($params['recoveryPassword']) ? $params['recoveryPassword'] : null;
03e52840d   Kload   Init
236
  
6d9380f96   Cédric Dupont   Update sources OC...
237
238
239
240
  				// we generate new keys if...
  				// ...we have a recovery password and the user enabled the recovery key
  				// ...encryption was activated for the first time (no keys exists)
  				// ...the user doesn't have any files
31b7f2792   Kload   Upgrade to ownclo...
241
  				if (($util->recoveryEnabledForUser() && $recoveryPassword)
6d9380f96   Cédric Dupont   Update sources OC...
242
243
  						|| !$util->userKeysExists()
  						|| !$view->file_exists($user . '/files')) {
03e52840d   Kload   Init
244
  
31b7f2792   Kload   Upgrade to ownclo...
245
  					$newUserPassword = $params['password'];
03e52840d   Kload   Init
246
  
31b7f2792   Kload   Upgrade to ownclo...
247
248
  					// make sure that the users home is mounted
  					\OC\Files\Filesystem::initMountPoints($user);
03e52840d   Kload   Init
249
  
31b7f2792   Kload   Upgrade to ownclo...
250
  					$keypair = Crypt::createKeypair();
03e52840d   Kload   Init
251
  
31b7f2792   Kload   Upgrade to ownclo...
252
253
254
  					// Disable encryption proxy to prevent recursive calls
  					$proxyStatus = \OC_FileProxy::$enabled;
  					\OC_FileProxy::$enabled = false;
03e52840d   Kload   Init
255
  
31b7f2792   Kload   Upgrade to ownclo...
256
257
  					// Save public key
  					$view->file_put_contents('/public-keys/' . $user . '.public.key', $keypair['publicKey']);
03e52840d   Kload   Init
258
  
f7d878ff1   kload   [enh] Update to 7...
259
260
261
262
263
264
265
266
267
268
269
  					// Encrypt private key with new password
  					$encryptedKey = \OCA\Encryption\Crypt::symmetricEncryptFileContent($keypair['privateKey'], $newUserPassword, Helper::getCipher());
  					if ($encryptedKey) {
  						Keymanager::setPrivateKey($encryptedKey, $user);
  
  						if ($recoveryPassword) { // if recovery key is set we can re-encrypt the key files
  							$util = new Util($view, $user);
  							$util->recoverUsersFiles($recoveryPassword);
  						}
  					} else {
  						\OCP\Util::writeLog('files_encryption', 'Could not update users encryption password', \OCP\Util::ERROR);
31b7f2792   Kload   Upgrade to ownclo...
270
271
272
273
  					}
  
  					\OC_FileProxy::$enabled = $proxyStatus;
  				}
03e52840d   Kload   Init
274
275
276
277
278
  			}
  		}
  	}
  
  	/*
6d9380f96   Cédric Dupont   Update sources OC...
279
  	 * check if files can be encrypted to every user.
03e52840d   Kload   Init
280
281
  	 */
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
282
  	 * @param array $params
03e52840d   Kload   Init
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
  	 */
  	public static function preShared($params) {
  
  		if (\OCP\App::isEnabled('files_encryption') === false) {
  			return true;
  		}
  
  		$l = new \OC_L10N('files_encryption');
  		$users = array();
  		$view = new \OC\Files\View('/public-keys/');
  
  		switch ($params['shareType']) {
  			case \OCP\Share::SHARE_TYPE_USER:
  				$users[] = $params['shareWith'];
  				break;
  			case \OCP\Share::SHARE_TYPE_GROUP:
  				$users = \OC_Group::usersInGroup($params['shareWith']);
  				break;
  		}
  
  		$notConfigured = array();
  		foreach ($users as $user) {
  			if (!$view->file_exists($user . '.public.key')) {
  				$notConfigured[] = $user;
  			}
  		}
  
  		if (count($notConfigured) > 0) {
  			$params['run'] = false;
  			$params['error'] = $l->t('Following users are not set up for encryption:') . ' ' . join(', ' , $notConfigured);
  		}
  
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
318
  	 * update share keys if a file was shared
03e52840d   Kload   Init
319
320
321
  	 */
  	public static function postShared($params) {
  
31b7f2792   Kload   Upgrade to ownclo...
322
323
324
325
  		if (\OCP\App::isEnabled('files_encryption') === false) {
  			return true;
  		}
  
03e52840d   Kload   Init
326
327
  		if ($params['itemType'] === 'file' || $params['itemType'] === 'folder') {
  
6d9380f96   Cédric Dupont   Update sources OC...
328
  			$path = \OC\Files\Filesystem::getPath($params['fileSource']);
03e52840d   Kload   Init
329
  
6d9380f96   Cédric Dupont   Update sources OC...
330
331
332
  			self::updateKeyfiles($path, $params['itemType']);
  		}
  	}
03e52840d   Kload   Init
333
  
6d9380f96   Cédric Dupont   Update sources OC...
334
335
336
337
338
339
340
341
342
343
344
345
  	/**
  	 * update keyfiles and share keys recursively
  	 *
  	 * @param string $path to the file/folder
  	 * @param string $type 'file' or 'folder'
  	 */
  	private static function updateKeyfiles($path, $type) {
  		$view = new \OC\Files\View('/');
  		$userId = \OCP\User::getUser();
  		$session = new \OCA\Encryption\Session($view);
  		$util = new Util($view, $userId);
  		$sharingEnabled = \OCP\Share::isEnabled();
03e52840d   Kload   Init
346
  
6d9380f96   Cédric Dupont   Update sources OC...
347
348
349
  		$mountManager = \OC\Files\Filesystem::getMountManager();
  		$mount = $mountManager->find('/' . $userId . '/files' . $path);
  		$mountPoint = $mount->getMountPoint();
03e52840d   Kload   Init
350
  
6d9380f96   Cédric Dupont   Update sources OC...
351
352
353
354
355
356
  		// if a folder was shared, get a list of all (sub-)folders
  		if ($type === 'folder') {
  			$allFiles = $util->getAllFiles($path, $mountPoint);
  		} else {
  			$allFiles = array($path);
  		}
03e52840d   Kload   Init
357
  
6d9380f96   Cédric Dupont   Update sources OC...
358
359
360
  		foreach ($allFiles as $path) {
  			$usersSharing = $util->getSharingUsersArray($sharingEnabled, $path);
  			$util->setSharedFileKeyfiles($session, $usersSharing, $path);
03e52840d   Kload   Init
361
362
363
364
  		}
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
365
  	 * unshare file/folder from a user with whom you shared the file before
03e52840d   Kload   Init
366
367
368
  	 */
  	public static function postUnshare($params) {
  
31b7f2792   Kload   Upgrade to ownclo...
369
370
371
372
  		if (\OCP\App::isEnabled('files_encryption') === false) {
  			return true;
  		}
  
03e52840d   Kload   Init
373
374
  		if ($params['itemType'] === 'file' || $params['itemType'] === 'folder') {
  
6d9380f96   Cédric Dupont   Update sources OC...
375
  			$view = new \OC\Files\View('/');
03e52840d   Kload   Init
376
377
  			$userId = \OCP\User::getUser();
  			$util = new Util($view, $userId);
6d9380f96   Cédric Dupont   Update sources OC...
378
  			$path = \OC\Files\Filesystem::getPath($params['fileSource']);
03e52840d   Kload   Init
379
380
381
382
383
384
385
386
387
388
389
390
  
  			// for group shares get a list of the group members
  			if ($params['shareType'] === \OCP\Share::SHARE_TYPE_GROUP) {
  				$userIds = \OC_Group::usersInGroup($params['shareWith']);
  			} else {
  				if ($params['shareType'] === \OCP\Share::SHARE_TYPE_LINK) {
  					$userIds = array($util->getPublicShareKeyId());
  				} else {
  					$userIds = array($params['shareWith']);
  				}
  			}
  
6d9380f96   Cédric Dupont   Update sources OC...
391
392
393
  			$mountManager = \OC\Files\Filesystem::getMountManager();
  			$mount = $mountManager->find('/' . $userId . '/files' . $path);
  			$mountPoint = $mount->getMountPoint();
03e52840d   Kload   Init
394
395
396
  
  			// if we unshare a folder we need a list of all (sub-)files
  			if ($params['itemType'] === 'folder') {
6d9380f96   Cédric Dupont   Update sources OC...
397
  				$allFiles = $util->getAllFiles($path, $mountPoint);
03e52840d   Kload   Init
398
399
400
401
402
403
404
405
406
407
408
409
  			} else {
  				$allFiles = array($path);
  			}
  
  			foreach ($allFiles as $path) {
  
  				// check if the user still has access to the file, otherwise delete share key
  				$sharingUsers = $util->getSharingUsersArray(true, $path);
  
  				// Unshare every user who no longer has access to the file
  				$delUsers = array_diff($userIds, $sharingUsers);
  
6d9380f96   Cédric Dupont   Update sources OC...
410
411
  				list($owner, $ownerPath) = $util->getUidAndFilename($path);
  
03e52840d   Kload   Init
412
  				// delete share key
6d9380f96   Cédric Dupont   Update sources OC...
413
  				Keymanager::delShareKey($view, $delUsers, $ownerPath, $owner);
03e52840d   Kload   Init
414
415
416
417
418
419
  			}
  
  		}
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
420
  	 * mark file as renamed so that we know the original source after the file was renamed
a293d369c   Kload   Update sources to...
421
422
423
424
  	 * @param array $params with the old path and the new path
  	 */
  	public static function preRename($params) {
  		$user = \OCP\User::getUser();
6d9380f96   Cédric Dupont   Update sources OC...
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
  		$view = new \OC\Files\View('/');
  		$util = new Util($view, $user);
  		list($ownerOld, $pathOld) = $util->getUidAndFilename($params['oldpath']);
  
  		// we only need to rename the keys if the rename happens on the same mountpoint
  		// otherwise we perform a stream copy, so we get a new set of keys
  		$mp1 = $view->getMountPoint('/' . $user . '/files/' . $params['oldpath']);
  		$mp2 = $view->getMountPoint('/' . $user . '/files/' . $params['newpath']);
  
  		$type = $view->is_dir('/' . $user . '/files/' . $params['oldpath']) ? 'folder' : 'file';
  
  		if ($mp1 === $mp2) {
  			self::$renamedFiles[$params['oldpath']] = array(
  				'uid' => $ownerOld,
  				'path' => $pathOld,
  				'type' => $type,
  				'operation' => 'rename',
  				);
  
  		}
  	}
  
  	/**
  	 * mark file as renamed so that we know the original source after the file was renamed
  	 * @param array $params with the old path and the new path
  	 */
  	public static function preCopy($params) {
  		$user = \OCP\User::getUser();
  		$view = new \OC\Files\View('/');
a293d369c   Kload   Update sources to...
454
455
456
457
458
459
460
  		$util = new Util($view, $user);
  		list($ownerOld, $pathOld) = $util->getUidAndFilename($params['oldpath']);
  
  		// we only need to rename the keys if the rename happens on the same mountpoint
  		// otherwise we perform a stream copy, so we get a new set of keys
  		$mp1 = $view->getMountPoint('/' . $user . '/files/' . $params['oldpath']);
  		$mp2 = $view->getMountPoint('/' . $user . '/files/' . $params['newpath']);
6d9380f96   Cédric Dupont   Update sources OC...
461
462
463
  
  		$type = $view->is_dir('/' . $user . '/files/' . $params['oldpath']) ? 'folder' : 'file';
  
a293d369c   Kload   Update sources to...
464
465
466
  		if ($mp1 === $mp2) {
  			self::$renamedFiles[$params['oldpath']] = array(
  				'uid' => $ownerOld,
6d9380f96   Cédric Dupont   Update sources OC...
467
468
469
  				'path' => $pathOld,
  				'type' => $type,
  				'operation' => 'copy');
a293d369c   Kload   Update sources to...
470
471
472
473
  		}
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
474
  	 * after a file is renamed/copied, rename/copy its keyfile and share-keys also fix the file size and fix also the sharing
03e52840d   Kload   Init
475
  	 *
6d9380f96   Cédric Dupont   Update sources OC...
476
  	 * @param array $params array with oldpath and newpath
03e52840d   Kload   Init
477
  	 */
6d9380f96   Cédric Dupont   Update sources OC...
478
  	public static function postRenameOrCopy($params) {
03e52840d   Kload   Init
479
480
481
482
483
484
485
486
487
  
  		if (\OCP\App::isEnabled('files_encryption') === false) {
  			return true;
  		}
  
  		// Disable encryption proxy to prevent recursive calls
  		$proxyStatus = \OC_FileProxy::$enabled;
  		\OC_FileProxy::$enabled = false;
  
6d9380f96   Cédric Dupont   Update sources OC...
488
  		$view = new \OC\Files\View('/');
03e52840d   Kload   Init
489
490
491
  		$userId = \OCP\User::getUser();
  		$util = new Util($view, $userId);
  
a293d369c   Kload   Update sources to...
492
493
494
495
  		if (isset(self::$renamedFiles[$params['oldpath']]['uid']) &&
  				isset(self::$renamedFiles[$params['oldpath']]['path'])) {
  			$ownerOld = self::$renamedFiles[$params['oldpath']]['uid'];
  			$pathOld = self::$renamedFiles[$params['oldpath']]['path'];
6d9380f96   Cédric Dupont   Update sources OC...
496
497
498
  			$type =  self::$renamedFiles[$params['oldpath']]['type'];
  			$operation = self::$renamedFiles[$params['oldpath']]['operation'];
  			unset(self::$renamedFiles[$params['oldpath']]);
a293d369c   Kload   Update sources to...
499
  		} else {
6d9380f96   Cédric Dupont   Update sources OC...
500
  			\OCP\Util::writeLog('Encryption library', "can't get path and owner from the file before it was renamed", \OCP\Util::DEBUG);
a293d369c   Kload   Update sources to...
501
502
503
504
505
  			return false;
  		}
  
  		list($ownerNew, $pathNew) = $util->getUidAndFilename($params['newpath']);
  
03e52840d   Kload   Init
506
  		// Format paths to be relative to user files dir
a293d369c   Kload   Update sources to...
507
508
509
  		if ($util->isSystemWideMountPoint($pathOld)) {
  			$oldKeyfilePath = 'files_encryption/keyfiles/' . $pathOld;
  			$oldShareKeyPath = 'files_encryption/share-keys/' . $pathOld;
03e52840d   Kload   Init
510
  		} else {
a293d369c   Kload   Update sources to...
511
512
  			$oldKeyfilePath = $ownerOld . '/' . 'files_encryption/keyfiles/' . $pathOld;
  			$oldShareKeyPath = $ownerOld . '/' . 'files_encryption/share-keys/' . $pathOld;
03e52840d   Kload   Init
513
514
  		}
  
a293d369c   Kload   Update sources to...
515
516
517
  		if ($util->isSystemWideMountPoint($pathNew)) {
  			$newKeyfilePath =  'files_encryption/keyfiles/' . $pathNew;
  			$newShareKeyPath =  'files_encryption/share-keys/' . $pathNew;
03e52840d   Kload   Init
518
  		} else {
a293d369c   Kload   Update sources to...
519
520
  			$newKeyfilePath = $ownerNew . '/files_encryption/keyfiles/' . $pathNew;
  			$newShareKeyPath = $ownerNew . '/files_encryption/share-keys/' . $pathNew;
03e52840d   Kload   Init
521
522
  		}
  
6d9380f96   Cédric Dupont   Update sources OC...
523
524
525
526
527
528
529
530
531
532
  		// create new key folders if it doesn't exists
  		if (!$view->file_exists(dirname($newShareKeyPath))) {
  				$view->mkdir(dirname($newShareKeyPath));
  		}
  		if (!$view->file_exists(dirname($newKeyfilePath))) {
  			$view->mkdir(dirname($newKeyfilePath));
  		}
  
  		// handle share keys
  		if ($type === 'file') {
03e52840d   Kload   Init
533
534
535
536
  			$oldKeyfilePath .= '.key';
  			$newKeyfilePath .= '.key';
  
  			// handle share-keys
6d9380f96   Cédric Dupont   Update sources OC...
537
  			$matches = Helper::findShareKeys($oldShareKeyPath, $view);
03e52840d   Kload   Init
538
  			foreach ($matches as $src) {
a293d369c   Kload   Update sources to...
539
  				$dst = \OC\Files\Filesystem::normalizePath(str_replace($pathOld, $pathNew, $src));
6d9380f96   Cédric Dupont   Update sources OC...
540
  				$view->$operation($src, $dst);
03e52840d   Kload   Init
541
542
543
544
  			}
  
  		} else {
  			// handle share-keys folders
6d9380f96   Cédric Dupont   Update sources OC...
545
  			$view->$operation($oldShareKeyPath, $newShareKeyPath);
03e52840d   Kload   Init
546
547
548
549
  		}
  
  		// Rename keyfile so it isn't orphaned
  		if ($view->file_exists($oldKeyfilePath)) {
6d9380f96   Cédric Dupont   Update sources OC...
550
  			$view->$operation($oldKeyfilePath, $newKeyfilePath);
03e52840d   Kload   Init
551
552
  		}
  
03e52840d   Kload   Init
553
  
6d9380f96   Cédric Dupont   Update sources OC...
554
555
  		// update sharing-keys
  		self::updateKeyfiles($params['newpath'], $type);
03e52840d   Kload   Init
556
557
558
559
560
  
  		\OC_FileProxy::$enabled = $proxyStatus;
  	}
  
  	/**
31b7f2792   Kload   Upgrade to ownclo...
561
  	 * set migration status and the init status back to '0' so that all new files get encrypted
03e52840d   Kload   Init
562
563
564
565
  	 * if the app gets enabled again
  	 * @param array $params contains the app ID
  	 */
  	public static function preDisable($params) {
31b7f2792   Kload   Upgrade to ownclo...
566
567
  		if ($params['app'] === 'files_encryption') {
  
6d9380f96   Cédric Dupont   Update sources OC...
568
  			\OC_Preferences::deleteAppFromAllUsers('files_encryption');
31b7f2792   Kload   Upgrade to ownclo...
569
570
571
572
573
574
575
576
577
578
579
580
581
582
  
  			$session = new \OCA\Encryption\Session(new \OC\Files\View('/'));
  			$session->setInitialized(\OCA\Encryption\Session::NOT_INITIALIZED);
  		}
  	}
  
  	/**
  	 * set the init status to 'NOT_INITIALIZED' (0) if the app gets enabled
  	 * @param array $params contains the app ID
  	 */
  	public static function postEnable($params) {
  		if ($params['app'] === 'files_encryption') {
  			$session = new \OCA\Encryption\Session(new \OC\Files\View('/'));
  			$session->setInitialized(\OCA\Encryption\Session::NOT_INITIALIZED);
03e52840d   Kload   Init
583
584
585
  		}
  	}
  
a293d369c   Kload   Update sources to...
586
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
587
  	 * if the file was really deleted we remove the encryption keys
a293d369c   Kload   Update sources to...
588
  	 * @param array $params
6d9380f96   Cédric Dupont   Update sources OC...
589
  	 * @return boolean|null
a293d369c   Kload   Update sources to...
590
591
592
593
594
595
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
  	 */
  	public static function postDelete($params) {
  
  		if (!isset(self::$deleteFiles[$params[\OC\Files\Filesystem::signal_param_path]])) {
  			return true;
  		}
  
  		$deletedFile = self::$deleteFiles[$params[\OC\Files\Filesystem::signal_param_path]];
  		$path = $deletedFile['path'];
  		$user = $deletedFile['uid'];
  
  		// we don't need to remember the file any longer
  		unset(self::$deleteFiles[$params[\OC\Files\Filesystem::signal_param_path]]);
  
  		$view = new \OC\Files\View('/');
  
  		// return if the file still exists and wasn't deleted correctly
  		if ($view->file_exists('/' . $user . '/files/' . $path)) {
  			return true;
  		}
  
  		// Disable encryption proxy to prevent recursive calls
  		$proxyStatus = \OC_FileProxy::$enabled;
  		\OC_FileProxy::$enabled = false;
  
  		// Delete keyfile & shareKey so it isn't orphaned
  		if (!Keymanager::deleteFileKey($view, $path, $user)) {
  			\OCP\Util::writeLog('Encryption library',
  				'Keyfile or shareKey could not be deleted for file "' . $user.'/files/'.$path . '"', \OCP\Util::ERROR);
  		}
  
  		Keymanager::delAllShareKeys($view, $user, $path);
  
  		\OC_FileProxy::$enabled = $proxyStatus;
  	}
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
627
  	 * remember the file which should be deleted and it's owner
a293d369c   Kload   Update sources to...
628
  	 * @param array $params
6d9380f96   Cédric Dupont   Update sources OC...
629
  	 * @return boolean|null
a293d369c   Kload   Update sources to...
630
631
632
633
634
635
636
637
638
639
  	 */
  	public static function preDelete($params) {
  		$path = $params[\OC\Files\Filesystem::signal_param_path];
  
  		// skip this method if the trash bin is enabled or if we delete a file
  		// outside of /data/user/files
  		if (\OCP\App::isEnabled('files_trashbin')) {
  			return true;
  		}
  
6d9380f96   Cédric Dupont   Update sources OC...
640
  		$util = new Util(new \OC\Files\View('/'), \OCP\USER::getUser());
a293d369c   Kload   Update sources to...
641
642
643
644
645
646
647
  		list($owner, $ownerPath) = $util->getUidAndFilename($path);
  
  		self::$deleteFiles[$params[\OC\Files\Filesystem::signal_param_path]] = array(
  			'uid' => $owner,
  			'path' => $ownerPath);
  	}
  
6d9380f96   Cédric Dupont   Update sources OC...
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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
  	/**
  	 * unmount file from yourself
  	 * remember files/folders which get unmounted
  	 */
  	public static function preUmount($params) {
  		$path = $params[\OC\Files\Filesystem::signal_param_path];
  		$user = \OCP\USER::getUser();
  
  		$view = new \OC\Files\View();
  		$itemType = $view->is_dir('/' . $user . '/files' . $path) ? 'folder' : 'file';
  
  		$util = new Util($view, $user);
  		list($owner, $ownerPath) = $util->getUidAndFilename($path);
  
  		self::$umountedFiles[$params[\OC\Files\Filesystem::signal_param_path]] = array(
  			'uid' => $owner,
  			'path' => $ownerPath,
  			'itemType' => $itemType);
  	}
  
  	/**
  	 * unmount file from yourself
  	 */
  	public static function postUmount($params) {
  
  		if (!isset(self::$umountedFiles[$params[\OC\Files\Filesystem::signal_param_path]])) {
  			return true;
  		}
  
  		$umountedFile = self::$umountedFiles[$params[\OC\Files\Filesystem::signal_param_path]];
  		$path = $umountedFile['path'];
  		$user = $umountedFile['uid'];
  		$itemType = $umountedFile['itemType'];
  
  		$view = new \OC\Files\View();
  		$util = new Util($view, $user);
  
  		// we don't need to remember the file any longer
  		unset(self::$umountedFiles[$params[\OC\Files\Filesystem::signal_param_path]]);
  
  		// if we unshare a folder we need a list of all (sub-)files
  		if ($itemType === 'folder') {
  			$allFiles = $util->getAllFiles($path);
  		} else {
  			$allFiles = array($path);
  		}
  
  		foreach ($allFiles as $path) {
  
  			// check if the user still has access to the file, otherwise delete share key
  			$sharingUsers = \OCP\Share::getUsersSharingFile($path, $user);
  			if (!in_array(\OCP\User::getUser(), $sharingUsers['users'])) {
  				Keymanager::delShareKey($view, array(\OCP\User::getUser()), $path, $user);
  			}
  		}
  	}
  
03e52840d   Kload   Init
705
  }