1
0

PublicKeyTokenProvider.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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. /** @var PublicKeyToken $token */
  249. $now = $this->time->getTime();
  250. if ($token->getLastActivity() < ($now - $activityInterval)) {
  251. $token->setLastActivity($now);
  252. $this->mapper->updateActivity($token, $now);
  253. $this->cacheToken($token);
  254. }
  255. }
  256. public function getTokenByUser(string $uid): array {
  257. return $this->mapper->getTokenByUser($uid);
  258. }
  259. public function getPassword(OCPIToken $savedToken, string $tokenId): string {
  260. if (!($savedToken instanceof PublicKeyToken)) {
  261. throw new InvalidTokenException("Invalid token type");
  262. }
  263. if ($savedToken->getPassword() === null) {
  264. throw new PasswordlessTokenException();
  265. }
  266. // Decrypt private key with tokenId
  267. $privateKey = $this->decrypt($savedToken->getPrivateKey(), $tokenId);
  268. // Decrypt password with private key
  269. return $this->decryptPassword($savedToken->getPassword(), $privateKey);
  270. }
  271. public function setPassword(OCPIToken $token, string $tokenId, string $password) {
  272. if (!($token instanceof PublicKeyToken)) {
  273. throw new InvalidTokenException("Invalid token type");
  274. }
  275. $this->atomic(function () use ($password, $token) {
  276. // When changing passwords all temp tokens are deleted
  277. $this->mapper->deleteTempToken($token);
  278. // Update the password for all tokens
  279. $tokens = $this->mapper->getTokenByUser($token->getUID());
  280. $hashedPassword = $this->hashPassword($password);
  281. foreach ($tokens as $t) {
  282. $publicKey = $t->getPublicKey();
  283. $t->setPassword($this->encryptPassword($password, $publicKey));
  284. $t->setPasswordHash($hashedPassword);
  285. $this->updateToken($t);
  286. }
  287. }, $this->db);
  288. }
  289. private function hashPassword(string $password): string {
  290. return $this->hasher->hash(sha1($password) . $password);
  291. }
  292. public function rotate(OCPIToken $token, string $oldTokenId, string $newTokenId): OCPIToken {
  293. if (!($token instanceof PublicKeyToken)) {
  294. throw new InvalidTokenException("Invalid token type");
  295. }
  296. // Decrypt private key with oldTokenId
  297. $privateKey = $this->decrypt($token->getPrivateKey(), $oldTokenId);
  298. // Encrypt with the new token
  299. $token->setPrivateKey($this->encrypt($privateKey, $newTokenId));
  300. $token->setToken($this->hashToken($newTokenId));
  301. $this->updateToken($token);
  302. return $token;
  303. }
  304. private function encrypt(string $plaintext, string $token): string {
  305. $secret = $this->config->getSystemValueString('secret');
  306. return $this->crypto->encrypt($plaintext, $token . $secret);
  307. }
  308. /**
  309. * @throws InvalidTokenException
  310. */
  311. private function decrypt(string $cipherText, string $token): string {
  312. $secret = $this->config->getSystemValueString('secret');
  313. try {
  314. return $this->crypto->decrypt($cipherText, $token . $secret);
  315. } catch (\Exception $ex) {
  316. // Retry with empty secret as a fallback for instances where the secret might not have been set by accident
  317. try {
  318. return $this->crypto->decrypt($cipherText, $token);
  319. } catch (\Exception $ex2) {
  320. // Delete the invalid token
  321. $this->invalidateToken($token);
  322. throw new InvalidTokenException("Could not decrypt token password: " . $ex->getMessage(), 0, $ex2);
  323. }
  324. }
  325. }
  326. private function encryptPassword(string $password, string $publicKey): string {
  327. openssl_public_encrypt($password, $encryptedPassword, $publicKey, OPENSSL_PKCS1_OAEP_PADDING);
  328. $encryptedPassword = base64_encode($encryptedPassword);
  329. return $encryptedPassword;
  330. }
  331. private function decryptPassword(string $encryptedPassword, string $privateKey): string {
  332. $encryptedPassword = base64_decode($encryptedPassword);
  333. openssl_private_decrypt($encryptedPassword, $password, $privateKey, OPENSSL_PKCS1_OAEP_PADDING);
  334. return $password;
  335. }
  336. private function hashToken(string $token): string {
  337. $secret = $this->config->getSystemValueString('secret');
  338. return hash('sha512', $token . $secret);
  339. }
  340. /**
  341. * @deprecated Fallback for instances where the secret might not have been set by accident
  342. */
  343. private function hashTokenWithEmptySecret(string $token): string {
  344. return hash('sha512', $token);
  345. }
  346. /**
  347. * @throws \RuntimeException when OpenSSL reports a problem
  348. */
  349. private function newToken(string $token,
  350. string $uid,
  351. string $loginName,
  352. $password,
  353. string $name,
  354. int $type,
  355. int $remember): PublicKeyToken {
  356. $dbToken = new PublicKeyToken();
  357. $dbToken->setUid($uid);
  358. $dbToken->setLoginName($loginName);
  359. $config = array_merge([
  360. 'digest_alg' => 'sha512',
  361. 'private_key_bits' => $password !== null && strlen($password) > 250 ? 4096 : 2048,
  362. ], $this->config->getSystemValue('openssl', []));
  363. // Generate new key
  364. $res = openssl_pkey_new($config);
  365. if ($res === false) {
  366. $this->logOpensslError();
  367. throw new \RuntimeException('OpenSSL reported a problem');
  368. }
  369. if (openssl_pkey_export($res, $privateKey, null, $config) === false) {
  370. $this->logOpensslError();
  371. throw new \RuntimeException('OpenSSL reported a problem');
  372. }
  373. // Extract the public key from $res to $pubKey
  374. $publicKey = openssl_pkey_get_details($res);
  375. $publicKey = $publicKey['key'];
  376. $dbToken->setPublicKey($publicKey);
  377. $dbToken->setPrivateKey($this->encrypt($privateKey, $token));
  378. if (!is_null($password) && $this->config->getSystemValueBool('auth.storeCryptedPassword', true)) {
  379. if (strlen($password) > IUserManager::MAX_PASSWORD_LENGTH) {
  380. 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');
  381. }
  382. $dbToken->setPassword($this->encryptPassword($password, $publicKey));
  383. $dbToken->setPasswordHash($this->hashPassword($password));
  384. }
  385. $dbToken->setName($name);
  386. $dbToken->setToken($this->hashToken($token));
  387. $dbToken->setType($type);
  388. $dbToken->setRemember($remember);
  389. $dbToken->setLastActivity($this->time->getTime());
  390. $dbToken->setLastCheck($this->time->getTime());
  391. $dbToken->setVersion(PublicKeyToken::VERSION);
  392. return $dbToken;
  393. }
  394. public function markPasswordInvalid(OCPIToken $token, string $tokenId) {
  395. if (!($token instanceof PublicKeyToken)) {
  396. throw new InvalidTokenException("Invalid token type");
  397. }
  398. $token->setPasswordInvalid(true);
  399. $this->mapper->update($token);
  400. $this->cacheToken($token);
  401. }
  402. public function updatePasswords(string $uid, string $password) {
  403. // prevent setting an empty pw as result of pw-less-login
  404. if ($password === '' || !$this->config->getSystemValueBool('auth.storeCryptedPassword', true)) {
  405. return;
  406. }
  407. $this->atomic(function () use ($password, $uid) {
  408. // Update the password for all tokens
  409. $tokens = $this->mapper->getTokenByUser($uid);
  410. $newPasswordHash = null;
  411. /**
  412. * - true: The password hash could not be verified anymore
  413. * and the token needs to be updated with the newly encrypted password
  414. * - false: The hash could still be verified
  415. * - missing: The hash needs to be verified
  416. */
  417. $hashNeedsUpdate = [];
  418. foreach ($tokens as $t) {
  419. if (!isset($hashNeedsUpdate[$t->getPasswordHash()])) {
  420. if ($t->getPasswordHash() === null) {
  421. $hashNeedsUpdate[$t->getPasswordHash() ?: ''] = true;
  422. } elseif (!$this->hasher->verify(sha1($password) . $password, $t->getPasswordHash())) {
  423. $hashNeedsUpdate[$t->getPasswordHash() ?: ''] = true;
  424. } else {
  425. $hashNeedsUpdate[$t->getPasswordHash() ?: ''] = false;
  426. }
  427. }
  428. $needsUpdating = $hashNeedsUpdate[$t->getPasswordHash() ?: ''] ?? true;
  429. if ($needsUpdating) {
  430. if ($newPasswordHash === null) {
  431. $newPasswordHash = $this->hashPassword($password);
  432. }
  433. $publicKey = $t->getPublicKey();
  434. $t->setPassword($this->encryptPassword($password, $publicKey));
  435. $t->setPasswordHash($newPasswordHash);
  436. $t->setPasswordInvalid(false);
  437. $this->updateToken($t);
  438. }
  439. }
  440. // If password hashes are different we update them all to be equal so
  441. // that the next execution only needs to verify once
  442. if (count($hashNeedsUpdate) > 1) {
  443. $newPasswordHash = $this->hashPassword($password);
  444. $this->mapper->updateHashesForUser($uid, $newPasswordHash);
  445. }
  446. }, $this->db);
  447. }
  448. private function logOpensslError() {
  449. $errors = [];
  450. while ($error = openssl_error_string()) {
  451. $errors[] = $error;
  452. }
  453. $this->logger->critical('Something is wrong with your openssl setup: ' . implode(', ', $errors));
  454. }
  455. }