PublicKeyTokenProvider.php 18 KB

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