Pergunta

I got a textbox that allows users to put image link (ex: http://abc.test.gif) & another textbox that allows user to put Alternate text (ex: "This is test.gif"), & a submit button.

When a user clicks on submit buton, the program will generate <img src="http://abc.test.gif" alt="This is test.gif"> this string & store it into DB for later use.

My question is: do i need to sanitize the imagelink "http://abc.test.gif" & the text in alt tag "This is test.gif"

For example, do i need to use UriUtils.isSafeUri("http://abc.test.gif"); & SafeHtmlUtils.fromString("This is test.gif"

Foi útil?

Solução

You are deliberately allowing the user to input anything he want that will go into the src and the alt attributes of the img tag. This is indeed open to any kind of XSS attack. Have a look here for some examples that still work in recent browsers.

Also, you are storing the string in your DB for later use (guessing), so the attack may occur at later time, when you will use such string to create a node in the DOM, with even more unpredictable results.

One solution could be to store only the URL and the alternative string in the database (with a proper input validation, if any), and generate the safe img snippet right when you need it, with a simple template like the following (or programmatically using SafeHtmlBuilder).

public interface Template extends SafeHtmlTemplates {
  @Template("<img src=\"{0}\" alt=\"{1}\"/>")
  SafeHtml img(SafeUri uri, SafeHtml alternativeText);
}

To be used like:

template.img(
    UriUtils.fromString(yourValidatedDbUrl),
    SafeHtmlUtils.fromString(yourValidatedAlternativeText));

This way you:

  • validate the user input;
  • store only the validated values (as-are);
  • generate the img snippet in a safe way only when really needed.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top