Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alf.nu random4 excercise, what is the answer?

Tags:

javascript

I was playing on this site, and I got stuck at the random4 problem.

So, basically, the problem is the following.

var random4 = new function() {
  var rand = Math.random();

  this.test = function(x) {
    return rand === x;
  }
};

What value of x should be passed to random4.test in order to have it return true?

Note that the code here is slightly different from the linked page. This is because we do not have access to the rand variable and I want to make this explicitly clear.

like image 275
stackoverflow Avatar asked Mar 13 '17 15:03

stackoverflow


1 Answers

Math.random() can be predictable, which can be exploited. In theory. The ES6 spec says

Returns a Number value with positive sign, greater than or equal to 0 but less than 1, chosen randomly or pseudo randomly with approximately uniform distribution over that range, using an implementation-dependent algorithm or strategy. This function takes no arguments.

(Emphasis mine.)

In practice, most modern browsers use xorshift128+ (Chrome, Firefox, Safari). Its implementation is rather brief and can be understood relatively easily. See this related question.

Can we attack this implementation and predict values in the sequence, or try to figure out previous values? According to Security.SX, we can. We really can. It is definitely not easy, but possible.

I don't know if this can really be used to solve the linked exercise. In theory, it could.


An alternative could be to pass in something that will always be equal to any number compared to it. That is, overload the strict equality === operator. Unfortunately, JavaScript does not support operator overloading, as far as I know. You can cheat and use post processing (cannot be used on the linked page), or fake it in some cases, but this challenge is not one of them as we have primitives that are compared using the strict equality operator - that one does not do casting or valueOf.

like image 194
Just a student Avatar answered Sep 28 '22 06:09

Just a student