[SalesForce] How to prevent html tags rendering as html entities when

I have an apex apex:outputtext used in VF page with escape="true". Setting escape = true shows the html entities instead of displaying the required html format. As the code is in managed package this should be XSS free using either escape=true or using HTMLENCODE VF function. Making XSS free makes the field to show the html entities.
For example

Controller:

String htmlString = '<p>Hello World</p>';

VF Page:

<apex:outputtext escape="true" value="{!htmlString }"/>

or just:

{!HTMLENCODE(htmlString )} 

will give the output:

&lt;p&gt;Hello World&lt;p&gt;

Expected result is <p>Hello World</p>. So how to get this output with XSS fix?

Best Answer

Thinking about it, you will never be able to use the escape="true" attribute to achieve what you want. You want your generated HTML to be rendered by the browser so you have to use escape="false"

That means you have to sanitize your HTML in the controller prior to it being rendered by your VF page. Which means you need to think about what you want to allow to pass that sanitization and what may not pass.

There's some good information about the topic on the OWASP web site and some more Salesforce specific stuff on developerforce. Looks like what you really need is an APEX version of the antisamy library.

I don't know of such a project, though others have used a web service to achieve the sanitization outside of the Salesforce environment. Surely not what you look for.

A Salesforce version of OWASPs ESAPI library has been published by Salesforce itself. That might help but unfortunately is no replacement for AntiSamy.