Skip to content

Implement safe-by-default URL policy - #991

Closed
ziegenberg wants to merge 2 commits into
simplepie:masterfrom
ziegenberg:fix-968
Closed

ziegenberg wants to merge 2 commits into
simplepie:masterfrom
ziegenberg:fix-968

Conversation

@ziegenberg

@ziegenberg ziegenberg commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

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.
  • Psr18Client: never forward a redirect Location that the policy rejects.
  • FileClient: new allow_local_files option 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 for extension()/body().
  • SimplePie: new set_allow_local_files() threads the flag into the lazy FileClient and the injected Psr18Client.
  • Existing local-file tests opt in explicitly; CHANGELOG and README document the new behaviour.

Fixes #968.

Copilot AI lite review requested due to automatic review settings September 23, 2026 19:44

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@jgalea jgalea left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. $requestedUrl and (for 301/308) $permanentUrl are 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 in SimplePie::fetch_data(), Locator and Sanitize of 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.
  2. The check calls isAllowed($requestedUrl) without $discovered = true, so with set_allow_local_files(true) a redirect to file:// 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 to file:///etc/passwd with the default policy; asserts permanent and final URIs stay https://example.com/redirect. Currently both come back as file:///etc/passwd.
  • testNonHttpRedirectIsNotForwardedEvenWithLocalFilesAllowed: 302 to file:// with local files allowed; asserts sendRequest() is called once. Currently it's called twice.

Further tests I'd suggest but haven't written:

  • testClientRejectsRedirectToLocalFile runs with allow_local_files => true. A copy with the default (false) would pin down the File-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.

@ziegenberg

ziegenberg commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @jgalea,

Could you paste the two tests so I could look into incorporating them?

Greetings,
Daniel

@jgalea

jgalea commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

Sure, here they are. They go at the end of tests/Unit/HTTP/Psr18ClientTest.php and need no new imports.

    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 file:///etc/passwd back as the permanent URI, the second sees sendRequest() called twice. With the Psr18Client change from my review applied, all 57 tests in tests/Unit/HTTP/ pass. If you go with throwing on a refused redirect instead of returning the 3xx response, the second test's last assertion would become an expectException().

@ziegenberg

Copy link
Copy Markdown
Contributor Author

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 Location is now checked against the policy before it's assigned to $requestedUrl/$permanentUrl, and the check passes $discovered = true. So a refused URL never leaks into the response's final/permanent URIs, and a file:// redirect is refused even when local files are allowed, matching the README.

Throwing vs. returning the 3xx. I went with throwing NotAllowedException on a refused redirect, for consistency with FileClient (where File sets success = false and the request ends in an exception). This means your second test's last assertion became expectException(), and the existing testRequestDoesNotForwardNonHttpRedirectLocation is now an exception assertion too. Both of your tests are in and pass.

On NotAllowedException extending ClientException. I thought about this carefully but kept it standalone (extends SimplePieException). A refused URL is not a failed request: no request is made, and, crucially, what makes a refusal is within the caller's remit, since the caller configures the policy that produces it. A broken network, by contrast, is not something the caller can configure. So a broad catch (ClientException) treating a refusal as a transport error would be wrong on both counts: it is not a request failure, and the cause is the caller's own configuration, not an external fault. Keeping it standalone means an existing catch (ClientException) does not absorb a refusal; it has to be handled deliberately. The downside you identified is real, and I've paid it: the internal catch sites in Locator, Sanitize and SimplePie are widened to catch (ClientException | NotAllowedException) so refusals still fail gracefully there. Downstream wrappers that catch ClientException will need an explicit NotAllowedException catch to keep treating refusals gracefully. I think that's the correct trade-off, but it's worth flagging as a BC consideration for the changelog.

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.

feed: in get_links(). You're right that it's no longer accepted. Those links were never fetchable as-is, so I've left the behavior as-is and noted the change in the commit message.

set_allow_local_files() default. I've dropped the default (set_allow_local_files(bool $allow)) so the opt-in is explicit: a no-arg call shouldn't read as disabling the feature.

On the WordPress note, good confirmation that there's no breakage there. And I'll add the default-false redirect test you suggested to pin the File-level and FileClient re-checks separately.

@jgalea

jgalea commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

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 Location (Location: /feed.xml, which RFC 9110 allows) doesn't start with http(s)://, so isAllowed($location, true) refuses it and the request ends in NotAllowedException: Refusing to fetch "/feed.xml". Relative redirects through Psr18Client were already broken on master (Guzzle throws "URI must include a scheme and host"), so nothing that worked before breaks, but the error now reads as a policy refusal. The default cURL client follows the same redirect fine.

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 302 Location: /feed.xml gets the 200 with final URI http://127.0.0.1:8991/feed.xml, and the existing Psr18Client tests still pass. file:///etc/passwd and php://filter/... come through absolutize_url() unchanged, so they're still refused with local files allowed. A mock test with Location: /feed.xml would pin it.

@jtojnar jtojnar left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. I am starting to think that allowing Psr18Client to fetch files was a mistake.

Comment thread src/HTTP/FileClient.php Resolved
Comment thread src/HTTP/FileClient.php Resolved
Comment thread src/HTTP/UrlPolicy.php Resolved
Comment thread README.markdown
Local files
------------

Fetching local files (filesystem paths) as feeds is **disabled by default** in

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/HTTP/UrlPolicy.php
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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That will require DNS lookups, at which point I am not sure about the naming of UrlPolicy .

Comment thread src/Locator.php Resolved
Comment thread src/Locator.php
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'])) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps split this into a separate commit since it is an unrelated, but welcome cleanup.

Comment thread src/Locator.php
if ($this->checked_feeds === $this->max_checked_feeds) {
break;
}
if (!Misc::is_remote_uri($value)) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@ziegenberg

Copy link
Copy Markdown
Contributor Author

Thanks. I am starting to think that allowing Psr18Client to fetch files was a mistake.

Good point, and I think you're right to raise it. Psr18Client wraps a PSR-18 HTTP client, and local files aren't HTTP, so reading them there is a layering violation rather than a transport concern. The set_allow_local_files() opt-in is the only thing that enables it today.

I'm happy to take it either way. If you'd prefer, I'll remove local-file support from Psr18Client entirely so it always refuses non-http(s), leaving FileClient as the only local-file transport. Or I can keep it behind the existing opt-in. I'd rather leave that call to you, since it's a maintainer decision about where the local-file feature belongs, and I don't want to guess at the direction you'd want long term.

Either way I'll adapt the affected tests and docs to match.

@ziegenberg

Copy link
Copy Markdown
Contributor Author

Fixed. The Location is now resolved against the current URL before the policy check (Misc::absolutize_url), so a relative Location like /feed.xml is treated as the absolute http(s) URL it points to and is followed, while file:// and php:// come through unchanged and stay refused. Added a mock test pinning the relative case.

@jtojnar

jtojnar commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

I would go as far as to remove it from FileClient too: #994

I left support for fetching local files in the entry point as that should be less surprising for consumers: #993

@ziegenberg

Copy link
Copy Markdown
Contributor Author

I'll wait for your #993 and #994 to be merged and then base my PR on your changes, right?

@ziegenberg

ziegenberg commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor Author

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.

@ziegenberg ziegenberg closed this Nov 3, 2026
@ziegenberg
ziegenberg deleted the fix-968 branch November 3, 2026 11:34
@jtojnar

jtojnar commented Nov 3, 2026

Copy link
Copy Markdown
Member

Thank you for your help in pushing this forward.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Should we filter for SSRF by default?

4 participants