Merge remote-tracking branch 'origin/master'
[phpmyadmin.git] / libraries / ip_allow_deny.lib.php
blobecd55a7514f3ff19e82f818e378bc4cac9677786
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * This library is used with the server IP allow/deny host authentication
5 * feature
7 * @package PhpMyAdmin
8 */
9 if (! defined('PHPMYADMIN')) {
10 exit;
13 /**
14 * Gets the "true" IP address of the current user
16 * @return string the ip of the user
18 * @access private
20 function PMA_getIp()
22 /* Get the address of user */
23 if (empty($_SERVER['REMOTE_ADDR'])) {
24 /* We do not know remote IP */
25 return false;
28 $direct_ip = $_SERVER['REMOTE_ADDR'];
30 /* Do we trust this IP as a proxy? If yes we will use it's header. */
31 if (!isset($GLOBALS['cfg']['TrustedProxies'][$direct_ip])) {
32 /* Return true IP */
33 return $direct_ip;
36 $trusted_header_value
37 = PMA_getenv($GLOBALS['cfg']['TrustedProxies'][$direct_ip]);
38 $matches = array();
39 // the $ checks that the header contains only one IP address,
40 // ?: makes sure the () don't capture
41 $is_ip = preg_match(
42 '|^(?:[0-9]{1,3}\.){3,3}[0-9]{1,3}$|',
43 $trusted_header_value, $matches
46 if ($is_ip && (count($matches) == 1)) {
47 // True IP behind a proxy
48 return $matches[0];
51 /* Return true IP */
52 return $direct_ip;
53 } // end of the 'PMA_getIp()' function
56 /**
57 * Matches for IPv4 or IPv6 addresses
59 * @param string $testRange string of IP range to match
60 * @param string $ipToTest string of IP to test against range
62 * @return boolean whether the IP mask matches
64 * @access public
66 function PMA_ipMaskTest($testRange, $ipToTest)
68 if (/*overload*/mb_strpos($testRange, ':') > -1
69 || /*overload*/mb_strpos($ipToTest, ':') > -1
70 ) {
71 // assume IPv6
72 $result = PMA_ipv6MaskTest($testRange, $ipToTest);
73 } else {
74 $result = PMA_ipv4MaskTest($testRange, $ipToTest);
77 return $result;
78 } // end of the "PMA_ipMaskTest()" function
81 /**
82 * Based on IP Pattern Matcher
83 * Originally by J.Adams <jna@retina.net>
84 * Found on <http://www.php.net/manual/en/function.ip2long.php>
85 * Modified for phpMyAdmin
87 * Matches:
88 * xxx.xxx.xxx.xxx (exact)
89 * xxx.xxx.xxx.[yyy-zzz] (range)
90 * xxx.xxx.xxx.xxx/nn (CIDR)
92 * Does not match:
93 * xxx.xxx.xxx.xx[yyy-zzz] (range, partial octets not supported)
95 * @param string $testRange string of IP range to match
96 * @param string $ipToTest string of IP to test against range
98 * @return boolean whether the IP mask matches
100 * @access public
102 function PMA_ipv4MaskTest($testRange, $ipToTest)
104 $result = true;
105 $match = preg_match(
106 '|([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)/([0-9]+)|',
107 $testRange,
108 $regs
110 if ($match) {
111 // performs a mask match
112 $ipl = ip2long($ipToTest);
113 $rangel = ip2long(
114 $regs[1] . '.' . $regs[2] . '.' . $regs[3] . '.' . $regs[4]
117 $maskl = 0;
119 for ($i = 0; $i < 31; $i++) {
120 if ($i < $regs[5] - 1) {
121 $maskl = $maskl + PMA_Util::pow(2, (30 - $i));
122 } // end if
123 } // end for
125 if (($maskl & $rangel) == ($maskl & $ipl)) {
126 return true;
129 return false;
132 // range based
133 $maskocts = explode('.', $testRange);
134 $ipocts = explode('.', $ipToTest);
136 // perform a range match
137 for ($i = 0; $i < 4; $i++) {
138 if (preg_match('|\[([0-9]+)\-([0-9]+)\]|', $maskocts[$i], $regs)) {
139 if (($ipocts[$i] > $regs[2]) || ($ipocts[$i] < $regs[1])) {
140 $result = false;
141 } // end if
142 } else {
143 if ($maskocts[$i] <> $ipocts[$i]) {
144 $result = false;
145 } // end if
146 } // end if/else
147 } //end for
149 return $result;
150 } // end of the "PMA_ipv4MaskTest()" function
154 * IPv6 matcher
155 * CIDR section taken from http://stackoverflow.com/a/10086404
156 * Modified for phpMyAdmin
158 * Matches:
159 * xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
160 * (exact)
161 * xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:[yyyy-zzzz]
162 * (range, only at end of IP - no subnets)
163 * xxxx:xxxx:xxxx:xxxx/nn
164 * (CIDR)
166 * Does not match:
167 * xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xx[yyy-zzz]
168 * (range, partial octets not supported)
170 * @param string $test_range string of IP range to match
171 * @param string $ip_to_test string of IP to test against range
173 * @return boolean whether the IP mask matches
175 * @access public
177 function PMA_ipv6MaskTest($test_range, $ip_to_test)
179 $result = true;
181 // convert to lowercase for easier comparison
182 $test_range = /*overload*/mb_strtolower($test_range);
183 $ip_to_test = /*overload*/mb_strtolower($ip_to_test);
185 $is_cidr = /*overload*/mb_strpos($test_range, '/') > -1;
186 $is_range = /*overload*/mb_strpos($test_range, '[') > -1;
187 $is_single = ! $is_cidr && ! $is_range;
189 $ip_hex = bin2hex(inet_pton($ip_to_test));
191 if ($is_single) {
192 $range_hex = bin2hex(inet_pton($test_range));
193 $result = $ip_hex === $range_hex;
194 return $result;
197 if ($is_range) {
198 // what range do we operate on?
199 $range_match = array();
200 $match = preg_match(
201 '/\[([0-9a-f]+)\-([0-9a-f]+)\]/', $test_range, $range_match
203 if ($match) {
204 $range_start = $range_match[1];
205 $range_end = $range_match[2];
207 // get the first and last allowed IPs
208 $first_ip = str_replace($range_match[0], $range_start, $test_range);
209 $first_hex = bin2hex(inet_pton($first_ip));
210 $last_ip = str_replace($range_match[0], $range_end, $test_range);
211 $last_hex = bin2hex(inet_pton($last_ip));
213 // check if the IP to test is within the range
214 $result = ($ip_hex >= $first_hex && $ip_hex <= $last_hex);
216 return $result;
219 if ($is_cidr) {
220 // Split in address and prefix length
221 list($first_ip, $subnet) = explode('/', $test_range);
223 // Parse the address into a binary string
224 $first_bin = inet_pton($first_ip);
225 $first_hex = bin2hex($first_bin);
227 $flexbits = 128 - $subnet;
229 // Build the hexadecimal string of the last address
230 $last_hex = $first_hex;
232 $pos = 31;
233 while ($flexbits > 0) {
234 // Get the character at this position
235 $orig = /*overload*/mb_substr($last_hex, $pos, 1);
237 // Convert it to an integer
238 $origval = hexdec($orig);
240 // OR it with (2^flexbits)-1, with flexbits limited to 4 at a time
241 $newval = $origval | (pow(2, min(4, $flexbits)) - 1);
243 // Convert it back to a hexadecimal character
244 $new = dechex($newval);
246 // And put that character back in the string
247 $last_hex = substr_replace($last_hex, $new, $pos, 1);
249 // We processed one nibble, move to previous position
250 $flexbits -= 4;
251 $pos -= 1;
254 // check if the IP to test is within the range
255 $result = ($ip_hex >= $first_hex && $ip_hex <= $last_hex);
258 return $result;
259 } // end of the "PMA_ipv6MaskTest()" function
263 * Runs through IP Allow/Deny rules the use of it below for more information
265 * @param string $type 'allow' | 'deny' type of rule to match
267 * @return bool Matched a rule ?
269 * @access public
271 * @see PMA_getIp()
273 function PMA_allowDeny($type)
275 global $cfg;
277 // Grabs true IP of the user and returns if it can't be found
278 $remote_ip = PMA_getIp();
279 if (empty($remote_ip)) {
280 return false;
283 // copy username
284 $username = $cfg['Server']['user'];
286 // copy rule database
287 $rules = $cfg['Server']['AllowDeny']['rules'];
289 // lookup table for some name shortcuts
290 $shortcuts = array(
291 'all' => '0.0.0.0/0',
292 'localhost' => '127.0.0.1/8'
295 // Provide some useful shortcuts if server gives us address:
296 if (PMA_getenv('SERVER_ADDR')) {
297 $shortcuts['localnetA'] = PMA_getenv('SERVER_ADDR') . '/8';
298 $shortcuts['localnetB'] = PMA_getenv('SERVER_ADDR') . '/16';
299 $shortcuts['localnetC'] = PMA_getenv('SERVER_ADDR') . '/24';
302 foreach ($rules as $rule) {
303 // extract rule data
304 $rule_data = explode(' ', $rule);
306 // check for rule type
307 if ($rule_data[0] != $type) {
308 continue;
311 // check for username
312 if (($rule_data[1] != '%') //wildcarded first
313 && ($rule_data[1] != $username)
315 continue;
318 // check if the config file has the full string with an extra
319 // 'from' in it and if it does, just discard it
320 if ($rule_data[2] == 'from') {
321 $rule_data[2] = $rule_data[3];
324 // Handle shortcuts with above array
325 if (isset($shortcuts[$rule_data[2]])) {
326 $rule_data[2] = $shortcuts[$rule_data[2]];
329 // Add code for host lookups here
330 // Excluded for the moment
332 // Do the actual matching now
333 if (PMA_ipMaskTest($rule_data[2], $remote_ip)) {
334 return true;
336 } // end while
338 return false;
339 } // end of the "PMA_AllowDeny()" function