Files

87 lines
3.5 KiB
PHP
Raw Permalink Normal View History

<?php
declare( strict_types=1 );
namespace StreamGoals\Core;
/**
* Works out the visitor's IP for rate limiting. Pure (takes the $_SERVER values as an array) so it is unit-testable.
*
* Behind a CDN or reverse proxy, PHP's REMOTE_ADDR is the proxy's address, so every visitor would share one rate
* limit. The owner can name the header their proxy sets. A header is ONLY trusted when the owner selected it, and
* only if it holds a valid IP address; otherwise we fall back to REMOTE_ADDR.
*/
final class ClientIp {
public const MODE_AUTO = 'auto'; // detect Cloudflare automatically (recommended)
public const MODE_DIRECT = ''; // no proxy: use REMOTE_ADDR
public const MODE_CLOUDFLARE = 'cloudflare'; // CF-Connecting-IP
public const MODE_REAL_IP = 'real_ip'; // X-Real-IP (nginx and many hosts)
public const MODE_FORWARDED = 'forwarded'; // last address in X-Forwarded-For (exactly one proxy in front)
public const MODES = array(
self::MODE_AUTO => 'Automatic (recommended): detects Cloudflare',
self::MODE_DIRECT => 'Not behind a proxy or CDN (most sites)',
self::MODE_CLOUDFLARE => 'Cloudflare (CF-Connecting-IP)',
self::MODE_REAL_IP => 'X-Real-IP header',
self::MODE_FORWARDED => 'X-Forwarded-For header (one proxy in front)',
);
/** @param array<string,mixed> $server $_SERVER-style values (already unslashed). */
public static function resolve( array $server, string $mode = self::MODE_DIRECT, ?array $extraCloudflareRanges = null ): string {
$remote = self::valid( $server['REMOTE_ADDR'] ?? null );
$fromHeader = null;
switch ( $mode ) {
case self::MODE_AUTO:
// Trust CF-Connecting-IP only when the connection itself comes from a Cloudflare address.
if ( null !== $remote && CloudflareRanges::isCloudflare( $remote, $extraCloudflareRanges ) ) {
$fromHeader = self::valid( $server['HTTP_CF_CONNECTING_IP'] ?? null );
}
break;
case self::MODE_CLOUDFLARE:
$fromHeader = self::valid( $server['HTTP_CF_CONNECTING_IP'] ?? null );
break;
case self::MODE_REAL_IP:
$fromHeader = self::valid( $server['HTTP_X_REAL_IP'] ?? null );
break;
case self::MODE_FORWARDED:
$raw = $server['HTTP_X_FORWARDED_FOR'] ?? null;
if ( is_string( $raw ) && '' !== trim( $raw ) ) {
$parts = array_map( 'trim', explode( ',', $raw ) );
$fromHeader = self::valid( end( $parts ) ); // the entry our proxy appended; earlier ones are client-supplied
}
break;
}
return $fromHeader ?? $remote ?? 'unknown';
}
/**
* Rate-limit BUCKET KEY for a resolved address (never use it as the "real" IP): IPv4 unchanged, IPv4-mapped IPv6
* becomes its IPv4, any other IPv6 collapses to its /64 (one subscriber/host can rotate freely inside a /64),
* 'unknown' stays, anything unparsable becomes 'unknown'.
*/
public static function bucketKey( string $ip ): string {
$ip = trim( $ip );
if ( 'unknown' === $ip || false === filter_var( $ip, FILTER_VALIDATE_IP ) ) {
return 'unknown';
}
if ( false === filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 ) ) {
return $ip;
}
$bin = inet_pton( $ip );
if ( false === $bin || 16 !== strlen( $bin ) ) {
return 'unknown';
}
if ( str_repeat( "\0", 10 ) . "\xff\xff" === substr( $bin, 0, 12 ) ) {
return (string) inet_ntop( substr( $bin, 12 ) );
}
return bin2hex( substr( $bin, 0, 8 ) ) . '/64';
}
private static function valid( mixed $v ): ?string {
if ( ! is_string( $v ) ) {
return null;
}
$v = trim( $v );
return false !== filter_var( $v, FILTER_VALIDATE_IP ) ? $v : null;
}
}