Spot The Bug

Alright, here’s the first post in the “Spot The Bug” series.  Below you’ll find a short page of Visualforce code that exhibits a problem.  Please respond in the comments with a) what the flaw is and b) how you would fix the flaw.  The first people (or person) to answer these correctly will receive a prize ($25 Amazon Gift Card for identifying the issue and another $25 gift card for fixing the issue).


    <h1>Hello, {!$}</h1><br/> 
    <apex:commandButton value="Submit" onclick="window.parent.location.href = '/00O?returnUrl=' + encode('{!$CurrentPage.parameters.url}');" />   </apex:form>

    function encode(str)
        str = str.replace('<', '');
        str = str.replace('>','');
        str = str.replace(''', '');
        return str;



There were several folks who were quick to point out that there is a Cross Site Scripting issue in the code above.  However many of you missed the location.  The {!$} reference is automatically escaped as is most input reflected back to the page in Visualforce.  We’ve got some great documentation that covers when/where encoding happens, but the most simple explanation is that unless you’re explicitly opting out of encoding the only thing generally not encoded is user input rendered into script blocks.

In this case there is a client side encoding function in place.  Nevermind that the encoding function is not complete, you can’t rely on client side encoding of a server side constructed page.  An attacker could change the input to end the encoding function and start their own JavaScript as was suggested in the comments.

Here’s an updated snippet of code that will correctly encode the values using the built in JSENCODE function (keep in mind there’s more than one way to fix this):

<apex:commandButton value=“Submit” onclick=“window.parent.location.href = ‘/00O?returnUrl={!JSENCODE($CurrentPage.parameters.url)}’ />

Thanks for all the great comments.  We’ll be posting these regularly and will fix some of the challenges we had in the first iteration of this.

Good Luck!

Leave your comments...

Spot The Bug