Introduction #

This page describes the mechanisms in Liferay to escape characters.

All the escape methods are designed to prevent XSS attacks and follows OWASP's recommendations for escaping. They can be found in the class HtmlUtil:

The Functions #

When to Escape #

Escaping at the right time is important to make sure that 1) data is not escaped multiple times and 2) data is not changed to a different value before all business logic is done processing.

General Rule 1 : Don't escape before persisting #

There's a few reason why it's generally a bad idea to escape the data before it's persisted.

  1. It increases the size of the data that must be stored
  2. You may need the original at some point in the future. If the data is escaped already, it'll be very difficult to get back the original.

General Rule 2 : Escape at the last minute #

Escaping should be done at the last minute. This avoids situations where the data is escaped before all the business logic is done. Practically, this means that most of the escaping should be done in .jsp files and not in .java files.

Pattern 1 : LanguageUtil #

The values in a Language.properties file may contain HTML elements and they are always safe. So, you should avoid

HtmlUtil.escape(LanguageUtil.format(pageContext, "entries-with-tag-x", tagName))

and instead do

LanguageUtil.format(pageContext, "entries-with-tag-x", HtmlUtil.escape(tagName))

0 Attachments
7472 Views
Average (2 Votes)
Comments

Showing 2 Comments

Marco Glur
2/11/11 12:12 AM

I don't understand Pattern 1, since the Language.properties should be free of formatting (HTML) according to known i18n patterns used in Java (clear separation). Of course there are rare exceptions sometimes.
With escaping in .jsp files, I'd prefer to use scrptlets by exception, which is solved using EL, for instance (${fn:escapeXml('some text with <escaped chars>')})

Samuel Kong
12/26/11 1:15 AM

Marco, I agree with you about pattern 1 if we had clear separation. Unfortunately, we don't have clear separation in the portal's Language.properties files because we want to be able to have text like

Visit <a href="{some-url}">{some-user-name}</a> profile

which mixes text with HTML code. So we need pattern 1 to prevent double escaping.