PublicKeyTokenProvider.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Authentication\Token;
  8. use OC\Authentication\Exceptions\ExpiredTokenException;
  9. use OC\Authentication\Exceptions\InvalidTokenException;
  10. use OC\Authentication\Exceptions\PasswordlessTokenException;
  11. use OC\Authentication\Exceptions\TokenPasswordExpiredException;
  12. use OC\Authentication\Exceptions\WipeTokenException;
  13. use OCP\AppFramework\Db\DoesNotExistException;
  14. use OCP\AppFramework\Db\TTransactional;
  15. use OCP\AppFramework\Utility\ITimeFactory;
  16. use OCP\Authentication\Token\IToken as OCPIToken;
  17. use OCP\ICache;
  18. use OCP\ICacheFactory;
  19. use OCP\IConfig;
  20. use OCP\IDBConnection;
  21. use OCP\IUserManager;
  22. use OCP\Security\ICrypto;
  23. use OCP\Security\IHasher;
  24. use Psr\Log\LoggerInterface;
  25. class PublicKeyTokenProvider implements IProvider {
  26. public const TOKEN_MIN_LENGTH = 22;
  27. /** Token cache TTL in seconds */
  28. private const TOKEN_CACHE_TTL = 10;
  29. use TTransactional;
  30. /** @var PublicKeyTokenMapper */
  31. private $mapper;
  32. /** @var ICrypto */
  33. private $crypto;
  34. /** @var IConfig */
  35. private $config;
  36. private IDBConnection $db;
  37. /** @var LoggerInterface */
  38. private $logger;
  39. /** @var ITimeFactory */
  40. private $time;
  41. /** @var ICache */
  42. private $cache;
  43. /** @var IHasher */
  44. private $hasher;
  45. public function __construct(PublicKeyTokenMapper $mapper,
  46. ICrypto $crypto,
  47. IConfig $config,
  48. IDBConnection $db,
  49. LoggerInterface $logger,
  50. ITimeFactory $time,
  51. IHasher $hasher,
  52. ICacheFactory $cacheFactory) {
  53. $this->mapper = $mapper;
  54. $this->crypto = $crypto;
  55. $this->config = $config;
  56. $this->db = $db;
  57. $this->logger = $logger;
  58. $this->time = $time;
  59. $this->cache = $cacheFactory->isLocalCacheAvailable()
  60. ? $cacheFactory->createLocal('authtoken_')
  61. : $cacheFactory->createInMemory();
  62. $this->hasher = $hasher;
  63. }
  64. /**
  65. * {@inheritDoc}
  66. */
  67. public function generateToken(string $token,
  68. string $uid,
  69. string $loginName,
  70. ?string $password,
  71. string $name,
  72. int $type = OCPIToken::TEMPORARY_TOKEN,
  73. int $remember = OCPIToken::DO_NOT_REMEMBER): OCPIToken {
  74. if (strlen($token) < self::TOKEN_MIN_LENGTH) {
  75. $exception = new InvalidTokenException('Token is too short, minimum of ' . self::TOKEN_MIN_LENGTH . ' characters is required, ' . strlen($token) . ' characters given');
  76. $this->logger->error('Invalid token provided when generating new token', ['exception' => $exception]);
  77. throw $exception;
  78. }
  79. if (mb_strlen($name) > 128) {
  80. $name = mb_substr($name, 0, 120) . '…';
  81. }
  82. // We need to check against one old token to see if there is a password
  83. // hash that we can reuse for detecting outdated passwords
  84. $randomOldToken = $this->mapper->getFirstTokenForUser($uid);
  85. $oldTokenMatches = $randomOldToken && $randomOldToken->getPasswordHash() && $password !== null && $this->hasher->verify(sha1($password) . $password, $randomOldToken->getPasswordHash());
  86. $dbToken = $this->newToken($token, $uid, $loginName, $password, $name, $type, $remember);
  87. if ($oldTokenMatches) {
  88. $dbToken->setPasswordHash($randomOldToken->getPasswordHash());
  89. }
  90. $this->mapper->insert($dbToken);
  91. if (!$oldTokenMatches && $password !== null) {
  92. $this->updatePasswords($uid, $password);
  93. }
  94. // Add the token to the cache
  95. $this->cacheToken($dbToken);
  96. return $dbToken;
  97. }
  98. public function getToken(string $tokenId): OCPIToken {
  99. /**
  100. * Token length: 72
  101. * @see \OC\Core\Controller\ClientFlowLoginController::generateAppPassword
  102. * @see \OC\Core\Controller\AppPasswordController::getAppPassword
  103. * @see \OC\Core\Command\User\AddAppPassword::execute
  104. * @see \OC\Core\Service\LoginFlowV2Service::flowDone
  105. * @see \OCA\Talk\MatterbridgeManager::generatePassword
  106. * @see \OCA\Preferred_Providers\Controller\PasswordController::generateAppPassword
  107. * @see \OCA\GlobalSiteSelector\TokenHandler::generateAppPassword
  108. *
  109. * Token length: 22-256 - https://www.php.net/manual/en/session.configuration.php#ini.session.sid-length
  110. * @see \OC\User\Session::createSessionToken
  111. *
  112. * Token length: 29
  113. * @see \OCA\Settings\Controller\AuthSettingsController::generateRandomDeviceToken
  114. * @see \OCA\Registration\Service\RegistrationService::generateAppPassword
  115. */
  116. if (strlen($tokenId) < self::TOKEN_MIN_LENGTH) {
  117. throw new InvalidTokenException('Token is too short for a generated token, should be the password during basic auth');
  118. }
  119. $tokenHash = $this->hashToken($tokenId);
  120. if ($token = $this->getTokenFromCache($tokenHash)) {
  121. $this->checkToken($token);
  122. return $token;
  123. }
  124. try {
  125. $token = $this->mapper->getToken($tokenHash);
  126. $this->cacheToken($token);
  127. } catch (DoesNotExistException $ex) {
  128. try {
  129. $token = $this->mapper->getToken($this->hashTokenWithEmptySecret($tokenId));
  130. $this->rotate($token, $tokenId, $tokenId);
  131. } catch (DoesNotExistException) {
  132. $this->cacheInvalidHash($tokenHash);
  133. throw new InvalidTokenException("Token does not exist: " . $ex->getMessage(), 0, $ex);
  134. }
  135. }
  136. $this->checkToken($token);
  137. return $token;
  138. }
  139. /**
  140. * @throws InvalidTokenException when token doesn't exist
  141. */
  142. private function getTokenFromCache(string $tokenHash): ?PublicKeyToken {
  143. $serializedToken = $this->cache->get($tokenHash);
  144. if ($serializedToken === false) {
  145. throw new InvalidTokenException('Token does not exist: ' . $tokenHash);
  146. }
  147. if ($serializedToken === null) {
  148. return null;
  149. }
  150. $token = unserialize($serializedToken, [
  151. 'allowed_classes' => [PublicKeyToken::class],
  152. ]);
  153. return $token instanceof PublicKeyToken ? $token : null;
  154. }
  155. private function cacheToken(PublicKeyToken $token): void {
  156. $this->cache->set($token->getToken(), serialize($token), self::TOKEN_CACHE_TTL);
  157. }
  158. private function cacheInvalidHash(string $tokenHash): void {
  159. // Invalid entries can be kept longer in cache since it’s unlikely to reuse them
  160. $this->cache->set($tokenHash, false, self::TOKEN_CACHE_TTL * 2);
  161. }
  162. public function getTokenById(int $tokenId): OCPIToken {
  163. try {
  164. $token = $this->mapper->getTokenById($tokenId);
  165. } catch (DoesNotExistException $ex) {
  166. throw new InvalidTokenException("Token with ID $tokenId does not exist: " . $ex->getMessage(), 0, $ex);
  167. }
  168. $this->checkToken($token);
  169. return $token;
  170. }
  171. private function checkToken($token): void {
  172. if ((int)$token->getExpires() !== 0 && $token->getExpires() < $this->time->getTime()) {
  173. throw new ExpiredTokenException($token);
  174. }
  175. if ($token->getType() === OCPIToken::WIPE_TOKEN) {
  176. throw new WipeTokenException($token);
  177. }
  178. if ($token->getPasswordInvalid() === true) {
  179. //The password is invalid we should throw an TokenPasswordExpiredException
  180. throw new TokenPasswordExpiredException($token);
  181. }
  182. }
  183. public function renewSessionToken(string $oldSessionId, string $sessionId): OCPIToken {
  184. return $this->atomic(function () use ($oldSessionId, $sessionId) {
  185. $token = $this->getToken($oldSessionId);
  186. if (!($token instanceof PublicKeyToken)) {
  187. throw new InvalidTokenException("Invalid token type");
  188. }
  189. $password = null;
  190. if (!is_null($token->getPassword())) {
  191. $privateKey = $this->decrypt($token->getPrivateKey(), $oldSessionId);
  192. $password = $this->decryptPassword($token->getPassword(), $privateKey);
  193. }
  194. $newToken = $this->generateToken(
  195. $sessionId,
  196. $token->getUID(),
  197. $token->getLoginName(),
  198. $password,
  199. $token->getName(),
  200. OCPIToken::TEMPORARY_TOKEN,
  201. $token->getRemember()
  202. );
  203. $newToken->setScope($token->getScopeAsArray());
  204. $this->cacheToken($newToken);
  205. $this->cacheInvalidHash($token->getToken());
  206. $this->mapper->delete($token);
  207. return $newToken;
  208. }, $this->db);
  209. }
  210. public function invalidateToken(string $token) {
  211. $tokenHash = $this->hashToken($token);
  212. $this->mapper->invalidate($this->hashToken($token));
  213. $this->mapper->invalidate($this->hashTokenWithEmptySecret($token));
  214. $this->cacheInvalidHash($tokenHash);
  215. }
  216. public function invalidateTokenById(string $uid, int $id) {
  217. $token = $this->mapper->getTokenById($id);
  218. if ($token->getUID() !== $uid) {
  219. return;
  220. }
  221. $this->mapper->invalidate($token->getToken());
  222. $this->cacheInvalidHash($token->getToken());
  223. }
  224. public function invalidateOldTokens() {
  225. $olderThan = $this->time->getTime() - $this->config->getSystemValueInt('session_lifetime', 60 * 60 * 24);
  226. $this->logger->debug('Invalidating session tokens older than ' . date('c', $olderThan), ['app' => 'cron']);
  227. $this->mapper->invalidateOld($olderThan, OCPIToken::DO_NOT_REMEMBER);
  228. $rememberThreshold = $this->time->getTime() - $this->config->getSystemValueInt('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
  229. $this->logger->debug('Invalidating remembered session tokens older than ' . date('c', $rememberThreshold), ['app' => 'cron']);
  230. $this->mapper->invalidateOld($rememberThreshold, OCPIToken::REMEMBER);
  231. }
  232. public function invalidateLastUsedBefore(string $uid, int $before): void {
  233. $this->mapper->invalidateLastUsedBefore($uid, $before);
  234. }
  235. public function updateToken(OCPIToken $token) {
  236. if (!($token instanceof PublicKeyToken)) {
  237. throw new InvalidTokenException("Invalid token type");
  238. }
  239. $this->mapper->update($token);
  240. $this->cacheToken($token);
  241. }
  242. public function updateTokenActivity(OCPIToken $token) {
  243. if (!($token instanceof PublicKeyToken)) {
  244. throw new InvalidTokenException("Invalid token type");
  245. }
  246. $activityInterval = $this->config->getSystemValueInt('token_auth_activity_update', 60);
  247. $activityInterval = min(max($activityInterval, 0), 300);
  248. $updatedFields = $token->getUpdatedFields();
  249. unset($updatedFields['lastActivity']);
  250. /** @var PublicKeyToken $token */
  251. $now = $this->time->getTime();
  252. if ($token->getLastActivity() < ($now - $activityInterval) || count($updatedFields)) {
  253. $this->mapper->updateActivity($token, $now);
  254. $this->cacheToken($token);
  255. }
  256. }
  257. public function getTokenByUser(string $uid): array {
  258. return $this->mapper->getTokenByUser($uid);
  259. }
  260. public function getPassword(OCPIToken $savedToken, string $tokenId): string {
  261. if (!($savedToken instanceof PublicKeyToken)) {
  262. throw new InvalidTokenException("Invalid token type");
  263. }
  264. if ($savedToken->getPassword() === null) {
  265. throw new PasswordlessTokenException();
  266. }
  267. // Decrypt private key with tokenId
  268. $privateKey = $this->decrypt($savedToken->getPrivateKey(), $tokenId);
  269. // Decrypt password with private key
  270. return $this->decryptPassword($savedToken->getPassword(), $privateKey);
  271. }
  272. public function setPassword(OCPIToken $token, string $tokenId, string $password) {
  273. if (!($token instanceof PublicKeyToken)) {
  274. throw new InvalidTokenException("Invalid token type");
  275. }
  276. $this->atomic(function () use ($password, $token) {
  277. // When changing passwords all temp tokens are deleted
  278. $this->mapper->deleteTempToken($token);
  279. // Update the password for all tokens
  280. $tokens = $this->mapper->getTokenByUser($token->getUID());
  281. $hashedPassword = $this->hashPassword($password);
  282. foreach ($tokens as $t) {
  283. $publicKey = $t->getPublicKey();
  284. $t->setPassword($this->encryptPassword($password, $publicKey));
  285. $t->setPasswordHash($hashedPassword);
  286. $this->updateToken($t);
  287. }
  288. }, $this->db);
  289. }
  290. private function hashPassword(string $password): string {
  291. return $this->hasher->hash(sha1($password) . $password);
  292. }
  293. public function rotate(OCPIToken $token, string $oldTokenId, string $newTokenId): OCPIToken {
  294. if (!($token instanceof PublicKeyToken)) {
  295. throw new InvalidTokenException("Invalid token type");
  296. }
  297. // Decrypt private key with oldTokenId
  298. $privateKey = $this->decrypt($token->getPrivateKey(), $oldTokenId);
  299. // Encrypt with the new token
  300. $token->setPrivateKey($this->encrypt($privateKey, $newTokenId));
  301. $token->setToken($this->hashToken($newTokenId));
  302. $this->updateToken($token);
  303. return $token;
  304. }
  305. private function encrypt(string $plaintext, string $token): string {
  306. $secret = $this->config->getSystemValueString('secret');
  307. return $this->crypto->encrypt($plaintext, $token . $secret);
  308. }
  309. /**
  310. * @throws InvalidTokenException
  311. */
  312. private function decrypt(string $cipherText, string $token): string {
  313. $secret = $this->config->getSystemValueString('secret');
  314. try {
  315. return $this->crypto->decrypt($cipherText, $token . $secret);
  316. } catch (\Exception $ex) {
  317. // Retry with empty secret as a fallback for instances where the secret might not have been set by accident
  318. try {
  319. return $this->crypto->decrypt($cipherText, $token);
  320. } catch (\Exception $ex2) {
  321. // Delete the invalid token
  322. $this->invalidateToken($token);
  323. throw new InvalidTokenException("Could not decrypt token password: " . $ex->getMessage(), 0, $ex2);
  324. }
  325. }
  326. }
  327. private function encryptPassword(string $password, string $publicKey): string {
  328. openssl_public_encrypt($password, $encryptedPassword, $publicKey, OPENSSL_PKCS1_OAEP_PADDING);
  329. $encryptedPassword = base64_encode($encryptedPassword);
  330. return $encryptedPassword;
  331. }
  332. private function decryptPassword(string $encryptedPassword, string $privateKey): string {
  333. $encryptedPassword = base64_decode($encryptedPassword);
  334. openssl_private_decrypt($encryptedPassword, $password, $privateKey, OPENSSL_PKCS1_OAEP_PADDING);
  335. return $password;
  336. }
  337. private function hashToken(string $token): string {
  338. $secret = $this->config->getSystemValueString('secret');
  339. return hash('sha512', $token . $secret);
  340. }
  341. /**
  342. * @deprecated Fallback for instances where the secret might not have been set by accident
  343. */
  344. private function hashTokenWithEmptySecret(string $token): string {
  345. return hash('sha512', $token);
  346. }
  347. /**
  348. * @throws \RuntimeException when OpenSSL reports a problem
  349. */
  350. private function newToken(string $token,
  351. string $uid,
  352. string $loginName,
  353. $password,
  354. string $name,
  355. int $type,
  356. int $remember): PublicKeyToken {
  357. $dbToken = new PublicKeyToken();
  358. $dbToken->setUid($uid);
  359. $dbToken->setLoginName($loginName);
  360. $config = array_merge([
  361. 'digest_alg' => 'sha512',
  362. 'private_key_bits' => $password !== null && strlen($password) > 250 ? 4096 : 2048,
  363. ], $this->config->getSystemValue('openssl', []));
  364. // Generate new key
  365. $res = openssl_pkey_new($config);
  366. if ($res === false) {
  367. $this->logOpensslError();
  368. throw new \RuntimeException('OpenSSL reported a problem');
  369. }
  370. if (openssl_pkey_export($res, $privateKey, null, $config) === false) {
  371. $this->logOpensslError();
  372. throw new \RuntimeException('OpenSSL reported a problem');
  373. }
  374. // Extract the public key from $res to $pubKey
  375. $publicKey = openssl_pkey_get_details($res);
  376. $publicKey = $publicKey['key'];
  377. $dbToken->setPublicKey($publicKey);
  378. $dbToken->setPrivateKey($this->encrypt($privateKey, $token));
  379. if (!is_null($password) && $this->config->getSystemValueBool('auth.storeCryptedPassword', true)) {
  380. if (strlen($password) > IUserManager::MAX_PASSWORD_LENGTH) {
  381. throw new \RuntimeException('Trying to save a password with more than 469 characters is not supported. If you want to use big passwords, disable the auth.storeCryptedPassword option in config.php');
  382. }
  383. $dbToken->setPassword($this->encryptPassword($password, $publicKey));
  384. $dbToken->setPasswordHash($this->hashPassword($password));
  385. }
  386. $dbToken->setName($name);
  387. $dbToken->setToken($this->hashToken($token));
  388. $dbToken->setType($type);
  389. $dbToken->setRemember($remember);
  390. $dbToken->setLastActivity($this->time->getTime());
  391. $dbToken->setLastCheck($this->time->getTime());
  392. $dbToken->setVersion(PublicKeyToken::VERSION);
  393. return $dbToken;
  394. }
  395. public function markPasswordInvalid(OCPIToken $token, string $tokenId) {
  396. if (!($token instanceof PublicKeyToken)) {
  397. throw new InvalidTokenException("Invalid token type");
  398. }
  399. $token->setPasswordInvalid(true);
  400. $this->mapper->update($token);
  401. $this->cacheToken($token);
  402. }
  403. public function updatePasswords(string $uid, string $password) {
  404. // prevent setting an empty pw as result of pw-less-login
  405. if ($password === '' || !$this->config->getSystemValueBool('auth.storeCryptedPassword', true)) {
  406. return;
  407. }
  408. $this->atomic(function () use ($password, $uid) {
  409. // Update the password for all tokens
  410. $tokens = $this->mapper->getTokenByUser($uid);
  411. $newPasswordHash = null;
  412. /**
  413. * - true: The password hash could not be verified anymore
  414. * and the token needs to be updated with the newly encrypted password
  415. * - false: The hash could still be verified
  416. * - missing: The hash needs to be verified
  417. */
  418. $hashNeedsUpdate = [];
  419. foreach ($tokens as $t) {
  420. if (!isset($hashNeedsUpdate[$t->getPasswordHash()])) {
  421. if ($t->getPasswordHash() === null) {
  422. $hashNeedsUpdate[$t->getPasswordHash() ?: ''] = true;
  423. } elseif (!$this->hasher->verify(sha1($password) . $password, $t->getPasswordHash())) {
  424. $hashNeedsUpdate[$t->getPasswordHash() ?: ''] = true;
  425. } else {
  426. $hashNeedsUpdate[$t->getPasswordHash() ?: ''] = false;
  427. }
  428. }
  429. $needsUpdating = $hashNeedsUpdate[$t->getPasswordHash() ?: ''] ?? true;
  430. if ($needsUpdating) {
  431. if ($newPasswordHash === null) {
  432. $newPasswordHash = $this->hashPassword($password);
  433. }
  434. $publicKey = $t->getPublicKey();
  435. $t->setPassword($this->encryptPassword($password, $publicKey));
  436. $t->setPasswordHash($newPasswordHash);
  437. $t->setPasswordInvalid(false);
  438. $this->updateToken($t);
  439. }
  440. }
  441. // If password hashes are different we update them all to be equal so
  442. // that the next execution only needs to verify once
  443. if (count($hashNeedsUpdate) > 1) {
  444. $newPasswordHash = $this->hashPassword($password);
  445. $this->mapper->updateHashesForUser($uid, $newPasswordHash);
  446. }
  447. }, $this->db);
  448. }
  449. private function logOpensslError() {
  450. $errors = [];
  451. while ($error = openssl_error_string()) {
  452. $errors[] = $error;
  453. }
  454. $this->logger->critical('Something is wrong with your openssl setup: ' . implode(', ', $errors));
  455. }
  456. }