fix: improve accuracy of is_valid_hostname() (#7435)

* fix: improve accuracy of is_valid_hostname()
fixes discovery code attempting to add discover invalid dns names
the old code allowed some invalid hostnames, this is more thorough
add tests

* fix merge error
This commit is contained in:
Tony Murray
2017-10-05 16:04:17 -05:00
committed by GitHub
parent b89ed26852
commit a2b9342f05
2 changed files with 30 additions and 5 deletions

View File

@@ -626,8 +626,13 @@ function is_valid_hostname($hostname)
// labels to start with digits. No other symbols, punctuation characters, or
// white space are permitted. While a hostname may not contain other characters,
// such as the underscore character (_), other DNS names may contain the underscore
// maximum length is 253 characters, maximum segment size is 63
return ctype_alnum(str_replace(array('_', '-', '.'), '', $hostname));
return (
preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*\.?$/i", $hostname) //valid chars check
&& preg_match("/^.{1,253}$/", $hostname) //overall length check
&& preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*\.?$/", $hostname)
);
}
/*

View File

@@ -25,10 +25,6 @@
namespace LibreNMS\Tests;
use LibreNMS\Util\IP;
use LibreNMS\Util\IPv4;
use LibreNMS\Util\IPv6;
class CommonFunctionsTest extends \PHPUnit_Framework_TestCase
{
public function testStrContains()
@@ -122,4 +118,28 @@ class CommonFunctionsTest extends \PHPUnit_Framework_TestCase
$this->assertSame('UnderscoreName', str_to_class('underscore_name'));
$this->assertSame('LibreNMS\\AllOfThemName', str_to_class('all OF-thEm_NaMe', 'LibreNMS\\'));
}
public function testIsValidHostname()
{
$this->assertTrue(is_valid_hostname('a'), 'a');
$this->assertTrue(is_valid_hostname('a.'), 'a.');
$this->assertTrue(is_valid_hostname('0'), '0');
$this->assertTrue(is_valid_hostname('a.b'), 'a.b');
$this->assertTrue(is_valid_hostname('localhost'), 'localhost');
$this->assertTrue(is_valid_hostname('google.com'), 'google.com');
$this->assertTrue(is_valid_hostname('news.google.co.uk'), 'news.google.co.uk');
$this->assertTrue(is_valid_hostname('xn--fsqu00a.xn--0zwm56d'), 'xn--fsqu00a.xn--0zwm56d');
$this->assertFalse(is_valid_hostname('goo gle.com'), 'goo gle.com');
$this->assertFalse(is_valid_hostname('google..com'), 'google..com');
$this->assertFalse(is_valid_hostname('google.com '), 'google.com ');
$this->assertFalse(is_valid_hostname('google-.com'), 'google-.com');
$this->assertFalse(is_valid_hostname('.google.com'), '.google.com');
$this->assertFalse(is_valid_hostname('<script'), '<script');
$this->assertFalse(is_valid_hostname('alert('), 'alert(');
$this->assertFalse(is_valid_hostname('.'), '.');
$this->assertFalse(is_valid_hostname('..'), '..');
$this->assertFalse(is_valid_hostname(' '), 'Just a space');
$this->assertFalse(is_valid_hostname('-'), '-');
$this->assertFalse(is_valid_hostname(''), 'Empty string');
}
}