If I have:
var test = {toString: function(){alert("evil code"); return "test";}};
how can I convert test
to a string? without calling test.toString()
and without using a typeof x == "string"
check since I want to allow non strings.
Note: this is for a FF extension dealing with objects from a content page's js scope.
Values can be explicitly converted to strings by calling either String() or n. toString() . With the String() function, let's convert a Boolean value to a string by passing the value true into the parameters for String() .
We can convert Object to String in java using toString() method of Object class or String. valueOf(object) method. You can convert any object to String in java whether it is user-defined class, StringBuilder, StringBuffer or anything else.
Example 1: Convert Object to String Using JSON.stringify() method is used to convert an object to a string. The typeof operator gives the data type of the result variable.
JavaScript allows you to modify the properties of pretty much any object that is accessible to your script, including Object.prototype
itself, meaning any object is vulnerable to "evil code" in the manner that you explained.
Only primitives are guaranteed to be safe, so the only way to ensure that "evil code" is never executed is to do something like this:
function safeToString(x) {
switch (typeof x) {
case 'object':
return 'object';
case 'function':
return 'function';
default:
return x + '';
}
}
One option is:
Object.prototype.toString.call(test)
This gives:
"[object Object]"
in the case of test. Basically, it just gives type information. However, I wonder what the exact scenario is here. How is the evil object getting loaded into the page? If they can execute arbitrary code on the page, you're basically out of luck. Among other things, it is then possible to redefine Object.prototype.toString
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With