How to prevent JavaScript Injection Attacks - javascript

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.

Related

Safe Javascript/Sql connection

im trying to create a simple website with HTML/CSS and Javascript. Basically the user should be able to input a number into a textfield and "send it" with a button. When the button got pressed i want to run a Javascript function that searches the number in a sql database.
Creating all that stuff shouldnt be a big problem for me, but i have no clue how to create a safe connection between JS and SQL. I have read that a direct connection with javascript is very insecure.
Some people recommend to use java or c# to built an sql connection. How would that work? Basically just an Javascript code, that runs an java/c# application(which builds an sql connection) and returns the needed sql data?
Also heard that its possible to create a sql connection with node.js, is this safe? Or is another method more suitable?
Greetings
I have read that a direct connection with javascript is very insecure
The danger is in giving direct access to your database to the client. JavaScript is most commonly run client-side in web browsers, so for it to access the database you would have to give the browser (and thus the visitor) a username and password on your database server and let them run raw SQL.
There are many possible security risks with this and it just isn't worth it.
(Aside: You can't make arbitrary socket connections with browser-side JavaScript, so it's impossible to connect to most database servers from it anyway).
If you want to expose data to JavaScript running in the web browser, then the standard approach is to write a webservice.
You can write the webservice in any programming language you like (including JavaScript). It listens for HTTP requests, reads data out of them, possibly performs authn/authz, the queries the database (applying the well-documented defences against SQL Injection attacks) and returns the result (often formatted as JSON).
The client-side JavaScript, therefore, just has to make an HTTP request (e.g. with XMLHttpRequest or fetch) with parameters passed in the query string or request body, and process the data it gets back from it.
Connecting to a database using client side javascript is very insecure as the javascript will need to know the login details. And since the client side javascript is on the client side, any user will be able to see the login details in plain text.
The best way to do this is to make a webservice on a server. When the button is clicked it will make a GET/POST request to the webservice with the entered number as a parameter. The webservice, which can be made using any language pretty much, will create the connection with the database and insert the row itself.
Although I would advise going the webservice route since it will be much easier to make secure. Playing with javascript to database is extremely dangerous unless you have a really good system and understand exactly what you are doing; but if you really want to do it and have an application that requires it, then can use PouchDB connected with CouchDB.
PouchDB is run locally and can sync with CouchDB over HTTP.
https://pouchdb.com/
https://couchdb.apache.org/
There is an answer here discussing basic security with pouchDb synchronizing with couchDb. Basically, each person needs separate login credentials and credentials should never be stored in the page code.
PouchDB security
There are some neat uses for pouchDB: https://pouchdb.com/users.html

How to prevent .load() from browser console?

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

javascript global variables - protection

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.

Getting something unique about user's computer with JavaScript?

Here's the idea:
If I can get something unique about a computer with JavaScript from an HTML page (probably the MAC address), then can I use this data as another security check?
Is that possible?
I am not going to check the computer at client side, i am going to send it to server to check. If nothing sent, user will be blocked. So it is not something that any developer+firebug combination can bypass. I just want to send one more string with username and password which is unique to computer and no one else knows if they don't entered to the system from that computer. Like a password hidden from user itself.
You can try using a tracking cookie; note however that such mechanisms are considered transient (e.g. cookies can be erased). In-browser JavaScript is sandboxed so that it does not have access to components outside the page. Note also that any feeling of security you'll gain with JavaScript is illusory - the script runs on the client side, where it can be modified (therefore there's no way to tell whether the "unique" piece of data is genuine or faked) or disabled altogether.
If you're trying to prevent random people from hacking at your app, you may want to ban them after a certain number of failed attempts. This will not get you any security, it's more of a flytrap - it limits the annoyances somewhat.
Finally, if you want actual security, go for HTTPS with real (NOT self-signed) server certificates and client-side certificates - see e.g. this for an implementation (that example, however, uses self-signed server certificates, which is not very secure). This is a mechanism that is well-implemented in the browser itself, and provides you with a somewhat secure system (complete with a secure keystore) of identifying your users (as opposed to a fundamentally flawed JS "security", or relying on user-readable files). Oh, and your data is encrypted while on the wire, that's a bonus.
SSL actually does what you're asking for: verifies that the client machine has a certificate issued to that user. This mechanism works inside the browser, not just inside the webpage; thus, it is much harder to subvert this than an in-page JavaScript. It stores a large unique identifier (clientside certificate) in a secure way, and it can prove to the server that it actually has that identifier - which is pretty much your initial requirement.
(Incidentally, using SSL, the data will be protected in transit, and the client can validate the server's identity; those weren't your requirements, but they're more or less necessary to assure that you're actually talking to the real client and real server)
JavaScript within a Web browser executes within a sandbox and has no access to the underlying hardware. Besides, MAC addresses aren't guaranteed to be unique.
No. And you shouldn't implement security with JavaScript only as any competent developer with Firebug will get around it in no time.

Could browser javascript harm my backend server?

I'm coding an application where I want to let the user learn javascript in this way:
The user write javascript code on the browser like in an IDE.
The user saves it and the code will be saved as a string in my backend No-SQL database (MongoDB/CouchDB).
The user opens the application some days later and I pass that string to the web browser where the code will be executed with eval().
There will be only JSON data transferred between backend server and web browser. The server won't do anything on the code string, it will only save it directly into the database.
Could this code possibly do any damage on the server side?
On the server-side, no. Unless the scripts runs on IE and create multiple files disk. Or make some request to your system inserting billions of new entries...
So you have to take care with requests (flood control), be careful with IE and be careful with SQL injections.
Examples
Creating file in IE
SQL Injection
And the request I'm talking about could be something like:
ajax.post("page_save_js.ext", "code=flood");
Then each time it runs it will insert a new code, flooding the server. StackOverflow controls this flood using captcha after some requests in a short amount of time.
No harm can come from this if its just stored as a string in the DB.
Its really no different than storing any other string. Its just data at that point.
anytime you accept input from a user you must check to make sure it doesn't contain things like sql injection or js injection.
So it can be dangerous to your server (sql injection could wipe/output your db) and to your users (js injection could send them to nefarious sites)
Your server code won't run the javascript unless you tell it to somehow, so that won't cause problems. (And of course you should avoid any SQL injection issues.)
However, if you provide sensitive information in the page (hidden or otherwise), or allow javascript to make ajax calls into methods on your servier, those can be security issues.
Using a nosql database only makes you invulnerable against "SQL injection", but there are very similar QL injection attack vectors. So you still have to escape your data or use data safe APIs (the equivalent of prepared statements in the SQL world).
Some examples of NOSQL-injections are given on http://www.kalzumeus.com/2010/09/22/security-lessons-learned-from-the-diaspora-launch/ (Search for "NoSQL Doesn’t Mean No SQL Injection" within that page).
For the client side: If possible you should make sure that the java script is only delivered to the user who uploaded it unless the user is trusted. This includes a CSRF check on the login form. Wikipedia failed on this in the past.

Categories