1
0

SecurityHeaders.php 5.5 KB

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