function DrupalKernel::setupTrustedHosts

Same name in other branches
  1. 9 core/lib/Drupal/Core/DrupalKernel.php \Drupal\Core\DrupalKernel::setupTrustedHosts()
  2. 8.9.x core/lib/Drupal/Core/DrupalKernel.php \Drupal\Core\DrupalKernel::setupTrustedHosts()
  3. 11.x 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'] = [
    '^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/installing-drupal/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 1693

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;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.