VerificationToken.php 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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. public function __construct(
  37. private IConfig $config,
  38. private ICrypto $crypto,
  39. private ITimeFactory $timeFactory,
  40. private ISecureRandom $secureRandom,
  41. private IJobList $jobList
  42. ) {
  43. }
  44. /**
  45. * @throws InvalidTokenException
  46. */
  47. protected function throwInvalidTokenException(int $code): void {
  48. throw new InvalidTokenException($code);
  49. }
  50. public function check(
  51. string $token,
  52. ?IUser $user,
  53. string $subject,
  54. string $passwordPrefix = '',
  55. bool $expiresWithLogin = false,
  56. ): void {
  57. if ($user === null || !$user->isEnabled()) {
  58. $this->throwInvalidTokenException(InvalidTokenException::USER_UNKNOWN);
  59. }
  60. $encryptedToken = $this->config->getUserValue($user->getUID(), 'core', $subject, null);
  61. if ($encryptedToken === null) {
  62. $this->throwInvalidTokenException(InvalidTokenException::TOKEN_NOT_FOUND);
  63. }
  64. try {
  65. $decryptedToken = $this->crypto->decrypt($encryptedToken, $passwordPrefix.$this->config->getSystemValueString('secret'));
  66. } catch (\Exception $e) {
  67. // Retry with empty secret as a fallback for instances where the secret might not have been set by accident
  68. try {
  69. $decryptedToken = $this->crypto->decrypt($encryptedToken, $passwordPrefix);
  70. } catch (\Exception $e2) {
  71. $this->throwInvalidTokenException(InvalidTokenException::TOKEN_DECRYPTION_ERROR);
  72. }
  73. }
  74. $splitToken = explode(':', $decryptedToken);
  75. if (count($splitToken) !== 2) {
  76. $this->throwInvalidTokenException(InvalidTokenException::TOKEN_INVALID_FORMAT);
  77. }
  78. if ($splitToken[0] < ($this->timeFactory->getTime() - self::TOKEN_LIFETIME)
  79. || ($expiresWithLogin && $user->getLastLogin() > $splitToken[0])) {
  80. $this->throwInvalidTokenException(InvalidTokenException::TOKEN_EXPIRED);
  81. }
  82. if (!hash_equals($splitToken[1], $token)) {
  83. $this->throwInvalidTokenException(InvalidTokenException::TOKEN_MISMATCH);
  84. }
  85. }
  86. public function create(
  87. IUser $user,
  88. string $subject,
  89. string $passwordPrefix = '',
  90. ): string {
  91. $token = $this->secureRandom->generate(
  92. 21,
  93. ISecureRandom::CHAR_DIGITS.
  94. ISecureRandom::CHAR_LOWER.
  95. ISecureRandom::CHAR_UPPER
  96. );
  97. $tokenValue = $this->timeFactory->getTime() .':'. $token;
  98. $encryptedValue = $this->crypto->encrypt($tokenValue, $passwordPrefix . $this->config->getSystemValueString('secret'));
  99. $this->config->setUserValue($user->getUID(), 'core', $subject, $encryptedValue);
  100. $jobArgs = json_encode([
  101. 'userId' => $user->getUID(),
  102. 'subject' => $subject,
  103. 'pp' => $passwordPrefix,
  104. 'notBefore' => $this->timeFactory->getTime() + self::TOKEN_LIFETIME * 2, // multiply to provide a grace period
  105. ]);
  106. $this->jobList->add(CleanUpJob::class, $jobArgs);
  107. return $token;
  108. }
  109. public function delete(string $token, IUser $user, string $subject): void {
  110. $this->config->deleteUserValue($user->getUID(), 'core', $subject);
  111. }
  112. }