SecurityHeaders.php 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2023 Côme Chilliet <come.chilliet@nextcloud.com>
  5. *
  6. * @author Côme Chilliet <come.chilliet@nextcloud.com>
  7. *
  8. * @license GNU AGPL version 3 or any later version
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as
  12. * published by the Free Software Foundation, either version 3 of the
  13. * License, or (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. *
  23. */
  24. namespace OCA\Settings\SetupChecks;
  25. use OCP\Http\Client\IClientService;
  26. use OCP\IConfig;
  27. use OCP\IL10N;
  28. use OCP\IURLGenerator;
  29. use OCP\SetupCheck\ISetupCheck;
  30. use OCP\SetupCheck\SetupResult;
  31. use Psr\Log\LoggerInterface;
  32. class SecurityHeaders implements ISetupCheck {
  33. use CheckServerResponseTrait;
  34. public function __construct(
  35. protected IL10N $l10n,
  36. protected IConfig $config,
  37. protected IURLGenerator $urlGenerator,
  38. protected IClientService $clientService,
  39. protected LoggerInterface $logger,
  40. ) {
  41. }
  42. public function getCategory(): string {
  43. return 'security';
  44. }
  45. public function getName(): string {
  46. return $this->l10n->t('HTTP headers');
  47. }
  48. public function run(): SetupResult {
  49. $urls = [
  50. ['get', $this->urlGenerator->linkToRoute('heartbeat'), [200]],
  51. ];
  52. $securityHeaders = [
  53. 'X-Content-Type-Options' => ['nosniff', null],
  54. 'X-Robots-Tag' => ['noindex,nofollow', null],
  55. 'X-Frame-Options' => ['sameorigin', 'deny'],
  56. 'X-Permitted-Cross-Domain-Policies' => ['none', null],
  57. ];
  58. foreach ($urls as [$verb,$url,$validStatuses]) {
  59. $works = null;
  60. foreach ($this->runRequest($verb, $url, ['httpErrors' => false]) as $response) {
  61. // Check that the response status matches
  62. if (!in_array($response->getStatusCode(), $validStatuses)) {
  63. $works = false;
  64. continue;
  65. }
  66. $msg = '';
  67. $msgParameters = [];
  68. foreach ($securityHeaders as $header => [$expected, $accepted]) {
  69. /* Convert to lowercase and remove spaces after comas */
  70. $value = preg_replace('/,\s+/', ',', strtolower($response->getHeader($header)));
  71. if ($value !== $expected) {
  72. if ($accepted !== null && $value === $accepted) {
  73. $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";
  74. } else {
  75. $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";
  76. }
  77. }
  78. }
  79. $xssfields = array_map('trim', explode(';', $response->getHeader('X-XSS-Protection')));
  80. if (!in_array('1', $xssfields) || !in_array('mode=block', $xssfields)) {
  81. $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";
  82. }
  83. $referrerPolicy = $response->getHeader('Referrer-Policy');
  84. if (!preg_match('/(no-referrer(-when-downgrade)?|strict-origin(-when-cross-origin)?|same-origin)(,|$)/', $referrerPolicy)) {
  85. $msg .= $this->l10n->t(
  86. '- 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}.',
  87. [
  88. 'Referrer-Policy',
  89. 'no-referrer',
  90. 'no-referrer-when-downgrade',
  91. 'strict-origin',
  92. 'strict-origin-when-cross-origin',
  93. 'same-origin',
  94. ]
  95. )."\n";
  96. $msgParameters['w3c-recommendation'] = [
  97. 'type' => 'highlight',
  98. 'id' => 'w3c-recommendation',
  99. 'name' => 'W3C Recommendation',
  100. 'link' => 'https://www.w3.org/TR/referrer-policy/',
  101. ];
  102. }
  103. $transportSecurityValidity = $response->getHeader('Strict-Transport-Security');
  104. $minimumSeconds = 15552000;
  105. if (preg_match('/^max-age=(\d+)(;.*)?$/', $transportSecurityValidity, $m)) {
  106. $transportSecurityValidity = (int)$m[1];
  107. if ($transportSecurityValidity < $minimumSeconds) {
  108. $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";
  109. }
  110. } elseif (!empty($transportSecurityValidity)) {
  111. $msg .= $this->l10n->t('- The `Strict-Transport-Security` HTTP header is malformed: `%s`. For enhanced security, it is recommended to enable HSTS.', [$transportSecurityValidity])."\n";
  112. } else {
  113. $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";
  114. }
  115. if (!empty($msg)) {
  116. return SetupResult::warning(
  117. $this->l10n->t('Some headers are not set correctly on your instance')."\n".$msg,
  118. $this->urlGenerator->linkToDocs('admin-security'),
  119. $msgParameters,
  120. );
  121. }
  122. // Skip the other requests if one works
  123. $works = true;
  124. break;
  125. }
  126. // If 'works' is null then we could not connect to the server
  127. if ($works === null) {
  128. return SetupResult::info(
  129. $this->l10n->t('Could not check that your web server serves security headers correctly. Please check manually.'),
  130. $this->urlGenerator->linkToDocs('admin-security'),
  131. );
  132. }
  133. // Otherwise if we fail we can abort here
  134. if ($works === false) {
  135. return SetupResult::warning(
  136. $this->l10n->t("Could not check that your web server serves security headers correctly, unable to query `%s`", [$url]),
  137. $this->urlGenerator->linkToDocs('admin-security'),
  138. );
  139. }
  140. }
  141. return SetupResult::success(
  142. $this->l10n->t('Your server is correctly configured to send security headers.')
  143. );
  144. }
  145. }