Просмотр исходного кода

Security fixes SimplePie (#9639)

Fix Sanitizer bypass via markup in attributes inside xmp, textarea, iframe
https://github.com/FreshRSS/simplepie/pull/101
https://github.com/simplepie/simplepie/pull/1026
https://github.com/FreshRSS/FreshRSS/security/advisories/GHSA-4xgp-wh7q-984f

Fix url remove credentials
https://github.com/FreshRSS/simplepie/pull/100
https://github.com/simplepie/simplepie/pull/1025
https://github.com/FreshRSS/FreshRSS/security/advisories/GHSA-g7fv-8j56-6v5f

Fix Feed credentials leak to other origins via autodiscovery ~~and redirects~~
https://github.com/FreshRSS/simplepie/pull/102
https://github.com/simplepie/simplepie/pull/1027
https://github.com/FreshRSS/FreshRSS/security/advisories/GHSA-7m4j-xpgq-7m3h

Contributes to: SSRF bypass: port-less HTTP proxy pinned on 80, but libcurl uses 1080
https://github.com/FreshRSS/FreshRSS/security/advisories/GHSA-fc32-79hf-pcmw
Alexandre Alapetite 8 часов назад
Родитель
Сommit
4c362293e1

+ 1 - 1
lib/composer.json

@@ -22,7 +22,7 @@
 		"marienfressinaud/lib_opml": "dev-main#f0e850b6394af90b898daf0e65fcc7363457b844",
 		"phpgt/cssxpath": "dev-master#9d416ccddb048aebd92724c4f8e92f88e3bfc412",
 		"phpmailer/phpmailer": "7.1.1",
-		"simplepie/simplepie": "dev-freshrss#1bfb15fbbdf6488b78253f76433c9268404eb3d3"
+		"simplepie/simplepie": "dev-freshrss#d4435cdf6a6156409dba7767ee55c3ff69b5477e"
 	},
 	"config": {
 		"sort-packages": true,

+ 19 - 4
lib/simplepie/simplepie/src/File.php

@@ -158,10 +158,25 @@ class File implements Response
                         $this->success = false;
                         return;
                     }
-                    // CURLOPT_PROXY ($proxy) is expected to already be scheme-less: the scheme comes from
-                    // CURLOPT_PROXYTYPE, and the caller (e.g. FreshRSS_http_Util::sanitizeCurlParams()) rejects
-                    // any scheme-containing value before it's ever stored or used.
-                    $proxy_url = "$proxy_scheme://$proxy"; // formatted as user:pass@hostname:port, with the part before @ being optional
+                    // Fail closed if the value of `CURLOPT_PROXY` is ambiguous and could be parsed
+                    // differently by the SSRF checks below and by cURL: the scheme (e.g. 'http://proxy:8080')
+                    // belongs to `CURLOPT_PROXYTYPE` instead, and credentials must be percent-encoded.
+                    if (preg_match('/[\/?\\\\#\s]/', $proxy) === 1) {
+                        $this->error = 'Ambiguous proxy URL: ' . \SimplePie\Misc::url_remove_credentials($proxy);
+                        $this->success = false;
+                        return;
+                    }
+                    // Add the port explicitly, using the documented defaults of cURL, as libcurl
+                    // 8.21.0-8.23.x does not use them: https://github.com/curl/curl/issues/23681
+                    if (preg_match('/:\d+$/D', $proxy) !== 1) {
+                        $port = is_int($curl_options[CURLOPT_PROXYPORT] ?? null) ? $curl_options[CURLOPT_PROXYPORT] : 0;
+                        $proxy .= ':' . ($port > 0 && $port < 65536 ? $port : ($proxy_scheme === 'https' ? 443 : 1080));
+                    }
+                    unset($curl_options[CURLOPT_PROXYPORT]); // Now part of `CURLOPT_PROXY`, and to keep the same port among cURL versions
+                    // Use the normalized value as the actual option as well, in case the caller did not
+                    // already do the same, so that the SSRF checks and the connection agree.
+                    $curl_options[CURLOPT_PROXY] = $proxy;
+                    $proxy_url = "$proxy_scheme://$proxy"; // `$proxy` is now guaranteed to be scheme-less and to end with an explicit port
                     $resolve = $this->get_curl_resolve_info($proxy_url);
                     if ($resolve === null) {
                         $this->error = 'Failed to fetch this URL, because the proxy’s IP is not in the allowlist [' .

+ 16 - 6
lib/simplepie/simplepie/src/Locator.php

@@ -60,10 +60,16 @@ class Locator implements RegistryAware
      */
     private $http_client = null;
 
+    /**
+     * @var string URL for which the cURL options were given (FreshRSS)
+     */
+    private $curl_options_url;
+
     /**
      * @param array<int, mixed> $curl_options
+     * @param string|null $curl_options_url URL for which the cURL options were given, if not the one of $file after redirects (FreshRSS)
      */
-    public function __construct(File $file, int $timeout = 10, ?string $useragent = null, int $max_checked_feeds = 10, bool $force_fsockopen = false, array $curl_options = [])
+    public function __construct(File $file, int $timeout = 10, ?string $useragent = null, int $max_checked_feeds = 10, bool $force_fsockopen = false, array $curl_options = [], ?string $curl_options_url = null)
     {
         $this->file = $file;
         $this->useragent = $useragent;
@@ -71,6 +77,7 @@ class Locator implements RegistryAware
         $this->max_checked_feeds = $max_checked_feeds;
         $this->force_fsockopen = $force_fsockopen;
         $this->curl_options = $curl_options;
+        $this->curl_options_url = $curl_options_url ?? $file->get_final_requested_uri();
 
         $body = $this->file->get_body_content();
 
@@ -261,7 +268,7 @@ class Locator implements RegistryAware
                     ];
 
                     try {
-                        $feed = $this->get_http_client()->request(Client::METHOD_GET, $href, $headers);
+                        $feed = $this->get_http_client($href)->request(Client::METHOD_GET, $href, $headers);
 
                         if ((!Misc::is_remote_uri($feed->get_final_requested_uri()) || ($feed->get_status_code() === 200 || $feed->get_status_code() > 206 && $feed->get_status_code() < 300)) && $this->is_feed($feed, true)) {
                             $feeds[$href] = $feed;
@@ -394,7 +401,7 @@ class Locator implements RegistryAware
                 ];
 
                 try {
-                    $feed = $this->get_http_client()->request(Client::METHOD_GET, $value, $headers);
+                    $feed = $this->get_http_client($value)->request(Client::METHOD_GET, $value, $headers);
 
                     if ((!Misc::is_remote_uri($feed->get_final_requested_uri()) || ($feed->get_status_code() === 200 || $feed->get_status_code() > 206 && $feed->get_status_code() < 300)) && $this->is_feed($feed)) {
                         return [$feed];
@@ -426,7 +433,7 @@ class Locator implements RegistryAware
                 ];
 
                 try {
-                    $feed = $this->get_http_client()->request(Client::METHOD_GET, $value, $headers);
+                    $feed = $this->get_http_client($value)->request(Client::METHOD_GET, $value, $headers);
 
                     if ((!Misc::is_remote_uri($feed->get_final_requested_uri()) || ($feed->get_status_code() === 200 || $feed->get_status_code() > 206 && $feed->get_status_code() < 300)) && $this->is_feed($feed)) {
                         return [$feed];
@@ -443,8 +450,10 @@ class Locator implements RegistryAware
 
     /**
      * Get a HTTP client
+     *
+     * @param string $url URL about to be requested
      */
-    private function get_http_client(): Client
+    private function get_http_client(string $url): Client
     {
         assert($this->registry !== null);
 
@@ -453,7 +462,8 @@ class Locator implements RegistryAware
                 'timeout' => $this->timeout,
                 'redirects' => 5,
                 'force_fsockopen' => $this->force_fsockopen,
-                'curl_options' => $this->curl_options,
+                // FreshRSS: credentials are only for the origin they were given for, not for feeds discovered elsewhere
+                'curl_options' => Misc::curl_options_for_origin($this->curl_options, $this->curl_options_url, $url),
             ];
 
             if ($this->useragent !== null) {

+ 36 - 4
lib/simplepie/simplepie/src/Misc.php

@@ -2212,10 +2212,42 @@ JS;
      */
     public static function url_remove_credentials(string $url)
     {
-        // Cast for PHPStan: I do not think this can fail.
-        // The regex is valid and there should be no backtracking.
-        // https://github.com/phpstan/phpstan/issues/11547
-        return (string) preg_replace('#^(https?://)[^/:@]+:[^/:@]+@#i', '$1', $url);
+        // String cast for PHPStan while waiting to update to PHPStan 2+
+        return (string) preg_replace('#^([a-z][a-z0-9+.-]*://)(?:[^/?\#@]*+@)++#i', '$1', $url);
+    }
+
+    /**
+     * Restrict cURL options given for one URL to what may be sent to another URL:
+     * credentials, cookies, custom HTTP headers, and request body are removed when the origin (scheme, host, port) differs.
+     * @param array<int, mixed> $curl_options the cURL options, as given for $from_url.
+     * @param string $from_url the URL for which the cURL options were given.
+     * @param string $to_url the URL about to be requested.
+     * @return array<int, mixed> the cURL options to use for $to_url.
+     */
+    public static function curl_options_for_origin(array $curl_options, string $from_url, string $to_url)
+    {
+        $origins = [];
+        foreach ([$from_url, $to_url] as $url) {
+            $url_parts = parse_url(strtolower($url));
+            if ($url_parts === false || !isset($url_parts['scheme'], $url_parts['host'])) {
+                $origins[] = null;
+                continue;
+            }
+            if (!isset($url_parts['port'])) {
+                $url_parts['port'] = $url_parts['scheme'] === 'https' ? 443 : 80;
+            }
+            $origins[] = [$url_parts['scheme'], $url_parts['host'], $url_parts['port']];
+        }
+        if ($origins[0] === null || $origins[0] !== $origins[1]) {
+            unset(
+                $curl_options[CURLOPT_USERPWD],
+                $curl_options[CURLOPT_COOKIE],
+                $curl_options[CURLOPT_HTTPHEADER],
+                $curl_options[CURLOPT_POST],
+                $curl_options[CURLOPT_POSTFIELDS]
+            );
+        }
+        return $curl_options;
     }
 }
 

+ 56 - 0
lib/simplepie/simplepie/src/Sanitize.php

@@ -515,6 +515,8 @@ class Sanitize implements RegistryAware
                     }
                 }
 
+                $this->flatten_raw_text_elements($xpath);
+
                 if (!empty($this->rename_attributes)) {
                     foreach ($this->rename_attributes as $attrib) {
                         $this->rename_attr($attrib, $xpath);
@@ -633,6 +635,60 @@ class Sanitize implements RegistryAware
         return $data;
     }
 
+    /**
+     * Elements whose content is read by Web browsers as text up to their first matching end tag,
+     * whereas HTML parsers may build child elements in them: all of them in the legacy libxml2
+     * parser (under PHP 8.4), and `<noscript>` in `Dom\HTMLDocument`, because server-side
+     * parsing of the HTML5 parser has scripting disabled.
+     * Serializing such child elements would let e.g. `<xmp><a title="<!--</xmp><img>-->">`
+     * end the element early in a browser and turn the rest of the attribute value into live markup.
+     * `<script>` and `<style>` are not listed because libxml2 already parses their content as text.
+     * @var list<string>
+     */
+    private const RAW_TEXT_ELEMENTS = [
+        'iframe',
+        'noembed',
+        'noframes',
+        'noscript',
+        'plaintext',
+        'textarea',
+        'title',
+        'xmp',
+    ];
+
+    /**
+     * Replace the content of raw text elements by its text only.
+     *
+     * Serializing child elements there would let e.g. `<xmp><a title="<!--</xmp><img>-->">`
+     * end the element early in a browser and turn the rest of the attribute value into live markup.
+     *
+     * Runs on every engine: the legacy libxml2 parser (under PHP 8.4) builds child elements in all
+     * of the listed elements, and with the native HTML5 parser (PHP 8.4+) it is a no-op for the
+     * other elements but still required for `<noscript>`, whose text children `saveHtml()`
+     * serializes literally, without escaping markup characters in attribute values.
+     */
+    private function flatten_raw_text_elements(\Dom\XPath $xpath): void
+    {
+        // Only HTML elements get raw text semantics in Web browsers. The HTML5 parser
+        // puts them in the XHTML namespace, matching the `registerNamespace()` calls above,
+        // whereas unprefixed name tests such as `self::iframe` would not match anything.
+        /** @var \Dom\NodeList<\Dom\Element> */
+        $elements = $xpath->query('//*[self::xh:' . implode(' or self::xh:', self::RAW_TEXT_ELEMENTS) . '][node()]');
+        foreach ($elements as $element) {
+            $text = $element->textContent;
+            while (($child = $element->firstChild) !== null) {
+                // This also removes comments and processing instructions, which `textContent` omits
+                $element->removeChild($child);
+            }
+            if ($text !== '') {
+                $ownerDocument = $element->ownerDocument;
+                assert($ownerDocument !== null, 'For PHPStan, element must have an owner document');
+                // Not `new \Dom\Text($text)`, which the `Dom\` polyfill (PHP < 8.4) does not implement
+                $element->appendChild($ownerDocument->createTextNode($text));
+            }
+        }
+    }
+
     /**
      * @param int-mask-of<SimplePie::CONSTRUCT_*> $type
      * @return string

+ 7 - 1
lib/simplepie/simplepie/src/SimplePie.php

@@ -2047,6 +2047,11 @@ class SimplePie
                 elseif (isset($this->data['feed_url'])) {
                     // Do not need to do feed autodiscovery yet.
                     if ($this->data['feed_url'] !== $this->data['url']) {
+                        // Like in the Locator, credentials are only for the origin they were given for
+                        $this->curl_options = Misc::curl_options_for_origin($this->curl_options, $this->data['url'], $this->data['feed_url']);
+                        if (is_object($this->http_client) && $this->http_client instanceof FileClient) {
+                            $this->http_client = null;
+                        }
                         $this->set_feed_url($this->data['feed_url']);
                         $this->data['url'] = $this->data['feed_url'];
 
@@ -2195,7 +2200,8 @@ class SimplePie
                 $this->useragent,
                 $this->max_checked_feeds,
                 $this->force_fsockopen,
-                $this->curl_options
+                $this->curl_options,
+                $this->feed_url, // URL as requested, before possible redirects
             ]);
 
             $http_client = $this->get_http_client();