matomo-org / component-network

Network component: manipulate IP addresses (ipv4, ipv6) in PHP used in the Matomo project
GNU Lesser General Public License v3.0
20 stars 12 forks source link

getHostname() ensure the returned hostname does only contain characters, digits, hypen and dots (security) #8

Open mattab opened 7 years ago

mattab commented 7 years ago

This was reported by email by a security researcher:

As described by another security researcher here, http://zoczus.blogspot.sg/2014/05/how-reverse-dns-can-help-us-with-xss.html, an attacker will need to be in control of an IP address where he can set the RDNS hostname to return JS script tags. After that, the attacker tunnels his traffic through that IP address and visits the target site. The getHostname() function will then resolve the IP address and obtain the JS code. Since it is not sanitized, any function which directly stores or displays the hostname will be susceptible to XSS.

The idea is to prevent the function from returning a special string which would trigger an XSS attack, for example <script>alert("1");</script>

Solution

According to RFC1123, valid hostnames can consist of only letters, digits and hyphens. Hence, valid RDNS names should only consist of letter, digits, hyphens and dots. It should thus be possible to sanitize the input to remove all other invalid characters without breaking RDNS resolution for legitimate hosts.

Our solution should also accept international / unicode domains in case the hostname would contain non english characters?

robocoder commented 6 years ago

See #11

robocoder commented 6 years ago

An alternative to #11 might be to use Cloudflare's DNS over HTTPS lookup instead of gethostbyaddr().

Pros:

Cons:

Pseudo-code:

<    $host = strtolower(@gethostbyaddr($stringIp));
---
>    $reverseIp = implode('.', array_reverse(explode('.', $stringIp)));
>    $url = 'https://cloudflare-dns.com/dns-query?ct=application/dns-json&name=' . $reverseIp . '.in-addr.arpa&type=PTR';
>    $json = json_decode(Http::sendHttpRequest($url), true);
>    $host = isset($json['Answer']['data']) ? strtolower($json['Answer']['data']) : false;