Writing · Security
Preventing SSRF in a Link Preview API
What an attacker tries against a service that fetches URLs for other people, how our social card API stops each attempt, and how we test that it still does.
Our social card API takes a URL, fetches the page, reads its Open Graph tags, then fetches the image they point at and measures it. Anyone can call it without signing up. That makes it a server-side request forgery (SSRF) target by design: the whole job is to make an HTTP request to an address someone else chose, from our network.
An attacker does not want our card checks. They want the request. A server can usually reach things the public internet cannot: a cloud provider’s metadata service, an admin port on loopback, a database on a private subnet. A link preview service that will fetch any URL and report what came back is a way to ask those questions from the inside. What follows applies to any service that fetches URLs on a caller’s behalf.
What an attacker tries
- Internal addresses directly.
http://127.0.0.1:8080/,http://10.0.0.1/,http://localhost/. - The cloud metadata endpoint.
http://169.254.169.254/, where many cloud platforms serve instance details and, on some setups, credentials. - Odd spellings of the same address.
http://2130706433/,http://0x7f000001/andhttp://127.1/are all loopback. So is an IPv6 address with an IPv4 address inside it. - A public name that resolves inward. A domain the attacker controls with a DNS record pointing at a private address.
- A redirect. A harmless public page that answers
302with aLocationon the inside. - DNS rebinding. A name that resolves to a public address when it is checked and a private one when it is connected to.
- Content the service fetches on its own. An
og:imageor a sitemap entry pointing inward, so the page the caller named is clean and the second request is not. - Huge or slow responses. A body that never ends, arrives a byte at a time, or decompresses to many times its size, to tie the service up or exhaust its memory.
Check where the name points
Matching on the text of a URL is the trap. There are too many ways to write an address, and a hostname says nothing about where it points. So the API parses the URL with a standards-conforming parser, which reduces the decimal, hex and shortened forms to one canonical address, and accepts only http and https. Then it resolves the hostname and checks every address it gets back.
An address is refused if it is private, loopback or link-local, which covers the metadata endpoint, or in carrier-grade NAT space, and the same goes for IPv6’s loopback, link-local, unique-local and multicast ranges. If a name resolves to several addresses and any one of them is internal, the request is refused, since an attacker can usually influence which one gets used. Names that only mean something inside a network, such as localhost or anything ending .local or .internal, are refused before they are looked up.
IPv4 addresses embedded in IPv6 need particular care. An IPv4-mapped address can be written with the IPv4 part dotted or in hex, and the resolver may hand back either. When we reviewed the guard in September it unwrapped only the dotted form, so a single DNS record in the hex form could have pointed a fetch at the metadata address. It now reads every IPv6 address as its 16 bytes before judging it, so each spelling of an address is the same address, and an IPv4 address carried inside any IPv6 form is checked as the IPv4 address it is. The test that proves it is described below.
A refusal gets its own error code, blocked_address, marked as not worth retrying, and it is a different code from a hostname that does not resolve. A caller with a typo should be told it is a typo.
Check again when connecting
Checking the address and then handing the URL to an HTTP client leaves a gap, because the client resolves the name a second time. A rebinding name answers the first lookup with a public address and the second with a private one, and the private one is what gets dialled.
The fix is to check the address at the moment of connecting. The API’s HTTP client uses a resolver of ours at connect time, and that resolver refuses any internal answer, so the address checked and the address dialled are the same. The earlier check stays, because its error is clearer.
Every hop gets the same treatment
The client never follows redirects by itself. Each 3xx is read, the next URL is built from its Location, and that URL goes back through the whole check: scheme, name, resolution, connect. The number of hops is capped.
Every fetch the API makes goes through the same function, so the og:image, the robots.txt beside it and a site scan’s sitemaps get exactly the guard the caller’s URL got.
The site scanner gets one more rule. A sitemap index lists other sitemaps, and nothing stops it listing other people’s URLs. Fetching those would turn one call into several requests at a third party chosen by someone else, from our address. They are all public addresses and pass the SSRF check, so the scanner fetches only children on the origin it was asked about.
Bound the size and the time
Each fetch has a byte cap, counted on the body after decompression, so a small compressed response cannot expand past it. Each connection has a timeout, and so does each read of the body, which matters because a server that sends headers promptly and then stalls would otherwise hold the request open indefinitely. Above those, the whole request has one deadline shared by every fetch it makes, set inside the platform’s own time limit, so a slow site gets an answer saying it was slow.
We use a current release of the HTTP client in place of the one bundled with the runtime, because the bundled one predates the fix for an unbounded chain of Content-Encoding headers. Parsing is bounded too. The head of a page is attacker-controlled input, and an earlier parser could be made to backtrack for seconds on a specially built page. It now walks the input once against a fixed budget, and a test asserts the time it takes.
Assume the guard will one day fail
The function that does the fetching runs outside any private network, with permission to write its own logs, count its own usage and look up API keys, and nothing else. A bypass would land somewhere with nothing worth reaching. Changes to it are applied to a full staging copy first, smoke-tested there, and promoted only if staging is healthy.
How we test it
The guard is tested in npm run check, which runs before every deploy. The tests cover:
- Spellings. Every form in the list above, plus
file:andgopher:URLs, must come back refused. - Near misses. Addresses just outside each blocked range must be allowed. Over-blocking is a failure too, because it refuses real sites.
- Second requests. A public page whose
og:imagepoints inward, and one that redirects inward, must never produce a request to the internal address. - Rebinding. The test stands up a real server on loopback, gives the first lookup a public answer and the connect-time lookup the loopback one, and asserts the server received no requests. A second test reaches the same server without the guard, so the refusal is shown to be the guard’s.
- Hostile sitemaps. A sitemap listing metadata, loopback and third-party URLs must produce a plan with only the same-origin page in it.
We also run mutation testing over the guard: the tool rewrites a range check on purpose and fails if the suite stays green. That is how we found that the near-miss addresses were missing.
Two more tools cover the parser that reads what comes back. og-fuzz feeds it 250,000 generated pages and asserts properties of the output, among them that a javascript: URL never reaches a caller as an image. og-corpus runs 75 real URLs through the whole checker and asserts 19 invariants. It found the slow real-world site that showed per-fetch timeouts alone do not bound a request, which is why the shared deadline exists. After every deploy, and three times a day besides, a smoke test calls the production API and confirms it answers and keeps its errors in the response body.
If you are building one
- Parse the URL with a standards-conforming parser and allow only the schemes you need.
- Resolve the name and refuse if any address is internal, IPv4-in-IPv6 forms included.
- Enforce the same check at connect time, so rebinding has nothing to exploit.
- Follow redirects yourself, and send every hop and every secondary fetch through the same check.
- Cap the bytes after decompression, time out each read, and set one deadline for the whole job.
- Run the fetcher where a bypass reaches nothing, with as few permissions as it can work with.
- Test the refusals, test the near misses, and check that the tests would notice a broken guard.
The API reference has the public contract, including every error code.