Considering the following link_to example:
link_to "Personal Website", @user.website
How can I protect it against XSS attack.
User table is in an external DB, so I cannot trust it. I have tried different approaches using sanitize and h but when I replace in my local DB user website by javascript:alert('XSS')
, javascript is still being executed when I click on the link.
Thanks in advance,
You can remove "javascript:" in the controller. That's ugly but works, with some caveats (browsers are awesome in what exactly they may accept as "javascript:"). This is not a very strong control.
You can add "http://" (or "https://") statically to the link href, and strip that from your user input. As "javascript:" only works if it's at the first character of an href, statically adding http:// as the beginning mitigates XSS.
You can also use the Content-Security-Policy
header to prevent inline Javascript from being run. This has implications on how you can structure your code, and is not supported in all browsers, but when it is suported, it's an excellent control.
As always, implementing multiple layers of defense (multiple of the above) will make your application more robust and secure against attacks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With