Hook window.location.* assignments and window.location.assign - javascript

I'm trying to intercept window.location.* assignments and window.location.assign calls to change the url assigned before leaving is that possible?
when I try to redefine the property setter I get an error that I can't redefine it.
Is my only option is to proxy the page and statically replace all assignments to window.location with string replace?
Although I rather avoid it since javascript is funky and something like this could also be valid so I would have to keep track of all assignments:
var l = window.location;
var c = l;
var t = c.assign;
t('...');

One solution would to be to create your own location change provider where you could intercept the URL and make changes accordingly. Your code could then always call your change provider rather than the standard window.location property.
Of coarse this would not work if you are in a situation where the code that is setting the location property is out of your control.
If the location setting code is out of your control, take a look at Javascript: How to intercept window.location change where the beforeunload event is used.

Unfortunately, I don't think you can do this. As you've found, the location property on window is non-configurable (at least in Chrome and Firefox). And as you know, it's very special: If you attempt to write to it (e.g., to replace it with your own customized object), instead of replacing the property in the normal way, it will convert what you give it to a string and attempt to navigate there. Consequently, there's no way for you to replace window.location with your own thing: Object.defineProperty won't let you (because it's non-configurable), and assignment won't work.
That leaves you with the task of identifying all writes to window.location in the JavaScript code on the page, which is impossible in the general case. While you could find all window.location and location references, and static analysis would tell you (absent eval or new Function) whether those window and location variables are the globals, you would need to evaluate the code step-by-step to find the kind of thing you mentioned in your question, or even something simple like:
(function(w) {
w.location = "https://stackoverflow.com";
})(this);
Completely changing the architecture of your solution, you could run a headless browser server-side and echo changes to its DOM to the client, intercepting all clicks and forwarding them to server-side code to pass to the headless browser. Which likely has its own significant challenges.

Related

Create empty URL object from scratch in JavaScript

I want to manually construct URL from parts using the URL object.
However, it's constructor requires a proper URL string to be passed to it, which doesn't allow to start from empty object and build it progressively.
Is there a way to overcome this limitation somehow?
What caused such design decision in the first place?
You have already figured out the workaround and there is no alternative other than passing the parts in or starting with a URL and mutating it.
I'll try to answer:
What caused such design decision in the first place?
By far the most common use case for URLs was to create a URL from a URL string. Someone actually did end up asking for the API you are describing in the URL spec and discussion mostly stalled.
We have an API in Node.js for constructing URLs from parts - but that creates a string one would still need to pass to the URL constructor.
So this is likely not a bad idea and it is currently blocked on someone actually doing the work of adding that capability.
The only workaround I've found so far is to use minimal correct URL to initialize the object and then to override it's parts (namely protocol and host).
const url = new URL('https://example.com');
url.protocol = 'http';
url.host = 'google.com';
console.log(url.toString()); // outputs: http://google.com/
However, it's still cumbersome for this use case.

Calling an overridden and frozen function

I'm building a security framework which injects a javascript file which will always be executed first, and blocks some functions to be executed.
The developers will make their own webapps and the script will make sure that some functionalities cannot be called.
Let's suppose the "blocking" script is like this:
window.alert = function(){Object.freeze(this)}
Is there any way for an application to circumvent this block, without using iframes/external files?
delete(window.alert) doesn't work in this scenario.
not if you can't stop that script running first, otherwise you could asign the original alert to something else:
var oldAlert = window.alert;
window.alert = function(){Object.freeze(this)}
How/why are you using alert? if its for debugging you'd be better off using console.log. if you are using it to notify users then maybe a dedicated modal would be the better option
Based on your updated question, it depends how your framework is loaded.
Lets say you provide the script to the developer to use, in that case they could very easily alter what your script does. if the code is running on in a env that isn't yours then you can assume it's not secure. browser plugins can block scripts, there would bypass any security based in a javascript file.
based on the work of #Abdennour TOUMI on this post : Opposite of Object.freeze or Object.seal in JavaScript, you can do something like that :
window.alert = function(){Object.freeze(this)} ;
Object.unfreezeAlert=function(){
return window.prompt;
}
window.alert = Object.unfreezeAlert(window.alert);
alert ('test4');
http://jsfiddle.net/scraaappy/pxv51zqg/
You need to set the alert property on Window.prototype, not on window. Otherwise:
Window.prototype.alert.call(window, 'This works.');

New ActiveXObject('Word.Application') creates new winword.exe process when IE security does not allow object to be created

We are using MS Word as a spell checker for a few fields on a private company web site, and when IE security settings are correct it works well. (Zone for the site set to Trusted, and trusted zone modified to allow control to run without prompting.)
The script we are using creates a word object and closes it afterward. While the object exists, a winword.exe process runs, but it is destroyed when the Word object is closed.
If our site is not set in the trusted zone (Internet zone with default security level) the call that creates the Word object fails as expected, but the winword.exe process is still created. I do not have any way to interact with this process in the script, so the process stays around until the user logs off (users have no way to manually destroy the process, and it wouldn't be a good solution even if they did.)
The call that attempts to create the object is...
try {
wordApplication = new ActiveXObject('Word.Application');
} catch(error) {
// irrelevant code removed, described in comments..
// notify user spell check cannot be used
// disable spell check option
}
So every time the page is loaded this code may be run again, creating yet another orphan winword.exe process.
wordApplication is, of course, undefined in the catch block.
I would like to be able to detect the browser security settings beforehand, but I have done some searching on this and do not think that it is possible.
Management here is happy with it as it is. As long as IE security is set correctly it works, and it works well for our purposes. (We may eventually look at other options for spell check functionality, but this was quick, inexpensive, and does everything we need it to do.)
This last problem bugs me and I'd like to do something about it, but I'm out of ideas and I have other things that are more in need of my attention.
Before I put it aside, I thought I'd ask for suggestions here.
I have not found an answer to this problem, and I am disturbed at what the problem implies about Internet Explorer security (I forgot to mention in my previous post the version I am using : IE 7.)
However, I did implement a workaround that I am not happy with, but nevertheless feel more comfortable with than no check at all...
The code now attempts to open another object first, and if that fails the code assumes that Word will not open either and issues an error. From this point on, no more calls to new ActiveXObject() will be made and any attempt at a spell check will result in an error.
try {
oMSInfo = new ActiveXObject('Msinfo32.MSInfo.1');
} catch (error) {
// error handling code not shown...
return;
}
This object does not start a new process when the call to new ActiveXObject() fails. It also does not have a noticable affect on system resources.
If your browser creates an instance of an object, the object itself is not blocked by the browser security policies, except it is a security leak.
Try "application.visible=true", or "application.show()" to find out, where the application is asking for user interaction.
Hint: 'typeof application=="undefined"' means, the variable 'application' is not defined, where 'typeof application=="unknown"' means, more or less, it is a defined variable, stuffed with an external, proprietary object and if you really need to know how to handle it, read the manual -- pressing [F11] in any open window of the mentioned application could help in that case.
Might be a useful resource: https://learn.microsoft.com/en-us/office/vba/api/Word.Application

Javascript security problem

ok, I start with a very simple method:
alert(someText);
"someText" is a variable, which users will pass a value in by a form.
Will there a chance that the user pass following text, and inject some code in my Javascript?
For example, can the user pass this in this method:
"anotherText"); alert("the nextText"
If so, how can I prevent it from happening? if not, can anyone mention some security concern about javascript?
No, it doesn't work that way. String values are not substituted where they are used, they are just used as strings. So there is no security problem.
The only time you may have to worry about this is when you use eval:
eval("alert(\" + someText + "\");");
(Yes, I realize this is a contrived example...)
Basically, as long as you're not calling "eval" (or some function that does), and you're not injecting Javascript created from users directly in to pages (via the script tag), you shouldn't have anything to worry about.
Once you have a variable inside javascript it won't matter much unless you do an eval or set the innerHTML property of a DOM element with it.
Aside from that, whether there's a potential for injection depends on how you're getting the value from the form to the javascript.
If for example the form is being submitted to the server and the value of the variable is being set by writing the javascript on the server side you could potentially have a problem.
Something like this would obviously leave the script open for injection.
var someText = "<?php echo $_POST["someText"]; ?>";
So it's hard to say whether you could have a security issue without knowing how you're getting the value from the form. In my experience the server side code is the cause of most XSS vectors. In terms of javascript you generally just have to watch for eval and innerHTML.
if "someText" is rendered by server, example JSP、velocity, then it is dangerous
eg
<script>
alert({{someText}})
</script>
then before JavaScript runtime,while HTML parsing,it is dangerous
but if, “sometext” is javascript variable ,#Zifre's answer is right;
beside, except "eval" keyword, new Function(sometext)、 location.href= sometext ...... may invoke some attacks

any method to change title of inputbox i.e prompt in javascript

i want to know if there is any way to change title of inputbox i.e prompt in javascript?
nope, you cannot change the title in the native javascript prompt. you could easily write a function of your own, though, which mimics the behavior of the prompt, but the flow won't be exactly the same (i.e. you'll have to use callbacks, rather than a return value, for the user input)
Something like:
function myPrompt(title, message, value, callback) {
// create form, that displays the title, message, and an input box with the value
// append the form to the dom, probably in some elevated (modal) manner
// if the user invoking myPrmopt didn't specify a callback, don't register listeners
if(typeof callback != 'function') return;
// register listeners:
// if there's a close button, equivalent to escaping out of a prompt:
closeBtn.click(function() { callback() }); // not passing any params
okBtn.click(function() { callback(input.value); });
}
If you are talking about changing the title of the window itself, then what i know it is not possible because this method has only two parameters which do not affect the title of the window. See this for more information.
Syntax:
prompt(msg,defaultText)
But you can not change the title which says"
"page at whatever address says...."
Note: The title varies in different browsers.
No, and not only that: you can't really use prompt any more, at all.
IE7 has removed it(*), ostensibly on security grounds. (I find Microsoft's reasoning somewhat spurious on this, especially compared to a lot of the questionable stuff IE has come up with in the past. But it's too late to complain about now.)
So today, for compatibility, you must use an in-document pop-up that runs asynchronously, with a callback function run on completion, similar to David's example. There are many pre-packaged scripts that will do this for you, but it does require that you re-write your calling code to deal with the response in an inline callback function instead of executing directly after the function call.
In any case, alert/confirm/prompt aren't great for usability (as they make the rest of the browser UI unresponsive), aren't very pretty, and have some sneaky concurrency issues in some browsers. If you can get rid of them for all but the most trivial cases (or debugging purposes), that's all for the better.
(*): actually it's still there, but hidden by a security warning infobar which silently prevents it working for at least the first time. This effectively makes the feature as good as useless.
inputbox.title="insert your text here ?";

Categories

Resources