I’ll show you eight different types that transform strings into a code that can be executed immediately. In this case, I am using only pure javascript, but libraries like jQuery have methods that implicitly can be exploited as Eval.
val()
The very one val
eval("alert('lorem ipsum')");
setTimeout()
setTimeout is the best known example of using eval
if you pass a string.
// Ambos são equivalentes
setTimeout("alert('lorem ipsum')", 100);
setTimeout(function(){ eval("alert('lorem ipsum')"); }, 100);
setInterval()
setInterval is similar to setTimeout, but performs at each time period and not only at the end of the chosen time.
// Ambos são equivalentes
setInterval("alert('lorem ipsum')", 100);
setInterval(function(){ eval("alert('lorem ipsum')"); }, 100);
new function()
Function implicitly can be considered a form of Eval because it strings accepted
var adder = new Function("a", "b", "return a + b");
alert(adder(3,5));
Document.write()
Document.write, if used to write tags <script>
, also works as eval
document.write('<script>alert("lorem ipsum")</script>')
Document.writeln()
Document.writeln is very similar to Document.write, but adds a new line to the end.
document.writeln('<script>alert("lorem ipsum")</script>')
Data URI
Data Uris are the most atypical example, but are eventually used to exploit faults in browsers.
var s = document.createElement('script');
s.src = 'data:text/javascript,' + encodeURIComponent('alert("lorem ipsum")')
document.body.appendChild(s);
Reference: own knowledge, MDN links and http://kubyshkin.ru/posts/studying-javascript-eval.html
GIFT
Similar to the data Uris approach, but inserting the code directly instead of resorting to the attribute src
:
var s = document.createElement('script');
s.appendChild(document.createTextNode('alert("lorem ipsum");'));
document.body.appendChild(s);
javascript:
Also similar to the date Uris, but inserting the code into the location
page:
location.replace('javascript:alert("lorem ipsum");void(0)');
Can refrasear / explain better "What are the ways to apply Eval in Javascript?". Refers to how javascript works internally, whether there are other methods that use Eval internally, or what practices to take into account?
– Sergio
@Sergio refers to the ways to apply the Val focused on who is creating a code, where it can execute an Val, so I’m trying to refer to the methods that perform in their code evaluation arguments. But the other two questions are interesting too, how it works internally and what practices should be taken into account, I will see if no one has asked them before and if not, I will put them separately, because the questions are quite different.
– Gabriel Gartz