If you use jQuery in your website, then you can simply reassign $
which will kill any code that uses it directly:
//some normal code
$("div").css("color", "red"); //boom!
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<SCRIPT>$ = "I COME FROM EVIL INPUT"</SCRIPT>
<div>Some content</div>
Yes, you can protect it via making sure jQuery is injected correctly into each script that needs it. That used to be pretty common when multiple libraries might grab the global $
, so you'd ensure that the $
variable is correct:
//some normal code but this time protected
(function($) {
// ^---<-- not using the global $ <-----
$("div").css("color", "red");// |
})(jQuery)// |
// ^^^^^^-->---------------------->-----------^
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<SCRIPT>$ = "I COME FROM EVIL INPUT"</SCRIPT>
<div>Some content</div>
However, this has slightly fallen out of favour recently - it's usually just jQuery that uses $
, so you don't always need to protect it. Are you sure every line where you have $
is not the global one?
If you are, then here is the next attack that is as simple as this one:
const someJSON = '{ "name" : "Fred", "age" : 42 }';
const obj = JSON.parse(someJSON); //boom!
console.log(obj.name);
<SCRIPT>JSON = "I COME FROM EVIL INPUT"</SCRIPT>
Do you use AJAX to communicate with the server? Or try to fetch stuff from localStorage? Well, I very much doubt you're as protective of JSON
as of $
and I doubt you have custom JSON readers.
I hope you can see the pattern now - anything that's attached to window
and is all caps can be targetted and thus cripple the application further.
I have little doubt that all caps JS can be manipulated to produce lowercase letters. I can't think of how right now, but when the attacker figures it out, you can expect even more brute but effective things:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<SCRIPT>$("HTML")["html"]("I COME FROM EVIL INPUT")</SCRIPT>
<!-- ^^^^ this needs to be lowercased...and boom! -->
<body>
<div>Some content</div>
<div>Some more content</div>
<div>Final content</div>
</body>