IpAllowDeny.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. <?php
  2. /**
  3. * This library is used with the server IP allow/deny host authentication
  4. * feature
  5. */
  6. declare(strict_types=1);
  7. namespace PhpMyAdmin;
  8. use function bin2hex;
  9. use function dechex;
  10. use function explode;
  11. use function hash_equals;
  12. use function hexdec;
  13. use function inet_pton;
  14. use function ip2long;
  15. use function is_array;
  16. use function mb_strpos;
  17. use function mb_strtolower;
  18. use function mb_substr;
  19. use function min;
  20. use function pow;
  21. use function preg_match;
  22. use function str_replace;
  23. use function substr_replace;
  24. /**
  25. * PhpMyAdmin\IpAllowDeny class
  26. */
  27. class IpAllowDeny
  28. {
  29. /**
  30. * Matches for IPv4 or IPv6 addresses
  31. *
  32. * @param string $testRange string of IP range to match
  33. * @param string $ipToTest string of IP to test against range
  34. *
  35. * @return bool whether the IP mask matches
  36. *
  37. * @access public
  38. */
  39. public function ipMaskTest($testRange, $ipToTest)
  40. {
  41. if (mb_strpos($testRange, ':') > -1
  42. || mb_strpos($ipToTest, ':') > -1
  43. ) {
  44. // assume IPv6
  45. $result = $this->ipv6MaskTest($testRange, $ipToTest);
  46. } else {
  47. $result = $this->ipv4MaskTest($testRange, $ipToTest);
  48. }
  49. return $result;
  50. }
  51. /**
  52. * Based on IP Pattern Matcher
  53. * Originally by J.Adams <jna@retina.net>
  54. * Found on <https://www.php.net/manual/en/function.ip2long.php>
  55. * Modified for phpMyAdmin
  56. *
  57. * Matches:
  58. * xxx.xxx.xxx.xxx (exact)
  59. * xxx.xxx.xxx.[yyy-zzz] (range)
  60. * xxx.xxx.xxx.xxx/nn (CIDR)
  61. *
  62. * Does not match:
  63. * xxx.xxx.xxx.xx[yyy-zzz] (range, partial octets not supported)
  64. *
  65. * @param string $testRange string of IP range to match
  66. * @param string $ipToTest string of IP to test against range
  67. *
  68. * @return bool whether the IP mask matches
  69. *
  70. * @access public
  71. */
  72. public function ipv4MaskTest($testRange, $ipToTest)
  73. {
  74. $result = true;
  75. $match = preg_match(
  76. '|([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)/([0-9]+)|',
  77. $testRange,
  78. $regs
  79. );
  80. if ($match) {
  81. // performs a mask match
  82. $ipl = ip2long($ipToTest);
  83. $rangel = ip2long(
  84. $regs[1] . '.' . $regs[2] . '.' . $regs[3] . '.' . $regs[4]
  85. );
  86. $maskl = 0;
  87. for ($i = 0; $i < 31; $i++) {
  88. if ($i >= $regs[5] - 1) {
  89. continue;
  90. }
  91. $maskl += pow(2, 30 - $i);
  92. }
  93. return ($maskl & $rangel) == ($maskl & $ipl);
  94. }
  95. // range based
  96. $maskocts = explode('.', $testRange);
  97. $ipocts = explode('.', $ipToTest);
  98. // perform a range match
  99. for ($i = 0; $i < 4; $i++) {
  100. if (preg_match('|\[([0-9]+)\-([0-9]+)\]|', $maskocts[$i], $regs)) {
  101. if (($ipocts[$i] > $regs[2]) || ($ipocts[$i] < $regs[1])) {
  102. $result = false;
  103. }
  104. } else {
  105. if ($maskocts[$i] <> $ipocts[$i]) {
  106. $result = false;
  107. }
  108. }
  109. }
  110. return $result;
  111. }
  112. /**
  113. * IPv6 matcher
  114. * CIDR section taken from https://stackoverflow.com/a/10086404
  115. * Modified for phpMyAdmin
  116. *
  117. * Matches:
  118. * xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
  119. * (exact)
  120. * xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:[yyyy-zzzz]
  121. * (range, only at end of IP - no subnets)
  122. * xxxx:xxxx:xxxx:xxxx/nn
  123. * (CIDR)
  124. *
  125. * Does not match:
  126. * xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xx[yyy-zzz]
  127. * (range, partial octets not supported)
  128. *
  129. * @param string $test_range string of IP range to match
  130. * @param string $ip_to_test string of IP to test against range
  131. *
  132. * @return bool whether the IP mask matches
  133. *
  134. * @access public
  135. */
  136. public function ipv6MaskTest($test_range, $ip_to_test)
  137. {
  138. $result = true;
  139. // convert to lowercase for easier comparison
  140. $test_range = mb_strtolower($test_range);
  141. $ip_to_test = mb_strtolower($ip_to_test);
  142. $is_cidr = mb_strpos($test_range, '/') > -1;
  143. $is_range = mb_strpos($test_range, '[') > -1;
  144. $is_single = ! $is_cidr && ! $is_range;
  145. $ip_hex = bin2hex((string) inet_pton($ip_to_test));
  146. if ($is_single) {
  147. $range_hex = bin2hex((string) inet_pton($test_range));
  148. return hash_equals($ip_hex, $range_hex);
  149. }
  150. if ($is_range) {
  151. // what range do we operate on?
  152. $range_match = [];
  153. $match = preg_match(
  154. '/\[([0-9a-f]+)\-([0-9a-f]+)\]/',
  155. $test_range,
  156. $range_match
  157. );
  158. if ($match) {
  159. $range_start = $range_match[1];
  160. $range_end = $range_match[2];
  161. // get the first and last allowed IPs
  162. $first_ip = str_replace($range_match[0], $range_start, $test_range);
  163. $first_hex = bin2hex((string) inet_pton($first_ip));
  164. $last_ip = str_replace($range_match[0], $range_end, $test_range);
  165. $last_hex = bin2hex((string) inet_pton($last_ip));
  166. // check if the IP to test is within the range
  167. $result = ($ip_hex >= $first_hex && $ip_hex <= $last_hex);
  168. }
  169. return $result;
  170. }
  171. if ($is_cidr) {
  172. // Split in address and prefix length
  173. [$first_ip, $subnet] = explode('/', $test_range);
  174. // Parse the address into a binary string
  175. $first_bin = inet_pton($first_ip);
  176. $first_hex = bin2hex((string) $first_bin);
  177. $flexbits = 128 - (int) $subnet;
  178. // Build the hexadecimal string of the last address
  179. $last_hex = $first_hex;
  180. $pos = 31;
  181. while ($flexbits > 0) {
  182. // Get the character at this position
  183. $orig = mb_substr($last_hex, $pos, 1);
  184. // Convert it to an integer
  185. $origval = hexdec($orig);
  186. // OR it with (2^flexbits)-1, with flexbits limited to 4 at a time
  187. $newval = $origval | pow(2, min(4, $flexbits)) - 1;
  188. // Convert it back to a hexadecimal character
  189. $new = dechex($newval);
  190. // And put that character back in the string
  191. $last_hex = substr_replace($last_hex, $new, $pos, 1);
  192. // We processed one nibble, move to previous position
  193. $flexbits -= 4;
  194. --$pos;
  195. }
  196. // check if the IP to test is within the range
  197. $result = ($ip_hex >= $first_hex && $ip_hex <= $last_hex);
  198. }
  199. return $result;
  200. }
  201. /**
  202. * Runs through IP Allow rules the use of it below for more information
  203. *
  204. * @see Core::getIp()
  205. *
  206. * @return bool Whether rule has matched
  207. *
  208. * @access public
  209. */
  210. public function allow()
  211. {
  212. return $this->allowDeny('allow');
  213. }
  214. /**
  215. * Runs through IP Deny rules the use of it below for more information
  216. *
  217. * @see Core::getIp()
  218. *
  219. * @return bool Whether rule has matched
  220. *
  221. * @access public
  222. */
  223. public function deny()
  224. {
  225. return $this->allowDeny('deny');
  226. }
  227. /**
  228. * Runs through IP Allow/Deny rules the use of it below for more information
  229. *
  230. * @see Core::getIp()
  231. *
  232. * @param string $type 'allow' | 'deny' type of rule to match
  233. *
  234. * @return bool Whether rule has matched
  235. *
  236. * @access public
  237. */
  238. private function allowDeny($type)
  239. {
  240. global $cfg;
  241. // Grabs true IP of the user and returns if it can't be found
  242. $remote_ip = Core::getIp();
  243. if (empty($remote_ip)) {
  244. return false;
  245. }
  246. // copy username
  247. $username = $cfg['Server']['user'];
  248. // copy rule database
  249. if (isset($cfg['Server']['AllowDeny']['rules'])) {
  250. $rules = $cfg['Server']['AllowDeny']['rules'];
  251. if (! is_array($rules)) {
  252. $rules = [];
  253. }
  254. } else {
  255. $rules = [];
  256. }
  257. // lookup table for some name shortcuts
  258. $shortcuts = [
  259. 'all' => '0.0.0.0/0',
  260. 'localhost' => '127.0.0.1/8',
  261. ];
  262. // Provide some useful shortcuts if server gives us address:
  263. if (Core::getenv('SERVER_ADDR')) {
  264. $shortcuts['localnetA'] = Core::getenv('SERVER_ADDR') . '/8';
  265. $shortcuts['localnetB'] = Core::getenv('SERVER_ADDR') . '/16';
  266. $shortcuts['localnetC'] = Core::getenv('SERVER_ADDR') . '/24';
  267. }
  268. foreach ($rules as $rule) {
  269. // extract rule data
  270. $rule_data = explode(' ', $rule);
  271. // check for rule type
  272. if ($rule_data[0] != $type) {
  273. continue;
  274. }
  275. // check for username
  276. if (($rule_data[1] !== '%') //wildcarded first
  277. && (! hash_equals($rule_data[1], $username))
  278. ) {
  279. continue;
  280. }
  281. // check if the config file has the full string with an extra
  282. // 'from' in it and if it does, just discard it
  283. if ($rule_data[2] === 'from') {
  284. $rule_data[2] = $rule_data[3];
  285. }
  286. // Handle shortcuts with above array
  287. if (isset($shortcuts[$rule_data[2]])) {
  288. $rule_data[2] = $shortcuts[$rule_data[2]];
  289. }
  290. // Add code for host lookups here
  291. // Excluded for the moment
  292. // Do the actual matching now
  293. if ($this->ipMaskTest($rule_data[2], $remote_ip)) {
  294. return true;
  295. }
  296. }
  297. return false;
  298. }
  299. }