JavaScript security issue - javascript

I wanna know how the following function set 'this' element and fetch the array cell out? please.
//my secure code
var priv = ['item-0','item-1'];
var api = {push: function(x){priv.push(x)}}
api.store = function(i,x){priv[i] = x}
//the attaker script
var result;
api.store('push',function(){result = this[0]});
api.push();
//the result is cell 0 of private array
//how?
//if i change the 'push' parameter then the result is empty!
document.write(result)

What happens is that api.store('push',function(){result = this[0]}); overrides the push method of the priv array. That means that after this line pushis no longer the push method that javascript natively provides but the attackers custom function, which is function(){result = this[0]}. Now, when you call api.push() it calls priv.push(x) which was overridden. Since push is called on an object, this is bound to the object, which is priv (more on that in the MDN article on this). Therefore, result = this[0] is equal to result = priv[0] and result will contain the first array entry.

Related

Waiting values to be set in iteration through list javascript

I'm creating an Access Control List, but when I set a function to its properties it doesn't work correctly, because the current iteration read function as a null value, but when I set it to func.toString() works.
Here's my running code.
line85: try to change the perm.when = func; to perm.when = func.toString(); it'll add correct. but i need it as a function.
if you write
console.log([func]); //[f]
perm.when = [func]; // [null]
Can I read it as a function instead of null?

Accessing value of key inside object

There's a handful of questions extremely similar to this, I know, but I can't seem to get anything to work.
For sake of brevity, I'll summarize this. I have this constructor function with strings assigned as values of the keys (assignment).
var Quote = function() {
this.quote1 = 'You can discover more about a person in an hour of play than in a year of conversation.';
this.quote2 = 'Nothing is at last sacred but the integrity of your own mind.';
this.quote3 = 'We have to fight them daily, like fleas, those many small worries about the morrow, for they sap our energies.';
this.quote4 = 'Ethics are so annoying. I avoid them on principle.';
this.quote5 = "Never trust anything that can think for itself if you can't see where it keeps its brain.";
};
module.exports = Quote;
Using AJAX I am printing the value of the keys inside the constructor to a static page. However... I am only successful in printing "quote1", "quote2", etc... (Just the name of the keys).
This is what my function for accessing the constructor looks like. My question is: How can I access the string values assigned to the keys inside the constructor? Is that possible?
Thank you in advance.
module.exports = function(object) {
var propArray = Object.keys(object);
var randomProp = propArray[Math.floor(Math.random() * propArray.length)];
return {quote: randomProp};
};
Inside your function, you should be able to access the quote by key using this:
object[randomProp]
In JavaScript, object properties can be accessed using square bracket notation. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects.
As you might have expected, there are several things wrong with your code :)
I've rewritten it with pretty thorough comments.
<script>
// create your 'Quote' class, which can be instantiated as many times as necessary
var Quote = function() {
this.quote1 = 'You can discover more about a person in an hour of play than in a year of conversation.';
this.quote2 = 'Nothing is at last sacred but the integrity of your own mind.';
this.quote3 = 'We have to fight them daily, like fleas, those many small worries about the morrow, for they sap our energies.';
this.quote4 = 'Ethics are so annoying. I avoid them on principle.';
this.quote5 = "Never trust anything that can think for itself if you can't see where it keeps its brain.";
};
// now let's set up the 'exports' method on the function's prototype
// this will allow any new instance of the Quote function to call or override this method
// without affecting the master 'Quote' class
Quote.prototype.exports = function() {
// you don't need to explicitly pass an object to this function
// just have it reference itself using the 'this' keyword
var propArray = Object.keys(this);
var randomProp = propArray[Math.floor(Math.random() * propArray.length)];
// objects in JavaScript can be handled like associative arrays
// simply access the key of 'this' with the value provided by 'randomProp'
return {quote: this[randomProp]};
};
// create a new instance of 'Quote'
// this guy can be used and manipulated independent of the master 'Quote' class
var module = new Quote();
// let's store the value returned by 'exports' in randomQuote
// note the () at the end of module.exports -- this tells JavaScript to treat the object as a function
var randomQuote = module.exports();
// write your quote to the document -- or do whatever else you want to with it at this point
document.write(randomQuote.quote);
</script>
Instead of return { quote: randomProp } you should use return object[randomProp].
You can access object properties via dot notation or square bracket notation.
Here's an example from jsbin
https://jsbin.com/yopeli/edit?js,console

Accessing parameters when the function expects none Javascript

I am writing a Javascript function to count the number of instances of an element in an unsorted array. It has a method signature like this
Array.prototype.numberOfOccurrences = function() {
}
Here is an example of expected behavior
var arr = [4, 0, 4];
Test.assertEquals(arr.numberOfOccurrences(4), 2);
My problem is that I don't know how to access the elements in the array. The function doesn't take any parameters so how do I reference the array being passed in?
Note: The instructions aren't very descriptive for this kata on code wars and adding a parameter to the function returns some error unexpected token.
Inside the function you are creating into the Array.prototype you can access all the prototype functions through the "this" keyword.
Meaning you can access the array items using numeric properties like this[0] or this[1] to a access the first and second item respectively.
You can also call functions which allows you to iterate over each item on the array, such as: forEach, filter, etc.
Please refer this page to see everything you can do with the array prototype:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype
Lastly don't forget that the JavaScript implementation varies on each browser, so a function that works on Chrome, might not work on InternetExplorer, always confirm on caniuse.com If the function you are used has the same implementation on your targets browsers.
Cheers.
Whether you should extend javascript base objects aside, this is your friend:
Array.prototype.numberOfOccurrences = function(valueToFind) {
return this.filter(function(item) {
return item === valueToFind;
}).length;
}
var a = [1,2,3,3,3,3];
console.log(a.numberOfOccurrences(3)); //4
As noted above, if you're not able to change the function signature for whatever reason you can specify it as follows:
Array.prototype.numberOfOccurrences = function() {
var valueToFind = arguments[0];
...
}
I would recommend adding the parameter to the function for clarities sake. Seems counter intuitive for a function like numberOfOccurences to not take in a parameter - numberOfOccurences of what?
Fiddle: http://jsfiddle.net/KyleMuir/g82b3f98/
You might try using the locally available variable 'arguments' inside of the function. So for example, your code might look like thsi:
Array.prototype.numberOfOccurrences = function() {
var args = arguments || {};
var testArray, testCheck;
if (args[0] && Array.isArray(args[0]) {
// do something with the array that was the first argument, like:
testArray = args[0];
testCheck = testArray.indexOf(args[1]);
return testCheck;
} else {
// do what you want to do if the function doesn't receive any arguments or the first argument
// received isn't an array.
}
}
'arguments' is always available to you inside a declared function.

How to use javascript variable in Web worker thread

I need to update my javascript array in Web worker thread.
I cannot accces my javascript array in Web worker thread.
My code is :
self.onmessage = function(event) {
var array = new Uint8Array(event.data);
var sum = 0;
var temparray = new Array();
for(var list = 0; list < array.length; list++ ){
var temp = myMethod(array[list]); //some operation
availableArray.push(temp);
}
self.postMessage("success");
}
I am getting this error:
availableArrayis undefined
availableArray.push(temp);
You define 2 variables that are arrays (or array-like objects): var array = new Uint8Array and var temparray = new Array, but then in the loop you use a variable that isn't declared anywhere availableArray, I suspect you want to change that variable to temparray.
The error message makes perfect sense: availableArray is not defined anywhere. You're using it as an array, and invoking the push method on it. However, JS, by default, creates a new variable for you whenever you use a var that hasn't been declared. The default value for a non-initialized variable is, of course, undefined. undefined doesn't have a push method, hence the error.
However, just a slight remark, though: in JS new Array is actually discouraged. Best use the array literal notation:
var temparray = [];
It's shorter and safer.

Saving a function in an array, and retrieving its index

How can I get the index of a function stored in an array? The following code returns -1
var myArray = [ function(){console.log('fct1')} ];
myArray.indexOf( function(){console.log('fct1')} );
jsFiddle
More details:
I'm using jQuery to delegate events. Each event has one or more callback functions to call. It's impossible for me to know what the functions are since they are not pre-coded. Each callback function will be stored in an array. When a new callback function is added, I want to verify that it isn't already in the array, to avoid duplicates which would be both called by the event.
Any object in JavaScript will not be equal to something similar, except itself.
var func = function() {
console.log('fct1')
};
console.log(Object.prototype.toString.call(func));
# [object Function]
Since functions are also objects in JavaScript, you cannot search for a function object with another function object which does the same.
To be able to get a match, you need to use the same function object, like this
var func = function() {
console.log('fct1')
};
var myArray = [func];
console.log(myArray.indexOf(func));
# 0
This happens due to multiple references.
Each function you declared has a different reference and is not equal to the other.
That's why indexOf doesn't identify it.
Try this:
var func = function(){console.log('fct1')};
var myArray = [func];
alert(myArray.indexOf(func)); // will alert 0.
Fiddle

Categories

Resources