1
0

SecurityHeaders.php 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\Settings\SetupChecks;
  8. use OCP\Http\Client\IClientService;
  9. use OCP\IConfig;
  10. use OCP\IL10N;
  11. use OCP\IURLGenerator;
  12. use OCP\SetupCheck\ISetupCheck;
  13. use OCP\SetupCheck\SetupResult;
  14. use Psr\Log\LoggerInterface;
  15. class SecurityHeaders implements ISetupCheck {
  16. use CheckServerResponseTrait;
  17. public function __construct(
  18. protected IL10N $l10n,
  19. protected IConfig $config,
  20. protected IURLGenerator $urlGenerator,
  21. protected IClientService $clientService,
  22. protected LoggerInterface $logger,
  23. ) {
  24. }
  25. public function getCategory(): string {
  26. return 'security';
  27. }
  28. public function getName(): string {
  29. return $this->l10n->t('HTTP headers');
  30. }
  31. public function run(): SetupResult {
  32. $urls = [
  33. ['get', $this->urlGenerator->linkToRoute('heartbeat'), [200]],
  34. ];
  35. $securityHeaders = [
  36. 'X-Content-Type-Options' => ['nosniff', null],
  37. 'X-Robots-Tag' => ['noindex,nofollow', null],
  38. 'X-Frame-Options' => ['sameorigin', 'deny'],
  39. 'X-Permitted-Cross-Domain-Policies' => ['none', null],
  40. ];
  41. foreach ($urls as [$verb,$url,$validStatuses]) {
  42. $works = null;
  43. foreach ($this->runRequest($verb, $url, ['httpErrors' => false]) as $response) {
  44. // Check that the response status matches
  45. if (!in_array($response->getStatusCode(), $validStatuses)) {
  46. $works = false;
  47. continue;
  48. }
  49. $msg = '';
  50. $msgParameters = [];
  51. foreach ($securityHeaders as $header => [$expected, $accepted]) {
  52. /* Convert to lowercase and remove spaces after comas */
  53. $value = preg_replace('/,\s+/', ',', strtolower($response->getHeader($header)));
  54. if ($value !== $expected) {
  55. if ($accepted !== null && $value === $accepted) {
  56. $msg .= $this->l10n->t('- The `%1$s` HTTP header is not set to `%2$s`. Some features might not work correctly, as it is recommended to adjust this setting accordingly.', [$header, $expected])."\n";
  57. } else {
  58. $msg .= $this->l10n->t('- The `%1$s` HTTP header is not set to `%2$s`. This is a potential security or privacy risk, as it is recommended to adjust this setting accordingly.', [$header, $expected])."\n";
  59. }
  60. }
  61. }
  62. $xssfields = array_map('trim', explode(';', $response->getHeader('X-XSS-Protection')));
  63. if (!in_array('1', $xssfields) || !in_array('mode=block', $xssfields)) {
  64. $msg .= $this->l10n->t('- The `%1$s` HTTP header does not contain `%2$s`. This is a potential security or privacy risk, as it is recommended to adjust this setting accordingly.', ['X-XSS-Protection', '1; mode=block'])."\n";
  65. }
  66. $referrerPolicy = $response->getHeader('Referrer-Policy');
  67. if (!preg_match('/(no-referrer(-when-downgrade)?|strict-origin(-when-cross-origin)?|same-origin)(,|$)/', $referrerPolicy)) {
  68. $msg .= $this->l10n->t(
  69. '- The `%1$s` HTTP header is not set to `%2$s`, `%3$s`, `%4$s`, `%5$s` or `%6$s`. This can leak referer information. See the {w3c-recommendation}.',
  70. [
  71. 'Referrer-Policy',
  72. 'no-referrer',
  73. 'no-referrer-when-downgrade',
  74. 'strict-origin',
  75. 'strict-origin-when-cross-origin',
  76. 'same-origin',
  77. ]
  78. )."\n";
  79. $msgParameters['w3c-recommendation'] = [
  80. 'type' => 'highlight',
  81. 'id' => 'w3c-recommendation',
  82. 'name' => 'W3C Recommendation',
  83. 'link' => 'https://www.w3.org/TR/referrer-policy/',
  84. ];
  85. }
  86. $transportSecurityValidity = $response->getHeader('Strict-Transport-Security');
  87. $minimumSeconds = 15552000;
  88. if (preg_match('/^max-age=(\d+)(;.*)?$/', $transportSecurityValidity, $m)) {
  89. $transportSecurityValidity = (int)$m[1];
  90. if ($transportSecurityValidity < $minimumSeconds) {
  91. $msg .= $this->l10n->t('- The `Strict-Transport-Security` HTTP header is not set to at least `%d` seconds (current value: `%d`). For enhanced security, it is recommended to use a long HSTS policy.', [$minimumSeconds, $transportSecurityValidity])."\n";
  92. }
  93. } elseif (!empty($transportSecurityValidity)) {
  94. $msg .= $this->l10n->t('- The `Strict-Transport-Security` HTTP header is malformed: `%s`. For enhanced security, it is recommended to enable HSTS.', [$transportSecurityValidity])."\n";
  95. } else {
  96. $msg .= $this->l10n->t('- The `Strict-Transport-Security` HTTP header is not set (should be at least `%d` seconds). For enhanced security, it is recommended to enable HSTS.', [$minimumSeconds])."\n";
  97. }
  98. if (!empty($msg)) {
  99. return SetupResult::warning(
  100. $this->l10n->t('Some headers are not set correctly on your instance')."\n".$msg,
  101. $this->urlGenerator->linkToDocs('admin-security'),
  102. $msgParameters,
  103. );
  104. }
  105. // Skip the other requests if one works
  106. $works = true;
  107. break;
  108. }
  109. // If 'works' is null then we could not connect to the server
  110. if ($works === null) {
  111. return SetupResult::info(
  112. $this->l10n->t('Could not check that your web server serves security headers correctly. Please check manually.'),
  113. $this->urlGenerator->linkToDocs('admin-security'),
  114. );
  115. }
  116. // Otherwise if we fail we can abort here
  117. if ($works === false) {
  118. return SetupResult::warning(
  119. $this->l10n->t("Could not check that your web server serves security headers correctly, unable to query `%s`", [$url]),
  120. $this->urlGenerator->linkToDocs('admin-security'),
  121. );
  122. }
  123. }
  124. return SetupResult::success(
  125. $this->l10n->t('Your server is correctly configured to send security headers.')
  126. );
  127. }
  128. }