Skip to content

Commit

Permalink
Rewrite host checks to be more predictable, add more test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
Synchro committed May 12, 2017
1 parent 5175bda commit 70e35cc
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 13 deletions.
34 changes: 23 additions & 11 deletions src/PHPMailer.php
Original file line number Diff line number Diff line change
Expand Up @@ -3373,23 +3373,35 @@ protected function serverHostname()

/**
* Validate whether a string contains a valid value to use as a hostname or IP address.
* IPv6 addresses must include [], e.g. `[::1]`, not just `::1`.
*
* @param string $host The host name or IP address to check
* @return bool
*/
public static function isValidHost($host)
{
return (boolean)(
!empty($host)
and is_string($host)
and strlen($host) < 256
and (
filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6)
or (!is_numeric(str_replace('.', '', $host))
and filter_var('http://' . $host, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)
)
)
);
//Simple syntax limits
if (empty($host)
or !is_string($host)
or strlen($host) > 256
) {
return false;
}
//Looks like a bracketed IPv6 address
if (trim($host, '[]') != $host) {
return (boolean)filter_var(trim($host, '[]'), FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
}
//If removing all the dots results in a numeric string, it must be an IPv4 address.
//Need to check this first because otherwise things like `999.0.0.0` are considered valid host names
if (is_numeric(str_replace('.', '', $host))) {
//Is it a valid IPv4 address?
return (boolean)filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
}
if (filter_var('http://' . $host, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)) {
//Is it a syntactically valid hostname?
return true;
}
return false;
}

/**
Expand Down
8 changes: 6 additions & 2 deletions test/phpmailerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2021,7 +2021,9 @@ public function testHostValidation()
'example.com',
'smtp.gmail.com',
'127.0.0.1',
'[::1]'
trim(str_repeat('a0123456789.', 21), '.'),
'[::1]',
'[0:1234:dc0:41:216:3eff:fe67:3e01]'
];
$bad = [
null,
Expand All @@ -2033,7 +2035,9 @@ public function testHostValidation()
'999.0.0.0',
'[1234]',
'[1234:::1]',
str_repeat('0123456789', 26)
trim(str_repeat('a0123456789.', 22), '.'),
'0:1234:dc0:41:216:3eff:fe67:3e01',
'[012q:1234:dc0:41:216:3eff:fe67:3e01]'
];
foreach ($good as $h) {
$this->assertTrue(PHPMailer::isValidHost($h), 'Good hostname denied: '.$h);
Expand Down

0 comments on commit 70e35cc

Please sign in to comment.