Automatic Cloudflare detection for rate limiting (trusts CF-Connecting-IP only from Cloudflare ranges)
- Core\CidrMatcher (IPv4/IPv6), Core\CloudflareRanges (published ranges, filterable) - ClientIp 'auto' mode, default for new installs; diagnostics show whether the connection is from Cloudflare Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5ea1e1d273
commit
43106d9edc
8 files changed
+171
-6
No files matched your search
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Core;
|
||||
|
||||
/** Pure IPv4/IPv6 CIDR membership test (no WordPress, no network). Malformed input never matches. */
|
||||
final class CidrMatcher {
|
||||
|
||||
/** @param string[] $cidrs e.g. ['173.245.48.0/20', '2606:4700::/32'] */
|
||||
public static function contains( string $ip, array $cidrs ): bool {
|
||||
$ipBin = @inet_pton( trim( $ip ) );
|
||||
if ( false === $ipBin ) {
|
||||
return false;
|
||||
}
|
||||
foreach ( $cidrs as $cidr ) {
|
||||
if ( self::inRange( $ipBin, (string) $cidr ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static function inRange( string $ipBin, string $cidr ): bool {
|
||||
$parts = explode( '/', trim( $cidr ), 2 );
|
||||
if ( 2 !== count( $parts ) || ! ctype_digit( $parts[1] ) ) {
|
||||
return false;
|
||||
}
|
||||
$netBin = @inet_pton( $parts[0] );
|
||||
if ( false === $netBin || strlen( $netBin ) !== strlen( $ipBin ) ) { // different address families never match
|
||||
return false;
|
||||
}
|
||||
$bits = (int) $parts[1];
|
||||
if ( $bits < 0 || $bits > strlen( $netBin ) * 8 ) {
|
||||
return false;
|
||||
}
|
||||
$fullBytes = intdiv( $bits, 8 );
|
||||
if ( $fullBytes > 0 && substr( $ipBin, 0, $fullBytes ) !== substr( $netBin, 0, $fullBytes ) ) {
|
||||
return false;
|
||||
}
|
||||
$rest = $bits % 8;
|
||||
if ( 0 === $rest ) {
|
||||
return true;
|
||||
}
|
||||
$mask = ( 0xFF << ( 8 - $rest ) ) & 0xFF;
|
||||
return ( ord( $ipBin[ $fullBytes ] ) & $mask ) === ( ord( $netBin[ $fullBytes ] ) & $mask );
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user