OWASP/owasp-java-encoder

How can I escape Javascript numbers on JSP files (as forJavaScript() doesn't work for negative numbers)?

Kacper86 opened this issue · 4 comments

Hi,

How can I properly escape Javascript numbers on JSP files?

forJavaScript() method is designed to work with strings and breaks negative javascript numbers (by encoding them as \-1). I look at the other methods, but I don't see a suitable one.

Thank you for your help!

Sure, here is an example

JSP file:

<%@ taglib prefix="e" uri="https://www.owasp.org/index.php/OWASP_Java_Encoder_Project" %>

<script type="text/javascript">
	var i = -5; //this will normally be var i = ${variableFromController}
	console.log(${e:forJavaScript(i)}); 
	console.log(${e:forJavaScript(-6)});
</script>

The browser will see the first console.log(${e:forJavaScript(i)}); as console.log(); (literally no argument) while the second console.log(${e:forJavaScript(-6)}); as console.log(\-6); which is a syntax error.

So, both console.log lines seem to produce invalid end result. What should I do in this case?

Hi Jim,

Thank you for your response!

First of all be sure to QUOTE all JS variables that come from untrusted data.
But I don't want to quote integers as they will become strings in that case (and I want numbers).

Also can you try this for me?

The following lines are not a valid javascript:
*alert ("test: " + (7 + **i));*
alert ("test: " + (7 + **i));

So, I assume you meant:
alert ("test: " + (7 + i));
which will of course create an alert with "test: 2" message.

After some thoughts, it might be that might question is silly. I just wanted to use escaping in order to protect Javascript code from XSS which is obviously necessary for strings. However, for numbers, I should probably just just native javascript functions: parseInt() or parseFloat(). They will make sure the input is safe in use in Javascript context.

Thank you for helping me realize that!