IpWhiteListService.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. <?php
  2. declare (strict_types=1);
  3. namespace app\service;
  4. class IpWhiteListService
  5. {
  6. /**
  7. * 验证IP是否在白名单中
  8. *
  9. * @param string $clientIp 客户端IP
  10. * @param string $whiteListIp 白名单IP配置
  11. * @return bool
  12. */
  13. public static function checkIpWhiteList(string $clientIp, string $whiteListIp): bool
  14. {
  15. // 如果白名单为空,表示不限制IP
  16. if (empty($whiteListIp)) {
  17. return true;
  18. }
  19. // 解析白名单IP配置
  20. $whiteList = self::parseWhiteListIp($whiteListIp);
  21. foreach ($whiteList as $allowedIp) {
  22. if (self::matchIp($clientIp, $allowedIp)) {
  23. return true;
  24. }
  25. }
  26. return false;
  27. }
  28. /**
  29. * 解析白名单IP配置
  30. * 支持格式:
  31. * - 单个IP: 192.168.1.1
  32. * - IP段: 192.168.1.0/24
  33. * - IP范围: 192.168.1.1-192.168.1.100
  34. * - 多个配置用逗号分隔: 192.168.1.1,10.0.0.0/8,172.16.0.1-172.16.0.100
  35. *
  36. * @param string $whiteListIp
  37. * @return array
  38. */
  39. public static function parseWhiteListIp(string $whiteListIp): array
  40. {
  41. $whiteList = [];
  42. $items = array_filter(array_map('trim', explode(',', $whiteListIp)));
  43. foreach ($items as $item) {
  44. if (!empty($item)) {
  45. $whiteList[] = $item;
  46. }
  47. }
  48. return $whiteList;
  49. }
  50. /**
  51. * 匹配IP地址
  52. *
  53. * @param string $clientIp 客户端IP
  54. * @param string $allowedIp 允许的IP配置
  55. * @return bool
  56. */
  57. private static function matchIp(string $clientIp, string $allowedIp): bool
  58. {
  59. // 精确匹配
  60. if ($clientIp === $allowedIp) {
  61. return true;
  62. }
  63. // CIDR格式匹配 (例: 192.168.1.0/24)
  64. if (strpos($allowedIp, '/') !== false) {
  65. return self::matchCidr($clientIp, $allowedIp);
  66. }
  67. // IP范围匹配 (例: 192.168.1.1-192.168.1.100)
  68. if (strpos($allowedIp, '-') !== false) {
  69. return self::matchRange($clientIp, $allowedIp);
  70. }
  71. // 通配符匹配 (例: 192.168.1.*)
  72. if (strpos($allowedIp, '*') !== false) {
  73. return self::matchWildcard($clientIp, $allowedIp);
  74. }
  75. return false;
  76. }
  77. /**
  78. * CIDR格式IP匹配
  79. *
  80. * @param string $clientIp
  81. * @param string $cidr
  82. * @return bool
  83. */
  84. private static function matchCidr(string $clientIp, string $cidr): bool
  85. {
  86. list($subnet, $mask) = explode('/', $cidr);
  87. if (!filter_var($subnet, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) ||
  88. !filter_var($clientIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
  89. return false;
  90. }
  91. $mask = intval($mask);
  92. if ($mask < 0 || $mask > 32) {
  93. return false;
  94. }
  95. $clientIpLong = ip2long($clientIp);
  96. $subnetLong = ip2long($subnet);
  97. $maskLong = (-1 << (32 - $mask));
  98. return ($clientIpLong & $maskLong) === ($subnetLong & $maskLong);
  99. }
  100. /**
  101. * IP范围匹配
  102. *
  103. * @param string $clientIp
  104. * @param string $range
  105. * @return bool
  106. */
  107. private static function matchRange(string $clientIp, string $range): bool
  108. {
  109. list($startIp, $endIp) = explode('-', $range, 2);
  110. $startIp = trim($startIp);
  111. $endIp = trim($endIp);
  112. if (!filter_var($startIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) ||
  113. !filter_var($endIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) ||
  114. !filter_var($clientIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
  115. return false;
  116. }
  117. $clientIpLong = ip2long($clientIp);
  118. $startIpLong = ip2long($startIp);
  119. $endIpLong = ip2long($endIp);
  120. return $clientIpLong >= $startIpLong && $clientIpLong <= $endIpLong;
  121. }
  122. /**
  123. * 通配符匹配
  124. *
  125. * @param string $clientIp
  126. * @param string $pattern
  127. * @return bool
  128. */
  129. private static function matchWildcard(string $clientIp, string $pattern): bool
  130. {
  131. $pattern = str_replace('.', '\.', $pattern);
  132. $pattern = str_replace('*', '[0-9]+', $pattern);
  133. $pattern = '/^' . $pattern . '$/';
  134. return preg_match($pattern, $clientIp) === 1;
  135. }
  136. /**
  137. * 获取客户端真实IP
  138. *
  139. * @return string
  140. */
  141. public static function getRealIp(): string
  142. {
  143. $headers = [
  144. 'HTTP_X_FORWARDED_FOR',
  145. 'HTTP_X_REAL_IP',
  146. 'HTTP_CLIENT_IP',
  147. 'HTTP_CF_CONNECTING_IP',
  148. 'HTTP_X_CLUSTER_CLIENT_IP',
  149. 'REMOTE_ADDR'
  150. ];
  151. foreach ($headers as $header) {
  152. if (!empty($_SERVER[$header])) {
  153. $ips = explode(',', $_SERVER[$header]);
  154. $ip = trim($ips[0]);
  155. if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
  156. return $ip;
  157. }
  158. }
  159. }
  160. return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
  161. }
  162. /**
  163. * 验证IP白名单格式
  164. *
  165. * @param string $whiteListIp
  166. * @return array [bool $isValid, string $message, array $parsedList]
  167. */
  168. public static function validateWhiteListFormat(string $whiteListIp): array
  169. {
  170. if (empty($whiteListIp)) {
  171. return [true, '白名单为空,表示不限制IP访问', []];
  172. }
  173. $items = self::parseWhiteListIp($whiteListIp);
  174. $validItems = [];
  175. $errors = [];
  176. foreach ($items as $item) {
  177. $validation = self::validateSingleIpFormat($item);
  178. if ($validation['valid']) {
  179. $validItems[] = [
  180. 'input' => $item,
  181. 'type' => $validation['type'],
  182. 'description' => $validation['description']
  183. ];
  184. } else {
  185. $errors[] = "'{$item}': " . $validation['message'];
  186. }
  187. }
  188. $isValid = empty($errors);
  189. $message = $isValid ? '白名单格式正确' : '白名单格式错误: ' . implode(', ', $errors);
  190. return [$isValid, $message, $validItems];
  191. }
  192. /**
  193. * 验证单个IP配置格式
  194. *
  195. * @param string $ipConfig
  196. * @return array
  197. */
  198. private static function validateSingleIpFormat(string $ipConfig): array
  199. {
  200. // 精确IP
  201. if (filter_var($ipConfig, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
  202. return [
  203. 'valid' => true,
  204. 'type' => 'exact',
  205. 'description' => "精确IP: {$ipConfig}"
  206. ];
  207. }
  208. // CIDR格式
  209. if (strpos($ipConfig, '/') !== false) {
  210. list($subnet, $mask) = explode('/', $ipConfig);
  211. if (filter_var($subnet, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) &&
  212. is_numeric($mask) && $mask >= 0 && $mask <= 32) {
  213. return [
  214. 'valid' => true,
  215. 'type' => 'cidr',
  216. 'description' => "CIDR网段: {$ipConfig}"
  217. ];
  218. }
  219. }
  220. // IP范围
  221. if (strpos($ipConfig, '-') !== false) {
  222. list($startIp, $endIp) = explode('-', $ipConfig, 2);
  223. $startIp = trim($startIp);
  224. $endIp = trim($endIp);
  225. if (filter_var($startIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) &&
  226. filter_var($endIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
  227. return [
  228. 'valid' => true,
  229. 'type' => 'range',
  230. 'description' => "IP范围: {$startIp} 到 {$endIp}"
  231. ];
  232. }
  233. }
  234. // 通配符
  235. if (strpos($ipConfig, '*') !== false) {
  236. $parts = explode('.', $ipConfig);
  237. if (count($parts) === 4) {
  238. $valid = true;
  239. foreach ($parts as $part) {
  240. if ($part !== '*' && (!is_numeric($part) || $part < 0 || $part > 255)) {
  241. $valid = false;
  242. break;
  243. }
  244. }
  245. if ($valid) {
  246. return [
  247. 'valid' => true,
  248. 'type' => 'wildcard',
  249. 'description' => "通配符IP: {$ipConfig}"
  250. ];
  251. }
  252. }
  253. }
  254. return [
  255. 'valid' => false,
  256. 'message' => '不支持的IP格式'
  257. ];
  258. }
  259. /**
  260. * 获取IP地理位置信息(简单实现)
  261. *
  262. * @param string $ip
  263. * @return array
  264. */
  265. public static function getIpInfo(string $ip): array
  266. {
  267. // 内网IP检测
  268. if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
  269. return [
  270. 'ip' => $ip,
  271. 'type' => 'private',
  272. 'location' => '内网IP',
  273. 'isp' => '内网'
  274. ];
  275. }
  276. // 这里可以集成第三方IP地理位置服务
  277. // 如:百度、腾讯、阿里云等IP查询API
  278. return [
  279. 'ip' => $ip,
  280. 'type' => 'public',
  281. 'location' => '未知',
  282. 'isp' => '未知'
  283. ];
  284. }
  285. }