How to externally influence JavaScript running in a page - javascript

I'd like to be able to make the JavaScript I've got in a web page behave differently by doing something or setting something externally. So there'll be logic checking if(something) execute functionality one, else execute functionality two. I can think of three ways of doing this, but I don't like any of them enough to choose it. At least not unless I can see if there's another blindingly obvious way of doing it that's somehow escaping me at the moment.
Add a harmless query string to the URL (e.g. ?choose_functionality_one=true) and my logic can simply look in the page URL. The reason I don't like this is the case where my code is running inside a cross-domain iframe and I can't even access the page's URL (only the iframe's URL). Yes I could pass the query string to the iframe, but only if I have control over the parent page, and I don't.
Create a cookie in the domain of the page, and my logic can simply look for it in document.cookie. This could be done with a bookmarklet easily enough, and wouldn't suffer from the cross-domain problem, because I simply open a window/tab to the domain where my code is running and run the bookmarklet in that context. This is my front-runner choice at the moment.
Add something to the browser's useragent string and look for that in my logic. Pretty easy on Firefox via about:config, but is less easy with the other browsers, and downright difficult on the Mac. Also, on some browsers, once you've set a custom value, you lose the ability to have the UA get auto-updated when you get a browser update. Your UA's version info is stuck in time to where it was when you first custom'ed it.
Can anyone think of another way that via email/IM/phone I can say to someone "do this" and they'll see the page behave differently for troubleshooting purposes. For the general population who haven't done that though, it's running completely normally.

The simplest option seems to be to make a debug page on your site that will let the user turn the "debug" cookie on/off and then queue your regular site code off the existence of the cookie. I'd suggest making the debug cookie expire in a fairly short amount of time so people don't inadvertently leave it on.
This option has the advantages you are interested in (no user agent modification, works on all platforms, works with iframes) and I can see no disadvantages except that it wouldn't work if someone had cookies off, though a lot of the web won't work without cookies these days so that seems like something you could live with.
In addition, it's also the simplest for your users to use. You can just direct them to the right page on your site and all they have to do is click the desired button to turn it on or off. You can make the page very self explanatory which is certainly much easier than any of the other options.
OK, if you only control code and no HTML, then you could do either implement a keyboard shortcut key that would enable the debug mode by setting the cookie. The instructions could be something like this: put the keyboard focus in X and then press Ctrl-D.
Or, you could implement some special type of click (like a Ctrl-click on some object or in some page corner). In this case the instructions could be something like: Hold down the Ctrl-key and click on object X on the page.
Your JS code could implement either of those shortcuts. You could even put up a prompt (all with dynamically created HTML objects) when the special key/click was engaged to confirm turning the debug mode on or off.

Related

How to detect whether a HTML file is opened in browser or some Application Software?

I need to do some changes in my HTML file based on whether it is opened in browser or Some Desktop Application.
Till now I've tried this in my script:
alert(navigator.appName);
alert(navigator.appCodeName);
alert(navigator.platform);
But the values are coming same whether the HTML file is opened in browser or some application Software.
How can i set a variable which toggle its value from 0 to 1 when opened in application Software and vice versa.
PS: Application Software like Matlab, MS Office , Britanica Encyclopedia etc.
Short answer, you can't.
Longer answer, to some extent. What you need to do is make a list of differences in each desktop apps implementation, based on known flaws, missing/existing properties, user agent flavours and so on (some of this called "browser spoofing"), to be able to sort them out. It will still be possible to trick this if one want to though.
Normally there is another way of dealing with the differences, the question is what is the different behaviour you want between the 2?
As a sample, and if you still need/insists to detect this, there is device detection libraries which can help as a start, like https://51degrees.com/device-detection
I still recommend to find another way to solve it.
UPDATE
As it is easy to create a desktop app and return the values needed for your page to believe it is a normal browser, I think the best solution is to ask the user on first page hit if they are on a normal browser or not (the one who is not will normally know) and then store in a cookie/set a flag and act upon what the user selected.
I mean it is easy to cheat your page either way so better trust on user selection.
You can use 2 step verification for such cases as devices are getting quite varied. First you can detect devices by media queries strings using innerWidth property. And then you can apply second filter matched by protocol it supports.
Secondly, this SO question might help Frame Buster Buster ... buster code needed

IE settings through Javascript or jquery

Is there any possibility to set the Internet Explorer settings by running Javascript file..?
I want to set the following settings in IE through javascript/Jquery
Go to, ‘Tools’ -> ’Internet options’.
Under ‘General’ tab, click the ‘Settings’ button in the ‘Browsing History’ section.
Choose the radio button "Every time I visit the webpage".
Click ‘OK’ and restart the IE.
This is not possible - it'd be a bit of a security hole if sites were able to do this...
Firstly, the short answer is no: You can't do what you're asking for.
Javascript within the browser is heavily restricted to only being able to access resources for the actual page being viewed. This is an important security feature.
You cannot access other pages or other tabs. You cannot access parts of the browser UI outside of the page itself. You cannot run external programs.
Even if you could, the way you've described it wouldn't work anyway: The settings page you've described is specific to one particular version of IE. So your hypothetical program wouldn't work in any other browser or even any other version of IE.
However, more importantly, you need to ask yourself why you're asking for this.
The thing is that you're trying to solve a problem with your site. You've found something that resolves it, and you've asked a question about how to automate that. But you need to work backward a bit -- stop trying to work out how to automate this particular solution: you need to ask yourself whether there might be a different way of solving the original problem, which could be automated.
The fact is this: the config setting you're trying to change is for handling how the browser deals with caching of files. There are ways of changing the behaviour of caching that can be scripted by your site. You might want to look at questions like this one for example.
The lesson here is this: Don't simply ask how to do something; explain why you're trying to do it as well. There might be an alternative solution that's better than the one you've thought of.
No, it's not possible to do using JavaScript.
This is not what Javascript designed to do. There is only a way to read browser setting from JS - using signed scripts.

Protect against browser extension injected Javascript code

Browsers allow extensions to inject code, manipulate the DOM, etc.
Over the years, I have noticed lots and various uncaught errors (using window.onerror) on a website (app) I am watching, generated by unknown browser extensions on Firefox, Chrome and Internet Explorer (all versions).
These errors didn't seem to be interrupting anything. Now I want to increase the security of this website, because it will start processing credit cards. I have seen with my own eyes malware/spyware infecting browsers with modified browser extensions (innocent browser extension, modified to report to attackers/script kiddies) working as keyloggers (using trivial onkey* event handlers, or just input.value checks).
Is there a way (meta tag, etc.) to inform a browser to disallow code injection or reading the DOM, standard or non-standard? The webpage is already SSL, yet this doesn't seem to matter (as in give a hint to the browser to activate stricter security for extensions).
.
Possible workarounds (kind of a stretch vs. a simple meta tag) suggested by others or off the top of my head:
Virtual keyboard for entering numbers + non textual inputs (aka img for digits)
remote desktop using Flash (someone suggested HTML5, yet that doesn't solve the browser extension listening on keyboard events; only Flash, Java, etc. can).
Very complex Javascript based protection (removes non white listed event listeners, in-memory input values along with inputs protected with actual asterix characters, etc.) (not feasible, unless it already exists)
Browser extension with the role of an antivirus or which could somehow protect a specific webpage (this is not feasible, maybe not even possible without creating a huge array of problems)
Edit: Google Chrome disables extensions in Incognito Mode, however, there is no standard way to detect or automatically enable Incognito Mode and so a permanent warning must be displayed.
Being able to disable someone's browser extension usually implies taking over the browser. I don't think it's possible. It would be a huge security risk. Your purpose maybe legit, but consider the scenario of webmasters programatically disabling addblockers for users in order to get them to view the advertisments.
In the end it's the user's responsability to make sure they have a clean OS when making online banking transactions. It's not the website's fault that the user is compromised
UPDATE
We should wrap things up.
Something like:
<meta name="disable-extension-feature" content="read-dom" />
or
<script type="text/javascript">
Browser.MakeExtension.MallwareLogger.to.not.read.that.user.types(true);
</script>
doesn't exist and i'm sure there won't be implemented in the near future.
Use any means necessary to best use the current up to date existing technologies and design your app as best as you can security wise. Don't waste your energy trying to cover for users who souldn't be making payments over the internet in the first place
UPDATE (2019-10-16): This isn't a "real" solution - meaning you should not rely on this as a security policy. Truth is, there is no "real" solution because malicious addons can hijack/spoof JavaScript in a way which in not detectable. The technique below was more of an exercise for me to figure out how to prevent simple key logging. You could expand on this technique to make it more difficult for hackers... but Vlad Balmos said it best in his answer below - Don't waste your energy trying to cover for users who souldn't be making payments over the internet in the first place.
You can get around the key logging by using a javascript prompt. I wrote a little test case (which ended up getting a little out of hand). This test case does the following:
Uses a prompt() to ask for the credit card number on focus.
Provides a failsafe when users check "prevent additional dialogs" or if the user is somehow able to type in the CC field
Periodically checks to make sure event handlers haven't been removed or spoofed and rebinds/ warns the user when necessary.
http://jsfiddle.net/ryanwheale/wQTtf/
prompt('Please enter your credit card number');
Tested in IE7+, Chrome, FF 3.6+, Android 2.3.5, iPad 2 (iOS 6.0)
Your question is interesting, and thoughtful (+1'd), however unfortunately the proposed security does not provide real security, thus no browser will ever implement it.
One of the core principle on browser/web/network security is to resist from the desire of implementing a bogus security feature. Web will be less secure with the feature than without!
Hear me out:
Everything execute on the client-side can be manipulated. Browsers are just another HTTP clients that talks to server; server should never ever trust the computation result, or checks done in front-end Javascript. If someone can simply bypass your "security" check code executed in a browser with a extension, they can surely fire the HTTP request directly to your server with curl to do that. At least, in a browser, skilled users can turn to Firebug or Web Inspector and bypass your script, just like what you do when you debug your website.
The <meta> tag stopping extensions from injection does make the website more robust, but not more secure. There are a thousand ways to write robust JavaScript than praying for not having an evil extension. Hide your global functions/objects being one of them, and perform environment sanity check being another. GMail checks for Firebug, for example. Many websites detects Ad block.
The <meta> tag does make sense in terms of privacy (again, not security). There should be a way to tell the browser that the information currently present in the DOM is sensitive (e.g. my bank balance) and should not be exposed to third parties. Yet, if an user uses OS from vender A, browser from vender B, extension from vender C without reading through it's source code to know exactly what they do, the user have already stated his trust to these venders. Your website will not be at fault here. Users who really cares about privacy will turn to their trusted OS and browser, and use another profile or private mode of the browser to check their sensitive information.
Conclusion: If you do all the input checks on sever-side (again), your website is secure enough that no <meta> tag can make it more secure. Well done!
I saw something similar being done many times, although the protection was directed in the other way: quite a few sites, when they offer sensitive information in a form of text would use a Flash widget to display the text (for example, e-mail addresses, which would be otherwise found by bots and spammed).
Flash applet may be configured to reject any code that comes from the HTML page, actually, unless you specifically expect this to be possible, it will not work out of the box. Flash also doesn't re-dispatch events to the browser, so if the keylogger works on the browser level, it won't be able to log the keys pressed. Certainly, Flash has its own disadvantages, but given all other options this seems the most feasible one. So, you don't need remote desktop via Flash, simple embedded applet will be just as good. Also, Flash alone can't be used to make a fully-functional remote desktop client, you'd be looking into NaCl or JavaFX, which would make this only usable by corporate users and only eventually by private users.
Other things to consider: write your own extension. Making Firefox extension is really easy + you could reuse a lot of your JavaScript code since it can also use JavaScript. I never wrote a Google Chrome or MSIE extension, but I would imagine it's not much more difficult. But you don't need to turn it into an antivirus extension. With the tools available, you could make it so no other extension can eavesdrop on what's going on inside your own extension. I'm not sure how friendly your audience will greet that, but if you are targeting corporate sector, then that audience is, in a way, a very good one, as they don't get to choose their tools... so you can just obligate them to use the extension.
Any more ideas? - well, this one is very straight-forward and efficient: have users open a pop-up window / separate tab and disable JavaScript in it :) I mean, you could decline to accept a credit card info if the JavaScript is enabled in the browser - obviously, it is very easy to check. This would require some mental effort from the users to find the setting, where they can disable it + they will be raging over a pop-up window... but almost certainly this will disable all code injection :)
This wont work, but i'll try something around document.createElement = function(){};
That should affect client side scripts (greasemonkey)
You can also try to submit the current DOM using an hidden input
myform.onsubmit=function(){myform.hiddeninput.value=document.body.innerHTML;} and check server side for unwanted DOM elements. I guess using a server side generated id/token on every element can help here (as injected DOM node will surely miss it)
=> page should look like
<html uniqueid="121234"> <body uniqueid="121234"><form uniqueid="121234"> ...
So finding un-tracked elements in the POST action should be easy (using xpath for example)
<?php
simplexml_load_string($_POST['currentdom'])->xpath("*:not(#uniqueid)") //style
Something around that for the DOM injection issue.
As for the keylogging part, i don't think you can do anything to prevent keylogger from a client side perspective (except using virtual keyboard & so), as there is no way to discern them from the browser internals. If you are paranoid, you should try a 100% canvas generated design (mimicking HTML element & interaction) as this might protect you (no DOM element to be bound to), but that would mean creating a browser in a browser.
And just that we all know we cannot explicitly block the extensions from our code,
one another way can be to find the list of event listeners attached to key fields like password, ssn and also events on body like keypress, keyup, keydown and verify whether the listener belongs to your code, if not just throw a flash message to disable addons.
And you can attach mutation events to your page and see if there are some new nodes being created / generated by a third party apart from your code.
ok its obvious that you will get into performance issues, but thats a trade off for your security.
any takers ?

Refreshing webpage after browser back button?

Let me begin by saying I do not want to "disable" or otherwise prevent the proper usage of the browser history buttons.
What I need is a javascript-based procedure (cross-browser compatible, hopefully) to refresh a webpage (staying on the same URL) after navigating to it using the back/forward buttons. This is necessary because during this process the server keeps track of the user's position/page, and if the user wants to jump back 3 pages I need to "inform" the server of the new location by reloading the page (or is there a better way to do it?) I already disabled caching through HTTP headers but this doesn't work for back/forward history, at least in Firefox 7.
Using jQuery is of course acceptable and desirable. I looked around a bit and found out about $(document).ready(). Now, please keep in mind I'm a complete javascript noob. I have zero experience, and the same goes for jQuery (I know what it does, I've looked at the docs, but that's about it). So I'm trying to understand how this works, but pages that mention this method seem to assume that the webdeveloper wants to modify the DOM from it, and there are a few quirks when you want to do that (load order and stuff). Since in my case I only need to refresh, it should hopefully be easier. So:
I understand this doesn't only run when you browse back, it also runs every time you load the page. How can I make sure I don't end up with an infinite loop? I want it to run once when I browse back, but not on load, after the automated refresh or otherwise. On a normal load I'd rather not have it running because the user would have to download each page twice, which is stupid!
Or is there a better way to do this? Any other ideas? Care to explain or point me in the right direction?
EDIT: I only need compatibility with:
Internet Explorer 8 or higher
Firefox 4 or higher
Recent-ish Chrome/Safari (I don't keep track of version numbers but why would someone not use up to date Chrome anyway?)
The best workaround I ever found for this problem is to use location.replace(), like so.
It does not directly address the problem from my original question; however, since that seems not to have a solution (for now), I recommend that everyone uses this client side function to protect the server side pages they do not wish to have executed again by a client using the back button. I'm sure this is better explained elsewhere on stackoverflow, but for the few people using my convoluted way of thinking to look the problem up, there you have it.
Its a bit of an abuse, but one of the ways of doing this would be to have your "proceed to next step" button as a form which POSTs. For example;
instead of
Proceed to next Page
you have
<form action = "foo" method = "POST"><input type = "submit" value = "Proceed to next page" /></form>
If the user hits back, they'll be forced to re-send their data to the server and your page would be refreshed. This would probably be really annoying to the user though!
But as i mentioned, major abuse of forms!
EDIT: This abuse will only work for certain scenarios though, you'll be the best judge of whether it's appropriate.

Why don't browsers send whether they have javascript enabled/disabled in the request header?

It just seems like something that would be really useful when developing server-side code. If you know that the browser won't be using javascript from the server-side, you could easily accommodate the user. Or if you just felt like it, redirect them to a page that says 'hey... we need you to use javascript for our application' etc.
Does anyone know why this is?
See the <noscript> tag, here.
I know it's probably not ideal (I don't have enough experience with it to pick it apart) but it certainly gives us enough flexibility to degrade somewhat gracefully.
As handy as it would be to have your server be aware of your browser's Javascript capability before page rendering began, I can see a strange edge case such as:
// hide malicious code from people without javascript
if ($header['javascript'] == 'false') {
show_regular_safe_website();
} else {
use_some_nasty_javascript_exploit();
}
One way I use is to have a landing page/login page. When the user presses the logon button then use javascript to submit the results or update a hidden field before posting the logon. If javascript is disabled then the javascript will not work and therefore you can assume they have it turned off.
The real reason is that when Netscape came out with JavaScript, they never thought to make the information available in the HTTP headers. Instead they created the <noscript> tag.
I suppose the Accept field could be used to such a purpose, like "Accept: text/javascript". But since it's proprietary the IETF would never include it in any standards and widespread adaptation is therefore unlikely. Web-developers has coped so far.

Categories

Resources