So we all know that eval is bad, and allowing users to create their own JavaScripts to run on your site is just potentially VERY dangerous, opening doors to all kinds of security risks.
My challenge however, is to come up with a solution, to allow users to create their own custom script snippets, that will execute on the client side. These scripts are basically prediction algorithms, that allow each individual user to build their very own customized prediction strategy, calculating and processing a set of data provided to them via AJAX.
Basically, on regular time intervals, an AJAX request is made by the system, a JS event is trigerred, notifying the client side each time new data has arrived. The above user scripts are allowed to hook into/subscribe to this event, executing the users algorithm on the received data, and outputting the result of their algorithm.
The following problem I have...If I allow users to create their own JavaScripts, they can pull all kinds of fancy tricks, like make cross browser unauthorized AJAX requests, invoke unintended input events and in plain short...attempt to hack the system with malicious intent.
I need to encapsulate these scripts, restricting them from using the browser context. For example they cannot make AJAX requests, or invoke click events on the page. The only access they have is to the data supplied, via a pre-determined input>process>output interface.
So my question is, how can my site, give users, SAFE, limited, scripting access? Is there for example a Lua script parser written in JavaScript or something likewise that can be utilised?
Would something like ADsafe work for your site?
Related
I want to create a Javascript widget that my users can put on their websites.
The widget is capable of creating audio, which in turn costs my users' money.
For the sake of illustration, let's say that every time a widget, placed on my user's site, is loaded by anyone on the internet (i.e. my users' users), I bill my user $1.
The widget is a Javascript code wrapped around an HTML audio player. The JS code makes a request to my backend API every time it is loaded, and upon receiving the response from my backend API, the player is constructed.
Diagram:
My concern is malicious usage by people who are not my users.
Let's say someone takes the widget's source code they found on a website that belongs to one of my users, and they put it on their site. They will, therefore, use my service but not pay for it. Instead, my actual user will pay for it (assuming I use a public API key as a way of distinguishing my users).
Usually, this is prevented by having a server-side library be responsible for any usages that might spend money. For example, I use Pusher as my WebSockets IaaS, and whenever I want to publish messages, I have to do it server-side, using their PHP SDK, with both private and public API keys.
In my use case, it's mandatory not to have a server-side library.
Question: how do I make sure that API requests I receive are legitimate?
I considered using the hostname where the widget is placed as a legitimacy measure. During the widget set-up, I could ask my users to whitelist certain (sub)domains and reject all requests that don't match the criteria, but this could be easily spoofed by, for example, a custom local domain or a CURL-crafted request.
I understand this may not be possible.
It seems like what you're asking is closely related to the topic of client side encryption. In most cases, the answer would be no, its not possible. However, in this case, it may be possible to implement something along the lines of the following. If you can get your clients to install a plugin (which you would build), you could encrypt your JS code after finishing it, and have your server serve this encrypted file. Normally, where this falls short, is that if you're sending an encrypted file, there needs to be a way for the client to decrypt it. This would require you to also serve an unecrypted JS file which would do the decoding, but by serving the unencrypted decoder you undo any security gained by encrypting your main JS file (the decryption file could be easily used to reverse engineer your encryption method/ just straight up run for people other than your intended users). Now, this is where having those API users (and the ability to communicate with them through means outside of server-client connections) comes in handy. If you build a decryption plugin, and give it to the API users (you could issue a unique decryption key for each user, but without server access implementing unique user keys would be very difficult/impossible), the plugin could then decrypt your served file in their browser, essentially guaranteeing that only users you have given the 'key' to can access your software. However, this approach has a few caveats. It implies that you trust your users enough that they wouldn't distribute the plugin (it would be against their intrest to distribute it anyway, as it could lead to higher chargers if people impersonate them). There are also probably a couple of other security concerns with this approach, however, I can't think of them right now. If any come to mind, I'll edit this post and add them.
apparently, I don't have enough reputation to comment yet, hence the post...
But in response to your post, I think that method seems much better than the one I suggested; I didn't realize you could control the API's response to the server.
I don't quite understand which of the following you mean:
a) Send a JS file to the user, with the sole purpose of determining if the player should also be sent (ie upon arriving, it pings the server with the client's API key/ url) and then the server would serve the file (in which case your approach seems safe to me, but others may find security problems with it).
or
b) Send a file with the JS and the audio player, which upon arriving, determines if the URL and API key are correct, and then allows the audio player to function normally (sending the API key to the server to track usage, not as a security feature).
If using option b, this would not improve security. If your code relies on security that runs on the client-side, and the security system was sent by the same means as the code, then almost without exception, the system designed is flawed and inherently unsafe.
I hope this makes helps, and if you disagree / have more questions, feel free to comment!
How about sending the following parameters from JavaScript widget to API backend:
Public API key (e.g. bbbe3b259f881cfc796f468619eb9d)
Current URL (e.g. https://example.com/articles/chiang-mai-thailand-january-2016-june-2016)
I will use the API key as a way of distinguishing my user and the current URL as a way of knowing which audio file to create (my widget will create an audio file based on the URL).
Furthermore, and this is crucial, I will have a user whitelist their domains and subdomains on my central site, where my users will get their widget code.
This is the same as what FB does for their integrations:
So if for example, my backend API receives the aforementioned sample URL, and the user has set up the widget to only allow URLs that belong to foo.com and bar.baz.com, I will reject the audio creation process and display an error.
Do you see any issues with this approach?
I want some content of my website to be dynamically loaded after login. A $.post(...) interacts with a servlet which validates the user's credentials, and then a $.load(url) loads the content from a separate page into a <div>. I noticed that, as long as I know where to fetch the content from, I can force this behavior from the chrome javascript console, bypassing validation.
How can I prevent a user from doing this?
You can't.
Once a document has been delivered to the user's browser it is completely under the control of the user. They can run any JS they like.
The URLs you present on your webserver are the public interface to it. Anyone can request them. You can use authentication/authorization to limit who gets a response, but you can't make that response conditional on the user running specific JavaScript that you supply.
The server needs to authorize the user each time it delivers restricted data. You can't do it once and then trust the browser to enforce it.
You can add a secret parameter to the url you load. By defining a random variable in the users session (server side) or in the database, and then return this variable once the validation is successful so your javascript code can use the variable in the next load call. In the load url you can check at the server side if the secret parameter had the correct value or not.
Hope its clear.
The simple answer is: You Can't.
JavaScript runs within the browser and therefore a user or application can run their own code whenever the feel like. This could be as simple as adding new CSS or running their own JS codes.
The main thing you can do to disable this is to ensure all of the requests are validated on your server side before being run as well as allowing only entry for certain types of information (like only allowing integers as numbers to stop strings coming through).
Something close to this sort of problem is XSS or Cross-Site Scripting. A 3rd party will try to inject some malicious code to a trusted website, usually some form of POST, to affect different users. Here is some more information on the matter
Cross-Site Scripting - Wikipedia
CSS - OWASP
After experimenting with scripts on facebook.com, I noticed that for a couple of minutes it didn't allow me to connect to facebook.com. This happened more than one time so I suspect that Facebook doesn't like to mess with their code using userscripts.
The Stack Overflow question Can a website know if I am running a userscript? answers the multiple ways a website can detect scripts.
Now I want to know how I can fool a website to not detect any scripts I may be running.
Is there a way to know what my userscript HTML changes trigger on the website?
For Firefox and Chrome there is no magic bullet to prevent detection, it is a process and an art...
The 3 principle ways that a site would detect a script are:
Out of sequence or too-frequent AJAX requests.
Changes to the page's code (HTML, global JS, or even CSS).
Unnatural mouse or keyboard action.
See "Can a website know if I am running a userscript?" for more information.
Some countermeasures:
For AJAX requests that your script makes:
Use Wireshark, or similar, to analyze the traffic of normal AJAX calls. Make sure that you send the same type of calls, in the same order.
Make sure that your requests show the same headers and data as the page's.
Do not send AJAX requests faster than the page does normally or faster than a user could reasonably trigger.
Consider adding random delays to your script's requests, so that they are not uniformly timed.
Beware of constantly changing fields in the page's requests. Be sure that you know how to generate the correct value; don't just cut and paste.
For changes that you make to the page's code:
The page can handle these either entirely locally, with it's own javascript, or it can also send back status or code fragments to the server.
Block and replace the page's javascript. Tools like NoScript, RequestPolicy, firewalls and proxies can be used to block the JS.
Then use Greasemonkey to add your edited version of the page's JS. Greasemonkey will run even if all of a page's JS is disabled.
If the page phones status home, and that status changes in response to your script's changes, Intercept and replace those messages. (This is not needed if you used the previous method.) You will need a custom firewall, proxy, or router to do this.
For events that you trigger (mouse clicks, filling out fields, etc.):
If the page checks for this, give it what it looks for. For example, instead of a click event, you may need a mouseover, mousedown, mouseup, mouseout sequence.
If that is not enough, then the countermeasures are the same as for changes made to the page's code (replace JS, intercept status messages).
Important!
In the rare event that you are battling a site that tries to thwart userscripts, it is like a war. The webmaster can adapt to what you are doing, and the environment can constantly change. So scripting for such a site is an ongoing process.
Scripts are executed on user's side - your side. Therefore site's server code cannot know if you run anything or not.
There's two things to note however:
Site can deliver some script to be run on your computer that will inspect its environment and will report back if necessary. Those are most often targeted to detect some specific script that site owner don't want to have in its environment.
Site author can inspect your requests and analyze if they don't match patterns that would match regular communication from site supplied forms or AJAX. Missing keys or keys not matching hardcoded order in query, headers that identify automation clients or missing browser headers and things like that. Hitting throttling limits if you do requests automatically much faster than human user should fits this category too.
Otherwise if you generate exactly the same responses and don't leave traces in globally accessible environment, it is impossible for site to tell if you're using userscript with either server or client side checks.
I am using some global variables on a web application, built on Html/Javascript. I am using these variables across pages (or portions of them), and sometimes they are used as post data for ajax calls. My question is: how secure is this? surely i can set different values for these variables (using a console for example) and then, the calls that rely on this var are made. Imagine the user sets some Id that corresponds to something that he even doesn't have access to..
How should this be done?
Thanks in advance
There is nothing different about this from any web application, from a point of view of security.
Anything sent from the browser must be treated as untrusted by the server. This includes URL parameters, form post data, cookies, http headers and anything controlled by javascript. All these items can be manipulated by an attacker.
Essentially, it doesn't matter what the values are in the client, you only need to worry about them when they hit your server in the form of a new HTTP request (this includes XHR). Until that point, variables with bad values can't do any damage.
Ensure your server can correctly authenticate the current user and only allow them access to data and actions that they are authorised to perform. Ensure that all data received from the browser is checked to be correct (if known) or of the correct datatype and within expected limits, rejecting the data and aborting the action if it is not.
if you use jquery, you can use
$.data()
With this, you can associate the data with an element, thus a unauthorized user will not be able to access it
Javascript has runtime type identification (everything is a var like visual basic), its a loosely typed language.
Javascript has its own security model though
User cannot access files (r/write)
It cannot access or look at user location, files, open windows without demand etc
It is not possible to protect the source of your javascript file either or even pwd protecting it as this is better done server side.
Even encryption or decryption doesnt work because somehow you need to tell your users the key
Worse, JavaScript can self-modify at run-time - and often does. That means that the security threat may not be in the syntax or the code when it's delivered to the client, but it might appear once the script is executed.
There is no JavaScript proxy that parses and rejects malicious script, no solution that proactively scans JavaScript for code-based exploits, no external answer to the problem. That means we have to rely on the browser developers to not only write a good browser with all the bells and whistles we like, but for security, as well.
Currently I have developed a site which is used for handle financial transactions. I have seen that some of my customers have done JavaScript injection attacks and have done some transactions which are not possible. As a example I have checked his cash balance before he place the order. But some of them did change that by running the following javascript in the address bar. They have taken the varible name by looking in to page source.
javascript:void(document.accounts.cashBalence.value="10000000")
Since this is critical I want to fixed it quickly. So is there a way to prevent JavaScript injection attacks?
You can obfuscate or hash variable names and/or values. However,
Don't use JavaScript, do every logic in the server-side instead.
In the end it's not even a problem of Javascript. Your server talks to the outside world using HTTP. It sends data using HTTP and receives data using HTTP. Anybody can request data from it using HTTP and anybody can send data to it using HTTP.
Think about this again:
Anybody can send data to your server through the very simple protocol that is HTTP.
The HTML and Javascript you're sending to people's browsers is just a nice help, an interface, to allow them to easily send data to your server. They could do the same using the curl command on their command line or by telnet'ing into port 80 and talk really low-level to it.
If your server blindly obeys any and all commands sent to it without checking their validity, you have no security whatsoever. Security and validity checks belong on the server, not on the client side interface. Because HTML and Javascript aren't the only interface to your server, nor are they in any way protectable and hence trustworthy.
Javascript runs in the user's browser. You ultimately have no control over it and should not trust it. Any verification you do in the browser is merely for the user's convenience so they can be alerted of problems as early as possible.
The backend code that accepts the order should do the authoritative check of the user's balance.
No client-side scripting (including Javascript) is good for verification, It should all be done on the server-side.
It is too unreliable to trust it specially if it is for financial records!!
It should be used for a better "user experience". Form validation while typing or whatever but not this!
Have found that if you make it to where server only excepts out going data not incoming data it works best but that poses a problem, if you are using a website that takes user input on the connected client then your preaty much screwed I sugset a simple java script line that in a sence makes it to where before you can send any java script you have to enter a basic set of variables so in a sence just have a login page start with somthing like this
System.out.printin ("Welcome, Would you like to login to edit?")
Then { System.in = "Yes"}
To prevent Javascript injection, you should have a Validation Feature whenever you allow your user to enter something. Try to use libraries that determine Javascript scripts that are entered to the form.
Also when displaying user inputs, you should Escape Texts to display it as is and will not be evaluated by the browser.
Utilize your server, your should place your business logic to the server and not to the client whether using Javascript or not. All data sent to the client are just view and should not process any business logic.