Teknik is a suite of services with attractive and functional interfaces. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

IP.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. <?php
  2. /**
  3. * Piwik - free/libre analytics platform
  4. *
  5. * @link http://piwik.org
  6. * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
  7. *
  8. */
  9. namespace Piwik;
  10. /**
  11. * Contains IP address helper functions (for both IPv4 and IPv6).
  12. *
  13. * As of Piwik 1.3, IP addresses are stored in the DB has VARBINARY(16),
  14. * and passed around in network address format which has the advantage of
  15. * being in big-endian byte order. This allows for binary-safe string
  16. * comparison of addresses (of the same length), even on Intel x86.
  17. *
  18. * As a matter of naming convention, we use `$ip` for the network address format
  19. * and `$ipString` for the presentation format (i.e., human-readable form).
  20. *
  21. * We're not using the network address format (in_addr) for socket functions,
  22. * so we don't have to worry about incompatibility with Windows UNICODE
  23. * and inetPtonW().
  24. *
  25. * @api
  26. */
  27. class IP
  28. {
  29. const MAPPED_IPv4_START = '::ffff:';
  30. /**
  31. * Removes the port and the last portion of a CIDR IP address.
  32. *
  33. * @param string $ipString The IP address to sanitize.
  34. * @return string
  35. */
  36. public static function sanitizeIp($ipString)
  37. {
  38. $ipString = trim($ipString);
  39. // CIDR notation, A.B.C.D/E
  40. $posSlash = strrpos($ipString, '/');
  41. if ($posSlash !== false) {
  42. $ipString = substr($ipString, 0, $posSlash);
  43. }
  44. $posColon = strrpos($ipString, ':');
  45. $posDot = strrpos($ipString, '.');
  46. if ($posColon !== false) {
  47. // IPv6 address with port, [A:B:C:D:E:F:G:H]:EEEE
  48. $posRBrac = strrpos($ipString, ']');
  49. if ($posRBrac !== false && $ipString[0] == '[') {
  50. $ipString = substr($ipString, 1, $posRBrac - 1);
  51. }
  52. if ($posDot !== false) {
  53. // IPv4 address with port, A.B.C.D:EEEE
  54. if ($posColon > $posDot) {
  55. $ipString = substr($ipString, 0, $posColon);
  56. }
  57. // else: Dotted quad IPv6 address, A:B:C:D:E:F:G.H.I.J
  58. } else if (strpos($ipString, ':') === $posColon) {
  59. $ipString = substr($ipString, 0, $posColon);
  60. }
  61. // else: IPv6 address, A:B:C:D:E:F:G:H
  62. }
  63. // else: IPv4 address, A.B.C.D
  64. return $ipString;
  65. }
  66. /**
  67. * Sanitize human-readable (user-supplied) IP address range.
  68. *
  69. * Accepts the following formats for $ipRange:
  70. * - single IPv4 address, e.g., 127.0.0.1
  71. * - single IPv6 address, e.g., ::1/128
  72. * - IPv4 block using CIDR notation, e.g., 192.168.0.0/22 represents the IPv4 addresses from 192.168.0.0 to 192.168.3.255
  73. * - IPv6 block using CIDR notation, e.g., 2001:DB8::/48 represents the IPv6 addresses from 2001:DB8:0:0:0:0:0:0 to 2001:DB8:0:FFFF:FFFF:FFFF:FFFF:FFFF
  74. * - wildcards, e.g., 192.168.0.*
  75. *
  76. * @param string $ipRangeString IP address range
  77. * @return string|bool IP address range in CIDR notation OR false
  78. */
  79. public static function sanitizeIpRange($ipRangeString)
  80. {
  81. $ipRangeString = trim($ipRangeString);
  82. if (empty($ipRangeString)) {
  83. return false;
  84. }
  85. // IPv4 address with wildcards '*'
  86. if (strpos($ipRangeString, '*') !== false) {
  87. if (preg_match('~(^|\.)\*\.\d+(\.|$)~D', $ipRangeString)) {
  88. return false;
  89. }
  90. $bits = 32 - 8 * substr_count($ipRangeString, '*');
  91. $ipRangeString = str_replace('*', '0', $ipRangeString);
  92. }
  93. // CIDR
  94. if (($pos = strpos($ipRangeString, '/')) !== false) {
  95. $bits = substr($ipRangeString, $pos + 1);
  96. $ipRangeString = substr($ipRangeString, 0, $pos);
  97. }
  98. // single IP
  99. if (($ip = @inet_pton($ipRangeString)) === false)
  100. return false;
  101. $maxbits = strlen($ip) * 8;
  102. if (!isset($bits))
  103. $bits = $maxbits;
  104. if ($bits < 0 || $bits > $maxbits) {
  105. return false;
  106. }
  107. return "$ipRangeString/$bits";
  108. }
  109. /**
  110. * Converts an IP address in presentation format to network address format.
  111. *
  112. * @param string $ipString IP address, either IPv4 or IPv6, e.g., `"127.0.0.1"`.
  113. * @return string Binary-safe string, e.g., `"\x7F\x00\x00\x01"`.
  114. */
  115. public static function P2N($ipString)
  116. {
  117. // use @inet_pton() because it throws an exception and E_WARNING on invalid input
  118. $ip = @inet_pton($ipString);
  119. return $ip === false ? "\x00\x00\x00\x00" : $ip;
  120. }
  121. /**
  122. * Convert network address format to presentation format.
  123. *
  124. * See also {@link prettyPrint()}.
  125. *
  126. * @param string $ip IP address in network address format.
  127. * @return string IP address in presentation format.
  128. */
  129. public static function N2P($ip)
  130. {
  131. // use @inet_ntop() because it throws an exception and E_WARNING on invalid input
  132. $ipStr = @inet_ntop($ip);
  133. return $ipStr === false ? '0.0.0.0' : $ipStr;
  134. }
  135. /**
  136. * Alias for {@link N2P()}.
  137. *
  138. * @param string $ip IP address in network address format.
  139. * @return string IP address in presentation format.
  140. */
  141. public static function prettyPrint($ip)
  142. {
  143. return self::N2P($ip);
  144. }
  145. /**
  146. * Returns true if `$ip` is an IPv4, IPv4-compat, or IPv4-mapped address, false
  147. * if otherwise.
  148. *
  149. * @param string $ip IP address in network address format.
  150. * @return bool True if IPv4, else false.
  151. */
  152. public static function isIPv4($ip)
  153. {
  154. // in case mbstring overloads strlen function
  155. $strlen = function_exists('mb_orig_strlen') ? 'mb_orig_strlen' : 'strlen';
  156. // IPv4
  157. if ($strlen($ip) == 4) {
  158. return true;
  159. }
  160. // IPv6 - transitional address?
  161. if ($strlen($ip) == 16) {
  162. if (substr_compare($ip, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff", 0, 12) === 0
  163. || substr_compare($ip, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 0, 12) === 0
  164. ) {
  165. return true;
  166. }
  167. }
  168. return false;
  169. }
  170. /**
  171. * Converts an IP address (in network address format) to presentation format.
  172. * This is a backward compatibility function for code that only expects
  173. * IPv4 addresses (i.e., doesn't support IPv6).
  174. *
  175. * This function does not support the long (or its string representation)
  176. * returned by the built-in ip2long() function, from Piwik 1.3 and earlier.
  177. *
  178. * @param string $ip IPv4 address in network address format.
  179. * @return string IP address in presentation format.
  180. */
  181. public static function long2ip($ip)
  182. {
  183. // IPv4
  184. if (strlen($ip) == 4) {
  185. return self::N2P($ip);
  186. }
  187. // IPv6 - transitional address?
  188. if (strlen($ip) == 16) {
  189. if (substr_compare($ip, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff", 0, 12) === 0
  190. || substr_compare($ip, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 0, 12) === 0
  191. ) {
  192. // remap 128-bit IPv4-mapped and IPv4-compat addresses
  193. return self::N2P(substr($ip, 12));
  194. }
  195. }
  196. return '0.0.0.0';
  197. }
  198. /**
  199. * Returns true if $ip is an IPv6 address, false if otherwise. This function does
  200. * a naive check. It assumes that whatever format $ip is in, it is well-formed.
  201. *
  202. * @param string $ip
  203. * @return bool
  204. */
  205. public static function isIPv6($ip)
  206. {
  207. return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
  208. }
  209. /**
  210. * Returns true if $ip is a IPv4 mapped address, false if otherwise.
  211. *
  212. * @param string $ip
  213. * @return bool
  214. */
  215. public static function isMappedIPv4($ip)
  216. {
  217. return substr($ip, 0, strlen(self::MAPPED_IPv4_START)) === self::MAPPED_IPv4_START;
  218. }
  219. /**
  220. * Returns an IPv4 address from a 'mapped' IPv6 address.
  221. *
  222. * @param string $ip eg, `'::ffff:192.0.2.128'`
  223. * @return string eg, `'192.0.2.128'`
  224. */
  225. public static function getIPv4FromMappedIPv6($ip)
  226. {
  227. return substr($ip, strlen(self::MAPPED_IPv4_START));
  228. }
  229. /**
  230. * Get low and high IP addresses for a specified range.
  231. *
  232. * @param array $ipRange An IP address range in presentation format.
  233. * @return array|bool Array `array($lowIp, $highIp)` in network address format, or false on failure.
  234. */
  235. public static function getIpsForRange($ipRange)
  236. {
  237. if (strpos($ipRange, '/') === false) {
  238. $ipRange = self::sanitizeIpRange($ipRange);
  239. }
  240. $pos = strpos($ipRange, '/');
  241. $bits = substr($ipRange, $pos + 1);
  242. $range = substr($ipRange, 0, $pos);
  243. $high = $low = @inet_pton($range);
  244. if ($low === false) {
  245. return false;
  246. }
  247. $lowLen = strlen($low);
  248. $i = $lowLen - 1;
  249. $bits = $lowLen * 8 - $bits;
  250. for ($n = (int)($bits / 8); $n > 0; $n--, $i--) {
  251. $low[$i] = chr(0);
  252. $high[$i] = chr(255);
  253. }
  254. $n = $bits % 8;
  255. if ($n) {
  256. $low[$i] = chr(ord($low[$i]) & ~((1 << $n) - 1));
  257. $high[$i] = chr(ord($high[$i]) | ((1 << $n) - 1));
  258. }
  259. return array($low, $high);
  260. }
  261. /**
  262. * Determines if an IP address is in a specified IP address range.
  263. *
  264. * An IPv4-mapped address should be range checked with an IPv4-mapped address range.
  265. *
  266. * @param string $ip IP address in network address format
  267. * @param array $ipRanges List of IP address ranges
  268. * @return bool True if in any of the specified IP address ranges; else false.
  269. */
  270. public static function isIpInRange($ip, $ipRanges)
  271. {
  272. $ipLen = strlen($ip);
  273. if (empty($ip) || empty($ipRanges) || ($ipLen != 4 && $ipLen != 16)) {
  274. return false;
  275. }
  276. foreach ($ipRanges as $range) {
  277. if (is_array($range)) {
  278. // already split into low/high IP addresses
  279. $range[0] = self::P2N($range[0]);
  280. $range[1] = self::P2N($range[1]);
  281. } else {
  282. // expect CIDR format but handle some variations
  283. $range = self::getIpsForRange($range);
  284. }
  285. if ($range === false) {
  286. continue;
  287. }
  288. $low = $range[0];
  289. $high = $range[1];
  290. if (strlen($low) != $ipLen) {
  291. continue;
  292. }
  293. // binary-safe string comparison
  294. if ($ip >= $low && $ip <= $high) {
  295. return true;
  296. }
  297. }
  298. return false;
  299. }
  300. /**
  301. * Returns the most accurate IP address availble for the current user, in
  302. * IPv4 format. This could be the proxy client's IP address.
  303. *
  304. * @return string IP address in presentation format.
  305. */
  306. public static function getIpFromHeader()
  307. {
  308. $clientHeaders = @Config::getInstance()->General['proxy_client_headers'];
  309. if (!is_array($clientHeaders)) {
  310. $clientHeaders = array();
  311. }
  312. $default = '0.0.0.0';
  313. if (isset($_SERVER['REMOTE_ADDR'])) {
  314. $default = $_SERVER['REMOTE_ADDR'];
  315. }
  316. $ipString = self::getNonProxyIpFromHeader($default, $clientHeaders);
  317. return self::sanitizeIp($ipString);
  318. }
  319. /**
  320. * Returns a non-proxy IP address from header.
  321. *
  322. * @param string $default Default value to return if there no matching proxy header.
  323. * @param array $proxyHeaders List of proxy headers.
  324. * @return string
  325. */
  326. public static function getNonProxyIpFromHeader($default, $proxyHeaders)
  327. {
  328. $proxyIps = array();
  329. $config = Config::getInstance()->General;
  330. if(isset($config['proxy_ips'])) {
  331. $proxyIps = $config['proxy_ips'];
  332. }
  333. if (!is_array($proxyIps)) {
  334. $proxyIps = array();
  335. }
  336. $proxyIps[] = $default;
  337. // examine proxy headers
  338. foreach ($proxyHeaders as $proxyHeader) {
  339. if (!empty($_SERVER[$proxyHeader])) {
  340. $proxyIp = self::getLastIpFromList($_SERVER[$proxyHeader], $proxyIps);
  341. if (strlen($proxyIp) && stripos($proxyIp, 'unknown') === false) {
  342. return $proxyIp;
  343. }
  344. }
  345. }
  346. return $default;
  347. }
  348. /**
  349. * Returns the last IP address in a comma separated list, subject to an optional exclusion list.
  350. *
  351. * @param string $csv Comma separated list of elements.
  352. * @param array $excludedIps Optional list of excluded IP addresses (or IP address ranges).
  353. * @return string Last (non-excluded) IP address in the list.
  354. */
  355. public static function getLastIpFromList($csv, $excludedIps = null)
  356. {
  357. $p = strrpos($csv, ',');
  358. if ($p !== false) {
  359. $elements = explode(',', $csv);
  360. for ($i = count($elements); $i--;) {
  361. $element = trim(Common::sanitizeInputValue($elements[$i]));
  362. if (empty($excludedIps) || (!in_array($element, $excludedIps) && !self::isIpInRange(self::P2N(self::sanitizeIp($element)), $excludedIps))) {
  363. return $element;
  364. }
  365. }
  366. }
  367. return trim(Common::sanitizeInputValue($csv));
  368. }
  369. /**
  370. * Retirms the hostname for a given IP address.
  371. *
  372. * @param string $ipStr Human-readable IP address.
  373. * @return string The hostname or unmodified $ipStr on failure.
  374. */
  375. public static function getHostByAddr($ipStr)
  376. {
  377. // PHP's reverse lookup supports ipv4 and ipv6
  378. // except on Windows before PHP 5.3
  379. $host = strtolower(@gethostbyaddr($ipStr));
  380. return $host === '' ? $ipStr : $host;
  381. }
  382. }