Skip to content

Commit 8e11531

Browse files
committed
Support CIDR in firewall
1 parent ab04ddf commit 8e11531

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

src/Tqdev/PhpCrudApi/Middleware/FirewallMiddleware.php

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,32 @@
22
namespace Tqdev\PhpCrudApi\Middleware;
33

44
use Tqdev\PhpCrudApi\Controller\Responder;
5+
use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
56
use Tqdev\PhpCrudApi\Record\ErrorCode;
67
use Tqdev\PhpCrudApi\Request;
78
use Tqdev\PhpCrudApi\Response;
8-
use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
99

1010
class FirewallMiddleware extends Middleware
1111
{
12+
private function ipMatch(String $ip, String $cidr): bool
13+
{
14+
if (strpos($cidr, '/') !== false) {
15+
list($subnet, $mask) = explode('/', trim($cidr));
16+
if ((ip2long($ip) & ~((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
17+
return true;
18+
}
19+
} else {
20+
if (ip2long($ip) == ip2long($cidr)) {
21+
return true;
22+
}
23+
}
24+
return false;
25+
}
26+
1227
private function isIpAllowed(String $ipAddress, String $allowedIpAddresses): bool
1328
{
1429
foreach (explode(',', $allowedIpAddresses) as $allowedIp) {
15-
if ($ipAddress == trim($allowedIp)) {
30+
if ($this->ipMatch($ipAddress, $allowedIp)) {
1631
return true;
1732
}
1833
}

0 commit comments

Comments
 (0)