Wednesday, July 2, 2014

Beware - malicious ScriptLink usage will hang up your SharePoint 2010/2013

SharePoint's ScriptLink is an useful class to include javascript resources within the HTML rendering. ScriptLink can be used declarative - in a masterpage, Visual WebPart, ... - and programmatically - code behind, webpart. But be aware, in case of incorrect usage, ScriptLink will effectively hang up your SharePoint site, both 2010 and 2013 versions!!.
An example of malicious usage is the following code, to include a javascript resource that is provisioned in (subfolder of) Style Library:
protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); ScriptLink.Register(this.Page, "/Style Library/styles/view-core.js", false); }
The issue here is that ScriptLink assumes all relative links to be within the SharePoint layouts folder. The url in the example is runtime by ScriptLink converted into "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\Style Library\styles\view-core.js".
On itself, this incorrect derived url reference will not directly break your SharePoint site; merely disrupt the expected behavior in browser as the javascript would not be found and loaded. However, ScriptLink also server-side validates the calculated script url as a cache safe url, and in case it cannot be validated will end the complete SharePoint Page rendering, not only that of the erroneous SharePoint artifact. The result in browser is an empty/white page:
<script type="text/javascript"> var gearPage = document.getElementById('GearPage'); if(null != gearPage) { gearPage.parentNode.removeChild(gearPage); document.title = "Error"; } </script>
The correct way to include through ScriptLink a javascript resource administrated in (subfolder of) Style Library, is to use the '~sitecollection' keyword:
protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); ScriptLink.Register( this.Page, "~sitecollection/Style Library/styles/view-core.js", false); }

No comments:

Post a Comment