Repository navigation
Implement safe-by-default URL policy - #991
ziegenberg wants to merge 2 commits into
Conversation
jgalea
left a comment
There was a problem hiding this comment.
Thanks for this. We run SimplePie inside WP RSS Aggregator, so the local-file part of #968 matters to us, and I think the shape here is right: refuse non-http(s) at the client layer, keep local files as an explicit opt-in, and never let content-derived URLs (autodiscovery, redirects) reach the filesystem.
It also makes @jtojnar's suggestion in #968 workable. Once SimplePie stops reading local files before the PSR-18 client is called, a consumer who wants IP-level filtering can plug in something like httplug-ssrf-plugin and it actually sees every request. Before this PR it couldn't, which was @ziegenberg's point.
A few things I'd change, plus two tests for the Psr18Client redirect path. Tests are on a branch I can push or paste, whichever you prefer.
I ran the suite on PHP 8.5: no new failures, phpstan and php-cs-fixer clean.
Scope wording
UrlPolicy::isAllowed() returns true for any http(s) URL ("Phase 2" comment), so this PR is about local files and stream wrappers, not private/loopback addresses. That's a reasonable split given the discussion in #968, but the CHANGELOG line says it "reduces the risk of SSRF". I'd say "local-file disclosure" there and in the README, and leave SSRF wording for whenever (or whether) IP filtering lands, so nobody reads this as covering internal hosts.
Notes by line
src/HTTP/Psr18Client.php:146-154
Two issues with the refused-redirect branch:
$requestedUrland (for 301/308)$permanentUrlare assigned the Location value before the policy check, so the returned response reports the refused URL as its final and permanent URI. Callers then see a non-remote final URI, and the checks inSimplePie::fetch_data(),LocatorandSanitizeof the form!Misc::is_remote_uri($file->get_final_requested_uri()) || <2xx>skip the status check and treat the 3xx body as a successful response. Consumers that persist the permanent URL after a 301 would also store the refused URL.- The check calls
isAllowed($requestedUrl)without$discovered = true, so withset_allow_local_files(true)a redirect tofile://is forwarded to the injected PSR-18 client. The README says redirects to non-http(s) are refused even when local files are allowed.
Something like:
$location = $response->getHeaderLine('Location');
if (!$this->urlPolicy->isAllowed($location, true)) {
break;
}
$requestedUrl = $location;
if ($statusCode === 301 || $statusCode === 308) {
$permanentUrl = $requestedUrl;
}It might also be worth throwing here instead of returning the 3xx response, so Psr18Client matches FileClient, where File sets success = false and the request ends in an exception.
src/HTTP/UrlPolicy.php:37
Nothing passes $discovered = true at the moment, so that argument is dead code outside the unit test. Either use it at the redirect check above (my preference) or drop it, and let the Locator keep its own is_remote_uri() guards.
src/HTTP/NotAllowedException.php:17
Would it be simpler for this to extend ClientException (or for the client to throw ClientException)? Anything that calls a Client and catches ClientException today, inside SimplePie or in a downstream wrapper, would then keep working without the ClientException | NotAllowedException changes in Locator, Sanitize and SimplePie. A refused URL is a failed request from the caller's point of view. If you want callers to tell it apart, a subclass still allows that.
src/SimplePie.php:853
set_allow_local_files(bool $allow = false): a setter whose default argument turns the feature off reads oddly, since $feed->set_allow_local_files() would disable it. enable_cache(bool $enable = true) and friends default to true. I'd either default to true or drop the default.
src/Locator.php:467 (is_candidate_fetchable)
get_links() used to accept feed as a scheme (/^(https?|feed)?$/i) and now doesn't. I don't think those links were ever fetchable as-is, so this is probably fine, but it's a behaviour change worth a line in the commit message, or run them through fix_protocol() if they should keep working.
src/HTTP/FileClient.php:79
The final-URI re-check is fine as a backstop. Worth knowing it's a no-op for file classes that don't update $url on redirect (WordPress's WP_SimplePie_File keeps the original URL), so it shouldn't be described as the thing that catches redirects for custom File classes.
Proposed extra tests
In tests/Unit/HTTP/Psr18ClientTest.php. Both fail on the PR as-is and pass with the change in the Psr18Client comment:
testRefusedPermanentRedirectDoesNotChangeResponseUris: 301 tofile:///etc/passwdwith the default policy; asserts permanent and final URIs stayhttps://example.com/redirect. Currently both come back asfile:///etc/passwd.testNonHttpRedirectIsNotForwardedEvenWithLocalFilesAllowed: 302 tofile://with local files allowed; assertssendRequest()is called once. Currently it's called twice.
Further tests I'd suggest but haven't written:
testClientRejectsRedirectToLocalFileruns withallow_local_files => true. A copy with the default (false) would pin down theFile-level check and the FileClient re-check separately.
WordPress core
WordPress's fetch_feed() registers WP_SimplePie_File in place of SimplePie\File. That class only fetches http(s):// URLs, through wp_safe_remote_request(), and fails anything else, so WordPress never read local files through SimplePie in the first place. With this PR, FileClient's check runs before the File class is created, so the result for WordPress is the same. The redirect checks added in File::__construct() don't run there because WP overrides the constructor; WP handles redirects and private-address filtering in its own HTTP API. No breakage that I can see, and nothing extra gained for WP.
|
Hi @jgalea, Could you paste the two tests so I could look into incorporating them? Greetings, |
|
Sure, here they are. They go at the end of private function createClientWithRedirectTo(int $statusCode, string $location, ?UrlPolicy $policy = null): Psr18Client
{
$request = $this->createMock(RequestInterface::class);
$request->method('withUri')->willReturn($request);
$requestFactory = $this->createMock(RequestFactoryInterface::class);
$requestFactory->method('createRequest')->willReturn($request);
$response = $this->createMock(ResponseInterface::class);
$response->method('getStatusCode')->willReturn($statusCode);
$response->method('hasHeader')->with('Location')->willReturn(true);
$response->method('getHeaderLine')->with('Location')->willReturn($location);
$httpClient = $this->createMock(ClientInterface::class);
$httpClient->expects($this->once())->method('sendRequest')->willReturn($response);
$client = new Psr18Client(
$httpClient,
$requestFactory,
$this->createMock(UriFactoryInterface::class)
);
if ($policy !== null) {
$client->setUrlPolicy($policy);
}
return $client;
}
public function testRefusedPermanentRedirectDoesNotChangeResponseUris(): void
{
$client = $this->createClientWithRedirectTo(301, 'file:///etc/passwd');
$response = $client->request(Client::METHOD_GET, 'https://example.com/redirect');
self::assertSame('https://example.com/redirect', $response->get_permanent_uri());
self::assertSame('https://example.com/redirect', $response->get_final_requested_uri());
}
public function testNonHttpRedirectIsNotForwardedEvenWithLocalFilesAllowed(): void
{
$policy = new UrlPolicy();
$policy->setAllowLocalFiles(true);
$client = $this->createClientWithRedirectTo(302, 'file:///etc/passwd', $policy);
$response = $client->request(Client::METHOD_GET, 'https://example.com/redirect');
self::assertSame(302, $response->get_status_code());
}On the current head (1535c78) both fail: the first gets |
|
Thanks, this is a genuinely useful review, and I verified each line-level point against the code; they're all accurate. I've adopted the Psr18Client fix and added your tests. Psr18Client redirect handling. Fixed as you suggested: the Throwing vs. returning the 3xx. I went with throwing On Wording. I changed the CHANGELOG and README from "SSRF" to "local-file disclosure", since this PR is about local files and stream wrappers rather than private-IP filtering.
On the WordPress note, good confirmation that there's no breakage there. And I'll add the default- |
|
Re-ran on 7f20624: our two tests pass, phpstan and php-cs-fixer are clean, and the full suite has the same 14 failures as master (the remote UTF-16 cases). One thing in the new redirect check: a relative Resolving the header against the current URL before the check fixes both: $location = $response->getHeaderLine('Location');
$location = Misc::absolutize_url($location, $requestedUrl) ?: $location;With that, Guzzle against a local server returning |
jtojnar
left a comment
There was a problem hiding this comment.
Thanks. I am starting to think that allowing Psr18Client to fetch files was a mistake.
| Local files | ||
| ------------ | ||
|
|
||
| Fetching local files (filesystem paths) as feeds is **disabled by default** in |
There was a problem hiding this comment.
I wonder if we should just disallow fetching raw files completely, and direct people to use SimplePie::set_raw_data(file_get_contents(…)) if they really need it.
It might make migration slightly more complicated but I do not expect any of the large consumers to intend supporting fetching local files anyway.
| public function isAllowed(string $url, bool $discovered = false): bool | ||
| { | ||
| if (Misc::is_remote_uri($url)) { | ||
| return true; // Phase 2: add private-IP/loopback checks here. |
There was a problem hiding this comment.
That will require DNS lookups, at which point I am not sure about the naming of UrlPolicy .
| if ($link->hasAttribute('href')) { | ||
| $href = trim($link->getAttribute('href')); | ||
| $parsed = $this->registry->call(Misc::class, 'parse_url', [$href]); | ||
| if ($parsed['scheme'] === '' || preg_match('/^(https?|feed)?$/i', $parsed['scheme'])) { |
There was a problem hiding this comment.
Perhaps split this into a separate commit since it is an unrelated, but welcome cleanup.
| if ($this->checked_feeds === $this->max_checked_feeds) { | ||
| break; | ||
| } | ||
| if (!Misc::is_remote_uri($value)) { |
There was a problem hiding this comment.
I would like this to go to get_links since that is what produces the arrays for both extension and body methods but we probably need it here as well since the method is public 🤷♀️
Introduce SimplePie\HTTP\UrlPolicy and make local-file fetching opt-in: - New UrlPolicy decides whether a URI may be fetched; http(s) URIs are always allowed, local files and stream wrappers are blocked by default, and discovered URLs (locator candidates, redirects) are always http(s)-only. - New NotAllowedException so callers can detect policy refusal. It extends SimplePieException rather than ClientException: a refusal is not a failed request, and its cause is the caller's own configuration, so a broad catch (ClientException) should not treat it as a request failure. - Psr18Client: gate in request(), setUrlPolicy(), and throw NotAllowedException on a refused redirect Location instead of forwarding it, passing $discovered so it is refused even when local files are allowed. - FileClient: new allow_local_files option verified before creating File, and a final-URI re-check after the request. - File: redirect targets must stay http(s) on both the curl and fsockopen branches, preventing reading local files via an http-to-file redirect. - Locator: autodiscovery candidates are filtered to http(s) before being requested; same for extension()/body(). get_links() no longer accepts the feed: scheme (those links were never fetchable as-is). - SimplePie: new set_allow_local_files() threads the flag into the lazy FileClient and the injected Psr18Client; the setter takes an explicit bool with no default. - Existing local-file tests opt in explicitly; CHANGELOG and README document the new behavior (local-file disclosure, not SSRF). Signed-off-by: Daniel Ziegenberg <[email protected]>
Good point, and I think you're right to raise it. I'm happy to take it either way. If you'd prefer, I'll remove local-file support from Either way I'll adapt the affected tests and docs to match. |
|
Fixed. The |
|
Closing as superseded by #993 and #994, which remove local-file support from the HTTP clients (fixing CVE-2026-111234) in line with the direction discussed here. The one remaining piece from this PR, the relative-Location redirect fix in Psr18Client, is being split out into a separate, smaller PR. |
|
Thank you for your help in pushing this forward. |
Introduce
SimplePie\HTTP\UrlPolicyand make local-file fetching opt-in:UrlPolicydecides whether a URI may be fetched; http(s) URIs are always allowed, local files and stream wrappers are blocked by default, and discovered URLs (locator candidates, redirects) are always http(s)-only.NotAllowedExceptionso callers can detect policy refusal.Psr18Client: never forward a redirect Location that the policy rejects.FileClient: newallow_local_filesoption is verified before creating File, and a final-URI re-check after the request.File: redirect targets must stay http(s) on both the curl and fsockopen branches, preventing reading local files via an http-to-file redirect.Locator: autodiscovery candidates are filtered to http(s) before being requested; same forextension()/body().SimplePie: newset_allow_local_files()threads the flag into the lazyFileClientand the injectedPsr18Client.CHANGELOGandREADMEdocument the new behaviour.Fixes #968.