1
0

PublicKeyTokenProvider.php 18 KB

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