0

I have below javascript function in same jsp file which open a new window based on the parameter passed in the link. It was told to me that I need to encode to prevent XSS attack.

     <script language="JavaScript">function openDocWindow(report,index,reportType) {

    link = '/ocs/jsp/single_report_frameset.jsp?      
    report_id='+index+'&id=13740995910316prfXwysgrSGk2Strm7pvxC'+
    index+'&startCount=0'+'&enclosure_id='+index;

    parent.window.open(link,'detail','width=640,height=480,toolbar=no,
    location=no,directories=no,status=yes,menubar=no,scrollbars=
   yes,resizable=yes,alwaysRaised=yes');
   return;
    }

So I thought to encode link veriable using encodeURIComponent() or encodeURI() but I need to know if I do like below then will it be able to prevent XSS attack?

 parent.window.open(encodeURIComponent(link),'detail','width=640,height=480,toolbar=no,
    location=no,directories=no,status=yes,menubar=no,scrollbars=
   yes,resizable=yes,alwaysRaised=yes');
   return;

Thanks for your help!

Pakira
  • 1,951
  • 3
  • 25
  • 54

1 Answers1

0

You need to use encodeURIComponent piece by piece:

function openDocWindow(report,index,reportType) {
  var link = '/ocs/jsp/single_report_frameset.jsp?report_id=' +
    encodeURIComponent(index) + 
    '&id=13740995910316prfXwysgrSGk2Strm7pvxC' +
    encodeURIComponent(index) +
    '&startCount=0&enclosure_id=' +
    encodeURIComponent(index);

    parent.window.open(link,'detail','width=640,height=480,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,alwaysRaised=yes');
    return;
}

I'd probably just encode it once and re-use the value; that's just for illustration. Basically any content from the page that may contain URI metacharacters has to be encoded. It's done in pieces because you're going to introduce metacharacters on purpose, for the uses they're designed for.

Now, will this prevent XSS? No, not at all; at least, depending on your definition of XSS, only for a small fraction of possible attacks. This encoding is only for URI interpretation. It's perfectly fine to pass a malicious user input string back this way, and it will be just as malicious when it ends up back on some page of your site if the site doesn't protect it when it's included.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Thanks for your help. Then how do I prevent XSS? I thought to use ESAPI.encoder().encodeForURL(String str) but I cannot pass link variable as a string argument of ESAPI methods. It says link cant be resolved . I tried this using ESAPI parent.window.open(ESAPI.encoder().encodeForURL(link.toString()),'detail','width=640,height=480,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,alwaysRaised=yes'); – Pakira Jul 18 '13 at 16:40