Tuesday, 27 September 2011

Javascript Obfuscation - The booleans

The booleans

In this section we will explore the different ways we can get boolean values. It might seems at the first look that there isn't much to say about the subject and I hope you will be surprised by the end of the post.

There is 2 common ways to get boolean values in an obfuscated way. The first one we will see is by using the "equality" operators and the second one is by using the "not" operator. It's also good to note that the "or" and "and" operator aren't used much in obfuscation to get boolean, simply because it doesn't always give boolean as an output (I will write up about this in an other blog post, this one).

The equality operator

Javascript has two operators to test for the "equality" of 2 variables. The first one "==" is more a similarity operator and the second one "===" is a strict equality operator. The first one is particularly interesting because it gives results that can be unexpected in various cases. Here are few example of this :

(null == undefined) => true
(false == "false") => false
(false == "0") => true
(NaN == NaN) => false
(2 == [[[2]]]) => true
([2] == [[[2]]]) => false

You can also see this Stack Overflow answer for more examples.

For the "===" operator there is less to say, because it's a strict operator. The only thing that gives a result that can be unexpected is the following :

(NaN === NaN) => false

NaN is a special value in Javascript. The way this value is defined, if you do an operation with this value the result will be NaN. This is why when you test if something equals NaN it will always be false.

The not operator

The not operator "!" in Javascript is commonly used to force something to be cast to a boolean value. But what is less known and that you can use in obfuscation is the result of this cast on value that aren't at the first look made to be cast to boolean. Here are few examples :

Expression Result
!0 true
!3 false
![] false
!({}) false
!"" true
!"0" false
!NaN true

1 comment: