Sandboxing javascript module - javascript

Is it possible to sandbox javascript module from DOM manipulation? Fo example
var Core = {
register: function(config){config.init()},
publicApi: {
msgbox: function(msg){alert(msg)}
}
}
Core.register({
name: 'testmodule',
init: function(){
/* from there i want to see only function defined in Core.publicApi, no jQuery direct access, no DOM */
}
});

Well, somewhat: you can sandbox the function, but its callees will also be sandboxed. That means even stuff in Core.publicApi won't be able to access document and the like. Or, at least, there's no bulletproof sandboxing in Javascript that will allow that bridging.
You can cripple what's available by temporarily overwriting the window variable:
var window = {"Core": Core};
But then no global variable (even such as alert) will exist for the callees. This will most likely break your API.
You can add another member (like _unsandboxed or whatever) into the new window variable to allow your API to access the members. But, as I said, it's not bulletproof since sandboxed functions can still access _unsandboxed.

Related

How do I make custom JavaScript console commands?

I've been trying to make custom console commands with JavaScript with no success. There seem to be no sources about my question.
When I say "JavaScript Console Commands" I mean I'd like to make my own commands from the console. For example, if the visitor types "custom.command()" in my website's console area, I want the output to be: console.log("This is my custom command");.
You don't have to do anything special; just create an object at global scope with functions on it, and the user will be able to use it from the devtools console.
For instance (in a script, not a module):
const custom = {
command() {
console.log("This is my custom command.");
},
};
Because that's at global scope, it creates a global, and so it is accessible in the console when your page is open.
(It doesn't have to be an object; you could just create a function at global scope, but your example usage was using an object.)
If you wanted to do this from a module, since the top level of a module isn't global scope, you'd have to do the same kind of thing you have to do to create a global in a function, which is covered by the answers to this question (in your case, it' basically assign to a property on window: window.custom = { /*...*/ };).

Set function default this value

Background:
I am running a sandboxed iframe which only has the permission "allow-scripts". In the sandbox a script is loaded with custom js provided by the user. Now i want to manage access to global functions/objects like XMLHttpRequest. Currently i achieve that with the following code:
const CLEARED_WINDOW_SCOPE= {};
const scope = { /* Here goes the globals the script should have access too */};
const propertyNames = Object.getOwnPropertyNames(window);
for(let property of propertyNames){
CLEARED_WINDOW_SCOPE[property] = undefined;
}
with(CLEARED_WINDOW_SCOPE){
with(scope){
(function (window, self, frames, globalThis){
${scriptContent}
}).call(scope, scope, scope, scope, scope);
}
}
The script does the following:
Create object with all window property names set to undefined
Create object with all properties the user should have access too
Wrap the user code with two with statements the first clears all globals the second grands access to the defined ones
Wrap the user code with a function that is called with the scope as this value
So far everything works perfectly as excepted.
Problem:
The main problem that i have right now is that when a user defines a function like that:
function aFunction(){
console.log(this);
}
He gains access to the normal window object because the default this value within a function is the window.
Question:
Is it somehow possible to change the default this value of a function to the this value of the surrounding scope. Since the user creates the script i can't wrap all function calls with aFunction.bind(scope). Or is there any other value to prevent the access to the global window object?
Is it somehow possible to change the default this value of a function to the this value of the surrounding scope.
No, but you can do the next best(?) thing: setting it to undefined. Just force strict mode:
"use strict";
// User's code
(function (){
console.log(this)
})();
Also, I'm not a JavaScript security expert, but JS sandboxing is a really complex topic because of things like prototype pollution.
Edit: As CherryDT noted in the comments, this method is not completely secure. Users can still access the <iframe> window by creating a function with the Function constructor, for example. Also, a reference to the main window can be obtained through the <iframe> window (window.parent).
It's maybe OK to use this solution for user-supplied code (since users can just open the DevTools console and start typing), but make sure the code comes from the user and never from a URL search parameter, for example. If the code is completely distrusted, I would recommend to use a well-known library like Google Caja.

Overriding jQuery function loses 'this' scope

I am trying to implement the following answer from another question:
https://stackoverflow.com/a/26469105/2402594
Basically I need to add an extra check to a jQuery function. The following code is in jQuery library:
But I can't modify the original jQuery, so I am creating a patch in a separate file. What I am doing is overriding the find function and add functionality as follows:
(function() {
var originalFind = jQuery.fn.find;
jQuery.fn.find = function () {
try {
document === document;
}
catch (err) {
document = window.document;
}
return originalFind.apply(this, arguments);
};
})();
The function is overridden correctly, however, when the code calls 'find', my 'try' doesn't throw any exception when it should because the scope is different than the one inside the Sizzle function, so the original issue is still there.
I have also tried duplicating all of the Sizzle code, adding my modification and assigning it to jQuery.fn.find as done above, however the scope issue is still there and some crashes happen.
I need 'document' to be set before it reaches the following check or it crashes due to permission denied:
How could I share the scope so that the try/catch can be done correctly? Is it even possible? Any other ideas?
Thank you
As we all known, JavaScript has function scope: Each function creates a new scope. Scope determines the accessibility (visibility) of these variables. Variables defined inside a function are not accessible (visible) from outside the function.
So, if the document is defined in the JQuery library function, I think you can't access it. You could try to define a global variable to store the document, then, you can access it in the JQuery library function and the override function.
More details about Javascript Scope, check these links: link1 and link2

Make variable accessible like window

Lets say I have one variable var car = 'VW' in index.html
index.html is the binding of my application, from there I access several modules:
<script>
var car = 'VW';
var Initializer = require('./js/initializer');
Initializer.check_requirements();
</script>
Now in initializer I try to access this variable what does not work.
var Initializer = {
check_requirements: function(){console.log(car)};
};
module.exports = Initializer;
However when I attach the variable car to window:
window.car = 'VW';
Then Im able to access it in my module over window.car;
How do I create an global variable car that I can also access in my modules, so that I do not have to attach to window?
Thanks
In a browser context, a "global" variable is in fact a property of the window object, which acts as the global context. The syntax you have in your question, a bare var statement in a script tag in an HTML page, will in fact add that var name as a property to the window. However, since you're using what looks like a CommonJS require statement here, which is not natively supported in most browsers, there's probably a compile step you're not including in your question that's preventing this from working the way you expect.
However, the short answer is, don't do this if you can avoid it. Most applications of global variables are better accomplished with parameters, e.g. Initializer.check_requirements(car);, or in a separate module storing configuration settings, or other approaches.

How should I store my javascript variables?

I am currently coding in this way:
<script type="text/javascript">
var linkObj;
Is this a safe way to store data? My concern is what if a jQuery or other plug-in was to also use the variable linkObj. Also if I declare my variable like this then can it also be seen by other functions in scripts located in other js files that I include?
$(document).ready(function(){
var linkObj;
});
as long as you use the var keyword, any variable defined in that scope won't be accessible by other plugins.
I you declare a variable this way it will be accessible to all scripts running on the page.
If you just want to use it locally, wrap it in a function:
(function() {var linkObj; ... })()
However, this way nothing outside of the function will be able to access it.
If you want to explicitly share certain variables between different scripts, you could also use an object as a namespace:
var myProject = {}
myProject.linkObj = ...
This will minimize how many global names you have to rely on.
Wrap it in a closure:
<script type="text/javascript">
(function() {
var linkObj;
// Rest of your code
})();
</script>
This way no script outside your own will have access to linkObj.
Is this a safe way to store data?
This is not storing data per se, it's only declaring a variable in a script block in what I assume is an HTML page. When you reload the page in the future, it will not hold previous values.
My concern is what if a jQuery or other plug-in was to also use the variable linkObj.
That's a valid concern, like others have pointed out. However, you would expect plugins not to rely on scope outside the plug-in. This shouldn't impact a lot as good plug-in design would likely prevent this from happening.
Also if I declare my variable like this then can it also be seen by other functions in scripts located in other js files that I include?
Yes. As long as their execution is triggered after your script block gets loaded. This normally follows the order in which your script declaration appears in the page. Or regardless of the order they appear on the page if they are executed, for example, after the jQuery DOM 'ready' event.
It's common to hear that is good to avoid 'global namespace pollution', which relates to this concern. To accomplish that you can use a function to contain code, and directly invoke that function in your script block.
(function () {
var a = 1; // the scope is within the function
alert('The variable a is equal to: ' + a);
}) (); // the parenthesis invoke the function immediately

Categories