From 172fd3329682fe0684b4e9077547581a33089bd4 Mon Sep 17 00:00:00 2001 From: kriss <462679766@qq.com> Date: Wed, 10 Jan 2024 18:01:49 +0800 Subject: [PATCH] =?UTF-8?q?feature:=20=E5=AF=B9=20host=20=E7=9A=84?= =?UTF-8?q?=E7=A6=81=E7=94=A8=E5=A2=9E=E5=8A=A0=20ip=20=E7=9A=84=E6=94=AF?= =?UTF-8?q?=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Middleware/HostForbiddenMiddleware.php | 50 ++++++++++++++-------- 1 file changed, 32 insertions(+), 18 deletions(-) diff --git a/src/Middleware/HostForbiddenMiddleware.php b/src/Middleware/HostForbiddenMiddleware.php index 82315ca..104d31e 100644 --- a/src/Middleware/HostForbiddenMiddleware.php +++ b/src/Middleware/HostForbiddenMiddleware.php @@ -10,15 +10,9 @@ class HostForbiddenMiddleware implements MiddlewareInterface { protected $config = [ 'enable' => true, - 'host_white_list_default' => [ - // 常规的内网地址允许访问 - '127.0.0.1', - 'localhost', - '192.168.', - '172.16.', - '10.', - ], - 'host_white_list' => [], + 'ip_white_list_intranet' => true, // 允许所有内网访问 + 'ip_white_list' => [], // 允许访问的 ip + 'host_white_list' => [], // 允许访问的 host ]; public function __construct(array $config = []) @@ -36,24 +30,44 @@ public function __construct(array $config = []) public function process(Request $request, callable $handler): Response { if ($this->config['enable']) { - $host = $request->host(); - if (!$this->isInWhiteList($host)) { - return response('Forbidden for: ' . $host, 403); + [$can, $ip] = $this->checkIp($request); + if (!$can) { + [$can, $host] = $this->checkHost($request); + if (!$can) { + return response("Forbidden for ip({$ip}) and host({$host})", 403); + } } } return $handler($request); } - private function isInWhiteList(string $host): bool + private function checkIp(Request $request): array { - $whiteList = array_merge($this->config['host_white_list_default'], $this->config['host_white_list']); - foreach ($whiteList as $needle) { + if ($this->config['ip_white_list_intranet'] === null || $this->config['ip_white_list'] === null) { + return [true, '']; + } + $ip = $request->getRealIp(); + if ($this->config['ip_white_list_intranet'] && Request::isIntranetIp($ip)) { + return [true, '']; + } + if (in_array($ip, $this->config['ip_white_list'] ?? [])) { + return [true, '']; + } + return [false, $ip]; + } + + private function checkHost(Request $request): array + { + if ($this->config['host_white_list'] === null) { + return [true, '']; + } + $host = $request->host(); + foreach ($this->config['host_white_list'] as $needle) { if ($needle !== '' && strpos($host, $needle) !== false) { - return true; + return [true, '']; } } - - return false; + return [false, $host]; } }