CsrfToken.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. private string $encryptedValue = '';
  37. /**
  38. * @param string $value Value of the token. Can be encrypted or not encrypted.
  39. */
  40. public function __construct(
  41. private string $value,
  42. ) {
  43. }
  44. /**
  45. * Encrypted value of the token. This is used to mitigate BREACH alike
  46. * vulnerabilities. For display measures do use this functionality.
  47. */
  48. public function getEncryptedValue(): string {
  49. if ($this->encryptedValue === '') {
  50. $sharedSecret = random_bytes(\strlen($this->value));
  51. $this->encryptedValue = base64_encode($this->value ^ $sharedSecret) . ':' . base64_encode($sharedSecret);
  52. }
  53. return $this->encryptedValue;
  54. }
  55. /**
  56. * The unencrypted value of the token. Used for decrypting an already
  57. * encrypted token.
  58. */
  59. public function getDecryptedValue(): string {
  60. $token = explode(':', $this->value);
  61. if (\count($token) !== 2) {
  62. return '';
  63. }
  64. $obfuscatedToken = $token[0];
  65. $secret = $token[1];
  66. return base64_decode($obfuscatedToken) ^ base64_decode($secret);
  67. }
  68. }