Adding some validation for IP determination via XFF headers, in preparation for addin...
[lhc/web/wiklou.git] / includes / ProxyTools.php
1 <?php
2
3 if ( !defined( 'MEDIAWIKI' ) ) {
4 die();
5 }
6
7 /**
8 * Functions for dealing with proxies
9 */
10
11
12 /**
13 * Work out the IP address based on various globals
14 */
15 function wfGetIP()
16 {
17 global $wgSquidServers, $wgSquidServersNoPurge;
18
19 /* collect the originating ips */
20 # Client connecting to this webserver
21 if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
22 $ipchain = array( $_SERVER['REMOTE_ADDR'] );
23 } else {
24 # Running on CLI?
25 $ipchain = array( '127.0.0.1' );
26 }
27 $ip = $ipchain[0];
28
29 # Get list of trusted proxies
30 # Flipped for quicker access
31 $trustedProxies = array_flip( array_merge( $wgSquidServers, $wgSquidServersNoPurge ) );
32 if ( count( $trustedProxies ) ) {
33 # Append XFF on to $ipchain
34 if ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
35 $ipchain = array_merge( $ipchain, array_map( 'trim', explode( ',', $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) );
36 }
37 # Step through XFF list and find the last address in the list which is a trusted server
38 # Set $ip to the IP address given by that trusted server, unless the address is not sensible (e.g. private)
39 foreach ( $ipchain as $i => $curIP ) {
40 if ( array_key_exists( $curIP, $trustedProxies ) ) {
41 if ( isset( $ipchain[$i + 1] ) && wfIsIPPublic( $ipchain[$i + 1] ) ) {
42 $ip = $ipchain[$i + 1];
43 }
44 } else {
45 break;
46 }
47 }
48 }
49
50 return $ip;
51 }
52
53 function wfIP2Unsigned( $ip )
54 {
55 $n = ip2long( $ip );
56 if ( $n == -1 ) {
57 $n = false;
58 } elseif ( $n < 0 ) {
59 $n += pow( 2, 32 );
60 }
61 return $n;
62 }
63
64 /**
65 * Determine if an IP address really is an IP address, and if it is public,
66 * i.e. not RFC 1918 or similar
67 */
68 function wfIsIPPublic( $ip )
69 {
70 $n = wfIP2Unsigned( $ip );
71 if ( !$n ) {
72 return false;
73 }
74
75 static $privateRanges = false;
76 if ( !$privateRanges ) {
77 $privateRanges = array(
78 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
79 array( '172.16.0.0', '172.31.255.255' ), # "
80 array( '192.168.0.0', '192.168.255.255' ), # "
81 array( '0.0.0.0', '0.255.255.255' ), # this network
82 array( '127.0.0.0', '127.255.255.255' ), # loopback
83 );
84 }
85
86 foreach ( $privateRanges as $r ) {
87 $start = wfIP2Unsigned( $r[0] );
88 $end = wfIP2Unsigned( $r[1] );
89 if ( $n >= $start && $n <= $end ) {
90 return false;
91 }
92 }
93 return true;
94 }
95
96 ?>