diff options
author | Stefan Giehl <stefan@matomo.org> | 2021-11-10 22:14:21 +0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-11-10 22:14:21 +0300 |
commit | e8e0f2ac53317d4474e52816a1ee506883e9c95d (patch) | |
tree | bcdf3ddb7386f1f3ba108abbd8a573610364bc90 /config | |
parent | 16912f4137f0c728e8e9ca54cfa2be8014f1a3d8 (diff) |
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
Diffstat (limited to 'config')
-rw-r--r-- | config/global.php | 39 |
1 files changed, 25 insertions, 14 deletions
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); } } |