02a1babb827e0a8bc4847153626b02aacba52a4a
[lhc/web/wiklou.git] / includes / IP.php
1 <?php
2 /**
3 * Functions and constants to play with IP addresses and ranges
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @author Ashar Voultoiz <hashar at free dot fr>, Aaron Schulz
22 */
23
24 // Some regex definition to "play" with IP address and IP address blocks
25
26 // An IPv4 address is made of 4 bytes from x00 to xFF which is d0 to d255
27 define( 'RE_IP_BYTE', '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])' );
28 define( 'RE_IP_ADD' , RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.' . RE_IP_BYTE );
29 // An IPv4 block is an IP address and a prefix (d1 to d32)
30 define( 'RE_IP_PREFIX', '(3[0-2]|[12]?\d)' );
31 define( 'RE_IP_BLOCK', RE_IP_ADD . '\/' . RE_IP_PREFIX );
32
33 // An IPv6 address is made up of 8 words (each x0000 to xFFFF).
34 // However, the "::" abbreviation can be used on consecutive x0000 words.
35 define( 'RE_IPV6_WORD', '([0-9A-Fa-f]{1,4})' );
36 define( 'RE_IPV6_PREFIX', '(12[0-8]|1[01][0-9]|[1-9]?\d)');
37 define( 'RE_IPV6_ADD',
38 '(' . // starts with "::" (includes the address "::")
39 '(::|:(:' . RE_IPV6_WORD . '){1,7})' .
40 '|' . // ends with "::" (not including the address "::")
41 RE_IPV6_WORD . '(:' . RE_IPV6_WORD . '){0,6}::' .
42 '|' . // has no "::"
43 RE_IPV6_WORD . '(:' . RE_IPV6_WORD . '){7}' .
44 '|' . // contains one "::" in the middle ("^" check always fails if no "::" found)
45 RE_IPV6_WORD . '(:(?P<abbr>(?(abbr)|:))?' . RE_IPV6_WORD . '){1,6}(?(abbr)|^)' .
46 ')'
47 );
48 // An IPv6 block is an IP address and a prefix (d1 to d128)
49 define( 'RE_IPV6_BLOCK', RE_IPV6_ADD . '\/' . RE_IPV6_PREFIX );
50 // For IPv6 canonicalization (NOT for strict validation; these are quite lax!)
51 define( 'RE_IPV6_GAP', ':(?:0+:)*(?::(?:0+:)*)?' );
52 define( 'RE_IPV6_V4_PREFIX', '0*' . RE_IPV6_GAP . '(?:ffff:)?' );
53
54 // This might be useful for regexps used elsewhere, matches any IPv6 or IPv6 address or network
55 define( 'IP_ADDRESS_STRING',
56 '(?:' .
57 RE_IP_ADD . '(\/' . RE_IP_PREFIX . '|)' . // IPv4
58 '|' .
59 RE_IPV6_ADD . '(\/' . RE_IPV6_PREFIX . '|)' . // IPv6
60 ')'
61 );
62
63 /**
64 * A collection of public static functions to play with IP address
65 * and IP blocks.
66 */
67 class IP {
68 /**
69 * Determine if a string is as valid IP address or network (CIDR prefix).
70 * SIIT IPv4-translated addresses are rejected.
71 * Note: canonicalize() tries to convert translated addresses to IPv4.
72 *
73 * @param $ip String: possible IP address
74 * @return Boolean
75 */
76 public static function isIPAddress( $ip ) {
77 return (bool)preg_match( '/^' . IP_ADDRESS_STRING . '$/', $ip );
78 }
79
80 /**
81 * Given a string, determine if it as valid IP in IPv6 only.
82 * Note: Unlike isValid(), this looks for networks too.
83 *
84 * @param $ip String: possible IP address
85 * @return Boolean
86 */
87 public static function isIPv6( $ip ) {
88 return (bool)preg_match( '/^' . RE_IPV6_ADD . '(\/' . RE_IPV6_PREFIX . '|)$/', $ip );
89 }
90
91 /**
92 * Given a string, determine if it as valid IP in IPv4 only.
93 * Note: Unlike isValid(), this looks for networks too.
94 *
95 * @param $ip String: possible IP address
96 * @return Boolean
97 */
98 public static function isIPv4( $ip ) {
99 return (bool)preg_match( '/^' . RE_IP_ADD . '(\/' . RE_IP_PREFIX . '|)$/', $ip );
100 }
101
102 /**
103 * Validate an IP address. Ranges are NOT considered valid.
104 * SIIT IPv4-translated addresses are rejected.
105 * Note: canonicalize() tries to convert translated addresses to IPv4.
106 *
107 * @param $ip String
108 * @return Boolean: True if it is valid.
109 */
110 public static function isValid( $ip ) {
111 return ( preg_match( '/^' . RE_IP_ADD . '$/', $ip )
112 || preg_match( '/^' . RE_IPV6_ADD . '$/', $ip ) );
113 }
114
115 /**
116 * Validate an IP Block (valid address WITH a valid prefix).
117 * SIIT IPv4-translated addresses are rejected.
118 * Note: canonicalize() tries to convert translated addresses to IPv4.
119 *
120 * @param $ipblock String
121 * @return Boolean: True if it is valid.
122 */
123 public static function isValidBlock( $ipblock ) {
124 return ( preg_match( '/^' . RE_IPV6_BLOCK . '$/', $ipblock )
125 || preg_match( '/^' . RE_IP_BLOCK . '$/', $ipblock ) );
126 }
127
128 /**
129 * Convert an IP into a nice standard form.
130 * IPv6 addresses in octet notation are expanded to 8 words.
131 * IPv4 addresses are just trimmed.
132 *
133 * @param $ip String: IP address in quad or octet form (CIDR or not).
134 * @return String
135 */
136 public static function sanitizeIP( $ip ) {
137 $ip = trim( $ip );
138 if ( $ip === '' ) {
139 return null;
140 }
141 if ( self::isIPv4( $ip ) || !self::isIPv6( $ip ) ) {
142 return $ip; // nothing else to do for IPv4 addresses or invalid ones
143 }
144 // Remove any whitespaces, convert to upper case
145 $ip = strtoupper( $ip );
146 // Expand zero abbreviations
147 $abbrevPos = strpos( $ip, '::' );
148 if ( $abbrevPos !== false ) {
149 // We know this is valid IPv6. Find the last index of the
150 // address before any CIDR number (e.g. "a:b:c::/24").
151 $CIDRStart = strpos( $ip, "/" );
152 $addressEnd = ( $CIDRStart !== false )
153 ? $CIDRStart - 1
154 : strlen( $ip ) - 1;
155 // If the '::' is at the beginning...
156 if ( $abbrevPos == 0 ) {
157 $repeat = '0:';
158 $extra = ( $ip == '::' ) ? '0' : ''; // for the address '::'
159 $pad = 9; // 7+2 (due to '::')
160 // If the '::' is at the end...
161 } elseif ( $abbrevPos == ( $addressEnd - 1 ) ) {
162 $repeat = ':0';
163 $extra = '';
164 $pad = 9; // 7+2 (due to '::')
165 // If the '::' is in the middle...
166 } else {
167 $repeat = ':0';
168 $extra = ':';
169 $pad = 8; // 6+2 (due to '::')
170 }
171 $ip = str_replace( '::',
172 str_repeat( $repeat, $pad - substr_count( $ip, ':' ) ) . $extra,
173 $ip
174 );
175 }
176 // Remove leading zereos from each bloc as needed
177 $ip = preg_replace( '/(^|:)0+' . RE_IPV6_WORD . '/', '$1$2', $ip );
178 return $ip;
179 }
180
181 /**
182 * Given an unsigned integer, returns an IPv6 address in octet notation
183 *
184 * @param $ip_int String: IP address.
185 * @return String
186 */
187 public static function toOctet( $ip_int ) {
188 return self::hexToOctet( wfBaseConvert( $ip_int, 10, 16, 32, false ) );
189 }
190
191 /**
192 * Convert an IPv4 or IPv6 hexadecimal representation back to readable format
193 *
194 * @param $hex String: number, with "v6-" prefix if it is IPv6
195 * @return String: quad-dotted (IPv4) or octet notation (IPv6)
196 */
197 public static function formatHex( $hex ) {
198 if ( substr( $hex, 0, 3 ) == 'v6-' ) { // IPv6
199 return self::hexToOctet( substr( $hex, 3 ) );
200 } else { // IPv4
201 return self::hexToQuad( $hex );
202 }
203 }
204
205 /**
206 * Converts a hexadecimal number to an IPv6 address in octet notation
207 *
208 * @param $ip_hex String: pure hex (no v6- prefix)
209 * @return String (of format a:b:c:d:e:f:g:h)
210 */
211 public static function hexToOctet( $ip_hex ) {
212 // Pad hex to 32 chars (128 bits)
213 $ip_hex = str_pad( strtoupper( $ip_hex ), 32, '0', STR_PAD_LEFT );
214 // Separate into 8 words
215 $ip_oct = substr( $ip_hex, 0, 4 );
216 for ( $n = 1; $n < 8; $n++ ) {
217 $ip_oct .= ':' . substr( $ip_hex, 4 * $n, 4 );
218 }
219 // NO leading zeroes
220 $ip_oct = preg_replace( '/(^|:)0+' . RE_IPV6_WORD . '/', '$1$2', $ip_oct );
221 return $ip_oct;
222 }
223
224 /**
225 * Converts a hexadecimal number to an IPv4 address in quad-dotted notation
226 *
227 * @param $ip_hex String: pure hex
228 * @return String (of format a.b.c.d)
229 */
230 public static function hexToQuad( $ip_hex ) {
231 // Pad hex to 8 chars (32 bits)
232 $ip_hex = str_pad( strtoupper( $ip_hex ), 8, '0', STR_PAD_LEFT );
233 // Separate into four quads
234 $s = '';
235 for ( $i = 0; $i < 4; $i++ ) {
236 if ( $s !== '' ) {
237 $s .= '.';
238 }
239 $s .= base_convert( substr( $ip_hex, $i * 2, 2 ), 16, 10 );
240 }
241 return $s;
242 }
243
244 /**
245 * Determine if an IP address really is an IP address, and if it is public,
246 * i.e. not RFC 1918 or similar
247 * Comes from ProxyTools.php
248 *
249 * @param $ip String
250 * @return Boolean
251 */
252 public static function isPublic( $ip ) {
253 if ( self::isIPv6( $ip ) ) {
254 return self::isPublic6( $ip );
255 }
256 $n = self::toUnsigned( $ip );
257 if ( !$n ) {
258 return false;
259 }
260
261 // ip2long accepts incomplete addresses, as well as some addresses
262 // followed by garbage characters. Check that it's really valid.
263 if ( $ip != long2ip( $n ) ) {
264 return false;
265 }
266
267 static $privateRanges = false;
268 if ( !$privateRanges ) {
269 $privateRanges = array(
270 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
271 array( '172.16.0.0', '172.31.255.255' ), # "
272 array( '192.168.0.0', '192.168.255.255' ), # "
273 array( '0.0.0.0', '0.255.255.255' ), # this network
274 array( '127.0.0.0', '127.255.255.255' ), # loopback
275 );
276 }
277
278 foreach ( $privateRanges as $r ) {
279 $start = self::toUnsigned( $r[0] );
280 $end = self::toUnsigned( $r[1] );
281 if ( $n >= $start && $n <= $end ) {
282 return false;
283 }
284 }
285 return true;
286 }
287
288 /**
289 * Determine if an IPv6 address really is an IP address, and if it is public,
290 * i.e. not RFC 4193 or similar
291 *
292 * @param $ip String
293 * @return Boolean
294 */
295 private static function isPublic6( $ip ) {
296 static $privateRanges = false;
297 if ( !$privateRanges ) {
298 $privateRanges = array(
299 array( 'fc::', 'fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff' ), # RFC 4193 (local)
300 array( '0:0:0:0:0:0:0:1', '0:0:0:0:0:0:0:1' ), # loopback
301 );
302 }
303 $n = self::toHex( $ip );
304 foreach ( $privateRanges as $r ) {
305 $start = self::toHex( $r[0] );
306 $end = self::toHex( $r[1] );
307 if ( $n >= $start && $n <= $end ) {
308 return false;
309 }
310 }
311 return true;
312 }
313
314 /**
315 * Return a zero-padded upper case hexadecimal representation of an IP address.
316 *
317 * Hexadecimal addresses are used because they can easily be extended to
318 * IPv6 support. To separate the ranges, the return value from this
319 * function for an IPv6 address will be prefixed with "v6-", a non-
320 * hexadecimal string which sorts after the IPv4 addresses.
321 *
322 * @param $ip String: quad dotted/octet IP address.
323 * @return String
324 */
325 public static function toHex( $ip ) {
326 if ( self::isIPv6( $ip ) ) {
327 $n = 'v6-' . self::IPv6ToRawHex( $ip );
328 } else {
329 $n = self::toUnsigned( $ip );
330 if ( $n !== false ) {
331 $n = wfBaseConvert( $n, 10, 16, 8, false );
332 }
333 }
334 return $n;
335 }
336
337 /**
338 * Given an IPv6 address in octet notation, returns a pure hex string.
339 *
340 * @param $ip String: octet ipv6 IP address.
341 * @return String: pure hex (uppercase)
342 */
343 private static function IPv6ToRawHex( $ip ) {
344 $ip = self::sanitizeIP( $ip );
345 if ( !$ip ) {
346 return null;
347 }
348 $r_ip = '';
349 foreach ( explode( ':', $ip ) as $v ) {
350 $r_ip .= str_pad( $v, 4, 0, STR_PAD_LEFT );
351 }
352 return $r_ip;
353 }
354
355 /**
356 * Given an IP address in dotted-quad/octet notation, returns an unsigned integer.
357 * Like ip2long() except that it actually works and has a consistent error return value.
358 * Comes from ProxyTools.php
359 *
360 * @param $ip String: quad dotted IP address.
361 * @return Mixed: string/int/false
362 */
363 public static function toUnsigned( $ip ) {
364 if ( self::isIPv6( $ip ) ) {
365 $n = self::toUnsigned6( $ip );
366 } else {
367 $n = ip2long( $ip );
368 if ( $n < 0 ) {
369 $n += pow( 2, 32 );
370 }
371 }
372 return $n;
373 }
374
375 private static function toUnsigned6( $ip ) {
376 return wfBaseConvert( self::IPv6ToRawHex( $ip ), 16, 10 );
377 }
378
379 /**
380 * Convert a network specification in CIDR notation
381 * to an integer network and a number of bits
382 *
383 * @param $range String: IP with CIDR prefix
384 * @return array(int or string, int)
385 */
386 public static function parseCIDR( $range ) {
387 if ( self::isIPv6( $range ) ) {
388 return self::parseCIDR6( $range );
389 }
390 $parts = explode( '/', $range, 2 );
391 if ( count( $parts ) != 2 ) {
392 return array( false, false );
393 }
394 list( $network, $bits ) = $parts;
395 $network = ip2long( $network );
396 if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 32 ) {
397 if ( $bits == 0 ) {
398 $network = 0;
399 } else {
400 $network &= ~( ( 1 << ( 32 - $bits ) ) - 1);
401 }
402 # Convert to unsigned
403 if ( $network < 0 ) {
404 $network += pow( 2, 32 );
405 }
406 } else {
407 $network = false;
408 $bits = false;
409 }
410 return array( $network, $bits );
411 }
412
413 /**
414 * Given a string range in a number of formats,
415 * return the start and end of the range in hexadecimal.
416 *
417 * Formats are:
418 * 1.2.3.4/24 CIDR
419 * 1.2.3.4 - 1.2.3.5 Explicit range
420 * 1.2.3.4 Single IP
421 *
422 * 2001:0db8:85a3::7344/96 CIDR
423 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
424 * 2001:0db8:85a3::7344 Single IP
425 * @param $range String: IP range
426 * @return array(string, string)
427 */
428 public static function parseRange( $range ) {
429 // CIDR notation
430 if ( strpos( $range, '/' ) !== false ) {
431 if ( self::isIPv6( $range ) ) {
432 return self::parseRange6( $range );
433 }
434 list( $network, $bits ) = self::parseCIDR( $range );
435 if ( $network === false ) {
436 $start = $end = false;
437 } else {
438 $start = sprintf( '%08X', $network );
439 $end = sprintf( '%08X', $network + pow( 2, ( 32 - $bits ) ) - 1 );
440 }
441 // Explicit range
442 } elseif ( strpos( $range, '-' ) !== false ) {
443 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
444 if ( self::isIPv6( $start ) && self::isIPv6( $end ) ) {
445 return self::parseRange6( $range );
446 }
447 if ( self::isIPv4( $start ) && self::isIPv4( $end ) ) {
448 $start = self::toUnsigned( $start );
449 $end = self::toUnsigned( $end );
450 if ( $start > $end ) {
451 $start = $end = false;
452 } else {
453 $start = sprintf( '%08X', $start );
454 $end = sprintf( '%08X', $end );
455 }
456 } else {
457 $start = $end = false;
458 }
459 } else {
460 # Single IP
461 $start = $end = self::toHex( $range );
462 }
463 if ( $start === false || $end === false ) {
464 return array( false, false );
465 } else {
466 return array( $start, $end );
467 }
468 }
469
470 /**
471 * Convert a network specification in IPv6 CIDR notation to an
472 * integer network and a number of bits
473 *
474 * @return array(string, int)
475 */
476 private static function parseCIDR6( $range ) {
477 # Explode into <expanded IP,range>
478 $parts = explode( '/', IP::sanitizeIP( $range ), 2 );
479 if ( count( $parts ) != 2 ) {
480 return array( false, false );
481 }
482 list( $network, $bits ) = $parts;
483 $network = self::IPv6ToRawHex( $network );
484 if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 128 ) {
485 if ( $bits == 0 ) {
486 $network = "0";
487 } else {
488 # Native 32 bit functions WONT work here!!!
489 # Convert to a padded binary number
490 $network = wfBaseConvert( $network, 16, 2, 128 );
491 # Truncate the last (128-$bits) bits and replace them with zeros
492 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT );
493 # Convert back to an integer
494 $network = wfBaseConvert( $network, 2, 10 );
495 }
496 } else {
497 $network = false;
498 $bits = false;
499 }
500 return array( $network, (int)$bits );
501 }
502
503 /**
504 * Given a string range in a number of formats, return the
505 * start and end of the range in hexadecimal. For IPv6.
506 *
507 * Formats are:
508 * 2001:0db8:85a3::7344/96 CIDR
509 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
510 * 2001:0db8:85a3::7344/96 Single IP
511 * @return array(string, string)
512 */
513 private static function parseRange6( $range ) {
514 # Expand any IPv6 IP
515 $range = IP::sanitizeIP( $range );
516 // CIDR notation...
517 if ( strpos( $range, '/' ) !== false ) {
518 list( $network, $bits ) = self::parseCIDR6( $range );
519 if ( $network === false ) {
520 $start = $end = false;
521 } else {
522 $start = wfBaseConvert( $network, 10, 16, 32, false );
523 # Turn network to binary (again)
524 $end = wfBaseConvert( $network, 10, 2, 128 );
525 # Truncate the last (128-$bits) bits and replace them with ones
526 $end = str_pad( substr( $end, 0, $bits ), 128, 1, STR_PAD_RIGHT );
527 # Convert to hex
528 $end = wfBaseConvert( $end, 2, 16, 32, false );
529 # see toHex() comment
530 $start = "v6-$start";
531 $end = "v6-$end";
532 }
533 // Explicit range notation...
534 } elseif ( strpos( $range, '-' ) !== false ) {
535 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
536 $start = self::toUnsigned6( $start );
537 $end = self::toUnsigned6( $end );
538 if ( $start > $end ) {
539 $start = $end = false;
540 } else {
541 $start = wfBaseConvert( $start, 10, 16, 32, false );
542 $end = wfBaseConvert( $end, 10, 16, 32, false );
543 }
544 # see toHex() comment
545 $start = "v6-$start";
546 $end = "v6-$end";
547 } else {
548 # Single IP
549 $start = $end = self::toHex( $range );
550 }
551 if ( $start === false || $end === false ) {
552 return array( false, false );
553 } else {
554 return array( $start, $end );
555 }
556 }
557
558 /**
559 * Determine if a given IPv4/IPv6 address is in a given CIDR network
560 *
561 * @param $addr String: the address to check against the given range.
562 * @param $range String: the range to check the given address against.
563 * @return Boolean: whether or not the given address is in the given range.
564 */
565 public static function isInRange( $addr, $range ) {
566 $hexIP = self::toHex( $addr );
567 list( $start, $end ) = self::parseRange( $range );
568 return ( strcmp( $hexIP, $start ) >= 0 &&
569 strcmp( $hexIP, $end ) <= 0 );
570 }
571
572 /**
573 * Convert some unusual representations of IPv4 addresses to their
574 * canonical dotted quad representation.
575 *
576 * This currently only checks a few IPV4-to-IPv6 related cases. More
577 * unusual representations may be added later.
578 *
579 * @param $addr String: something that might be an IP address
580 * @return String: valid dotted quad IPv4 address or null
581 */
582 public static function canonicalize( $addr ) {
583 if ( self::isValid( $addr ) ) {
584 return $addr;
585 }
586 // Turn mapped addresses from ::ce:ffff:1.2.3.4 to 1.2.3.4
587 if ( strpos( $addr, ':' ) !== false && strpos( $addr, '.' ) !== false ) {
588 $addr = substr( $addr, strrpos( $addr, ':' ) + 1 );
589 if ( self::isIPv4( $addr ) ) {
590 return $addr;
591 }
592 }
593 // IPv6 loopback address
594 $m = array();
595 if ( preg_match( '/^0*' . RE_IPV6_GAP . '1$/', $addr, $m ) ) {
596 return '127.0.0.1';
597 }
598 // IPv4-mapped and IPv4-compatible IPv6 addresses
599 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . '(' . RE_IP_ADD . ')$/i', $addr, $m ) ) {
600 return $m[1];
601 }
602 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . RE_IPV6_WORD .
603 ':' . RE_IPV6_WORD . '$/i', $addr, $m ) )
604 {
605 return long2ip( ( hexdec( $m[1] ) << 16 ) + hexdec( $m[2] ) );
606 }
607
608 return null; // give up
609 }
610 }