PublicKeyTokenProvider.php 18 KB

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