PublicKeyTokenProvider.php 18 KB

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