1
0

CsrfToken.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Leon Klingele <git@leonklingele.de>
  7. * @author Lukas Reschke <lukas@statuscode.ch>
  8. *
  9. * @license AGPL-3.0
  10. *
  11. * This code is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU Affero General Public License, version 3,
  13. * as published by the Free Software Foundation.
  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, version 3,
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>
  22. *
  23. */
  24. namespace OC\Security\CSRF;
  25. /**
  26. * Class CsrfToken represents the stored or provided CSRF token. To mitigate
  27. * BREACH alike vulnerabilities the token is returned in an encrypted value as
  28. * well in an unencrypted value. For display measures to the user always the
  29. * unencrypted one should be chosen.
  30. *
  31. * @package OC\Security\CSRF
  32. */
  33. class CsrfToken {
  34. /** @var string */
  35. private $value;
  36. /** @var string */
  37. private $encryptedValue = '';
  38. /**
  39. * @param string $value Value of the token. Can be encrypted or not encrypted.
  40. */
  41. public function __construct(string $value) {
  42. $this->value = $value;
  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. * @return string
  49. */
  50. public function getEncryptedValue(): string {
  51. if($this->encryptedValue === '') {
  52. $sharedSecret = random_bytes(\strlen($this->value));
  53. $this->encryptedValue = base64_encode($this->value ^ $sharedSecret) . ':' . base64_encode($sharedSecret);
  54. }
  55. return $this->encryptedValue;
  56. }
  57. /**
  58. * The unencrypted value of the token. Used for decrypting an already
  59. * encrypted token.
  60. *
  61. * @return string
  62. */
  63. public function getDecryptedValue(): string {
  64. $token = explode(':', $this->value);
  65. if (\count($token) !== 2) {
  66. return '';
  67. }
  68. $obfuscatedToken = $token[0];
  69. $secret = $token[1];
  70. return base64_decode($obfuscatedToken) ^ base64_decode($secret);
  71. }
  72. }