|
|
|
|
@ -13,6 +13,8 @@ use IPLib\Address\IPv4; |
|
|
|
|
use IPLib\Address\IPv6; |
|
|
|
|
use IPLib\Factory; |
|
|
|
|
use IPLib\ParseStringFlag; |
|
|
|
|
use IPLib\Range\RangeInterface; |
|
|
|
|
use IPLib\Range\Subnet; |
|
|
|
|
use Symfony\Component\HttpFoundation\IpUtils; |
|
|
|
|
use function filter_var; |
|
|
|
|
|
|
|
|
|
@ -27,6 +29,41 @@ class IpAddressClassifier { |
|
|
|
|
'192.0.0.0/24', // See RFC 6890 |
|
|
|
|
]; |
|
|
|
|
|
|
|
|
|
private RangeInterface $nat64Range; |
|
|
|
|
private RangeInterface $rfc8215; |
|
|
|
|
private RangeInterface $teredo; |
|
|
|
|
private RangeInterface $ipv4Compatible; |
|
|
|
|
|
|
|
|
|
public function __construct() { |
|
|
|
|
$this->nat64Range = Subnet::parseString('64:ff9b::/96'); |
|
|
|
|
$this->rfc8215 = Subnet::parseString('64:ff9b:1::/48'); |
|
|
|
|
$this->teredo = Subnet::parseString('2001::/32'); |
|
|
|
|
$this->ipv4Compatible = Subnet::parseString('::0:0/96'); |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
/** |
|
|
|
|
* Get the ipv4 that an ipv6 address maps to, if any. |
|
|
|
|
* |
|
|
|
|
* Note that this is not just ipv6 representations of ipv4 addresses, |
|
|
|
|
* but also any NAT or proxy style translation addresses |
|
|
|
|
*/ |
|
|
|
|
public function getMappedIpv4(IPv6 $ip): ?IPv4 { |
|
|
|
|
$ipv4 = $ip->toIPv4(); |
|
|
|
|
$ipv6Bytes = $ip->getBytes(); |
|
|
|
|
if ($ipv4) { |
|
|
|
|
return $ipv4; |
|
|
|
|
} elseif ($this->nat64Range->contains($ip)) { |
|
|
|
|
return IPv4::fromBytes(array_slice($ipv6Bytes, -4, 4)); |
|
|
|
|
} elseif ($this->ipv4Compatible->contains($ip)) { |
|
|
|
|
return IPv4::fromBytes(array_slice($ipv6Bytes, -4, 4)); |
|
|
|
|
} elseif ($this->teredo->contains($ip)) { |
|
|
|
|
$xorBytes = array_slice($ipv6Bytes, -4, 4); |
|
|
|
|
return IPv4::fromBytes(array_map(fn (int $byte) => $byte ^ 0xFF, $xorBytes)); |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
return null; |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
/** |
|
|
|
|
* Check host identifier for local IPv4 and IPv6 address ranges |
|
|
|
|
* |
|
|
|
|
@ -43,12 +80,16 @@ class IpAddressClassifier { |
|
|
|
|
} |
|
|
|
|
/* Replace by normalized form */ |
|
|
|
|
if ($parsedIp instanceof IPv6) { |
|
|
|
|
$ipv4 = $parsedIp->toIPv4(); |
|
|
|
|
$ipv6Bytes = $parsedIp->getBytes(); |
|
|
|
|
// rfc8215 is a generic reservation for ipv6/ipv4 translation mechanisms, |
|
|
|
|
// no assumptions can be made about how ipv4 addresses are encoded within. |
|
|
|
|
// |
|
|
|
|
// Thus the only thing we can do is treat them all as local |
|
|
|
|
if ($this->rfc8215->contains($parsedIp)) { |
|
|
|
|
return true; |
|
|
|
|
} |
|
|
|
|
$ipv4 = $this->getMappedIpv4($parsedIp); |
|
|
|
|
if ($ipv4) { |
|
|
|
|
$ip = (string)$ipv4; |
|
|
|
|
} elseif (array_slice($ipv6Bytes, 0, 4) === [0x00, 0x64, 0xFF, 0x9B]) { |
|
|
|
|
$ip = (string)IPv4::fromBytes(array_slice($ipv6Bytes, -4, 4)); |
|
|
|
|
} else { |
|
|
|
|
$ip = (string)$parsedIp; |
|
|
|
|
} |
|
|
|
|
|