Recently I was asked to review and test an APEX application to fulfill the security team requirements before we can publish it, making an emphasis in escaping special characters.
In General, APEX takes care of this. If you see the attributes of an Page Item or a Region, you're going to find a switch (On by default) to escape especial characters, but we found an exception.
So the scenario would be this, let's say we create a simple list based on a query like the one shown bellow
Then add this list to a region displayed as links list
So the example looks like this:
Now, if you allow users to insert data that is going to be shown in a list, here is where the issue comes up. Let's use a form to add a new profile
The new record shows correctly here
Now let's add another record, this time adding some JavaScript conde and see what happens
JavaScript code was executed!! Execution happens when the list region is loaded. As you can see bellow, after closing the alert, the script characters are not escaped in the list. And we don't have an attribute to avoid this behavior.
But don't worry, there is a solution. APEX comes with a series of packages and API's to help us, one of them is apex_escape that "provides functions for escaping special characters in strings to ensure that the data is suitable for further processing".
So, let's add to our query apex_escape.html function and see how the output changes.
Now we can see the special characters being escaped in the list, and that piece of code is no longer executed.