Sfoglia il codice sorgente

Normalize cURL proxy options during requests (#9604)

Ref: [GHSA-fc32-79hf-pcmw](https://github.com/FreshRSS/FreshRSS/security/advisories/GHSA-fc32-79hf-pcmw) (considered a bug), https://github.com/curl/curl/issues/23681, https://github.com/FreshRSS/FreshRSS/discussions/9286#discussioncomment-18392518

Fixed issues:
* Using wrong default HTTP port for proxies (supposed to be 1080 not 80).
* Lack of system configuration support for a mix of `CURLOPT_{PROXY,PROXYTYPE,PROXYPORT}` options, along with user defined feed options.

* Normalize cURL proxy options during requests

* Use `CURLPROXY_HTTPS` in tests instead of 2

* Fix some more mismatched port cases

* Remove changelog
Avoid changelog in PRs to reduce conflicts

* Minor comments reduction

---------

Co-authored-by: Alexandre Alapetite <alexandre@alapetite.fr>
Inverle 1 giorno fa
parent
commit
feeec153c4

+ 2 - 2
app/Models/Feed.php

@@ -107,8 +107,8 @@ class FreshRSS_Feed extends Minz_Model {
 
 	/** Must match the proxy of `FreshRSS_SimplePieCustom`, which stores `Retry-After`. */
 	public function proxyParam(): string {
-		$curl_options = array_replace(FreshRSS_Context::systemConf()->curl_options,
-			FreshRSS_http_Util::sanitizeCurlParams($this->attributeArray('curl_params') ?? []));
+		$curl_options = FreshRSS_http_Util::normalizeProxyOptions(array_replace(FreshRSS_Context::systemConf()->curl_options,
+			FreshRSS_http_Util::sanitizeCurlParams($this->attributeArray('curl_params') ?? [])));
 		$proxyType = $curl_options[CURLOPT_PROXYTYPE] ?? 0;
 		if (is_int($proxyType) && ($proxyType < 0 || $proxyType === 3)) {	// 3 is legacy for NONE
 			return '';	// Proxy disabled for this feed

+ 1 - 0
app/Models/SimplePieCustom.php

@@ -44,6 +44,7 @@ final class FreshRSS_SimplePieCustom extends \SimplePie\SimplePie
 				unset($curl_options[CURLOPT_PROXY]);
 			}
 		}
+		$curl_options = FreshRSS_http_Util::normalizeProxyOptions($curl_options);
 		if (defined('CURLOPT_PROTOCOLS_STR') && is_int(CURLOPT_PROTOCOLS_STR)) {
 			$curl_options[CURLOPT_PROTOCOLS_STR] = 'http,https';
 			if (defined('CURLOPT_REDIR_PROTOCOLS_STR') && is_int(CURLOPT_REDIR_PROTOCOLS_STR)) {

+ 71 - 23
app/Utils/httpUtil.php

@@ -3,6 +3,8 @@ declare(strict_types=1);
 
 final class FreshRSS_http_Util {
 
+	private const PROXY_INVALID_CHARS = '~[/?#\\\\\s]~';
+
 	private const RETRY_AFTER_PATH = DATA_PATH . '/Retry-After/';
 	private const NAT64_PREFIX_RFC6052 = '64:ff9b::/96';
 
@@ -141,15 +143,62 @@ final class FreshRSS_http_Util {
 				$curl_params[$k] = array_filter($curl_params[$k],
 					fn($header) => is_string($header) && !preg_match('/^(Remote[-_\s]*User|X[-_\s]*WebAuth[-_\s]*User)\\s*:/i', $header));
 			}
-			// Forbid '/' in CURLOPT_PROXY [user[:pass]@]host[:port] (the scheme comes from CURLOPT_PROXYTYPE),
-			// to reject e.g. 'http://example.net/://decoy' and 'localhost:9050/path/to.sock'
-			if ($k === CURLOPT_PROXY && (!is_string($curl_params[$k]) || str_contains($curl_params[$k], '/'))) {
+			// Forbid '/', '?', '#', '\' and whitespace in CURLOPT_PROXY [user[:pass]@]host[:port] (the scheme comes from CURLOPT_PROXYTYPE),
+			// to reject e.g. decoy hosts 'http://example.net/://decoy' and Unix sockets 'localhost:9050/path/to.sock'.
+			// Credentials must be percent-encoded.
+			if ($k === CURLOPT_PROXY && (!is_string($curl_params[$k]) || preg_match(self::PROXY_INVALID_CHARS, $curl_params[$k]) === 1)) {
 				unset($curl_params[$k], $curl_params[CURLOPT_PROXYTYPE]);
 			}
 		}
 		return $curl_params;
 	}
 
+	/**
+	 * Make the proxy options explicit, so that the SSRF checks use the same proxy address as cURL will connect to:
+	 * `CURLOPT_PROXY` becomes `[user[:pass]@]host:port`, scheme moved to `CURLOPT_PROXYTYPE`, and `CURLOPT_PROXYPORT` removed.
+	 * The port is the explicit one, else `CURLOPT_PROXYPORT`, else the documented port defaults of cURL
+	 * (443 for https, 1080 otherwise), which versions 8.21.0-8.23.x do not follow, hence made explicit.
+	 * A scheme is only accepted in the system config, as `sanitizeCurlParams()` rejects it for feeds.
+	 * @param array<mixed> $curl_options
+	 * @return array<int,mixed>
+	 */
+	public static function normalizeProxyOptions(array $curl_options): array {
+		$curl_options = array_filter($curl_options, is_int(...), ARRAY_FILTER_USE_KEY);
+		$proxy = $curl_options[CURLOPT_PROXY] ?? null;
+		$type = $curl_options[CURLOPT_PROXYTYPE] ?? CURLPROXY_HTTP;
+		if (!is_string($proxy) || $proxy === '' || !is_int($type) || $type < 0 || $type === 3) {	// 3 is legacy for NONE
+			return $curl_options;	// No proxy, or disabled for this feed
+		}
+		defined('CURLPROXY_HTTPS') or define('CURLPROXY_HTTPS', 2);	// Compatibility cURL 7.51
+		if (preg_match('#^([a-z0-9]+)://([^/]*)/?$#i', $proxy, $matches) === 1) {
+			$type = match (strtolower($matches[1])) {	// As in cURL, the scheme takes precedence over `CURLOPT_PROXYTYPE`
+				'http' => CURLPROXY_HTTP,
+				'https' => CURLPROXY_HTTPS,
+				'socks4' => CURLPROXY_SOCKS4,
+				'socks4a' => CURLPROXY_SOCKS4A,
+				'socks5' => CURLPROXY_SOCKS5,
+				'socks5h' => CURLPROXY_SOCKS5_HOSTNAME,
+				default => null,
+			};
+			if ($type === null) {
+				return $curl_options;	// Unsupported scheme, left as is for the checks to fail
+			}
+			$proxy = $matches[2];
+		}
+		if (preg_match(self::PROXY_INVALID_CHARS, $proxy) === 1) {	// Makes the port check below safe, so it can't be tricked with e.g. 127.0.0.1?:6379
+			return $curl_options;	// Invalid, left as is for the checks to fail
+		}
+		if (preg_match('/:\\d+$/', $proxy) !== 1) {	// Does not end with :port (an IPv6 address like [::1] ends with ']', so is not mistaken for a port)
+			$port = $curl_options[CURLOPT_PROXYPORT] ?? null;
+			// Port defaults according to https://curl.se/libcurl/c/CURLOPT_PROXYPORT.html
+			$proxy .= ':' . (is_int($port) && $port > 0 && $port < 65536 ? $port : ($type === CURLPROXY_HTTPS ? 443 : 1080));
+		}
+		$curl_options[CURLOPT_PROXY] = $proxy;
+		$curl_options[CURLOPT_PROXYTYPE] = $type;
+		unset($curl_options[CURLOPT_PROXYPORT]);	// Now in `CURLOPT_PROXY`, and some cURL versions let it override a port equal to the scheme default
+		return $curl_options;
+	}
+
 	private static function idn_to_puny(string $url): string {
 		if (function_exists('idn_to_ascii')) {
 			$idn = parse_url($url, PHP_URL_HOST);
@@ -302,6 +351,7 @@ final class FreshRSS_http_Util {
 
 	/**
 	 * Returns a value for CURLOPT_RESOLVE as an array, null if no allowed IPs were found, false if the domain failed to resolve.
+	 * For proxy URLs, cURL options must be passed through `FreshRSS_http_Util::normalizeProxyOptions(...)` first.
 	 *
 	 * @return array<string>|null|false
 	 */
@@ -331,15 +381,17 @@ final class FreshRSS_http_Util {
 			$internal_host_allowlist = FreshRSS_Context::systemConf()->internal_host_allowlist;
 		}
 
+		// Fill in default port for website URLs if missing.
+		// Not for proxy URLs: their default port varies by cURL version
+		// (https://github.com/curl/curl/issues/23681), so the proxy port must have been made explicit by `normalizeProxyOptions()`.
 		$port = parse_url($url)['port'] ?? match ($scheme) {
 			'http' => 80,
 			'https' => 443,
-			'socks4' => 1080,
-			'socks4a' => 1080,
-			'socks5' => 1080,
-			'socks5h' => 1080,
-			default => 0,
+			default => null,
 		};
+		if (!is_int($port)) {
+			return false;	// Missing or ambiguous proxy port
+		}
 		if (in_array('*', $internal_host_allowlist, true)) {
 			return [];	// Disables SSRF checks entirely (unsafe)
 		}
@@ -496,22 +548,15 @@ final class FreshRSS_http_Util {
 		}
 
 		$accept = '';
-		$proxy = is_string(FreshRSS_Context::systemConf()->curl_options[CURLOPT_PROXY] ?? null) ? FreshRSS_Context::systemConf()->curl_options[CURLOPT_PROXY] : '';
-		$proxy_type = is_int(FreshRSS_Context::systemConf()->curl_options[CURLOPT_PROXYTYPE] ?? null) ?
-			FreshRSS_Context::systemConf()->curl_options[CURLOPT_PROXYTYPE] : 0;
-		if (!empty($options)) {
-			$proxy = is_string($options[CURLOPT_PROXY] ?? null) ? $options[CURLOPT_PROXY] : $proxy;
-			$proxy_type = is_int($options[CURLOPT_PROXYTYPE] ?? null) ? $options[CURLOPT_PROXYTYPE] : $proxy_type;
-			if (is_array($options[CURLOPT_HTTPHEADER] ?? null)) {
-				// Add Accept header if it is not set
-				if (preg_grep('/^Accept\\s*:/i', $options[CURLOPT_HTTPHEADER]) === false) {
-					$options[CURLOPT_HTTPHEADER][] = 'Accept: ' . $accept;
-				}
+		$proxy_options = self::normalizeProxyOptions(array_replace(FreshRSS_Context::systemConf()->curl_options, $options, $curl_options));
+		$proxy = is_string($proxy_options[CURLOPT_PROXY] ?? null) ? $proxy_options[CURLOPT_PROXY] : '';
+		$proxy_type = is_int($proxy_options[CURLOPT_PROXYTYPE] ?? null) ? $proxy_options[CURLOPT_PROXYTYPE] : 0;
+		if (!empty($options) && is_array($options[CURLOPT_HTTPHEADER] ?? null)) {
+			// Add Accept header if it is not set
+			if (preg_grep('/^Accept\\s*:/i', $options[CURLOPT_HTTPHEADER]) === false) {
+				$options[CURLOPT_HTTPHEADER][] = 'Accept: ' . $accept;
 			}
 		}
-		$proxy_type = is_int($curl_options[CURLOPT_PROXYTYPE] ?? null) ? $curl_options[CURLOPT_PROXYTYPE] : $proxy_type;
-		// CURLOPT_PROXY is already scheme-less by the time it reaches here:
-		$proxy = is_string($curl_options[CURLOPT_PROXY] ?? null) ? $curl_options[CURLOPT_PROXY] : $proxy;
 
 		if (($retryAfter = FreshRSS_http_Util::getRetryAfter($url, $proxy)) > 0) {
 			Minz_Log::warning('For that domain, will first retry after ' . date('c', $retryAfter) . '. ' . \SimplePie\Misc::url_remove_credentials($url));
@@ -580,7 +625,7 @@ final class FreshRSS_http_Util {
 					// Unsupported proxy type
 					return ['body' => '', 'effective_url' => '', 'redirect_count' => 0, 'fail' => true, 'status' => -500, 'error' => '', 'method' => $c_method];
 				}
-				$proxy_url = "$proxy_scheme://$proxy"; // CURLOPT_PROXY ($proxy) is formatted as user:pass@hostname:port, with the part before @ being optional
+				$proxy_url = "$proxy_scheme://$proxy"; // `$proxy` is formatted as [user[:pass]@]host:port] (cURL proxy options are normalized before).
 				$resolve = self::getCurlResolveInfo($proxy_url);
 				if ($resolve === null) {
 					Minz_Log::warning('Failed to fetch this URL, because the proxy’s IP is not in the allowlist [' .
@@ -649,6 +694,9 @@ final class FreshRSS_http_Util {
 			}
 
 			curl_setopt_array($ch, $curl_options);
+			if ($proxy !== '') {	// Same address (with explicit port) as checked above, because the default proxy port of cURL varies
+				curl_setopt_array($ch, [CURLOPT_PROXY => $proxy, CURLOPT_PROXYTYPE => $proxy_type, CURLOPT_PROXYPORT => 0]);
+			}
 			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);	// We handle HTTP redirections manually for security
 
 			$body = curl_exec($ch);

+ 2 - 2
config.default.php

@@ -170,8 +170,8 @@ return [
 		//CURLOPT_PROXYTYPE => CURLPROXY_HTTP,
 		//CURLOPT_PROXY => '127.0.0.1',
 		//CURLOPT_PROXYPORT => 8080,
-		//CURLOPT_PROXYAUTH => CURLAUTH_BASIC,
-		//CURLOPT_PROXYUSERPWD => 'user:password',
+		// Alternatively, the type and port can be given in the address: //CURLOPT_PROXY => 'http://127.0.0.1:8080',
+		// CURLOPT_PROXYAUTH and CURLOPT_PROXYUSERPWD are not supported, credentials can be put in the URL instead.
 	],
 
 	'db' => [

+ 26 - 1
docs/en/admins/17_configs_not_ui.md

@@ -70,7 +70,32 @@ the global cURL options:
 ],
 ```
 
-This is useful for proxies such as VPN gateway containers. The option applies
+In the system config, `CURLOPT_PROXY` accepts `[scheme://][user:password@]host[:port]`, and the proxy can be described in several equivalent ways:
+
+```php
+// Type and port as separate options
+CURLOPT_PROXY => 'proxy.example.net',
+CURLOPT_PROXYTYPE => CURLPROXY_HTTP,
+CURLOPT_PROXYPORT => 8080,
+
+// Port in the address
+CURLOPT_PROXY => 'proxy.example.net:8080',
+CURLOPT_PROXYTYPE => CURLPROXY_HTTP,
+
+// Type and port in the address
+CURLOPT_PROXY => 'http://proxy.example.net:8080',
+```
+
+* The supported schemes are `http`, `https`, `socks4`, `socks4a`, `socks5` and `socks5h`.
+	If a scheme is given, it takes precedence over `CURLOPT_PROXYTYPE` (as in cURL).
+* If the address contains a port, it takes precedence over `CURLOPT_PROXYPORT`.
+	Otherwise, `CURLOPT_PROXYPORT` is used, and finally 443 for an `https` proxy or 1080 for the others.
+	FreshRSS always passes the port explicitly in the address to cURL (and no longer uses `CURLOPT_PROXYPORT` for the request),
+	because the default port of cURL, and how it combines `CURLOPT_PROXYPORT` with the address, depends on its version.
+* The proxy address (with its port) must be allowed by `internal_host_allowlist` if it is on a local network.
+* Proxies set per feed (in the user interface) do not accept a scheme, as their type is a separate setting.
+
+This is useful for proxies such as VPN gateway containers. The options apply
 to all feed requests unless overridden by a feed-specific configuration.
 
 ## Force HTTPS

+ 104 - 0
tests/app/Utils/httpUtilTest.php

@@ -38,6 +38,16 @@ final class httpUtilTest extends \PHPUnit\Framework\TestCase {
 			// port, so an allowlisted host:port could otherwise be smuggled into connecting to an
 			// arbitrary local socket.
 			'rejects a SOCKS Unix-domain-socket path' => ['localhost:9050/path/to.sock', false],
+			// Certain characters complicate normalizing of proxy URLs, so they're disallowed.
+			'rejects a query delimiter' => ['127.0.0.1?:6379', false],
+			'rejects a fragment delimiter' => ['127.0.0.1#:6379', false],
+			'rejects a query hiding a decoy host' => ['127.0.0.1?@10.0.0.1:80', false],
+			'rejects a fragment hiding a decoy host' => ['8.8.8.8#@127.0.0.1', false],
+			'rejects a backslash' => ['127.0.0.1\\@8.8.8.8:80', false],
+			'rejects a space' => ['127.0.0.1 :80', false],
+			'rejects a tab' => ["127.0.0.1\t:80", false],
+			'rejects a newline' => ["127.0.0.1\n:80", false],
+			'accepts percent-encoded credentials' => ['user:p%3Fss%23w%40rd@proxy.example.com:3128', true],
 			'accepts bare host:port' => ['127.0.0.1:8080', true],
 			'accepts hostname:port' => ['proxy.example.com:3128', true],
 			'accepts host:port with credentials' => ['user:pass@203.0.113.5:1080', true],
@@ -45,6 +55,100 @@ final class httpUtilTest extends \PHPUnit\Framework\TestCase {
 		];
 	}
 
+	/**
+	 * @param array<int,mixed> $options
+	 * @param array<int,mixed> $expected
+	 */
+	#[DataProvider('provideProxyOptions')]
+	public function test_normalizeProxyOptions(array $options, array $expected): void {
+		self::assertEquals($expected, FreshRSS_http_Util::normalizeProxyOptions($options));
+	}
+
+	/** @return array<string,array{array<int,mixed>,array<int,mixed>}> */
+	public static function provideProxyOptions(): array {
+		return [
+			'CURLOPT_PROXYPORT is added' => [
+				[CURLOPT_PROXY => 'proxy.internal', CURLOPT_PROXYTYPE => CURLPROXY_HTTP, CURLOPT_PROXYPORT => 3128],
+				[CURLOPT_PROXY => 'proxy.internal:3128', CURLOPT_PROXYTYPE => CURLPROXY_HTTP]],
+			'port in CURLOPT_PROXY wins' => [
+				[CURLOPT_PROXY => 'proxy.internal:3128', CURLOPT_PROXYPORT => 4000],
+				[CURLOPT_PROXY => 'proxy.internal:3128', CURLOPT_PROXYTYPE => CURLPROXY_HTTP]],
+			'scheme in system config' => [
+				[CURLOPT_PROXY => 'http://proxy.internal:3128/'],
+				[CURLOPT_PROXY => 'proxy.internal:3128', CURLOPT_PROXYTYPE => CURLPROXY_HTTP]],
+			'scheme wins over type' => [
+				[CURLOPT_PROXY => 'socks5h://user:pass@proxy.internal', CURLOPT_PROXYTYPE => CURLPROXY_HTTP],
+				[CURLOPT_PROXY => 'user:pass@proxy.internal:1080', CURLOPT_PROXYTYPE => CURLPROXY_SOCKS5_HOSTNAME]],
+			'scheme with CURLOPT_PROXYPORT' => [
+				[CURLOPT_PROXY => 'http://proxy.internal', CURLOPT_PROXYPORT => 3128],
+				[CURLOPT_PROXY => 'proxy.internal:3128', CURLOPT_PROXYTYPE => CURLPROXY_HTTP]],
+			'scheme in uppercase' => [
+				[CURLOPT_PROXY => 'HTTP://proxy.internal:3128'],
+				[CURLOPT_PROXY => 'proxy.internal:3128', CURLOPT_PROXYTYPE => CURLPROXY_HTTP]],
+			'HTTPS scheme' => [
+				[CURLOPT_PROXY => 'https://proxy.internal'],
+				[CURLOPT_PROXY => 'proxy.internal:443', CURLOPT_PROXYTYPE => CURLPROXY_HTTPS]],
+			'unsupported scheme is left as is' => [
+				[CURLOPT_PROXY => 'ftp://proxy.internal:3128'],
+				[CURLOPT_PROXY => 'ftp://proxy.internal:3128']],
+			'default port for HTTPS' => [
+				[CURLOPT_PROXY => 'proxy.internal', CURLOPT_PROXYTYPE => CURLPROXY_HTTPS],
+				[CURLOPT_PROXY => 'proxy.internal:443', CURLOPT_PROXYTYPE => CURLPROXY_HTTPS]],
+			'IPv6 without port' => [
+				[CURLOPT_PROXY => '[::1]', CURLOPT_PROXYPORT => 3128],
+				[CURLOPT_PROXY => '[::1]:3128', CURLOPT_PROXYTYPE => CURLPROXY_HTTP]],
+			'IPv6 with port' => [
+				[CURLOPT_PROXY => '[::1]:3128'],
+				[CURLOPT_PROXY => '[::1]:3128', CURLOPT_PROXYTYPE => CURLPROXY_HTTP]],
+			'invalid value is left as is' => [
+				[CURLOPT_PROXY => 'http://127.0.0.1:8080/://8.8.8.8'],
+				[CURLOPT_PROXY => 'http://127.0.0.1:8080/://8.8.8.8']],
+			'query is left as is' => [
+				[CURLOPT_PROXY => '127.0.0.1?:6379'],
+				[CURLOPT_PROXY => '127.0.0.1?:6379']],
+			'fragment is left as is' => [
+				[CURLOPT_PROXY => 'http://127.0.0.1#:6379'],
+				[CURLOPT_PROXY => 'http://127.0.0.1#:6379']],
+			'proxy disabled' => [
+				[CURLOPT_PROXY => 'proxy.internal', CURLOPT_PROXYTYPE => -1],
+				[CURLOPT_PROXY => 'proxy.internal', CURLOPT_PROXYTYPE => -1]],
+			'no proxy' => [[CURLOPT_PROXYPORT => 3128], [CURLOPT_PROXYPORT => 3128]],
+		];
+	}
+
+	/** An ambiguous feed proxy must be rejected by sanitization, before the port check of `getCurlResolveInfo()`. */
+	#[DataProvider('provideAmbiguousFeedProxies')]
+	public function test_feedProxyIsNotAmbiguousForAllowlistCheck(string $proxy): void {
+		putenv('INTERNAL_HOST_ALLOWLIST=127.0.0.1:80');
+		try {
+			$options = FreshRSS_http_Util::normalizeProxyOptions(
+				FreshRSS_http_Util::sanitizeCurlParams([CURLOPT_PROXY => $proxy, CURLOPT_PROXYTYPE => CURLPROXY_HTTP]));
+			self::assertArrayNotHasKey(CURLOPT_PROXY, $options);
+			self::assertArrayNotHasKey(CURLOPT_PROXYTYPE, $options);
+		} finally {
+			putenv('INTERNAL_HOST_ALLOWLIST');
+		}
+	}
+
+	/** @return array<string,array{string}> */
+	public static function provideAmbiguousFeedProxies(): array {
+		return [
+			'query with port' => ['127.0.0.1?:6379'],
+			'fragment with port' => ['127.0.0.1#:6379'],
+			'query without port' => ['127.0.0.1?'],
+			'fragment without port' => ['127.0.0.1#'],
+			'query then credentials' => ['10.0.0.1?@:6379'],
+		];
+	}
+
+	public function test_proxyPortIsUsedByAllowlistCheck(): void {
+		putenv('INTERNAL_HOST_ALLOWLIST=127.0.0.1:3128');
+		$options = FreshRSS_http_Util::normalizeProxyOptions([CURLOPT_PROXY => '127.0.0.1', CURLOPT_PROXYPORT => 3128]);
+		self::assertIsString($options[CURLOPT_PROXY]);
+		self::assertSame([], FreshRSS_http_Util::getCurlResolveInfo('http://' . $options[CURLOPT_PROXY]));
+		putenv('INTERNAL_HOST_ALLOWLIST');
+	}
+
 	#[DataProvider('provideUrlsForCheckUrl')]
 	public function test_checkUrl(string $url, string|false $expected): void {
 		self::assertSame($expected, FreshRSS_http_Util::checkUrl($url));