XSS overide functions

HacksLand | The computer science playground

Posted by Thilan Dissanayaka on Apr 30, 2020

One of my friend gave me a JavaScript code and asked to trigger an alert() by changing one variable. So following is simplified code. I removed unwanted parts of the whole code.I posted it on our facebook community too.

So take a look at this code.

var alfa = {
	beta: function(a) {
		var str = 'HacksLand.net';
		var b = str.length;
		var c = a + 5;
		console.log(a);
	},

	gamma : 'JustForFun :-)'  
}

var x =  /* find the value of x to get alert(1)*/ ;

alfa.beta(x);

Hear we have to change variable x. But alert should be generated after the function call. If there is no condition like that we can simply change the code as following.

var x = 5; alert(1);

But if we do as this the alert comes before function call. Also there is no challenge this way.

 

For this challenge we can use a concept in JavaScript JS always try to represent an object in primitive. Let's think there is a n JavaScript object as obj. What happen if we try to add it to a number. JavaScript tries to get the value of the object. Every object have two default methods as valueOf() and toString(). We can try to overide one of these these function to exploit above code. Let's see following example.

var o = {
	valueOf : function() {
		console.log('valueOf() function called');
	}
};

var a = 1 + o;

valueOf function replaced by  our ow function. When we add object to one JavaScript calls o.valueOf() method. So our function get executed.

Now let's focus on our actual challenge. We can use following payload to exploit it.

 

var x = {
toString: function () {
      alert('1');
   }
}

So whenever beta() function called it try to run a.toString() Because it want to convert s to a string So at that point our exploit will run and make an alert(1).

var alfa = {
	beta: function(a) {
		var str = 'HacksLand.net';
		var b = str.length;
		var c = a + 5;
		console.log(a);
	},

	gamma : 'JustForFun :-)'  
}

var x = {
 toString: function () {
   alert('1');
 }
}

alfa.beta(x);

Hear we go.

Hope you learned something new Thank you for reading.

Hi, I'm Thilan. An engineering student from SriLanka. I love to code with Python, JavaScript PHP and C.

Also read

Aug 12
IP Address Explained

In this tutorial I'm going to cover an important topic in networking. Yes it's internet protocol.....

Aug 18
Linux user management

Today I bought you another tutorial on Linux. Hear we are going to discus about basic user....

May 16
Stack architecture theory tutorial

The stack is an important concept in computer science. If you are planning to learn reverse....

Comments