Difference between revisions of "Avoid the JavaScript Protocol to Open a new Window"

From OWASP
Jump to: navigation, search
 
Line 4: Line 4:
 
     value=&lt;%=request.getParameter("value")%&gt;', 'w3c','location=no')"&gt;Window.open() Method&lt;/a&gt;</pre>
 
     value=&lt;%=request.getParameter("value")%&gt;', 'w3c','location=no')"&gt;Window.open() Method&lt;/a&gt;</pre>
  
The above example is difficult to encode safely due to the nesting of various contexts; in order these are: HTML Attribute, URL, JavaScript, URL. To make the encoding easier and increase the overall safety this can be refactored into the following:
+
The above example is difficult to encode safely due to the nesting of various contexts; in order these are: HTML Attribute, JavaScript, URL. To make the encoding easier and increase the overall safety this can be refactored into the following:
  
 
<pre>&lt;a href="http://www.w3schools.com/jsref/met_win_open.asp?
 
<pre>&lt;a href="http://www.w3schools.com/jsref/met_win_open.asp?

Latest revision as of 12:52, 4 December 2011

The JavaScript Protocol should be avoided as it is extremely complicated to use safely with untrusted data. It is common to see the JavaScript protocol used to open a new window as such:

<a href="javascript:window.open('http://www.w3schools.com/jsref/met_win_open.asp?
    value=<%=request.getParameter("value")%>', 'w3c','location=no')">Window.open() Method</a>

The above example is difficult to encode safely due to the nesting of various contexts; in order these are: HTML Attribute, JavaScript, URL. To make the encoding easier and increase the overall safety this can be refactored into the following:

<a href="http://www.w3schools.com/jsref/met_win_open.asp?
    value=<%=EASPI.getEncoder().encodeForURL(request.getParameter("value"))%>" 
    onclick="window.open(this.href, 'w3c','location=no'); return false;">Window.open() Method</a>

The above simplifies the required encoding by removing the deep nesting of various contexts within the DOM. It is important to note that the onclick method must "return false;" in this scenario to prevent the window or frame from navigating to the URL specified.

Authors and Primary Editors

Jeremy Long - jeremy.long [at] owasp.org