You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.3 KiB

3 years ago
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Leon Klingele <git@leonklingele.de>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Roeland Jago Douma <roeland@famdouma.nl>
  10. *
  11. * @license AGPL-3.0
  12. *
  13. * This code is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License, version 3,
  15. * as published by the Free Software Foundation.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License, version 3,
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>
  24. *
  25. */
  26. namespace OC\Security\CSRF;
  27. /**
  28. * Class CsrfToken represents the stored or provided CSRF token. To mitigate
  29. * BREACH alike vulnerabilities the token is returned in an encrypted value as
  30. * well in an unencrypted value. For display measures to the user always the
  31. * unencrypted one should be chosen.
  32. *
  33. * @package OC\Security\CSRF
  34. */
  35. class CsrfToken {
  36. /** @var string */
  37. private $value;
  38. /** @var string */
  39. private $encryptedValue = '';
  40. /**
  41. * @param string $value Value of the token. Can be encrypted or not encrypted.
  42. */
  43. public function __construct(string $value) {
  44. $this->value = $value;
  45. }
  46. /**
  47. * Encrypted value of the token. This is used to mitigate BREACH alike
  48. * vulnerabilities. For display measures do use this functionality.
  49. *
  50. * @return string
  51. */
  52. public function getEncryptedValue(): string {
  53. if ($this->encryptedValue === '') {
  54. $sharedSecret = random_bytes(\strlen($this->value));
  55. $this->encryptedValue = base64_encode($this->value ^ $sharedSecret) . ':' . base64_encode($sharedSecret);
  56. }
  57. return $this->encryptedValue;
  58. }
  59. /**
  60. * The unencrypted value of the token. Used for decrypting an already
  61. * encrypted token.
  62. *
  63. * @return string
  64. */
  65. public function getDecryptedValue(): string {
  66. $token = explode(':', $this->value);
  67. if (\count($token) !== 2) {
  68. return '';
  69. }
  70. $obfuscatedToken = $token[0];
  71. $secret = $token[1];
  72. return base64_decode($obfuscatedToken) ^ base64_decode($secret);
  73. }
  74. }