1762 words, 9 min read

If you render content from other websites, you’ll eventually run into broken images. Some hosts refuse hotlinking, some check the Referer header, and your own Content Security Policy may only allow images from a short list of origins. The result is the same: a page full of broken image icons.

One fix is to stop showing images. Another is to serve them yourself through a small proxy. This post walks through the second option and, more importantly, the ways it can go wrong.

The idea

  1. Rewrite every remote image URL in your content to point to your own server.
  2. When the browser requests it, fetch the original image server-side and stream it back.

Because the image now comes from your own origin, your CSP is happy. Because your server makes the request without a Referer, most hotlink protection doesn’t trigger.

The catch: you’ve just built a service that makes HTTP requests to URLs chosen by someone else. That is exactly the shape of an SSRF vulnerability, so most of the work is making it safe.

Step 1: sign the URLs

An unauthenticated /proxy?url=... endpoint is an open proxy. Anyone can use it to hide their traffic, hammer a third party, or probe your internal network.

Instead, only proxy URLs that your own code generated. Sign the source URL and put the signature in the path:

def path(src), do: "/proxy/image/" <> sign(src)

def verify(token), do: Plug.Crypto.MessageVerifier.verify(token, secret())

defp sign(src), do: Plug.Crypto.MessageVerifier.sign(src, secret())

defp secret do
  base = MyAppWeb.Endpoint.config(:secret_key_base)
  Plug.Crypto.KeyGenerator.generate(base, "image proxy")
end

A few notes:

  • MessageVerifier is deterministic: the same URL always gives the same token. Phoenix.Token includes a timestamp, which would make every render produce a different URL. That breaks HTTP caching and any cache of rendered HTML.
  • Deriving the key with a dedicated salt keeps the proxy’s signatures separate from your other uses of the secret.
  • Signing is not a complete defense. The URLs still originate from third-party pages, so the fetch itself has to be safe too.

Step 2: rewrite the content

If your content is Markdown, a regular expression over the image syntax is enough for a first version:

@image ~r/!\[([^\]]*)\]\((https?:\/\/[^)\s]+)((?:\s+"[^"]*")?)\)/

def rewrite_markdown(markdown) do
  Regex.replace(@image, markdown, fn _, alt, src, title ->
    "![#{alt}](#{path(src)}#{title})"
  end)
end

Only absolute http(s) sources are rewritten. Relative paths and data: URIs stay untouched. The known limitation: an image example inside a code block gets rewritten too. If that matters, rewrite on the parsed AST instead.

Step 3: fetch defensively

This is the dangerous part. Everything below matters.

Block private addresses

Before connecting, resolve the host and refuse anything that isn’t a public address: loopback, private ranges, link-local (which includes cloud metadata endpoints), carrier-grade NAT, and multicast. Don’t forget IPv6, including IPv4-mapped addresses like ::ffff:127.0.0.1.

def public_address?({a, b, _, _}) do
  not (a in [0, 10, 127] or
         a >= 224 or
         (a == 100 and b in 64..127) or
         (a == 169 and b == 254) or
         (a == 172 and b in 16..31) or
         (a == 192 and b == 168))
end

def public_address?({0, 0, 0, 0, 0, 0xFFFF, hi, lo}) do
  public_address?({div(hi, 256), rem(hi, 256), div(lo, 256), rem(lo, 256)})
end

def public_address?({0, 0, 0, 0, 0, 0, 0, _}), do: false
def public_address?({first, _, _, _, _, _, _, _}) when first in 0xFC00..0xFDFF, do: false
def public_address?({first, _, _, _, _, _, _, _}) when first in 0xFE80..0xFEBF, do: false
def public_address?({first, _, _, _, _, _, _, _}) when first >= 0xFF00, do: false
def public_address?({_, _, _, _, _, _, _, _}), do: true

Check every address a hostname resolves to, not just the first.

Follow redirects yourself

If the HTTP client follows redirects automatically, an attacker can point a public URL at http://169.254.169.254/..., and your check on the first host is useless. Turn automatic redirects off, follow them manually with a small limit, and run the full validation on every hop:

defp fetch(_src, hops_left) when hops_left < 0, do: {:error, :too_many_redirects}

defp fetch(src, hops_left) do
  with {:ok, uri} <- parse(src),
       :ok <- ensure_public_host(uri.host),
       {:ok, response} <- request(src) do
    handle_response(response, src, hops_left)
  end
end

Limit what you accept

  • Timeouts. A slow host shouldn’t tie up a worker. Use a short receive timeout and disable retries.
  • Size. Stream the body and stop once it passes a limit (say 10 MB), rather than loading whatever the server sends into memory.
  • Content type. Allow a short list of raster formats: PNG, JPEG, GIF, WebP, and AVIF. Leave SVG out. It can contain script, and serving it from your origin is an XSS risk.

With Req, the streaming limit looks like this. The accumulator lives on the response:

defp collect({:data, data}, {request, response}) do
  chunks = Req.Response.get_private(response, :chunks, [])
  size = Req.Response.get_private(response, :size, 0) + byte_size(data)

  response =
    response
    |> Req.Response.put_private(:chunks, [data | chunks])
    |> Req.Response.put_private(:size, size)

  if size > @max_bytes do
    {:halt, {request, Req.Response.put_private(response, :too_large, true)}}
  else
    {:cont, {request, response}}
  end
end

Don’t send a referer

Simply don’t set one. Send a plain user agent and an Accept: image/* header.

Step 4: serve it safely

The controller verifies the token, fetches the image, and responds. Even though you only allow raster images, add defense in depth:

def show(conn, %{"token" => token}) do
  with {:ok, src} <- ImageProxy.verify(token),
       {:ok, body, content_type} <- ImageProxy.fetch(src) do
    conn
    |> put_resp_content_type(content_type, nil)
    |> put_resp_header("cache-control", "public, max-age=604800, immutable")
    |> put_resp_header("content-security-policy", "default-src 'none'; sandbox")
    |> put_resp_header("x-content-type-options", "nosniff")
    |> send_resp(200, body)
  else
    _ -> send_resp(conn, 404, "")
  end
end

Always return a plain 404 on failure. Don’t leak the reason to the client. Log it instead.

Put the route in a scope with no browser pipeline. An image doesn’t need a session, CSRF protection, or HTML security headers.

Testing it

Req’s plug option lets you stub the remote server without any network access:

Req.Test.stub(ImageProxy, fn conn ->
  conn
  |> Plug.Conn.put_resp_content_type("image/png")
  |> Plug.Conn.send_resp(200, png)
end)

assert {:ok, ^png, "image/png"} = ImageProxy.fetch("https://93.184.216.34/a.png")

Using an IP literal in the test URL avoids a real DNS lookup. The tests worth writing:

  • the token round-trips, and a tampered or garbage token is rejected
  • tokens are deterministic
  • loopback, private, link-local, and IPv4-mapped IPv6 hosts are refused
  • non-http(s) schemes are refused
  • SVG and other content types are refused
  • an oversized body is refused
  • a redirect to a private address is refused
  • a redirect loop gives up
  • no Referer header is sent

Pitfalls I ran into

  • Hidden middleware can block the route. If you have a plug that blocks suspicious paths (many apps do, to deflect scanners), a path like /proxy/... may be on its list. My tests got a friendly “not found” page with a 200 status until I allowlisted the route.
  • Where Req keeps streaming state. With into: as a function, the accumulator is {request, response}, and the final response is built from the one you return. State stored on the request is gone by the time you get the result. Store it on the response.
  • Sigils and parentheses. ~s(...) breaks as soon as your test string contains parentheses. Use ~s|...|.

What’s still missing

  • DNS rebinding. The code resolves the host to validate it, then the HTTP client resolves it again to connect. A hostile DNS server could answer differently the second time. Closing that gap means connecting to the validated IP while still sending the right Host header and TLS server name. Signed URLs shrink the exposure but don’t remove it.
  • Server-side caching. The Cache-Control header lets browsers and CDNs cache, but your server will still refetch on a cold cache. A CDN in front is the cheapest fix. Storing the images yourself also keeps them alive after the source disappears.
  • Cost. You now pay for the bandwidth, and you’re re-serving other people’s images. Think about whether that’s acceptable for your use case.

Should you do this at all?

Not always. If you don’t care about the images, stripping them is simpler, has no attack surface, and costs nothing to run. Before building a proxy, check why the images are broken. If it’s your own CSP, the cheapest fix may be a configuration change. If it’s Referer-based hotlink protection, a no-referrer referrer policy on the images may be enough.

The proxy earns its place when you want the images, the hosts really do block direct loading, and you’re willing to own the security and operations that come with fetching URLs on behalf of the internet.