ContentSecurityPolicyNonceManager.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. // Safari 12+
  71. '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/(1[2-9]|[2-9][0-9])\.[0-9]+ Safari\/[0-9.A-Z]+$/',
  72. ];
  73. if($this->request->isUserAgent($browserWhitelist)) {
  74. return true;
  75. }
  76. return false;
  77. }
  78. }