Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Prevent XSS when using link_to with model attribute given to href

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,

like image 324
smndiaye Avatar asked Oct 30 '22 17:10

smndiaye


1 Answers

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.

like image 90
Gabor Lengyel Avatar answered Nov 15 '22 07:11

Gabor Lengyel