Skip to content

Commit

Permalink
MDL-67861 libraries: Refactor is_ip_in_subnet_list in ip_utils
Browse files Browse the repository at this point in the history
  • Loading branch information
brendanheywood authored and stronk7 committed Mar 5, 2020
1 parent c70d7d0 commit c4665bc
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 12 deletions.
21 changes: 21 additions & 0 deletions lib/classes/ip_utils.php
Expand Up @@ -224,4 +224,25 @@ public static function is_domain_in_allowed_list($domain, $alloweddomains) {
}
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;
}

}
13 changes: 1 addition & 12 deletions lib/moodlelib.php
Expand Up @@ -9104,24 +9104,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);
}

/**
Expand Down
28 changes: 28 additions & 0 deletions lib/tests/ip_utils_test.php
Expand Up @@ -376,4 +376,32 @@ public function data_domain_addresses() {
[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));
}

}

0 comments on commit c4665bc

Please sign in to comment.