Javascript functions embedded in arguments run automatically? - javascript

I am investigating defending against various types of attacks and I've found one I don't quite understand.
I have the following html:
<body onload="foo(''/alert(/Gotcha/)/'');">
<script>
function foo(){
alert("Inside Foo");
}
</script>
</body>
</html>
If you run this, you'll see an alert that says "/Gotcha/" followed immediately by one that says "Inside Foo".
What's going on? Why is the alert in the argument (that foo doesn't even have) running?
What's more, if I remove any of those slashes or single-quotes in the argument, it doesn't work.
if I change it to
<body onload="foo('/alert(/Gotcha/)/');">
All I get is "Inside Foo".
if I change it to
<body onload="foo('/alert(Gotcha)/');">
or remove any of the /s I don't get anything.
What is it about the ' and the / that makes this work?

We have a complicated expression there so let's break it up:
foo(''/alert(/Gotcha/)/'');
JS interprets this as a call to a function foo with ''/alert(/Gotcha/)/'' as a parameter (functions in JS do not have hard params, you can send as many as you'd like, even if the function declaration does not specify them)
The parameter is evaluated as the string '' followed by the division character /, followed by the alert function, then another division and another empty string
The parameter for the alert is evaluated since it's not a string, but a regular expression and the string representation is, incidentally, the same as the input regular expression string
The alert is executed with the string representation of the regex to evaluate the parameter for foo and the result of the whole parameter expression is NaN because the strings aren't divisible which doesn't really matter since the function foo does not use it
The function foo is executed.

The reason the argument in the foo call runs is because it is being interpreted as JavaScript. The arguments you are passing in foo(''/alert(/Gotcha/)/'' is essentially 2 strings and in the middle of them is a alert call.

Function arguments are all evaluated before the function is called. So when you write:
foo(alert('/Gotcha/'));
it first evaluates alert('/Gotcha/'), which causes /Gotcha/ to be displayed. Then the return value of alert() is passed as a parameter to foo(). foo() ignores its parameter, but that doesn't matter for the first step.
When you change it to
foo('/alert(/Gotcha/)/');
then the argument is a literal string, not a function call. So evaluating it just returns the string contents, it doesn't call the alert() function.
I can't see any reason why
<body onload="foo('/alert(Gotcha)/');">
would behave any differently from
<body onload="foo('/alert(/Gotcha/)/');">
so I suspect that your actual code has a typo that you didn't copy here. Check your Javascript console for syntax error messages.

Q: "Javascript functions embedded in arguments run automatically?"
A: It has nothing to do with function arguments. The foo function is there to simply add to the confusion of an already obfuscated expression. This is a simply a complicated way of writing an equivalent of:
onload="alert(/Gotcha/)"
which wants to alert the content of /Gotcha/ regex literal.
The regex literal provided in the string of the body onload assignment is simply the passive value of the alert function provided in that same string and has no share in what's going on there.
Everything else is simply a clever way of masking a simple assignment such as the above given onload="alert(/Gotcha/)" line of code.
The only thing that makes it work is the fact that inline event assignments are strings that need to get evaluated in order to get executed.
Therefore eval( ''/alert(/Gotcha/)/'' ) will do the same. Or putting it all back in its original form: eval( "foo(''/alert(/Gotcha/)/'');" ).
So yes, it is possible to execute any kind of string content assigned inline to an element event. But then, so is the setTimeout("foo(''/alert(/Gotcha/)/'');", 1000) capable of doing exactly the same.
So, "no" it has nothing to do with function arguments, but with the parsing of string content to the inline event of document body element.
EDIT:
Inline JavaScript on strings containing html for Images is (for the reasons explained above on why that Gotcha alert works) the most dangerous code injection without the need of user input. That's because image elements can handle onerror events, to which any arbitrary block of code can be executed, as in:
<img
src="http://Idontexist.com/wrongfolder/missingimage.jpg"
onerror="your arbitrary, but well written (malicious) code here!"
>

Related

Malware JS : meaning of a line of code : (_0x4f64, 550906), document[_0x35e70a(408)](atob(unescape(_0x35e70a(409))))

In an obfuscated js code, I have this line that I can't understand :
(_0x4f64, 550906), document[_0x35e70a(408)](atob(unescape(_0x35e70a(409))));
Could you explain me this code particularly ?
(_0x4f64, 550906), document[_0x35e70a(408)]
_0x35e70a(408)
This is a function call, passing in 408.
document[_0x35e70a(408)]
This accesses a property on the document object.
(_0x4f64, 550906),
This is just a variable and a number, separated by the comma operator. The comma operator says to evaluate them both, and use the result of the last one. So this is just 550906. But then another comma operator connects it to the document access we saw before, so the 550906 gets ignored too. So basically, this does nothing.
Putting it all together: that code calls a function, then uses the return value to access a property on document.

Calling function with colon notation

I would like to ask what does mean this:
document:HideContent('content1');
I can't find any explanation why function HideContent defined as regular function is called with colon (":") instead of dot "." as usual.
Does this have any special meaning? Or dos it have some features?
That syntax can only possibly be a label. It's creating the label document and then executes one statement within it (HideContent()). Since the label isn't used within any loop construct by the author, it's pointless.
I suspect the author of the code doesn't really know Javascript and wanted to do something like call HideContent in the "global scope", but found document.HideContent to not work and pounded on the code until it stopped throwing errors. That the result is rather nonsensical and doesn't actually do what they thought it does didn't occur to them. This will work exactly the same when you simply omit document:.
(BTW, the "global scope" resolution would correctly be window.HideContent().)

Calling toUppercase() on a string variable

I'm a beginner and just successfully trouble-shoot my code. I'm glad that I found it, however it took me a long time. I'm hoping to learn why it happened.
Here's the buggy original code. Assume that the variable [nextAlpha] has already been assigned a string value:
nextAlpha.toUpperCase();
Through some creative testing I was able to determine it was the line causing issues. I thought perhaps it's not actually updating the value of variable [nextAlpha]. I tried this instead, and it worked:
nextAlpha = nextAlpha.toUpperCase();
I've left the rest of my code out, but assume that [var = nextAlpha] has already been declared at the top of my script, which I think means "globally." With that information, I thought it was enough to simply call the method on the variable. Why doesn't this "update" the string to upper case like it does when I go the extra step to (re)assign it to the original [nextAlpha] string?
toUpperCase returns the converted string as a new object - it does not perform the conversion on nextAlpha.
From the Mozilla reference:
The toUpperCase method returns the value of the string converted to uppercase. toUpperCase does not affect the value of the string itself.
reference
In JavaScript, Strings are immutable:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
Unlike in languages like C, JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. However, it is still possible to create another string based on an operation on the original string
toUpperCase() is a function (so return a value) not a property (affect the variable itself)

Mysterious line of Javascript code

I am investigating a bug in some software that has uses an in-house developed Javascript library. The error that I am dealing with appears on the line below:
GetVal1("dispLetter")(GetVal1("dispLetter").selectedIndex).value + '~' + (bFinal == true ? '1' : '0');
I initially wasn't sure if this line was even valid, however, according to source control this line was around since this file was created while the error is relatively recent. When I debugged I discovered that this line throws an error that says GetVal1(...) is not a function. I double checked to confirm that the Javascript file with the function definition is included, the header looks like this:
function GetVal1(strHTMLId)
So, I guess my question is, is this line valid Javascript code? Is there anything you can tell that could be throwing the error? Thank you.
GetVal1("dispLetter")(GetVal1("dispLetter").selectedIndex).value + ...
does the following:
calls GetVal1 with the argument "dispLetter".
calls GetVal1 with the argument "dispLetter", again.
retrieves the property selectedIndex of the return value of the second invocation of GetVal1
Calls the return value of the first invocation of GetVal1, with one argument, the value of selectedIndex. This fails your case, and complains the value is not callable.
The return value's value property is dereferenced. String concatenation follows.
In other words, this code seems to assume that the first invocation of GetVal1("dispLetter") returns a function (which is unusual), and the second invocation returns an object with the property selectedIndex (which is unusual, given the first invocation returns a function).
Some ideas:
If there used to be a new keyword before the line. Then the first invocation would be a constructor call. It is unexpected that a constructor call would return a function while a non-constructor call would not, though.
If there used to be a trailing period on the previous line (or is now), GetVal1 would refer (or refers now) to a property of some object. I smell a violation of naming conventions, though, if GetVal1 is meant to be an object property.
The global GetVal1 is (or recently ceased to be) shadowed by a function of the same name. Once again, I smell a violation of naming conventions.
Most likely, GetVal1 itself has changed. Verify GetVal1 can return a function when given this string as the first argument.
Perhaps the state bound to the GetVal1 function has changed (say, one more extra call somewhere before the code. This most likely a design error, though, if this function returns a different type of object on each invocation with the same arguments. But then again, there likely is a design error or naming violation somewhere in the code.
Another plausible explanation is that this line was there from the beginning, but it was never reached before. In this case, it could have been wrong the whole time.

In javascript what does this syntax `(function(window,undfined)){}(window)` accomplish

I am trying to understand how to "chain" JavaScript events together like jQuery does. I found a question here on S.O. that was similar to my goal, but I do not understand the code in the answer.
Code Source
(function( window, undefined ) {
...etc...
}(window)
What does that mean? What is it doing? It reminds me of Jquery's $(document).ready(){} function, but I don't know why this person wrapped his code in this anonymous function that passes window and undefined.
My ultimate goal is to figure out how to execute methods on an object by chaining methods together like jQuery. I know that jQuery already does this but I am looking into this primarily for growth as a developer.
It defines a function (using a function operator as opposed to a function statement). The parenthesis around it ensure that it is treated as the operator rather than the statement.
It then executes it immediately, passing window as an argument.
Essentially, this is the same as:
var myFunction = function( window, undefined ) {
...etc...
};
myFunction(window);
… but without the interstitial variable.
This has nothing to do with jQuery style function chaining, where each method effectively ends with return this (so calling a method on the return value of another method is the same as calling it on the original object).
When a function is called with fewer arguments than its signature contains, the trailing arguments are assigned the value undefined.
So the above is a roundabout way of getting hold of the undefined value even if some lunatic has redefined it by saying var undefined= 'hello';. (This is illegal anyway in ECMAScript Fifth Edition's ‘strict mode’, but JavaScript coders do some weird things sometimes.)
There isn't really a good reason for passing in window like this though... the traditional way to get window if you can't rely on window is to call a function directly and use this.
Either way, this is simply defensive coding against pathological author JavaScript. It's not something you should worry about whilst writing your own code (in any case there's no way you can stop every way someone might mess up their JS environment), and it's nothing to do with chaining.

Categories

Resources