*More robust IPv6 validation (exclude ambiguous IPs)
[lhc/web/wiklou.git] / includes / IP.php
1 <?php
2 /*
3 * Collection of public static functions to play with IP address
4 * and IP blocks.
5 *
6 * @Author "Ashar Voultoiz" <hashar@altern.org>
7 * @License GPL v2 or later
8 */
9
10 // Some regex definition to "play" with IP address and IP address blocks
11
12 // An IP is made of 4 bytes from x00 to xFF which is d0 to d255
13 define( 'RE_IP_BYTE', '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])');
14 define( 'RE_IP_ADD' , RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.' . RE_IP_BYTE );
15 // An IPv4 block is an IP address and a prefix (d1 to d32)
16 define( 'RE_IP_PREFIX', '(3[0-2]|[12]?\d)');
17 define( 'RE_IP_BLOCK', RE_IP_ADD . '\/' . RE_IP_PREFIX);
18 // For IPv6 canonicalization (NOT for strict validation; these are quite lax!)
19 define( 'RE_IPV6_WORD', '([0-9A-Fa-f]{1,4})' );
20 define( 'RE_IPV6_GAP', ':(?:0+:)*(?::(?:0+:)*)?' );
21 define( 'RE_IPV6_V4_PREFIX', '0*' . RE_IPV6_GAP . '(?:ffff:)?' );
22 // An IPv6 block is an IP address and a prefix (d1 to d128)
23 define( 'RE_IPV6_PREFIX', '(12[0-8]|1[01][0-9]|[1-9]?\d)');
24 // An IPv6 IP is made up of 8 octets. However abbreviations like "::" can be used. This is lax!
25 define( 'RE_IPV6_ADD', '(:(:' . RE_IPV6_WORD . '){1,7}|' . RE_IPV6_WORD . '(:{1,2}' . RE_IPV6_WORD . '|::$){1,7})' );
26 define( 'RE_IPV6_BLOCK', RE_IPV6_ADD . '\/' . RE_IPV6_PREFIX );
27 // This might be useful for regexps used elsewhere, matches any IPv6 or IPv6 address or network
28 define( 'IP_ADDRESS_STRING', RE_IP_ADD . '(\/' . RE_IP_PREFIX . '|)|' . RE_IPV6_ADD . '(\/' . RE_IPV6_PREFIX . '|)');
29
30 class IP {
31 /**
32 * Given a string, determine if it as valid IP
33 * Unlike isValid(), this looks for networks too
34 * @param $ip IP address.
35 * @return string
36 */
37 public static function isIPAddress( $ip ) {
38 if ( !$ip ) return false;
39 // IPv6 IPs with two "::" strings are ambiguous and this invalid
40 return preg_match( '/^' . IP_ADDRESS_STRING . '$/', $ip) && ( substr_count($ip, '::') < 2 );
41 }
42
43 public static function isIPv6( $ip ) {
44 // IPv6 IPs with two "::" strings are ambiguous and this invalid
45 return preg_match( '/^' . RE_IPV6_ADD . '(\/' . RE_IPV6_PREFIX . '|)$/', $ip) && ( substr_count($ip, '::') < 2);
46 }
47
48 public static function isIPv4( $ip ) {
49 return preg_match( '/^' . RE_IP_ADD . '(\/' . RE_IP_PREFIX . '|)$/', $ip);
50 }
51
52 /**
53 * Given an IP address in dotted-quad notation, returns an IPv6 octet.
54 * See http://www.answers.com/topic/ipv4-compatible-address
55 * IPs with the first 92 bits as zeros are reserved from IPv6
56 * @param $ip quad-dotted IP address.
57 * @return string
58 */
59 public static function IPv4toIPv6( $ip ) {
60 if ( !$ip ) return null;
61 // Convert only if needed
62 if ( self::isIPv6( $ip ) ) return $ip;
63 // IPv4 CIDRs
64 if ( strpos( $ip, '/' ) !== false ) {
65 $parts = explode( '/', $ip, 2 );
66 if ( count( $parts ) != 2 ) {
67 return false;
68 }
69 $network = self::toUnsigned( $parts[0] );
70 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
71 $bits = $parts[1] + 96;
72 return self::toOctet( $network ) . "/$bits";
73 } else {
74 return false;
75 }
76 }
77 return self::toOctet( self::toUnsigned( $ip ) );
78 }
79
80 /**
81 * Given an IPv6 address in octet notation, returns an unsigned integer.
82 * @param $ip octet ipv6 IP address.
83 * @return string
84 */
85 public static function toUnsigned6( $ip ) {
86 if ( !$ip ) return null;
87 $ip = explode(':', self::sanitizeIP( $ip ) );
88 $r_ip = '';
89 foreach ($ip as $v) {
90 $r_ip .= wfBaseConvert( $v, 16, 2, 16);
91 }
92 return wfBaseConvert($r_ip, 2, 10);
93 }
94
95 /**
96 * Given an IPv6 address in octet notation, returns the expanded octet.
97 * @param $ip octet ipv6 IP address.
98 * @return string
99 */
100 public static function sanitizeIP( $ip ) {
101 if ( !$ip ) return null;
102 // Only IPv6 addresses can be expanded
103 if ( !self::isIPv6( $ip ) ) return $ip;
104 // Remove any whitespaces, convert to upper case
105 $ip = strtoupper( trim($ip) );
106 // Expand zero abbreviations
107 if ( substr_count($ip, '::') ) {
108 $ip = str_replace('::', str_repeat(':0', 8 - substr_count($ip, ':')) . ':', $ip);
109 }
110 // For IPs that start with "::", correct the final IP so that it starts with '0' and not ':'
111 if ( strpos( $ip, ':' ) === 0 ) $ip = "0$ip";
112 // Remove leading zereos from each bloc as needed
113 $ip = explode( ':', $ip );
114 for ( $n=0; $n < count($ip); $n++ ) {
115 $ip[$n] = preg_replace( '/^0+' . RE_IPV6_WORD . '/', '$1', $ip[$n] );
116 }
117 $ip = implode( ':', $ip );
118 return $ip;
119 }
120
121 /**
122 * Given an unsigned integer, returns an IPv6 address in octet notation
123 * @param $ip integer IP address.
124 * @return string
125 */
126 public static function toOctet( $ip_int ) {
127 // Convert integer to binary
128 $ip_int = wfBaseConvert($ip_int, 10, 2, 128);
129 // Seperate into 8 octets
130 $ip_oct = wfBaseConvert( substr( $ip_int, 0, 16 ), 2, 16, 1, false );
131 for ($n=1; $n < 8; $n++) {
132 // Convert to hex, and add ":" marks, with NO leading zeroes
133 $ip_oct .= ':' . wfBaseConvert( substr($ip_int, 16*$n, 16), 2, 16, 1, false );
134 }
135 return $ip_oct;
136 }
137
138 /**
139 * Convert a network specification in IPv6 CIDR notation to an integer network and a number of bits
140 * @return array(string, int)
141 */
142 public static function parseCIDR6( $range ) {
143 # Expand any IPv6 IP
144 $parts = explode( '/', IP::sanitizeIP( $range ), 2 );
145 if ( count( $parts ) != 2 ) {
146 return array( false, false );
147 }
148 $network = self::toUnsigned6( $parts[0] );
149 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 128 ) {
150 $bits = $parts[1];
151 if ( $bits == 0 ) {
152 $network = 0;
153 } else {
154 # Native 32 bit functions WONT work here!!!
155 # Convert to a padded binary number
156 $network = wfBaseConvert( $network, 10, 2, 128 );
157 # Truncate the last (128-$bits) bits and replace them with zeros
158 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT );
159 # Convert back to an integer
160 $network = wfBaseConvert( $network, 2, 10 );
161 }
162 } else {
163 $network = false;
164 $bits = false;
165 }
166
167 return array( $network, $bits );
168 }
169
170 /**
171 * Given a string range in a number of formats, return the start and end of
172 * the range in hexadecimal. For IPv6.
173 *
174 * Formats are:
175 * 2001:0db8:85a3::7344/96 CIDR
176 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
177 * 2001:0db8:85a3::7344/96 Single IP
178 * @return array(string, int)
179 */
180 public static function parseRange6( $range ) {
181 # Expand any IPv6 IP
182 $range = IP::sanitizeIP( $range );
183 if ( strpos( $range, '/' ) !== false ) {
184 # CIDR
185 list( $network, $bits ) = self::parseCIDR6( $range );
186 if ( $network === false ) {
187 $start = $end = false;
188 } else {
189 $start = wfBaseConvert( $network, 10, 16, 32, false );
190 # Turn network to binary (again)
191 $end = wfBaseConvert( $network, 10, 2, 128 );
192 # Truncate the last (128-$bits) bits and replace them with ones
193 $end = str_pad( substr( $end, 0, $bits ), 128, 1, STR_PAD_RIGHT );
194 # Convert to hex
195 $end = wfBaseConvert( $end, 2, 16, 32, false );
196 }
197 } elseif ( strpos( $range, '-' ) !== false ) {
198 # Explicit range
199 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
200 $start = self::toUnsigned6( $start ); $end = self::toUnsigned6( $end );
201 if ( $start > $end ) {
202 $start = $end = false;
203 } else {
204 $start = wfBaseConvert( $start, 10, 16, 32, false );
205 $end = wfBaseConvert( $end, 10, 16, 32, false );
206 }
207 } else {
208 # Single IP
209 $start = $end = self::toHex( $range );
210 }
211 if ( $start === false || $end === false ) {
212 return array( false, false );
213 } else {
214 return array( $start, $end );
215 }
216 }
217
218 /**
219 * Validate an IP address.
220 * @return boolean True if it is valid.
221 */
222 public static function isValid( $ip ) {
223 return ( preg_match( '/^' . RE_IP_ADD . '$/', $ip) || preg_match( '/^' . RE_IPV6_ADD . '$/', $ip) );
224 }
225
226 /**
227 * Validate an IP Block.
228 * @return boolean True if it is valid.
229 */
230 public static function isValidBlock( $ipblock ) {
231 return ( count(self::toArray($ipblock)) == 1 + 5 );
232 }
233
234 /**
235 * Determine if an IP address really is an IP address, and if it is public,
236 * i.e. not RFC 1918 or similar
237 * Comes from ProxyTools.php
238 */
239 public static function isPublic( $ip ) {
240 $n = self::toUnsigned( $ip );
241 if ( !$n ) {
242 return false;
243 }
244
245 // ip2long accepts incomplete addresses, as well as some addresses
246 // followed by garbage characters. Check that it's really valid.
247 if( $ip != long2ip( $n ) ) {
248 return false;
249 }
250
251 static $privateRanges = false;
252 if ( !$privateRanges ) {
253 $privateRanges = array(
254 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
255 array( '172.16.0.0', '172.31.255.255' ), # "
256 array( '192.168.0.0', '192.168.255.255' ), # "
257 array( '0.0.0.0', '0.255.255.255' ), # this network
258 array( '127.0.0.0', '127.255.255.255' ), # loopback
259 );
260 }
261
262 foreach ( $privateRanges as $r ) {
263 $start = self::toUnsigned( $r[0] );
264 $end = self::toUnsigned( $r[1] );
265 if ( $n >= $start && $n <= $end ) {
266 return false;
267 }
268 }
269 return true;
270 }
271
272 /**
273 * Split out an IP block as an array of 4 bytes and a mask,
274 * return false if it can't be determined
275 *
276 * @parameter $ip string A quad dotted/octet IP address
277 * @return array
278 */
279 public static function toArray( $ipblock ) {
280 $matches = array();
281 if( preg_match( '/^' . RE_IP_ADD . '(?:\/(?:'.RE_IP_PREFIX.'))?' . '$/', $ipblock, $matches ) ) {
282 return $matches;
283 } else if ( preg_match( '/^' . RE_IPV6_ADD . '(?:\/(?:'.RE_IPV6_PREFIX.'))?' . '$/', $ipblock, $matches ) ) {
284 return $matches;
285 } else {
286 return false;
287 }
288 }
289
290 /**
291 * Return a zero-padded hexadecimal representation of an IP address.
292 *
293 * Hexadecimal addresses are used because they can easily be extended to
294 * IPv6 support. To separate the ranges, the return value from this
295 * function for an IPv6 address will be prefixed with "v6-", a non-
296 * hexadecimal string which sorts after the IPv4 addresses.
297 *
298 * @param $ip Quad dotted/octet IP address.
299 * @return hexidecimal
300 */
301 public static function toHex( $ip ) {
302 $n = self::toUnsigned( $ip );
303 if ( $n !== false ) {
304 $n = ( self::isIPv6($ip) ) ? wfBaseConvert( $n, 10, 16, 32, false ) : wfBaseConvert( $n, 10, 16, 8, false );
305 }
306 return $n;
307 }
308
309 /**
310 * Given an IP address in dotted-quad notation, returns an unsigned integer.
311 * Like ip2long() except that it actually works and has a consistent error return value.
312 * Comes from ProxyTools.php
313 * @param $ip Quad dotted IP address.
314 * @return integer
315 */
316 public static function toUnsigned( $ip ) {
317 // Use IPv6 functions if needed
318 if ( self::isIPv6( $ip ) ) {
319 return self::toUnsigned6( $ip );
320 }
321 if ( $ip == '255.255.255.255' ) {
322 $n = -1;
323 } else {
324 $n = ip2long( $ip );
325 if ( $n == -1 || $n === false ) { # Return value on error depends on PHP version
326 $n = false;
327 }
328 }
329 if ( $n < 0 ) {
330 $n += pow( 2, 32 );
331 }
332 return $n;
333 }
334
335 /**
336 * Convert a dotted-quad IP to a signed integer
337 * Returns false on failure
338 */
339 public static function toSigned( $ip ) {
340 if ( $ip == '255.255.255.255' ) {
341 $n = -1;
342 } else {
343 $n = ip2long( $ip );
344 if ( $n == -1 ) {
345 $n = false;
346 }
347 }
348 return $n;
349 }
350
351 /**
352 * Convert a network specification in CIDR notation to an integer network and a number of bits
353 * @return array(string, int)
354 */
355 public static function parseCIDR( $range ) {
356 $parts = explode( '/', $range, 2 );
357 if ( count( $parts ) != 2 ) {
358 return array( false, false );
359 }
360 $network = self::toSigned( $parts[0] );
361 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
362 $bits = $parts[1];
363 if ( $bits == 0 ) {
364 $network = 0;
365 } else {
366 $network &= ~((1 << (32 - $bits)) - 1);
367 }
368 # Convert to unsigned
369 if ( $network < 0 ) {
370 $network += pow( 2, 32 );
371 }
372 } else {
373 $network = false;
374 $bits = false;
375 }
376 return array( $network, $bits );
377 }
378
379 /**
380 * Given a string range in a number of formats, return the start and end of
381 * the range in hexadecimal. For IPv4.
382 *
383 * Formats are:
384 * 1.2.3.4/24 CIDR
385 * 1.2.3.4 - 1.2.3.5 Explicit range
386 * 1.2.3.4 Single IP
387 * @return array(string, int)
388 */
389 public static function parseRange( $range ) {
390 // Use IPv6 functions if needed
391 if ( self::isIPv6( $range ) ) {
392 return self::parseRange6( $range );
393 }
394 if ( strpos( $range, '/' ) !== false ) {
395 # CIDR
396 list( $network, $bits ) = self::parseCIDR( $range );
397 if ( $network === false ) {
398 $start = $end = false;
399 } else {
400 $start = sprintf( '%08X', $network );
401 $end = sprintf( '%08X', $network + pow( 2, (32 - $bits) ) - 1 );
402 }
403 } elseif ( strpos( $range, '-' ) !== false ) {
404 # Explicit range
405 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
406 $start = self::toUnsigned( $start ); $end = self::toUnsigned( $end );
407 if ( $start > $end ) {
408 $start = $end = false;
409 } else {
410 $start = sprintf( '%08X', $start );
411 $end = sprintf( '%08X', $end );
412 }
413 } else {
414 # Single IP
415 $start = $end = self::toHex( $range );
416 }
417 if ( $start === false || $end === false ) {
418 return array( false, false );
419 } else {
420 return array( $start, $end );
421 }
422 }
423
424 /**
425 * Determine if a given IPv4 address is in a given CIDR network
426 * @param $addr The address to check against the given range.
427 * @param $range The range to check the given address against.
428 * @return bool Whether or not the given address is in the given range.
429 */
430 public static function isInRange( $addr, $range ) {
431 // Convert to IPv6 if needed
432 $unsignedIP = self::toUnsigned6( self::IPv4toIPv6($addr) );
433 list( $start, $end ) = self::parseRange6( self::IPv4toIPv6($range) );
434 return (($unsignedIP >= $start) && ($unsignedIP <= $end));
435 }
436
437 /**
438 * Convert some unusual representations of IPv4 addresses to their
439 * canonical dotted quad representation.
440 *
441 * This currently only checks a few IPV4-to-IPv6 related cases. More
442 * unusual representations may be added later.
443 *
444 * @param $addr something that might be an IP address
445 * @return valid dotted quad IPv4 address or null
446 */
447 public static function canonicalize( $addr ) {
448 if ( self::isValid( $addr ) )
449 return $addr;
450
451 // IPv6 loopback address
452 $m = array();
453 if ( preg_match( '/^0*' . RE_IPV6_GAP . '1$/', $addr, $m ) )
454 return '127.0.0.1';
455
456 // IPv4-mapped and IPv4-compatible IPv6 addresses
457 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . '(' . RE_IP_ADD . ')$/i', $addr, $m ) )
458 return $m[1];
459 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . RE_IPV6_WORD . ':' . RE_IPV6_WORD . '$/i', $addr, $m ) )
460 return long2ip( ( hexdec( $m[1] ) << 16 ) + hexdec( $m[2] ) );
461
462 return null; // give up
463 }
464 }
465
466 ?>