Skip to content

Commit

Permalink
[HttpFoundation] added a check for the host header value
Browse files Browse the repository at this point in the history
  • Loading branch information
fabpot committed Dec 7, 2012
1 parent fc89d6b commit 0489799
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 12 deletions.
24 changes: 15 additions & 9 deletions src/Symfony/Component/HttpFoundation/Request.php
Expand Up @@ -696,26 +696,32 @@ public function isSecure()
*
* @return string
*
* @throws \UnexpectedValueException when the host name is invalid
*
* @api
*/
public function getHost()
{
if (self::$trustProxy && $host = $this->headers->get('X_FORWARDED_HOST')) {
$elements = explode(',', $host);

$host = trim($elements[count($elements) - 1]);
} else {
if (!$host = $this->headers->get('HOST')) {
if (!$host = $this->server->get('SERVER_NAME')) {
$host = $this->server->get('SERVER_ADDR', '');
}
$host = $elements[count($elements) - 1];
} elseif (!$host = $this->headers->get('HOST')) {
if (!$host = $this->server->get('SERVER_NAME')) {
$host = $this->server->get('SERVER_ADDR', '');
}
}

// Remove port number from host
$host = preg_replace('/:\d+$/', '', $host);
// Trim and remove port number from host
$host = trim(preg_replace('/:\d+$/', '', $host));

// as the host can come from the user (HTTP_HOST and depending on the configuration, SERVER_NAME too can come from the user)
// check that it does not contain forbidden characters (see RFC 952 and RFC 2181)
if ($host && !preg_match('/^\[?(?:[a-zA-Z0-9-:\]_]+\.?)+$/', $host)) {
throw new \UnexpectedValueException('Invalid Host');
}

return trim($host);
return $host;
}

/**
Expand Down
14 changes: 11 additions & 3 deletions tests/Symfony/Tests/Component/HttpFoundation/RequestTest.php
Expand Up @@ -417,9 +417,6 @@ public function testGetQueryString()
$this->assertEquals('foo=1&foo=2', $request->getQueryString(), '->getQueryString() allows repeated parameters');
}

/**
* @covers Symfony\Component\HttpFoundation\Request::getHost
*/
public function testGetHost()
{
$request = new Request();
Expand Down Expand Up @@ -458,6 +455,17 @@ public function testGetHost()

$request->initialize(array(), array(), array(), array(), array(), array('SERVER_NAME' => 'www.exemple.com', 'HTTP_HOST' => 'www.host.com'));
$this->assertEquals('www.host.com', $request->getHost(), '->getHost() value from Host header has priority over SERVER_NAME ');

}

/**
* @expectedException RuntimeException
*/
public function testGetHostWithFakeHttpHostValue()
{
$request = new Request();
$request->initialize(array(), array(), array(), array(), array(), array('HTTP_HOST' => 'www.host.com?query=string'));
$request->getHost();
}

/**
Expand Down

0 comments on commit 0489799

Please sign in to comment.