CsrfToken.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. }