UserHooks.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bjoern Schiessle <bjoern@schiessle.org>
  6. * @author Björn Schießle <bjoern@schiessle.org>
  7. * @author Clark Tomlinson <fallen013@gmail.com>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Roeland Jago Douma <roeland@famdouma.nl>
  11. * @author Thomas Müller <thomas.mueller@tmit.eu>
  12. *
  13. * @license AGPL-3.0
  14. *
  15. * This code is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License, version 3,
  17. * as published by the Free Software Foundation.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License, version 3,
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>
  26. *
  27. */
  28. namespace OCA\Encryption\Hooks;
  29. use OC\Files\Filesystem;
  30. use OCA\Encryption\Crypto\Crypt;
  31. use OCA\Encryption\Hooks\Contracts\IHook;
  32. use OCA\Encryption\KeyManager;
  33. use OCA\Encryption\Recovery;
  34. use OCA\Encryption\Session;
  35. use OCA\Encryption\Users\Setup;
  36. use OCA\Encryption\Util;
  37. use OCP\Encryption\Exceptions\GenericEncryptionException;
  38. use OCP\IUserManager;
  39. use OCP\IUserSession;
  40. use OCP\Util as OCUtil;
  41. use Psr\Log\LoggerInterface;
  42. class UserHooks implements IHook {
  43. /**
  44. * list of user for which we perform a password reset
  45. * @var array<string, true>
  46. */
  47. protected static array $passwordResetUsers = [];
  48. public function __construct(
  49. private KeyManager $keyManager,
  50. private IUserManager $userManager,
  51. private LoggerInterface $logger,
  52. private Setup $userSetup,
  53. private IUserSession $userSession,
  54. private Util $util,
  55. private Session $session,
  56. private Crypt $crypt,
  57. private Recovery $recovery,
  58. ) {
  59. }
  60. /**
  61. * Connects Hooks
  62. *
  63. * @return null
  64. */
  65. public function addHooks() {
  66. OCUtil::connectHook('OC_User', 'post_login', $this, 'login');
  67. OCUtil::connectHook('OC_User', 'logout', $this, 'logout');
  68. // this hooks only make sense if no master key is used
  69. if ($this->util->isMasterKeyEnabled() === false) {
  70. OCUtil::connectHook('OC_User',
  71. 'post_setPassword',
  72. $this,
  73. 'setPassphrase');
  74. OCUtil::connectHook('OC_User',
  75. 'pre_setPassword',
  76. $this,
  77. 'preSetPassphrase');
  78. OCUtil::connectHook('\OC\Core\LostPassword\Controller\LostController',
  79. 'post_passwordReset',
  80. $this,
  81. 'postPasswordReset');
  82. OCUtil::connectHook('\OC\Core\LostPassword\Controller\LostController',
  83. 'pre_passwordReset',
  84. $this,
  85. 'prePasswordReset');
  86. OCUtil::connectHook('OC_User',
  87. 'post_createUser',
  88. $this,
  89. 'postCreateUser');
  90. OCUtil::connectHook('OC_User',
  91. 'post_deleteUser',
  92. $this,
  93. 'postDeleteUser');
  94. }
  95. }
  96. /**
  97. * Startup encryption backend upon user login
  98. *
  99. * @note This method should never be called for users using client side encryption
  100. * @param array $params
  101. * @return boolean|null
  102. */
  103. public function login($params) {
  104. // ensure filesystem is loaded
  105. if (!\OC\Files\Filesystem::$loaded) {
  106. $this->setupFS($params['uid']);
  107. }
  108. if ($this->util->isMasterKeyEnabled() === false) {
  109. $this->userSetup->setupUser($params['uid'], $params['password']);
  110. }
  111. $this->keyManager->init($params['uid'], $params['password']);
  112. }
  113. /**
  114. * remove keys from session during logout
  115. */
  116. public function logout() {
  117. $this->session->clear();
  118. }
  119. /**
  120. * setup encryption backend upon user created
  121. *
  122. * @note This method should never be called for users using client side encryption
  123. * @param array $params
  124. */
  125. public function postCreateUser($params) {
  126. $this->userSetup->setupUser($params['uid'], $params['password']);
  127. }
  128. /**
  129. * cleanup encryption backend upon user deleted
  130. *
  131. * @param array $params : uid, password
  132. * @note This method should never be called for users using client side encryption
  133. */
  134. public function postDeleteUser($params) {
  135. $this->keyManager->deletePublicKey($params['uid']);
  136. }
  137. public function prePasswordReset($params) {
  138. $user = $params['uid'];
  139. self::$passwordResetUsers[$user] = true;
  140. }
  141. public function postPasswordReset($params) {
  142. $uid = $params['uid'];
  143. $password = $params['password'];
  144. $this->keyManager->backupUserKeys('passwordReset', $uid);
  145. $this->keyManager->deleteUserKeys($uid);
  146. $this->userSetup->setupUser($uid, $password);
  147. unset(self::$passwordResetUsers[$uid]);
  148. }
  149. /**
  150. * If the password can't be changed within Nextcloud, than update the key password in advance.
  151. *
  152. * @param array $params : uid, password
  153. * @return boolean|null
  154. */
  155. public function preSetPassphrase($params) {
  156. $user = $this->userManager->get($params['uid']);
  157. if ($user && !$user->canChangePassword()) {
  158. $this->setPassphrase($params);
  159. }
  160. }
  161. /**
  162. * Change a user's encryption passphrase
  163. *
  164. * @param array $params keys: uid, password
  165. * @return boolean|null
  166. */
  167. public function setPassphrase($params) {
  168. // if we are in the process to resetting a user password, we have nothing
  169. // to do here
  170. if (isset(self::$passwordResetUsers[$params['uid']])) {
  171. return true;
  172. }
  173. // Get existing decrypted private key
  174. $user = $this->userSession->getUser();
  175. // current logged in user changes his own password
  176. if ($user && $params['uid'] === $user->getUID()) {
  177. $privateKey = $this->session->getPrivateKey();
  178. // Encrypt private key with new user pwd as passphrase
  179. $encryptedPrivateKey = $this->crypt->encryptPrivateKey($privateKey, $params['password'], $params['uid']);
  180. // Save private key
  181. if ($encryptedPrivateKey) {
  182. $this->keyManager->setPrivateKey($user->getUID(),
  183. $this->crypt->generateHeader() . $encryptedPrivateKey);
  184. } else {
  185. $this->logger->error('Encryption could not update users encryption password');
  186. }
  187. // NOTE: Session does not need to be updated as the
  188. // private key has not changed, only the passphrase
  189. // used to decrypt it has changed
  190. } else { // admin changed the password for a different user, create new keys and re-encrypt file keys
  191. $userId = $params['uid'];
  192. $this->initMountPoints($userId);
  193. $recoveryPassword = $params['recoveryPassword'] ?? null;
  194. $recoveryKeyId = $this->keyManager->getRecoveryKeyId();
  195. $recoveryKey = $this->keyManager->getSystemPrivateKey($recoveryKeyId);
  196. try {
  197. $decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $recoveryPassword);
  198. } catch (\Exception $e) {
  199. $decryptedRecoveryKey = false;
  200. }
  201. if ($decryptedRecoveryKey === false) {
  202. $message = 'Can not decrypt the recovery key. Maybe you provided the wrong password. Try again.';
  203. throw new GenericEncryptionException($message, $message);
  204. }
  205. // we generate new keys if...
  206. // ...we have a recovery password and the user enabled the recovery key
  207. // ...encryption was activated for the first time (no keys exists)
  208. // ...the user doesn't have any files
  209. if (
  210. ($this->recovery->isRecoveryEnabledForUser($userId) && $recoveryPassword)
  211. || !$this->keyManager->userHasKeys($userId)
  212. || !$this->util->userHasFiles($userId)
  213. ) {
  214. // backup old keys
  215. //$this->backupAllKeys('recovery');
  216. $newUserPassword = $params['password'];
  217. $keyPair = $this->crypt->createKeyPair();
  218. // Save public key
  219. $this->keyManager->setPublicKey($userId, $keyPair['publicKey']);
  220. // Encrypt private key with new password
  221. $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $newUserPassword, $userId);
  222. if ($encryptedKey) {
  223. $this->keyManager->setPrivateKey($userId, $this->crypt->generateHeader() . $encryptedKey);
  224. if ($recoveryPassword) { // if recovery key is set we can re-encrypt the key files
  225. $this->recovery->recoverUsersFiles($recoveryPassword, $userId);
  226. }
  227. } else {
  228. $this->logger->error('Encryption Could not update users encryption password');
  229. }
  230. }
  231. }
  232. }
  233. /**
  234. * init mount points for given user
  235. *
  236. * @param string $user
  237. * @throws \OC\User\NoUserException
  238. */
  239. protected function initMountPoints($user) {
  240. Filesystem::initMountPoints($user);
  241. }
  242. /**
  243. * setup file system for user
  244. *
  245. * @param string $uid user id
  246. */
  247. protected function setupFS($uid) {
  248. \OC_Util::setupFS($uid);
  249. }
  250. }