CsrfToken.php 2.1 KB

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