NEW: Moved allowed-hosts checking to a middleware.

This commit is contained in:
Sam Minnee 2017-06-23 15:08:08 +12:00 committed by Damian Mooyman
parent db080c0603
commit 72a7655e95
3 changed files with 51 additions and 8 deletions

View File

@ -3,7 +3,13 @@ Name: requestprocessors
---
SilverStripe\Control\Director:
middlewares:
AllowedHostsMiddleware: '%$SilverStripe\Control\AllowedHostsMiddleware'
SessionMiddleware: 'SilverStripe\Control\SessionMiddleware'
RequestProcessor: 'SilverStripe\Control\RequestProcessor'
FlushMiddleware: '%$SilverStripe\Control\FlushMiddleware'
SilverStripe\Core\Injector\Injector:
SilverStripe\Control\AllowedHostsMiddleware:
properties:
AllowedHosts: "`SS_ALLOWED_HOSTS`"

View File

@ -0,0 +1,45 @@
<?php
namespace SilverStripe\Control;
/**
* Secures requests by only allowing a whitelist of Host values
*/
class AllowedHostsMiddleware implements HTTPMiddleware
{
private $allowedHosts = null;
/**
* @return string A comma-separted list of allowed Host header values
*/
public function getAllowedHosts()
{
return $this->allowedHosts;
}
/**
* @param $allowedHosts string A comma-separted list of allowed Host header values
*/
public function setAllowedHosts($allowedHosts)
{
$this->allowedHosts = $allowedHosts;
}
/**
* @inheritdoc
*/
public function process(HTTPRequest $request, callable $delegate)
{
if ($this->allowedHosts && !Director::is_cli()) {
$allowedHosts = preg_split('/ *, */', $this->allowedHosts);
// check allowed hosts
if (!in_array($request->getHeader('Host'), $allowedHosts)) {
return new HTTPResponse('Invalid Host', 400);
}
}
return $delegate($request);
}
}

View File

@ -123,14 +123,6 @@ class Director implements TemplateGlobalProvider
*/
public static function direct(HTTPRequest $request)
{
// check allowed hosts
if (getenv('SS_ALLOWED_HOSTS') && !static::is_cli()) {
$allowedHosts = explode(',', getenv('SS_ALLOWED_HOSTS'));
if (!in_array(static::host(), $allowedHosts)) {
return new HTTPResponse('Invalid Host', 400);
}
}
// Generate output
return static::handleRequest($request);
}