From e8e0f2ac53317d4474e52816a1ee506883e9c95d Mon Sep 17 00:00:00 2001 From: Stefan Giehl Date: Wed, 10 Nov 2021 20:14:21 +0100 Subject: Ensure DNS records are only requested for IP allowlist when needed (#18285) * Ensure DNS records are only requested for IP allowlist when needed - only request dns records it it's not an IP range - cache DNS results for 30 seconds to reduce DNS requests * apply review feedback --- config/global.php | 39 +++++++++++++++++++++++++-------------- 1 file changed, 25 insertions(+), 14 deletions(-) (limited to 'config') diff --git a/config/global.php b/config/global.php index f7834df256..1e43a2e479 100644 --- a/config/global.php +++ b/config/global.php @@ -167,24 +167,35 @@ return array( foreach ($ips as $ip) { $ip = trim($ip); - if (filter_var($ip, FILTER_VALIDATE_IP)) { + if (filter_var($ip, FILTER_VALIDATE_IP) || \Matomo\Network\IPUtils::getIPRangeBounds($ip) !== null) { $ipsResolved[] = $ip; } else { - $ipFromHost = @gethostbyname($ip); - if (!empty($ipFromHost)) { - // we don't check using filter_var if it's an IP as "gethostbyname" will return the $ip if it's not a hostname - // and we then assume it is an IP range. Otherwise IP ranges would not be added. Ideally would above check if it is an - // IP range before trying to get host by name. - $ipsResolved[] = $ipFromHost; - } - - if (function_exists('dns_get_record')) { - $entry = @dns_get_record($ip, DNS_AAAA); - if (!empty($entry['0']['ipv6']) - && filter_var($entry['0']['ipv6'], FILTER_VALIDATE_IP)) { - $ipsResolved[] = $entry['0']['ipv6']; + $lazyCache = \Piwik\Cache::getLazyCache(); + $cacheKey = 'DNS.' . md5($ip); + + $resolvedIps = $lazyCache->fetch($cacheKey); + + if (!is_array($resolvedIps)) { + $resolvedIps = []; + + $ipFromHost = @gethostbyname($ip); + if (!empty($ipFromHost) && $ipFromHost !== $ip) { + $resolvedIps[] = $ipFromHost; + } + + if (function_exists('dns_get_record')) { + $entry = @dns_get_record($ip, DNS_AAAA); + + if (!empty($entry['0']['ipv6']) + && filter_var($entry['0']['ipv6'], FILTER_VALIDATE_IP)) { + $resolvedIps[] = $entry['0']['ipv6']; + } } + + $lazyCache->save($cacheKey, $resolvedIps, 30); } + + $ipsResolved = array_merge($ipsResolved, $resolvedIps); } } -- cgit v1.2.3