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.

UserHooks.php 9.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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\ILogger;
  39. use OCP\IUserManager;
  40. use OCP\IUserSession;
  41. use OCP\Util as OCUtil;
  42. class UserHooks implements IHook {
  43. /**
  44. * list of user for which we perform a password reset
  45. * @var array
  46. */
  47. protected static $passwordResetUsers = [];
  48. /**
  49. * @var KeyManager
  50. */
  51. private $keyManager;
  52. /**
  53. * @var IUserManager
  54. */
  55. private $userManager;
  56. /**
  57. * @var ILogger
  58. */
  59. private $logger;
  60. /**
  61. * @var Setup
  62. */
  63. private $userSetup;
  64. /**
  65. * @var IUserSession
  66. */
  67. private $userSession;
  68. /**
  69. * @var Util
  70. */
  71. private $util;
  72. /**
  73. * @var Session
  74. */
  75. private $session;
  76. /**
  77. * @var Recovery
  78. */
  79. private $recovery;
  80. /**
  81. * @var Crypt
  82. */
  83. private $crypt;
  84. /**
  85. * UserHooks constructor.
  86. *
  87. * @param KeyManager $keyManager
  88. * @param IUserManager $userManager
  89. * @param ILogger $logger
  90. * @param Setup $userSetup
  91. * @param IUserSession $userSession
  92. * @param Util $util
  93. * @param Session $session
  94. * @param Crypt $crypt
  95. * @param Recovery $recovery
  96. */
  97. public function __construct(KeyManager $keyManager,
  98. IUserManager $userManager,
  99. ILogger $logger,
  100. Setup $userSetup,
  101. IUserSession $userSession,
  102. Util $util,
  103. Session $session,
  104. Crypt $crypt,
  105. Recovery $recovery) {
  106. $this->keyManager = $keyManager;
  107. $this->userManager = $userManager;
  108. $this->logger = $logger;
  109. $this->userSetup = $userSetup;
  110. $this->userSession = $userSession;
  111. $this->util = $util;
  112. $this->session = $session;
  113. $this->recovery = $recovery;
  114. $this->crypt = $crypt;
  115. }
  116. /**
  117. * Connects Hooks
  118. *
  119. * @return null
  120. */
  121. public function addHooks() {
  122. OCUtil::connectHook('OC_User', 'post_login', $this, 'login');
  123. OCUtil::connectHook('OC_User', 'logout', $this, 'logout');
  124. // this hooks only make sense if no master key is used
  125. if ($this->util->isMasterKeyEnabled() === false) {
  126. OCUtil::connectHook('OC_User',
  127. 'post_setPassword',
  128. $this,
  129. 'setPassphrase');
  130. OCUtil::connectHook('OC_User',
  131. 'pre_setPassword',
  132. $this,
  133. 'preSetPassphrase');
  134. OCUtil::connectHook('\OC\Core\LostPassword\Controller\LostController',
  135. 'post_passwordReset',
  136. $this,
  137. 'postPasswordReset');
  138. OCUtil::connectHook('\OC\Core\LostPassword\Controller\LostController',
  139. 'pre_passwordReset',
  140. $this,
  141. 'prePasswordReset');
  142. OCUtil::connectHook('OC_User',
  143. 'post_createUser',
  144. $this,
  145. 'postCreateUser');
  146. OCUtil::connectHook('OC_User',
  147. 'post_deleteUser',
  148. $this,
  149. 'postDeleteUser');
  150. }
  151. }
  152. /**
  153. * Startup encryption backend upon user login
  154. *
  155. * @note This method should never be called for users using client side encryption
  156. * @param array $params
  157. * @return boolean|null
  158. */
  159. public function login($params) {
  160. // ensure filesystem is loaded
  161. if (!\OC\Files\Filesystem::$loaded) {
  162. $this->setupFS($params['uid']);
  163. }
  164. if ($this->util->isMasterKeyEnabled() === false) {
  165. $this->userSetup->setupUser($params['uid'], $params['password']);
  166. }
  167. $this->keyManager->init($params['uid'], $params['password']);
  168. }
  169. /**
  170. * remove keys from session during logout
  171. */
  172. public function logout() {
  173. $this->session->clear();
  174. }
  175. /**
  176. * setup encryption backend upon user created
  177. *
  178. * @note This method should never be called for users using client side encryption
  179. * @param array $params
  180. */
  181. public function postCreateUser($params) {
  182. $this->userSetup->setupUser($params['uid'], $params['password']);
  183. }
  184. /**
  185. * cleanup encryption backend upon user deleted
  186. *
  187. * @param array $params : uid, password
  188. * @note This method should never be called for users using client side encryption
  189. */
  190. public function postDeleteUser($params) {
  191. $this->keyManager->deletePublicKey($params['uid']);
  192. }
  193. public function prePasswordReset($params) {
  194. $user = $params['uid'];
  195. self::$passwordResetUsers[$user] = true;
  196. }
  197. public function postPasswordReset($params) {
  198. $uid = $params['uid'];
  199. $password = $params['password'];
  200. $this->keyManager->backupUserKeys('passwordReset', $uid);
  201. $this->keyManager->deleteUserKeys($uid);
  202. $this->userSetup->setupUser($uid, $password);
  203. unset(self::$passwordResetUsers[$uid]);
  204. }
  205. /**
  206. * If the password can't be changed within Nextcloud, than update the key password in advance.
  207. *
  208. * @param array $params : uid, password
  209. * @return boolean|null
  210. */
  211. public function preSetPassphrase($params) {
  212. $user = $this->userManager->get($params['uid']);
  213. if ($user && !$user->canChangePassword()) {
  214. $this->setPassphrase($params);
  215. }
  216. }
  217. /**
  218. * Change a user's encryption passphrase
  219. *
  220. * @param array $params keys: uid, password
  221. * @return boolean|null
  222. */
  223. public function setPassphrase($params) {
  224. // if we are in the process to resetting a user password, we have nothing
  225. // to do here
  226. if (isset(self::$passwordResetUsers[$params['uid']])) {
  227. return true;
  228. }
  229. // Get existing decrypted private key
  230. $user = $this->userSession->getUser();
  231. // current logged in user changes his own password
  232. if ($user && $params['uid'] === $user->getUID()) {
  233. $privateKey = $this->session->getPrivateKey();
  234. // Encrypt private key with new user pwd as passphrase
  235. $encryptedPrivateKey = $this->crypt->encryptPrivateKey($privateKey, $params['password'], $params['uid']);
  236. // Save private key
  237. if ($encryptedPrivateKey) {
  238. $this->keyManager->setPrivateKey($user->getUID(),
  239. $this->crypt->generateHeader() . $encryptedPrivateKey);
  240. } else {
  241. $this->logger->error('Encryption could not update users encryption password');
  242. }
  243. // NOTE: Session does not need to be updated as the
  244. // private key has not changed, only the passphrase
  245. // used to decrypt it has changed
  246. } else { // admin changed the password for a different user, create new keys and re-encrypt file keys
  247. $userId = $params['uid'];
  248. $this->initMountPoints($userId);
  249. $recoveryPassword = isset($params['recoveryPassword']) ? $params['recoveryPassword'] : null;
  250. $recoveryKeyId = $this->keyManager->getRecoveryKeyId();
  251. $recoveryKey = $this->keyManager->getSystemPrivateKey($recoveryKeyId);
  252. try {
  253. $decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $recoveryPassword);
  254. } catch (\Exception $e) {
  255. $decryptedRecoveryKey = false;
  256. }
  257. if ($decryptedRecoveryKey === false) {
  258. $message = 'Can not decrypt the recovery key. Maybe you provided the wrong password. Try again.';
  259. throw new GenericEncryptionException($message, $message);
  260. }
  261. // we generate new keys if...
  262. // ...we have a recovery password and the user enabled the recovery key
  263. // ...encryption was activated for the first time (no keys exists)
  264. // ...the user doesn't have any files
  265. if (
  266. ($this->recovery->isRecoveryEnabledForUser($userId) && $recoveryPassword)
  267. || !$this->keyManager->userHasKeys($userId)
  268. || !$this->util->userHasFiles($userId)
  269. ) {
  270. // backup old keys
  271. //$this->backupAllKeys('recovery');
  272. $newUserPassword = $params['password'];
  273. $keyPair = $this->crypt->createKeyPair();
  274. // Save public key
  275. $this->keyManager->setPublicKey($userId, $keyPair['publicKey']);
  276. // Encrypt private key with new password
  277. $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $newUserPassword, $userId);
  278. if ($encryptedKey) {
  279. $this->keyManager->setPrivateKey($userId, $this->crypt->generateHeader() . $encryptedKey);
  280. if ($recoveryPassword) { // if recovery key is set we can re-encrypt the key files
  281. $this->recovery->recoverUsersFiles($recoveryPassword, $userId);
  282. }
  283. } else {
  284. $this->logger->error('Encryption Could not update users encryption password');
  285. }
  286. }
  287. }
  288. }
  289. /**
  290. * init mount points for given user
  291. *
  292. * @param string $user
  293. * @throws \OC\User\NoUserException
  294. */
  295. protected function initMountPoints($user) {
  296. Filesystem::initMountPoints($user);
  297. }
  298. /**
  299. * setup file system for user
  300. *
  301. * @param string $uid user id
  302. */
  303. protected function setupFS($uid) {
  304. \OC_Util::setupFS($uid);
  305. }
  306. }