diff --git a/includes/common.php b/includes/common.php index 89cfe90dae..e2bb01ef5c 100644 --- a/includes/common.php +++ b/includes/common.php @@ -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) + ); } /* diff --git a/tests/CommonFunctionsTest.php b/tests/CommonFunctionsTest.php index 737fc98e37..10662a65ed 100644 --- a/tests/CommonFunctionsTest.php +++ b/tests/CommonFunctionsTest.php @@ -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('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'); + } }