PublicKeyTokenProvider.php 18 KB

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