/** * Validate "Host" (untrusted user input) * * @param string $host Contents of Host: header from Request * @param array $trustedHosts An array of trusted hosts * * @return boolean True if valid; false otherwise */ public static function isValidHost($host, $trustedHosts) { // Only punctuation we allow is '[', ']', ':', '.' and '-' $hostLength = Piwik_Common::strlen($host); if ($hostLength !== strcspn($host, '`~!@#$%^&*()_+={}\\|;"\'<>,?/ ')) { return false; } $untrustedHost = Piwik_Common::mb_strtolower($host); $hostRegex = Piwik_Common::mb_strtolower(str_replace('.', '\\.', '/(^|.)' . implode('|', $trustedHosts) . '(:[0-9]+)?$/')); return 0 !== preg_match($hostRegex, rtrim($untrustedHost, '.')); }
/** * Validate "Host" (untrusted user input) * * @param string|false $host Contents of Host: header from Request. If false, gets the * value from the request. * * @return boolean True if valid; false otherwise */ public static function isValidHost($host = false) { // only do trusted host check if it's enabled if (isset(Piwik_Config::getInstance()->General['enable_trusted_host_check']) && Piwik_Config::getInstance()->General['enable_trusted_host_check'] == 0) { return true; } if ($host === false) { $host = $_SERVER['HTTP_HOST']; if (empty($host)) { return true; } } // if host is in hardcoded whitelist, assume it's valid if (in_array($host, self::$alwaysTrustedHosts)) { return true; } $trustedHosts = @Piwik_Config::getInstance()->General['trusted_hosts']; // if no trusted hosts, just assume it's valid if (empty($trustedHosts)) { self::saveTrustedHostnameInConfig($host); return true; } // Only punctuation we allow is '[', ']', ':', '.' and '-' $hostLength = Piwik_Common::strlen($host); if ($hostLength !== strcspn($host, '`~!@#$%^&*()_+={}\\|;"\'<>,?/ ')) { return false; } foreach ($trustedHosts as &$trustedHost) { $trustedHost = preg_quote($trustedHost); } $untrustedHost = Piwik_Common::mb_strtolower($host); $untrustedHost = rtrim($untrustedHost, '.'); $hostRegex = Piwik_Common::mb_strtolower('/(^|.)' . implode('|', $trustedHosts) . '$/'); $result = preg_match($hostRegex, $untrustedHost); // var_dump($hostRegex);var_dump($untrustedHost);var_dump($result); return 0 !== $result; }