PublicKeyTokenProvider.php 18 KB

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