From a96918043312ab4575e79c62fbbfe8c0f3de411c Mon Sep 17 00:00:00 2001 From: Thomas Portelange Date: Wed, 28 Jun 2023 10:25:19 +0200 Subject: [PATCH 1/2] add anonymize --- src/Control/Util/IPUtils.php | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/Control/Util/IPUtils.php b/src/Control/Util/IPUtils.php index 0e2e46e1575..a51b9991975 100644 --- a/src/Control/Util/IPUtils.php +++ b/src/Control/Util/IPUtils.php @@ -131,4 +131,36 @@ public static function checkIP6($requestIP, $ip) return true; } + + /** + * Anonymizes an IP/IPv6. + * + * Removes the last byte for v4 and the last 8 bytes for v6 IPs + */ + public static function anonymize(string $ip): string + { + $wrappedIPv6 = false; + if (str_starts_with($ip, '[') && str_ends_with($ip, ']')) { + $wrappedIPv6 = true; + $ip = substr($ip, 1, -1); + } + + $packedAddress = inet_pton($ip); + if (4 === \strlen($packedAddress)) { + $mask = '255.255.255.0'; + } elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff:ffff'))) { + $mask = '::ffff:ffff:ff00'; + } elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff'))) { + $mask = '::ffff:ff00'; + } else { + $mask = 'ffff:ffff:ffff:ffff:0000:0000:0000:0000'; + } + $ip = inet_ntop($packedAddress & inet_pton($mask)); + + if ($wrappedIPv6) { + $ip = '['.$ip.']'; + } + + return $ip; + } } From a019b34facc35066fce3355118a2dcb67fcf01a0 Mon Sep 17 00:00:00 2001 From: Thomas Portelange Date: Wed, 28 Jun 2023 10:56:22 +0200 Subject: [PATCH 2/2] csfix --- src/Control/Util/IPUtils.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Control/Util/IPUtils.php b/src/Control/Util/IPUtils.php index a51b9991975..0d8d4e57c82 100644 --- a/src/Control/Util/IPUtils.php +++ b/src/Control/Util/IPUtils.php @@ -1,4 +1,5 @@ */ + namespace SilverStripe\Control\Util; /** @@ -158,7 +160,7 @@ public static function anonymize(string $ip): string $ip = inet_ntop($packedAddress & inet_pton($mask)); if ($wrappedIPv6) { - $ip = '['.$ip.']'; + $ip = '[' . $ip . ']'; } return $ip;