IpWhiteListService.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. * @param string $whiteListIp
  140. * @return array [bool $isValid, string $message, array $parsedList]
  141. */
  142. public static function validateWhiteListFormat(string $whiteListIp): array
  143. {
  144. if (empty($whiteListIp)) {
  145. return [true, '白名单为空,表示不限制IP访问', []];
  146. }
  147. $items = self::parseWhiteListIp($whiteListIp);
  148. $validItems = [];
  149. $errors = [];
  150. foreach ($items as $item) {
  151. $validation = self::validateSingleIpFormat($item);
  152. if ($validation['valid']) {
  153. $validItems[] = [
  154. 'input' => $item,
  155. 'type' => $validation['type'],
  156. 'description' => $validation['description']
  157. ];
  158. } else {
  159. $errors[] = "'{$item}': " . $validation['message'];
  160. }
  161. }
  162. $isValid = empty($errors);
  163. $message = $isValid ? 'IP白名单格式正确' : 'IP白名单格式错误: ' . implode(', ', $errors);
  164. return [$isValid, $message, $validItems];
  165. }
  166. /**
  167. * 验证单个IP配置格式
  168. *
  169. * @param string $ipConfig
  170. * @return array
  171. */
  172. private static function validateSingleIpFormat(string $ipConfig): array
  173. {
  174. // 精确IP
  175. if (filter_var($ipConfig, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
  176. return [
  177. 'valid' => true,
  178. 'type' => 'exact',
  179. 'description' => "精确IP: {$ipConfig}"
  180. ];
  181. }
  182. // CIDR格式
  183. if (strpos($ipConfig, '/') !== false) {
  184. list($subnet, $mask) = explode('/', $ipConfig);
  185. if (filter_var($subnet, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) &&
  186. is_numeric($mask) && $mask >= 0 && $mask <= 32) {
  187. return [
  188. 'valid' => true,
  189. 'type' => 'cidr',
  190. 'description' => "CIDR网段: {$ipConfig}"
  191. ];
  192. }
  193. }
  194. // IP范围
  195. if (strpos($ipConfig, '-') !== false) {
  196. list($startIp, $endIp) = explode('-', $ipConfig, 2);
  197. $startIp = trim($startIp);
  198. $endIp = trim($endIp);
  199. if (filter_var($startIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) &&
  200. filter_var($endIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
  201. return [
  202. 'valid' => true,
  203. 'type' => 'range',
  204. 'description' => "IP范围: {$startIp} 到 {$endIp}"
  205. ];
  206. }
  207. }
  208. // 通配符
  209. if (strpos($ipConfig, '*') !== false) {
  210. $parts = explode('.', $ipConfig);
  211. if (count($parts) === 4) {
  212. $valid = true;
  213. foreach ($parts as $part) {
  214. if ($part !== '*' && (!is_numeric($part) || $part < 0 || $part > 255)) {
  215. $valid = false;
  216. break;
  217. }
  218. }
  219. if ($valid) {
  220. return [
  221. 'valid' => true,
  222. 'type' => 'wildcard',
  223. 'description' => "通配符IP: {$ipConfig}"
  224. ];
  225. }
  226. }
  227. }
  228. return [
  229. 'valid' => false,
  230. 'message' => '不支持的IP格式'
  231. ];
  232. }
  233. }