You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

626 lines
19 KiB

13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
12 years ago
12 years ago
13 years ago
13 years ago
13 years ago
12 years ago
12 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
11 years ago
13 years ago
13 years ago
13 years ago
11 years ago
  1. <?php
  2. /**
  3. * ownCloud
  4. *
  5. * @copyright (C) 2014 ownCloud, Inc.
  6. *
  7. * @author Sam Tuke <samtuke@owncloud.org>
  8. * @author Bjoern Schiessle <schiessle@owncloud.com>
  9. *
  10. * This library is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  12. * License as published by the Free Software Foundation; either
  13. * version 3 of the License, or any later version.
  14. *
  15. * This library is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public
  21. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
  22. *
  23. */
  24. namespace OCA\Files_Encryption;
  25. /**
  26. * Class for hook specific logic
  27. */
  28. class Hooks {
  29. // file for which we want to rename the keys after the rename operation was successful
  30. private static $renamedFiles = array();
  31. // file for which we want to delete the keys after the delete operation was successful
  32. private static $deleteFiles = array();
  33. // file for which we want to delete the keys after the delete operation was successful
  34. private static $unmountedFiles = array();
  35. /**
  36. * Startup encryption backend upon user login
  37. * @note This method should never be called for users using client side encryption
  38. */
  39. public static function login($params) {
  40. if (\OCP\App::isEnabled('files_encryption') === false) {
  41. return true;
  42. }
  43. $l = new \OC_L10N('files_encryption');
  44. $view = new \OC\Files\View('/');
  45. // ensure filesystem is loaded
  46. if (!\OC\Files\Filesystem::$loaded) {
  47. \OC_Util::setupFS($params['uid']);
  48. }
  49. $privateKey = Keymanager::getPrivateKey($view, $params['uid']);
  50. // if no private key exists, check server configuration
  51. if (!$privateKey) {
  52. //check if all requirements are met
  53. if (!Helper::checkRequirements() || !Helper::checkConfiguration()) {
  54. $error_msg = $l->t("Missing requirements.");
  55. $hint = $l->t('Please make sure that OpenSSL together with the PHP extension is enabled and configured properly. For now, the encryption app has been disabled.');
  56. \OC_App::disable('files_encryption');
  57. \OCP\Util::writeLog('Encryption library', $error_msg . ' ' . $hint, \OCP\Util::ERROR);
  58. \OCP\Template::printErrorPage($error_msg, $hint);
  59. }
  60. }
  61. $util = new Util($view, $params['uid']);
  62. // setup user, if user not ready force relogin
  63. if (Helper::setupUser($util, $params['password']) === false) {
  64. return false;
  65. }
  66. $session = $util->initEncryption($params);
  67. // Check if first-run file migration has already been performed
  68. $ready = false;
  69. $migrationStatus = $util->getMigrationStatus();
  70. if ($migrationStatus === Util::MIGRATION_OPEN && $session !== false) {
  71. $ready = $util->beginMigration();
  72. } elseif ($migrationStatus === Util::MIGRATION_IN_PROGRESS) {
  73. // refuse login as long as the initial encryption is running
  74. sleep(5);
  75. \OCP\User::logout();
  76. return false;
  77. }
  78. $result = true;
  79. // If migration not yet done
  80. if ($ready) {
  81. // Encrypt existing user files
  82. try {
  83. $result = $util->encryptAll('/' . $params['uid'] . '/' . 'files');
  84. } catch (\Exception $ex) {
  85. \OCP\Util::writeLog('Encryption library', 'Initial encryption failed! Error: ' . $ex->getMessage(), \OCP\Util::FATAL);
  86. $result = false;
  87. }
  88. if ($result) {
  89. \OC_Log::write(
  90. 'Encryption library', 'Encryption of existing files belonging to "' . $params['uid'] . '" completed'
  91. , \OC_Log::INFO
  92. );
  93. // Register successful migration in DB
  94. $util->finishMigration();
  95. } else {
  96. \OCP\Util::writeLog('Encryption library', 'Initial encryption failed!', \OCP\Util::FATAL);
  97. $util->resetMigrationStatus();
  98. \OCP\User::logout();
  99. }
  100. }
  101. return $result;
  102. }
  103. /**
  104. * remove keys from session during logout
  105. */
  106. public static function logout() {
  107. $session = new Session(new \OC\Files\View());
  108. $session->removeKeys();
  109. }
  110. /**
  111. * setup encryption backend upon user created
  112. * @note This method should never be called for users using client side encryption
  113. */
  114. public static function postCreateUser($params) {
  115. if (\OCP\App::isEnabled('files_encryption')) {
  116. $view = new \OC\Files\View('/');
  117. $util = new Util($view, $params['uid']);
  118. Helper::setupUser($util, $params['password']);
  119. }
  120. }
  121. /**
  122. * cleanup encryption backend upon user deleted
  123. * @note This method should never be called for users using client side encryption
  124. */
  125. public static function postDeleteUser($params) {
  126. if (\OCP\App::isEnabled('files_encryption')) {
  127. Keymanager::deletePublicKey(new \OC\Files\View(), $params['uid']);
  128. }
  129. }
  130. /**
  131. * If the password can't be changed within ownCloud, than update the key password in advance.
  132. */
  133. public static function preSetPassphrase($params) {
  134. if (\OCP\App::isEnabled('files_encryption')) {
  135. if ( ! \OC_User::canUserChangePassword($params['uid']) ) {
  136. self::setPassphrase($params);
  137. }
  138. }
  139. }
  140. /**
  141. * Change a user's encryption passphrase
  142. * @param array $params keys: uid, password
  143. */
  144. public static function setPassphrase($params) {
  145. if (\OCP\App::isEnabled('files_encryption') === false) {
  146. return true;
  147. }
  148. // Only attempt to change passphrase if server-side encryption
  149. // is in use (client-side encryption does not have access to
  150. // the necessary keys)
  151. if (Crypt::mode() === 'server') {
  152. $view = new \OC\Files\View('/');
  153. $session = new Session($view);
  154. // Get existing decrypted private key
  155. $privateKey = $session->getPrivateKey();
  156. if ($params['uid'] === \OCP\User::getUser() && $privateKey) {
  157. // Encrypt private key with new user pwd as passphrase
  158. $encryptedPrivateKey = Crypt::symmetricEncryptFileContent($privateKey, $params['password'], Helper::getCipher());
  159. // Save private key
  160. if ($encryptedPrivateKey) {
  161. Keymanager::setPrivateKey($encryptedPrivateKey, \OCP\User::getUser());
  162. } else {
  163. \OCP\Util::writeLog('files_encryption', 'Could not update users encryption password', \OCP\Util::ERROR);
  164. }
  165. // NOTE: Session does not need to be updated as the
  166. // private key has not changed, only the passphrase
  167. // used to decrypt it has changed
  168. } else { // admin changed the password for a different user, create new keys and reencrypt file keys
  169. $user = $params['uid'];
  170. $util = new Util($view, $user);
  171. $recoveryPassword = isset($params['recoveryPassword']) ? $params['recoveryPassword'] : null;
  172. // we generate new keys if...
  173. // ...we have a recovery password and the user enabled the recovery key
  174. // ...encryption was activated for the first time (no keys exists)
  175. // ...the user doesn't have any files
  176. if (($util->recoveryEnabledForUser() && $recoveryPassword)
  177. || !$util->userKeysExists()
  178. || !$view->file_exists($user . '/files')) {
  179. // backup old keys
  180. $util->backupAllKeys('recovery');
  181. $newUserPassword = $params['password'];
  182. // make sure that the users home is mounted
  183. \OC\Files\Filesystem::initMountPoints($user);
  184. $keypair = Crypt::createKeypair();
  185. // Disable encryption proxy to prevent recursive calls
  186. $proxyStatus = \OC_FileProxy::$enabled;
  187. \OC_FileProxy::$enabled = false;
  188. // Save public key
  189. Keymanager::setPublicKey($keypair['publicKey'], $user);
  190. // Encrypt private key with new password
  191. $encryptedKey = Crypt::symmetricEncryptFileContent($keypair['privateKey'], $newUserPassword, Helper::getCipher());
  192. if ($encryptedKey) {
  193. Keymanager::setPrivateKey($encryptedKey, $user);
  194. if ($recoveryPassword) { // if recovery key is set we can re-encrypt the key files
  195. $util = new Util($view, $user);
  196. $util->recoverUsersFiles($recoveryPassword);
  197. }
  198. } else {
  199. \OCP\Util::writeLog('files_encryption', 'Could not update users encryption password', \OCP\Util::ERROR);
  200. }
  201. \OC_FileProxy::$enabled = $proxyStatus;
  202. }
  203. }
  204. }
  205. }
  206. /**
  207. * after password reset we create a new key pair for the user
  208. *
  209. * @param array $params
  210. */
  211. public static function postPasswordReset($params) {
  212. $uid = $params['uid'];
  213. $password = $params['password'];
  214. $util = new Util(new \OC\Files\View(), $uid);
  215. $util->replaceUserKeys($password);
  216. }
  217. /*
  218. * check if files can be encrypted to every user.
  219. */
  220. /**
  221. * @param array $params
  222. */
  223. public static function preShared($params) {
  224. if (\OCP\App::isEnabled('files_encryption') === false) {
  225. return true;
  226. }
  227. $l = new \OC_L10N('files_encryption');
  228. $users = array();
  229. $view = new \OC\Files\View('/');
  230. switch ($params['shareType']) {
  231. case \OCP\Share::SHARE_TYPE_USER:
  232. $users[] = $params['shareWith'];
  233. break;
  234. case \OCP\Share::SHARE_TYPE_GROUP:
  235. $users = \OC_Group::usersInGroup($params['shareWith']);
  236. break;
  237. }
  238. $notConfigured = array();
  239. foreach ($users as $user) {
  240. if (!Keymanager::publicKeyExists($view, $user)) {
  241. $notConfigured[] = $user;
  242. }
  243. }
  244. if (count($notConfigured) > 0) {
  245. $params['run'] = false;
  246. $params['error'] = $l->t('Following users are not set up for encryption:') . ' ' . join(', ' , $notConfigured);
  247. }
  248. }
  249. /**
  250. * update share keys if a file was shared
  251. */
  252. public static function postShared($params) {
  253. if (\OCP\App::isEnabled('files_encryption') === false) {
  254. return true;
  255. }
  256. if ($params['itemType'] === 'file' || $params['itemType'] === 'folder') {
  257. $path = \OC\Files\Filesystem::getPath($params['fileSource']);
  258. self::updateKeyfiles($path);
  259. }
  260. }
  261. /**
  262. * update keyfiles and share keys recursively
  263. *
  264. * @param string $path to the file/folder
  265. */
  266. private static function updateKeyfiles($path) {
  267. $view = new \OC\Files\View('/');
  268. $userId = \OCP\User::getUser();
  269. $session = new Session($view);
  270. $util = new Util($view, $userId);
  271. $sharingEnabled = \OCP\Share::isEnabled();
  272. $mountManager = \OC\Files\Filesystem::getMountManager();
  273. $mount = $mountManager->find('/' . $userId . '/files' . $path);
  274. $mountPoint = $mount->getMountPoint();
  275. // if a folder was shared, get a list of all (sub-)folders
  276. if ($view->is_dir('/' . $userId . '/files' . $path)) {
  277. $allFiles = $util->getAllFiles($path, $mountPoint);
  278. } else {
  279. $allFiles = array($path);
  280. }
  281. foreach ($allFiles as $path) {
  282. $usersSharing = $util->getSharingUsersArray($sharingEnabled, $path);
  283. $util->setSharedFileKeyfiles($session, $usersSharing, $path);
  284. }
  285. }
  286. /**
  287. * unshare file/folder from a user with whom you shared the file before
  288. */
  289. public static function postUnshare($params) {
  290. if (\OCP\App::isEnabled('files_encryption') === false) {
  291. return true;
  292. }
  293. if ($params['itemType'] === 'file' || $params['itemType'] === 'folder') {
  294. $view = new \OC\Files\View('/');
  295. $userId = $params['uidOwner'];
  296. $userView = new \OC\Files\View('/' . $userId . '/files');
  297. $util = new Util($view, $userId);
  298. $path = $userView->getPath($params['fileSource']);
  299. // for group shares get a list of the group members
  300. if ($params['shareType'] === \OCP\Share::SHARE_TYPE_GROUP) {
  301. $userIds = \OC_Group::usersInGroup($params['shareWith']);
  302. } else {
  303. if ($params['shareType'] === \OCP\Share::SHARE_TYPE_LINK || $params['shareType'] === \OCP\Share::SHARE_TYPE_REMOTE) {
  304. $userIds = array($util->getPublicShareKeyId());
  305. } else {
  306. $userIds = array($params['shareWith']);
  307. }
  308. }
  309. $mountManager = \OC\Files\Filesystem::getMountManager();
  310. $mount = $mountManager->find('/' . $userId . '/files' . $path);
  311. $mountPoint = $mount->getMountPoint();
  312. // if we unshare a folder we need a list of all (sub-)files
  313. if ($params['itemType'] === 'folder') {
  314. $allFiles = $util->getAllFiles($path, $mountPoint);
  315. } else {
  316. $allFiles = array($path);
  317. }
  318. foreach ($allFiles as $path) {
  319. // check if the user still has access to the file, otherwise delete share key
  320. $sharingUsers = $util->getSharingUsersArray(true, $path);
  321. // Unshare every user who no longer has access to the file
  322. $delUsers = array_diff($userIds, $sharingUsers);
  323. $keyPath = Keymanager::getKeyPath($view, $util, $path);
  324. // delete share key
  325. Keymanager::delShareKey($view, $delUsers, $keyPath, $userId, $path);
  326. }
  327. }
  328. }
  329. /**
  330. * mark file as renamed so that we know the original source after the file was renamed
  331. * @param array $params with the old path and the new path
  332. */
  333. public static function preRename($params) {
  334. self::preRenameOrCopy($params, 'rename');
  335. }
  336. /**
  337. * mark file as copied so that we know the original source after the file was copied
  338. * @param array $params with the old path and the new path
  339. */
  340. public static function preCopy($params) {
  341. self::preRenameOrCopy($params, 'copy');
  342. }
  343. private static function preRenameOrCopy($params, $operation) {
  344. $user = \OCP\User::getUser();
  345. $view = new \OC\Files\View('/');
  346. $util = new Util($view, $user);
  347. // we only need to rename the keys if the rename happens on the same mountpoint
  348. // otherwise we perform a stream copy, so we get a new set of keys
  349. $mp1 = $view->getMountPoint('/' . $user . '/files/' . $params['oldpath']);
  350. $mp2 = $view->getMountPoint('/' . $user . '/files/' . $params['newpath']);
  351. $oldKeysPath = Keymanager::getKeyPath($view, $util, $params['oldpath']);
  352. if ($mp1 === $mp2) {
  353. self::$renamedFiles[$params['oldpath']] = array(
  354. 'operation' => $operation,
  355. 'oldKeysPath' => $oldKeysPath,
  356. );
  357. } else {
  358. self::$renamedFiles[$params['oldpath']] = array(
  359. 'operation' => 'cleanup',
  360. 'oldKeysPath' => $oldKeysPath,
  361. );
  362. }
  363. }
  364. /**
  365. * after a file is renamed/copied, rename/copy its keyfile and share-keys also fix the file size and fix also the sharing
  366. *
  367. * @param array $params array with oldpath and newpath
  368. */
  369. public static function postRenameOrCopy($params) {
  370. if (\OCP\App::isEnabled('files_encryption') === false) {
  371. return true;
  372. }
  373. $view = new \OC\Files\View('/');
  374. $userId = \OCP\User::getUser();
  375. $util = new Util($view, $userId);
  376. if (isset(self::$renamedFiles[$params['oldpath']]['operation']) &&
  377. isset(self::$renamedFiles[$params['oldpath']]['oldKeysPath'])) {
  378. $operation = self::$renamedFiles[$params['oldpath']]['operation'];
  379. $oldKeysPath = self::$renamedFiles[$params['oldpath']]['oldKeysPath'];
  380. unset(self::$renamedFiles[$params['oldpath']]);
  381. if ($operation === 'cleanup') {
  382. return $view->unlink($oldKeysPath);
  383. }
  384. } else {
  385. \OCP\Util::writeLog('Encryption library', "can't get path and owner from the file before it was renamed", \OCP\Util::DEBUG);
  386. return false;
  387. }
  388. list($ownerNew, $pathNew) = $util->getUidAndFilename($params['newpath']);
  389. if ($util->isSystemWideMountPoint($pathNew)) {
  390. $newKeysPath = 'files_encryption/keys/' . $pathNew;
  391. } else {
  392. $newKeysPath = $ownerNew . '/files_encryption/keys/' . $pathNew;
  393. }
  394. // create key folders if it doesn't exists
  395. if (!$view->file_exists(dirname($newKeysPath))) {
  396. $view->mkdir(dirname($newKeysPath));
  397. }
  398. $view->$operation($oldKeysPath, $newKeysPath);
  399. // update sharing-keys
  400. self::updateKeyfiles($params['newpath']);
  401. }
  402. /**
  403. * set migration status and the init status back to '0' so that all new files get encrypted
  404. * if the app gets enabled again
  405. * @param array $params contains the app ID
  406. */
  407. public static function preDisable($params) {
  408. if ($params['app'] === 'files_encryption') {
  409. \OC::$server->getConfig()->deleteAppFromAllUsers('files_encryption');
  410. $session = new Session(new \OC\Files\View('/'));
  411. $session->setInitialized(Session::NOT_INITIALIZED);
  412. }
  413. }
  414. /**
  415. * set the init status to 'NOT_INITIALIZED' (0) if the app gets enabled
  416. * @param array $params contains the app ID
  417. */
  418. public static function postEnable($params) {
  419. if ($params['app'] === 'files_encryption') {
  420. $session = new Session(new \OC\Files\View('/'));
  421. $session->setInitialized(Session::NOT_INITIALIZED);
  422. }
  423. }
  424. /**
  425. * if the file was really deleted we remove the encryption keys
  426. * @param array $params
  427. * @return boolean|null
  428. */
  429. public static function postDelete($params) {
  430. $path = $params[\OC\Files\Filesystem::signal_param_path];
  431. if (!isset(self::$deleteFiles[$path])) {
  432. return true;
  433. }
  434. $deletedFile = self::$deleteFiles[$path];
  435. $keyPath = $deletedFile['keyPath'];
  436. // we don't need to remember the file any longer
  437. unset(self::$deleteFiles[$path]);
  438. $view = new \OC\Files\View('/');
  439. // return if the file still exists and wasn't deleted correctly
  440. if ($view->file_exists('/' . \OCP\User::getUser() . '/files/' . $path)) {
  441. return true;
  442. }
  443. // Delete keyfile & shareKey so it isn't orphaned
  444. $view->unlink($keyPath);
  445. }
  446. /**
  447. * remember the file which should be deleted and it's owner
  448. * @param array $params
  449. * @return boolean|null
  450. */
  451. public static function preDelete($params) {
  452. $view = new \OC\Files\View('/');
  453. $path = $params[\OC\Files\Filesystem::signal_param_path];
  454. // skip this method if the trash bin is enabled or if we delete a file
  455. // outside of /data/user/files
  456. if (\OCP\App::isEnabled('files_trashbin')) {
  457. return true;
  458. }
  459. $util = new Util($view, \OCP\USER::getUser());
  460. $keysPath = Keymanager::getKeyPath($view, $util, $path);
  461. self::$deleteFiles[$path] = array(
  462. 'keyPath' => $keysPath);
  463. }
  464. /**
  465. * unmount file from yourself
  466. * remember files/folders which get unmounted
  467. */
  468. public static function preUnmount($params) {
  469. $view = new \OC\Files\View('/');
  470. $user = \OCP\User::getUser();
  471. $path = $params[\OC\Files\Filesystem::signal_param_path];
  472. $util = new Util($view, $user);
  473. list($owner, $ownerPath) = $util->getUidAndFilename($path);
  474. $keysPath = Keymanager::getKeyPath($view, $util, $path);
  475. self::$unmountedFiles[$path] = array(
  476. 'keyPath' => $keysPath,
  477. 'owner' => $owner,
  478. 'ownerPath' => $ownerPath
  479. );
  480. }
  481. /**
  482. * unmount file from yourself
  483. */
  484. public static function postUnmount($params) {
  485. $path = $params[\OC\Files\Filesystem::signal_param_path];
  486. $user = \OCP\User::getUser();
  487. if (!isset(self::$unmountedFiles[$path])) {
  488. return true;
  489. }
  490. $umountedFile = self::$unmountedFiles[$path];
  491. $keyPath = $umountedFile['keyPath'];
  492. $owner = $umountedFile['owner'];
  493. $ownerPath = $umountedFile['ownerPath'];
  494. $view = new \OC\Files\View();
  495. // we don't need to remember the file any longer
  496. unset(self::$unmountedFiles[$path]);
  497. // check if the user still has access to the file, otherwise delete share key
  498. $sharingUsers = \OCP\Share::getUsersSharingFile($path, $user);
  499. if (!in_array($user, $sharingUsers['users'])) {
  500. Keymanager::delShareKey($view, array($user), $keyPath, $owner, $ownerPath);
  501. }
  502. }
  503. }