ContentSecurityPolicyNonceManager.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch>
  5. *
  6. * @author Joas Schilling <coding@schilljs.com>
  7. * @author Lukas Reschke <lukas@statuscode.ch>
  8. * @author Roeland Jago Douma <roeland@famdouma.nl>
  9. *
  10. * @license GNU AGPL version 3 or any later version
  11. *
  12. * This program is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU Affero General Public License as
  14. * published by the Free Software Foundation, either version 3 of the
  15. * License, or (at your option) any later version.
  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
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. *
  25. */
  26. namespace OC\Security\CSP;
  27. use OC\AppFramework\Http\Request;
  28. use OC\Security\CSRF\CsrfTokenManager;
  29. use OCP\IRequest;
  30. /**
  31. * @package OC\Security\CSP
  32. */
  33. class ContentSecurityPolicyNonceManager {
  34. /** @var CsrfTokenManager */
  35. private $csrfTokenManager;
  36. /** @var IRequest */
  37. private $request;
  38. /** @var string */
  39. private $nonce = '';
  40. /**
  41. * @param CsrfTokenManager $csrfTokenManager
  42. * @param IRequest $request
  43. */
  44. public function __construct(CsrfTokenManager $csrfTokenManager,
  45. IRequest $request) {
  46. $this->csrfTokenManager = $csrfTokenManager;
  47. $this->request = $request;
  48. }
  49. /**
  50. * Returns the current CSP nounce
  51. *
  52. * @return string
  53. */
  54. public function getNonce(): string {
  55. if($this->nonce === '') {
  56. $this->nonce = base64_encode($this->csrfTokenManager->getToken()->getEncryptedValue());
  57. }
  58. return $this->nonce;
  59. }
  60. /**
  61. * Check if the browser supports CSP v3
  62. *
  63. * @return bool
  64. */
  65. public function browserSupportsCspV3(): bool {
  66. $browserWhitelist = [
  67. Request::USER_AGENT_CHROME,
  68. // Firefox 45+
  69. '/^Mozilla\/5\.0 \([^)]+\) Gecko\/[0-9.]+ Firefox\/(4[5-9]|[5-9][0-9])\.[0-9.]+$/',
  70. ];
  71. if($this->request->isUserAgent($browserWhitelist)) {
  72. return true;
  73. }
  74. return false;
  75. }
  76. }