You are here

protected static function DrupalKernel::setupTrustedHosts in Drupal 8

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/DrupalKernel.php \Drupal\Core\DrupalKernel::setupTrustedHosts()

Sets up the lists of trusted HTTP Host headers.

Since the HTTP Host header can be set by the user making the request, it is possible to create an attack vectors against a site by overriding this. Symfony provides a mechanism for creating a list of trusted Host values.

Host patterns (as regular expressions) can be configured through settings.php for multisite installations, sites using ServerAlias without canonical redirection, or configurations where the site responds to default requests. For example,

$settings['trusted_host_patterns'] = array(
  '^example\\.com$',
  '^*.example\\.com$',
);

Parameters

\Symfony\Component\HttpFoundation\Request $request: The request object.

array $host_patterns: The array of trusted host patterns.

Return value

bool TRUE if the Host header is trusted, FALSE otherwise.

See also

https://www.drupal.org/docs/8/install/trusted-host-settings

\Drupal\Core\Http\TrustedHostsRequestFactory

1 call to DrupalKernel::setupTrustedHosts()
DrupalKernel::initializeSettings in core/lib/Drupal/Core/DrupalKernel.php
Locate site path and initialize settings singleton.

File

core/lib/Drupal/Core/DrupalKernel.php, line 1582

Class

DrupalKernel
The DrupalKernel class is the core of Drupal itself.

Namespace

Drupal\Core

Code

protected static function setupTrustedHosts(Request $request, $host_patterns) {
  $request
    ->setTrustedHosts($host_patterns);

  // Get the host, which will validate the current request.
  try {
    $host = $request
      ->getHost();

    // Fake requests created through Request::create() without passing in the
    // server variables from the main request have a default host of
    // 'localhost'. If 'localhost' does not match any of the trusted host
    // patterns these fake requests would fail the host verification. Instead,
    // TrustedHostsRequestFactory makes sure to pass in the server variables
    // from the main request.
    $request_factory = new TrustedHostsRequestFactory($host);
    Request::setFactory([
      $request_factory,
      'createRequest',
    ]);
  } catch (\UnexpectedValueException $e) {
    return FALSE;
  }
  return TRUE;
}