ContentSecurityPolicyNonceManager.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch>
  5. *
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Pavel Krasikov <klonishe@gmail.com>
  10. * @author Roeland Jago Douma <roeland@famdouma.nl>
  11. * @author Sam Bull <aa6bs0@sambull.org>
  12. *
  13. * @license GNU AGPL version 3 or any later version
  14. *
  15. * This program is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License as
  17. * published by the Free Software Foundation, either version 3 of the
  18. * License, or (at your option) any later version.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  27. *
  28. */
  29. namespace OC\Security\CSP;
  30. use OC\AppFramework\Http\Request;
  31. use OC\Security\CSRF\CsrfTokenManager;
  32. use OCP\IRequest;
  33. /**
  34. * @package OC\Security\CSP
  35. */
  36. class ContentSecurityPolicyNonceManager {
  37. private string $nonce = '';
  38. public function __construct(
  39. private CsrfTokenManager $csrfTokenManager,
  40. private IRequest $request,
  41. ) {
  42. }
  43. /**
  44. * Returns the current CSP nonce
  45. */
  46. public function getNonce(): string {
  47. if ($this->nonce === '') {
  48. if (empty($this->request->server['CSP_NONCE'])) {
  49. $this->nonce = base64_encode($this->csrfTokenManager->getToken()->getEncryptedValue());
  50. } else {
  51. $this->nonce = $this->request->server['CSP_NONCE'];
  52. }
  53. }
  54. return $this->nonce;
  55. }
  56. /**
  57. * Check if the browser supports CSP v3
  58. */
  59. public function browserSupportsCspV3(): bool {
  60. $browserBlocklist = [
  61. Request::USER_AGENT_IE,
  62. ];
  63. if ($this->request->isUserAgent($browserBlocklist)) {
  64. return false;
  65. }
  66. return true;
  67. }
  68. }