From 516c8aa5060593319db73d565a8271229d1f3303 Mon Sep 17 00:00:00 2001 From: Brendan Heywood Date: Wed, 5 Feb 2020 22:50:20 +1100 Subject: [PATCH 1/1] MDL-67861 libraries: Refactor is_ip_in_subnet_list in ip_utils --- lib/classes/ip_utils.php | 21 +++++++++++++++++++++ lib/moodlelib.php | 13 +------------ lib/tests/ip_utils_test.php | 28 ++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 12 deletions(-) diff --git a/lib/classes/ip_utils.php b/lib/classes/ip_utils.php index 42abcb4b9f3..d2e9a3dd02e 100644 --- a/lib/classes/ip_utils.php +++ b/lib/classes/ip_utils.php @@ -224,4 +224,25 @@ final class ip_utils { } return false; } + + /** + * Is an ip in a given list of subnets? + * + * @param string $ip - the IP to test against the list + * @param string $list - the list of IP subnets + * @param string $delim a delimiter of the list + * @return bool + */ + public static function is_ip_in_subnet_list($ip, $list, $delim = "\n") { + $list = explode($delim, $list); + foreach ($list as $line) { + $tokens = explode('#', $line); + $subnet = trim($tokens[0]); + if (address_in_subnet($ip, $subnet)) { + return true; + } + } + return false; + } + } diff --git a/lib/moodlelib.php b/lib/moodlelib.php index d7fbbfb7f24..65f5a285d5c 100644 --- a/lib/moodlelib.php +++ b/lib/moodlelib.php @@ -9170,24 +9170,13 @@ function cleardoubleslashes ($path) { * @return bool */ function remoteip_in_list($list) { - $inlist = false; $clientip = getremoteaddr(null); if (!$clientip) { // Ensure access on cli. return true; } - - $list = explode("\n", $list); - foreach ($list as $line) { - $tokens = explode('#', $line); - $subnet = trim($tokens[0]); - if (address_in_subnet($clientip, $subnet)) { - $inlist = true; - break; - } - } - return $inlist; + return \core\ip_utils::is_ip_in_subnet_list($clientip, $list); } /** diff --git a/lib/tests/ip_utils_test.php b/lib/tests/ip_utils_test.php index 035f8d5301e..238d45796b7 100644 --- a/lib/tests/ip_utils_test.php +++ b/lib/tests/ip_utils_test.php @@ -376,4 +376,32 @@ class core_ip_utils_testcase extends basic_testcase { [false, 'trouble.com.au'] // The allowed domain (above) has a space at the front and so will return false. ]; } + + /** + * Data provider for test_is_ip_in_subnet_list. + * + * @return array + */ + public function data_is_ip_in_subnet_list() { + return [ + [true, '1.1.1.1', '1.1.1.1', "\n"], + [false, '1.1.1.1', '2.2.2.2', "\n"], + [true, '1.1.1.1', "1.1.1.5\n1.1.1.1", "\n"], + [true, '1.1.1.1', "1.1.1.5,1.1.1.1", ","], + ]; + } + + /** + * Test checking ips against a list of allowed domains. + * + * @param bool $expected Expected result + * @param string $ip IP address + * @param string $list list of IP subnets + * @param string $delim delimiter of list + * @dataProvider data_is_ip_in_subnet_list + */ + public function test_is_ip_in_subnet_list($expected, $ip, $list, $delim) { + $this->assertEquals($expected, \core\ip_utils::is_ip_in_subnet_list($ip, $list, $delim)); + } + } -- 2.43.0