Skip to content
Snippets Groups Projects
Commit 97285047 authored by Olav Morken's avatar Olav Morken
Browse files

Utilities: Add IPv6 support to ipCIDRcheck().

Thanks to Brook Schofield for implementing this!

git-svn-id: https://simplesamlphp.googlecode.com/svn/trunk@2896 44740490-163a-0410-bde0-09ae8108e29a
parent db17e644
No related branches found
No related tags found
No related merge requests found
......@@ -486,15 +486,50 @@ class SimpleSAML_Utilities {
static function ipCIDRcheck($cidr, $ip = null) {
if ($ip == null) $ip = $_SERVER['REMOTE_ADDR'];
list ($net, $mask) = explode('/', $cidr);
$ip_net = ip2long ($net);
$ip_mask = ~((1 << (32 - $mask)) - 1);
$ip_ip = ip2long ($ip);
$ip_ip_net = $ip_ip & $ip_mask;
return ($ip_ip_net == $ip_net);
if (strstr($ip, ':') || strstr($net, ':')) {
// Validate IPv6 with inet_pton, convert to hex with bin2hex
// then store as a long with hexdec
$ip_pack = inet_pton($ip);
$net_pack = inet_pton($net);
if ($ip_pack === false || $net_pack === false) {
// not valid IPv6 address (warning already issued)
return false;
}
$ip_ip = str_split(bin2hex($ip_pack),8);
foreach ($ip_ip as &$value) {
$value = hexdec($value);
}
$ip_net = str_split(bin2hex($net_pack),8);
foreach ($ip_net as &$value) {
$value = hexdec($value);
}
} else {
$ip_ip[0] = ip2long ($ip);
$ip_net[0] = ip2long ($net);
}
for($i = 0; $mask > 0 && $i < sizeof($ip_ip); $i++) {
if ($mask > 32) {
$iteration_mask = 32;
} else {
$iteration_mask = $mask;
}
$mask -= 32;
$ip_mask = ~((1 << (32 - $iteration_mask)) - 1);
$ip_net_mask = $ip_net[$i] & $ip_mask;
$ip_ip_mask = $ip_ip[$i] & $ip_mask;
if ($ip_ip_mask != $ip_net_mask)
return false;
}
return true;
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment