Refactored ConfigFile class so that it is no longer a singleton
[phpmyadmin.git] / libraries / ip_allow_deny.lib.php
blob86a88ed6e296b4ef3e49567fbae891118bd69840
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 $direct_ip = $_SERVER['REMOTE_ADDR'];
25 } else {
26 /* We do not know remote IP */
27 return false;
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 $trusted_header_value
33 = PMA_getenv($GLOBALS['cfg']['TrustedProxies'][$direct_ip]);
34 $matches = array();
35 // the $ checks that the header contains only one IP address,
36 // ?: makes sure the () don't capture
37 $is_ip = preg_match(
38 '|^(?:[0-9]{1,3}\.){3,3}[0-9]{1,3}$|',
39 $trusted_header_value, $matches
41 if ($is_ip && (count($matches) == 1)) {
42 // True IP behind a proxy
43 return $matches[0];
47 /* Return true IP */
48 return $direct_ip;
49 } // end of the 'PMA_getIp()' function
52 /**
53 * Matches for IPv4 or IPv6 addresses
55 * @param string $testRange string of IP range to match
56 * @param string $ipToTest string of IP to test against range
58 * @return boolean whether the IP mask matches
60 * @access public
62 function PMA_ipMaskTest($testRange, $ipToTest)
64 $result = true;
66 if (strpos($testRange, ':') > -1 || strpos($ipToTest, ':') > -1) {
67 // assume IPv6
68 $result = PMA_ipv6MaskTest($testRange, $ipToTest);
69 } else {
70 $result = PMA_ipv4MaskTest($testRange, $ipToTest);
73 return $result;
74 } // end of the "PMA_ipMaskTest()" function
77 /**
78 * Based on IP Pattern Matcher
79 * Originally by J.Adams <jna@retina.net>
80 * Found on <http://www.php.net/manual/en/function.ip2long.php>
81 * Modified for phpMyAdmin
83 * Matches:
84 * xxx.xxx.xxx.xxx (exact)
85 * xxx.xxx.xxx.[yyy-zzz] (range)
86 * xxx.xxx.xxx.xxx/nn (CIDR)
88 * Does not match:
89 * xxx.xxx.xxx.xx[yyy-zzz] (range, partial octets not supported)
91 * @param string $testRange string of IP range to match
92 * @param string $ipToTest string of IP to test against range
94 * @return boolean whether the IP mask matches
96 * @access public
98 function PMA_ipv4MaskTest($testRange, $ipToTest)
100 $result = true;
101 $match = preg_match(
102 '|([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)/([0-9]+)|',
103 $testRange,
104 $regs
106 if ($match) {
107 // performs a mask match
108 $ipl = ip2long($ipToTest);
109 $rangel = ip2long(
110 $regs[1] . '.' . $regs[2] . '.' . $regs[3] . '.' . $regs[4]
113 $maskl = 0;
115 for ($i = 0; $i < 31; $i++) {
116 if ($i < $regs[5] - 1) {
117 $maskl = $maskl + PMA_Util::pow(2, (30 - $i));
118 } // end if
119 } // end for
121 if (($maskl & $rangel) == ($maskl & $ipl)) {
122 return true;
123 } else {
124 return false;
126 } else {
127 // range based
128 $maskocts = explode('.', $testRange);
129 $ipocts = explode('.', $ipToTest);
131 // perform a range match
132 for ($i = 0; $i < 4; $i++) {
133 if (preg_match('|\[([0-9]+)\-([0-9]+)\]|', $maskocts[$i], $regs)) {
134 if (($ipocts[$i] > $regs[2]) || ($ipocts[$i] < $regs[1])) {
135 $result = false;
136 } // end if
137 } else {
138 if ($maskocts[$i] <> $ipocts[$i]) {
139 $result = false;
140 } // end if
141 } // end if/else
142 } //end for
143 } //end if/else
145 return $result;
146 } // end of the "PMA_ipv4MaskTest()" function
150 * IPv6 matcher
151 * CIDR section taken from http://stackoverflow.com/a/10086404
152 * Modified for phpMyAdmin
154 * Matches:
155 * xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
156 * (exact)
157 * xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:[yyyy-zzzz]
158 * (range, only at end of IP - no subnets)
159 * xxxx:xxxx:xxxx:xxxx/nn
160 * (CIDR)
162 * Does not match:
163 * xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xx[yyy-zzz]
164 * (range, partial octets not supported)
166 * @param string $test_range string of IP range to match
167 * @param string $ip_to_test string of IP to test against range
169 * @return boolean whether the IP mask matches
171 * @access public
173 function PMA_ipv6MaskTest($test_range, $ip_to_test)
175 $result = true;
177 // convert to lowercase for easier comparison
178 $test_range = strtolower($test_range);
179 $ip_to_test = strtolower($ip_to_test);
181 $is_cidr = strpos($test_range, '/') > -1;
182 $is_range = strpos($test_range, '[') > -1;
183 $is_single = ! $is_cidr && ! $is_range;
185 $ip_hex = bin2hex(inet_pton($ip_to_test));
187 if ($is_single) {
188 $range_hex = bin2hex(inet_pton($test_range));
189 $result = $ip_hex === $range_hex;
190 } elseif ($is_range) {
191 // what range do we operate on?
192 $range_match = array();
193 $match = preg_match(
194 '/\[([0-9a-f]+)\-([0-9a-f]+)\]/', $test_range, $range_match
196 if ($match) {
197 $range_start = $range_match[1];
198 $range_end = $range_match[2];
200 // get the first and last allowed IPs
201 $first_ip = str_replace($range_match[0], $range_start, $test_range);
202 $first_hex = bin2hex(inet_pton($first_ip));
203 $last_ip = str_replace($range_match[0], $range_end, $test_range);
204 $last_hex = bin2hex(inet_pton($last_ip));
206 // check if the IP to test is within the range
207 $result = ($ip_hex >= $first_hex && $ip_hex <= $last_hex);
209 } elseif ($is_cidr) {
210 // Split in address and prefix length
211 list($first_ip, $subnet) = explode('/', $test_range);
213 // Parse the address into a binary string
214 $first_bin = inet_pton($first_ip);
215 $first_hex = bin2hex($first_bin);
217 // Overwriting first address string to make sure notation is optimal
218 $first_ip = inet_ntop($first_bin);
220 $flexbits = 128 - $subnet;
222 // Build the hexadecimal string of the last address
223 $last_hex = $first_hex;
225 $pos = 31;
226 while ($flexbits > 0) {
227 // Get the character at this position
228 $orig = substr($last_hex, $pos, 1);
230 // Convert it to an integer
231 $origval = hexdec($orig);
233 // OR it with (2^flexbits)-1, with flexbits limited to 4 at a time
234 $newval = $origval | (pow(2, min(4, $flexbits)) - 1);
236 // Convert it back to a hexadecimal character
237 $new = dechex($newval);
239 // And put that character back in the string
240 $last_hex = substr_replace($last_hex, $new, $pos, 1);
242 // We processed one nibble, move to previous position
243 $flexbits -= 4;
244 $pos -= 1;
247 // check if the IP to test is within the range
248 $result = ($ip_hex >= $first_hex && $ip_hex <= $last_hex);
251 return $result;
252 } // end of the "PMA_ipv6MaskTest()" function
256 * Runs through IP Allow/Deny rules the use of it below for more information
258 * @param string $type 'allow' | 'deny' type of rule to match
260 * @return bool Matched a rule ?
262 * @access public
264 * @see PMA_getIp()
266 function PMA_allowDeny($type)
268 global $cfg;
270 // Grabs true IP of the user and returns if it can't be found
271 $remote_ip = PMA_getIp();
272 if (empty($remote_ip)) {
273 return false;
276 // copy username
277 $username = $cfg['Server']['user'];
279 // copy rule database
280 $rules = $cfg['Server']['AllowDeny']['rules'];
282 // lookup table for some name shortcuts
283 $shortcuts = array(
284 'all' => '0.0.0.0/0',
285 'localhost' => '127.0.0.1/8'
288 // Provide some useful shortcuts if server gives us address:
289 if (PMA_getenv('SERVER_ADDR')) {
290 $shortcuts['localnetA'] = PMA_getenv('SERVER_ADDR') . '/8';
291 $shortcuts['localnetB'] = PMA_getenv('SERVER_ADDR') . '/16';
292 $shortcuts['localnetC'] = PMA_getenv('SERVER_ADDR') . '/24';
295 foreach ($rules as $rule) {
296 // extract rule data
297 $rule_data = explode(' ', $rule);
299 // check for rule type
300 if ($rule_data[0] != $type) {
301 continue;
304 // check for username
305 if (($rule_data[1] != '%') //wildcarded first
306 && ($rule_data[1] != $username)
308 continue;
311 // check if the config file has the full string with an extra
312 // 'from' in it and if it does, just discard it
313 if ($rule_data[2] == 'from') {
314 $rule_data[2] = $rule_data[3];
317 // Handle shortcuts with above array
318 if (isset($shortcuts[$rule_data[2]])) {
319 $rule_data[2] = $shortcuts[$rule_data[2]];
322 // Add code for host lookups here
323 // Excluded for the moment
325 // Do the actual matching now
326 if (PMA_ipMaskTest($rule_data[2], $remote_ip)) {
327 return true;
329 } // end while
331 return false;
332 } // end of the "PMA_AllowDeny()" function