Safe Javascript/Sql connection - javascript

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

Related

Server overload ... with requests? How do I efficiently program server-client wise

SO, I have a server with MySQL database in it, and a client (browser) that retrieves data from the server and displays to the user.
I'm struggling over whether I should let client get all the data he needs from a MySQL server (using PHP), and let client to do all querying, adding, updating to the data with JavaScript or other related library, and send it back to the server for the server to update his data; OR
whether I should let client send requests (query, add, update, etc) to the server with relevant parameters for server to handle the user's data with, say, MySQL commands.
I think first way could relief the server because all the work is done by the clients' computer, and not by the server, but would be hard for me to learn or make a library that does all the querying and stuff that can otherwise be done with MySQL commands which I find easier to work with at this moment.
And I think the second way would be easier for me, because I can just use PHP and MySQL to perform whatever server needs to do for client, but it makes me think that it would load server with too many repetitive work for each client if there were too many clients.
Which method is better?
At this moment, I'm the only client and server is run on the same computer, so there won't be too much load of commands that server would need to run, but I want to know which method is most canonical and efficient security, efficiency, etc wise.
Both solutions have their pros and cons. If you have a huge set of data, you don't want to dump it all to the client, especially if they only need to view or modify a fraction of it. If any of your data needs to be protected against unwanted change (like a user increasing their access level, credit, etc) you can't place the logic on the client since that will be easy to hack. If neither is a concern, client-side logic may indeed take a lot of load off your database server.
There are client-side frameworks like Angular and React that make working with data easier, although they too have a learning curve. Check if they fit your needs.

Which is more efficient to send WebSocket updates with a MySQL database change

I'm currently experimenting with WebSockets in a bid to reduce / remove the need for constant AJAX requests in a potentially low bandwidth environment. All devices are WebSocket compliant so there's no issue there, and I'm trying to keep it to native PHP WebSockets, no node.js or other frameworks / libraries (Which so far has been fine).
What I'm looking to do is to decide how to go about notifying connected clients about an update to a database by another Client. The use case in question is a person pressing a button on their device, which then alerts that persons manager(s) to that press. So the two options I have though of are as follows:
1. Looping a Database Query (PHP)
My first thought was to insert a query into the WebSocket server that is effectively saying "Has the alert field changed? If so, notify the manager(s)". Whilst this is the most straightforward and sensible approach (That I can think of), it seems wasteful to have a PHP script designed to reduce strain on the server, that is now running a query every second, however, at least this would ensure that when a Database update is detected, the update is sent.
2. Sending a notification from the Client
Another thought I had, was that when the client updates the Database, they could in fact send a WebSocket notification themself. This has the advantage of reducing any intensive and looped queries, but also means that I'd need to have a WebSocket message being sent every time I want to change any data, such as:
$.post("AttemptDatabaseUpdate.php", {Data}).function(Result) // Don't worry about the semantics of this, it's not actual code
{
if(Result == "Successful")
{
SendWebSocketNotification(OtherData);
}
}
Maybe this is the best option, as it is the most efficient, but I worry that there is a chance the connection may drop between updating the Database, and sending the WebSocket notification, which may create a need for a fallback check in the PHP file, much like the one in the first solution, albeit at a longer interval (Say every 30 seconds).
3. MySQL Trigger?
This is purely a guess, but perhaps another option is to create a MySQL trigger, which can somehow notify the server.php file directly? I've no idea how this would work, and would hazard a guess that this may end up with the same or similar Query requirements as solution #1, but it's just a though...
Thank you in advance for your help :)
EDIT: Solution possibility 4
Another thought has just popped into my head in fact, whereby the PHP file used to update the database could in fact have a WebSocket message built into it. So that when the PHP file updates the database, the WebSocket server is notified via PHP, is this possible?
If you use websockets, you should use notifications from client. That's one of their main use cases.
If you're worried about inconsistencies due to connection dropping or something changing in-between, you could implement a system similar to HTTP ETags, where client would send a hash code that you can respond on server side if there is a conflict in updating.
Update: I guess I understood your initial issue a bit wrong. If I understand your use case correctly: you are sending database updates from a client and after that all connected clients need to be updated. In that case, I think server should send the update messages after DB updates have been done, so I agree with solution 4. I am assuming here that your websocket server is the same server running PHP and doing the DB updates.
However, depending on your use case, client should still send a hash value on the next request identifying its "view of the world", so you would not be doing identical updates multiple times if a connection gets broken.
Update 2: so it was now understood that you indeed use a separate, standalone websocket server. Basically you have two different web servers on the server side and are having an issue on how to communicate between the two. This is a real issue, and I'd recommend only using one server at a time - either take a look at using Apache websocket support (experimental and not really recommended) or migrating your php scripts to the websocket instance.
Neither PHP or Apache was really build with websockets in mind. It is quite easy to set up a standalone websocket server using only PHP, but it might not be so easy then to migrate the rest of the PHP stack to it if the code is relying on Apache/web server on. Apache websocket support also is hardly optimal. For a real websocket solution, unfortunately, best practice would be using a technology that is built for it from the ground up.
The better answer is to send notification through Server side when database is updated by PHP script, so that script have to add options of web sockets to directly send notification to all web socket clients registered.
User send content->Php script process content and save data according to true condition->check database is updated by checking return of mysql_query/other alternative->if true than use web-socket and send notification to all users
now this is more easy/handy/bandwidth saver.

How can i get the HTML5 Local storage values in server side

I am a .Net developer, I know that the HTM5 localstorage is client-side storage technique. I want to get the local storage data on the server-side.
For getting cookie value from server-side we have Request.Cookie in ASP.NET. Is there any solution like that to take the local storage value directly on the server-side? Please guide me. I am using the .net 4.0 framework
Thanks,
Jibu
You will need to pass this information from the client to the server using standard HTTP techniques. Using javascript you could fill:
Hidden fields
Query string parameters
POST
Ajax call to the server
...
It will all depend on how your application is organized, what kind of information is being stored, its volume, whether you want to redirect or not, ... But in all cases this should be done using javascript since that's the only way to access data stored in localStorage.
No. The whole point of local storage is that it is local. One of the advantages of it over cookies is that you can store lots of data in it. One of the advantages of cookies is that they are tiny so the overhead of including them in every HTTP request to a given host is small. There two advantages are incompatible so you won't want them in a single technology.
If you want to get the data on the server, then you need to get the client to send it explicitly (e.g. via Ajax).
This is a widescope question. (like the length of a piece of string), but Ill try to make this helpful:
If you have values in local store in webserver I assume your webserver is JSON? Or did you use the sql local storage option?
Regardless of type of storage, you need to build an interface that both handles:
a) Reading data from your local database -> its important to involve some kind of date or index value in here if you are aiming to sync databases... this is to make sure you send IN ORDER all transactions / updates which are in your database. For this to happen you must store your data not only as tables with inforamtion but also tables that contain events of when updates happened and what was updated. (change tables). This will help check in the server end that everything is sync and also means you dont send data to the server that is not needed and can be kept locally. ((otherwise what is the point of local store if you cant save yourself server database space by only syncing waht is necessary?)
b) A HTTP local server to send the data to your destination client server or database server, etc (however you have set your infrastructure) - I recommend using industry standards for your language and server, which is Ajax and JQuery. If you do a lot of streaming of data then i recommend looking into RXjs with Ajax to get a http interface built (interface in this sense just means a way to expose your client like an API and post http calls)
c) An event loop to handle how often and what triggers the synchronization so that you dont destroy your users machine with overdoing it (you dont want to do this too often, but also want to it to be meaninful rather than "every night" maybe user enabled whenever you detect an event which triggers wifi available again.) - i recommend using native wifi reading capabilities built into Apache Cordova and also industry standards for your server setup (for example Express.js for Node.JS).
Obviously the backend server needs to have its API set up and authentication / authorizations, etc.

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.

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