From 9728504700eca2b3a16b6a8d40068116c3f22ee0 Mon Sep 17 00:00:00 2001 From: Olav Morken <olav.morken@uninett.no> Date: Wed, 7 Sep 2011 08:36:29 +0000 Subject: [PATCH] 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 --- lib/SimpleSAML/Utilities.php | 53 ++++++++++++++++++++++++++++++------ 1 file changed, 44 insertions(+), 9 deletions(-) diff --git a/lib/SimpleSAML/Utilities.php b/lib/SimpleSAML/Utilities.php index b633c2e0d..03357c4e1 100644 --- a/lib/SimpleSAML/Utilities.php +++ b/lib/SimpleSAML/Utilities.php @@ -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; } -- GitLab