VerificationToken.php 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2021 Arthur Schiwon <blizzz@arthur-schiwon.de>
  5. *
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. *
  8. * @license GNU AGPL version 3 or any later version
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as
  12. * published by the Free Software Foundation, either version 3 of the
  13. * License, or (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  22. *
  23. */
  24. namespace OC\Security\VerificationToken;
  25. use OCP\AppFramework\Utility\ITimeFactory;
  26. use OCP\BackgroundJob\IJobList;
  27. use OCP\IConfig;
  28. use OCP\IUser;
  29. use OCP\Security\ICrypto;
  30. use OCP\Security\ISecureRandom;
  31. use OCP\Security\VerificationToken\InvalidTokenException;
  32. use OCP\Security\VerificationToken\IVerificationToken;
  33. use function json_encode;
  34. class VerificationToken implements IVerificationToken {
  35. protected const TOKEN_LIFETIME = 60 * 60 * 24 * 7;
  36. /** @var IConfig */
  37. private $config;
  38. /** @var ICrypto */
  39. private $crypto;
  40. /** @var ITimeFactory */
  41. private $timeFactory;
  42. /** @var ISecureRandom */
  43. private $secureRandom;
  44. /** @var IJobList */
  45. private $jobList;
  46. public function __construct(
  47. IConfig $config,
  48. ICrypto $crypto,
  49. ITimeFactory $timeFactory,
  50. ISecureRandom $secureRandom,
  51. IJobList $jobList
  52. ) {
  53. $this->config = $config;
  54. $this->crypto = $crypto;
  55. $this->timeFactory = $timeFactory;
  56. $this->secureRandom = $secureRandom;
  57. $this->jobList = $jobList;
  58. }
  59. /**
  60. * @throws InvalidTokenException
  61. */
  62. protected function throwInvalidTokenException(int $code): void {
  63. throw new InvalidTokenException($code);
  64. }
  65. public function check(string $token, ?IUser $user, string $subject, string $passwordPrefix = '', bool $expiresWithLogin = false): void {
  66. if ($user === null || !$user->isEnabled()) {
  67. $this->throwInvalidTokenException(InvalidTokenException::USER_UNKNOWN);
  68. }
  69. $encryptedToken = $this->config->getUserValue($user->getUID(), 'core', $subject, null);
  70. if ($encryptedToken === null) {
  71. $this->throwInvalidTokenException(InvalidTokenException::TOKEN_NOT_FOUND);
  72. }
  73. try {
  74. $decryptedToken = $this->crypto->decrypt($encryptedToken, $passwordPrefix.$this->config->getSystemValue('secret'));
  75. } catch (\Exception $e) {
  76. // Retry with empty secret as a fallback for instances where the secret might not have been set by accident
  77. try {
  78. $decryptedToken = $this->crypto->decrypt($encryptedToken, $passwordPrefix);
  79. } catch (\Exception $e2) {
  80. $this->throwInvalidTokenException(InvalidTokenException::TOKEN_DECRYPTION_ERROR);
  81. }
  82. }
  83. $splitToken = explode(':', $decryptedToken);
  84. if (count($splitToken) !== 2) {
  85. $this->throwInvalidTokenException(InvalidTokenException::TOKEN_INVALID_FORMAT);
  86. }
  87. if ($splitToken[0] < ($this->timeFactory->getTime() - self::TOKEN_LIFETIME)
  88. || ($expiresWithLogin && $user->getLastLogin() > $splitToken[0])) {
  89. $this->throwInvalidTokenException(InvalidTokenException::TOKEN_EXPIRED);
  90. }
  91. if (!hash_equals($splitToken[1], $token)) {
  92. $this->throwInvalidTokenException(InvalidTokenException::TOKEN_MISMATCH);
  93. }
  94. }
  95. public function create(IUser $user, string $subject, string $passwordPrefix = ''): string {
  96. $token = $this->secureRandom->generate(
  97. 21,
  98. ISecureRandom::CHAR_DIGITS.
  99. ISecureRandom::CHAR_LOWER.
  100. ISecureRandom::CHAR_UPPER
  101. );
  102. $tokenValue = $this->timeFactory->getTime() .':'. $token;
  103. $encryptedValue = $this->crypto->encrypt($tokenValue, $passwordPrefix . $this->config->getSystemValue('secret'));
  104. $this->config->setUserValue($user->getUID(), 'core', $subject, $encryptedValue);
  105. $jobArgs = json_encode([
  106. 'userId' => $user->getUID(),
  107. 'subject' => $subject,
  108. 'pp' => $passwordPrefix,
  109. 'notBefore' => $this->timeFactory->getTime() + self::TOKEN_LIFETIME * 2, // multiply to provide a grace period
  110. ]);
  111. $this->jobList->add(CleanUpJob::class, $jobArgs);
  112. return $token;
  113. }
  114. public function delete(string $token, IUser $user, string $subject): void {
  115. $this->config->deleteUserValue($user->getUID(), 'core', $subject);
  116. }
  117. }