How to avoid security risks with escape="False" in output tags

All we need is an easy explanation of the problem, so here it is.

Ok, say for example the output we need on the page must include HTML tags and we want to avoid any security risks…..

Scenerio 1: No user input, string is completely generated by apex code and displayed by the page. – Is there any risk, if so what is the best way to avoid

Scenerio 2: String is constructed in a way that user input is added to the string. The input has string.escapeSingleQuotes() AND .escapeHTML4() applied. – The obvious risks are Injection and XSS but those would appear to be negated by the applied methods. What if any additional risks are present?

Keep in mind that the application needs the output of the string to contain the HTML elements the apex code adds so it will not be an option to set escape="true"

This question is both a learning question and a best practice question as this is one of the most frequent reasons apps fail security review.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

For the first scenario, there’s no risk, because the code being emitted is directly created by the developer and is under the developer’s full control. There’s no risk of malicious injection, so there’s no security risk.

For the second scenario, you should escape the content that’s not under your control. For example, you might do this:

output += String.format('<td>{0}</td>', new String[] { userInput.escapeHtml4(); });

The intent is to make a cell (td) with whatever user content they desire. By escaping the input so that greater-than, less-than, ampersand, quote, and apostrophe are replaced with HTML entities, you guarantee that no script injection can occur, malforming the page or even executing arbitrary JavaScript.

escapeSingleQuotes is for SOQL, and should not be used for escaping HTML. It won’t cause any security problem, but it would cause extra apostrophes to appear in the output. Other than that, there’s no other risks that you’d run into, since escaping the four main character entities that would be used for XSS will eliminate any known security risk.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply