VerificationToken.php 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2021 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Security\VerificationToken;
  8. use OCP\AppFramework\Utility\ITimeFactory;
  9. use OCP\BackgroundJob\IJobList;
  10. use OCP\IConfig;
  11. use OCP\IUser;
  12. use OCP\Security\ICrypto;
  13. use OCP\Security\ISecureRandom;
  14. use OCP\Security\VerificationToken\InvalidTokenException;
  15. use OCP\Security\VerificationToken\IVerificationToken;
  16. use function json_encode;
  17. class VerificationToken implements IVerificationToken {
  18. protected const TOKEN_LIFETIME = 60 * 60 * 24 * 7;
  19. public function __construct(
  20. private IConfig $config,
  21. private ICrypto $crypto,
  22. private ITimeFactory $timeFactory,
  23. private ISecureRandom $secureRandom,
  24. private IJobList $jobList
  25. ) {
  26. }
  27. /**
  28. * @throws InvalidTokenException
  29. */
  30. protected function throwInvalidTokenException(int $code): void {
  31. throw new InvalidTokenException($code);
  32. }
  33. public function check(
  34. string $token,
  35. ?IUser $user,
  36. string $subject,
  37. string $passwordPrefix = '',
  38. bool $expiresWithLogin = false,
  39. ): void {
  40. if ($user === null || !$user->isEnabled()) {
  41. $this->throwInvalidTokenException(InvalidTokenException::USER_UNKNOWN);
  42. }
  43. $encryptedToken = $this->config->getUserValue($user->getUID(), 'core', $subject, null);
  44. if ($encryptedToken === null) {
  45. $this->throwInvalidTokenException(InvalidTokenException::TOKEN_NOT_FOUND);
  46. }
  47. try {
  48. $decryptedToken = $this->crypto->decrypt($encryptedToken, $passwordPrefix.$this->config->getSystemValueString('secret'));
  49. } catch (\Exception $e) {
  50. // Retry with empty secret as a fallback for instances where the secret might not have been set by accident
  51. try {
  52. $decryptedToken = $this->crypto->decrypt($encryptedToken, $passwordPrefix);
  53. } catch (\Exception $e2) {
  54. $this->throwInvalidTokenException(InvalidTokenException::TOKEN_DECRYPTION_ERROR);
  55. }
  56. }
  57. $splitToken = explode(':', $decryptedToken);
  58. if (count($splitToken) !== 2) {
  59. $this->throwInvalidTokenException(InvalidTokenException::TOKEN_INVALID_FORMAT);
  60. }
  61. if ($splitToken[0] < ($this->timeFactory->getTime() - self::TOKEN_LIFETIME)
  62. || ($expiresWithLogin && $user->getLastLogin() > $splitToken[0])) {
  63. $this->throwInvalidTokenException(InvalidTokenException::TOKEN_EXPIRED);
  64. }
  65. if (!hash_equals($splitToken[1], $token)) {
  66. $this->throwInvalidTokenException(InvalidTokenException::TOKEN_MISMATCH);
  67. }
  68. }
  69. public function create(
  70. IUser $user,
  71. string $subject,
  72. string $passwordPrefix = '',
  73. ): string {
  74. $token = $this->secureRandom->generate(
  75. 21,
  76. ISecureRandom::CHAR_DIGITS.
  77. ISecureRandom::CHAR_LOWER.
  78. ISecureRandom::CHAR_UPPER
  79. );
  80. $tokenValue = $this->timeFactory->getTime() .':'. $token;
  81. $encryptedValue = $this->crypto->encrypt($tokenValue, $passwordPrefix . $this->config->getSystemValueString('secret'));
  82. $this->config->setUserValue($user->getUID(), 'core', $subject, $encryptedValue);
  83. $jobArgs = json_encode([
  84. 'userId' => $user->getUID(),
  85. 'subject' => $subject,
  86. 'pp' => $passwordPrefix,
  87. 'notBefore' => $this->timeFactory->getTime() + self::TOKEN_LIFETIME * 2, // multiply to provide a grace period
  88. ]);
  89. $this->jobList->add(CleanUpJob::class, $jobArgs);
  90. return $token;
  91. }
  92. public function delete(string $token, IUser $user, string $subject): void {
  93. $this->config->deleteUserValue($user->getUID(), 'core', $subject);
  94. }
  95. }