User-generated SQL Query - sql

I'm developing a data warehouse using Ruby on Rails and I should allow the user to perform arbitrary SELECT queries on the application database.
I know this is what you usually SHOULDN'T do, but it's an interface my client actually needs (I can't think of all the possible queries the user might want to do and translate them to ActiveRecord queries). There could be complex joins and sub-queries and so on.
I'd rather do this (integrate it to my app) than let them access the DB via pgAdmin (I'm using postgresql).
My question is: what is the safest way of doing this? I should be able to escape anything like INSERT, UPDATE, DROP TABLE, etc...
I'm thinking of getting the query string and sanitizing these "dangerous" words and then using ActiveRecord::Base.connection.execute(sanitized_sql_string).
Is this a reasonable approach?

The safest way would be to let Postgres handle this security for you. Create a new user:
CREATE USER Reader; -- Your Rails app should logon with this user
Then, explicitly grant SELECT permissions on the objects you want them to be able to query:
GRANT INSERT ON TableFoo TO Reader;
GRANT INSERT ON TableBar TO Reader;
Then, they'll be able to run arbitrary SELECT queries from these two tables, but if they try an INSERT, they'll get Permission denied. You can then trap those security exceptions and handle them in your UI appropriately.

Create the application then create the database.
After this, in your database configuration (database.yml), connect to the database with some non-default user, say lame_user. Create this lame_user on your RDBMS, in your case PostgreSQL, and grant him only SELECT permissions on all of your tables.
You will now have the user postgres and the lame_user that can access your database, but only postgres can do all the stuff.
If the user tries to do anything besides SELECT's, an error will occur.
Resuming: Make this application constraint a database thing. It will be easier.

Related

How to avoid SQL injection and other security failure in JavaFX desktop application

Is there any method to avoid SQL injection and other security failure in JavaFX desktop application? If yes, how can I do it?
SQL Injection attacks are related to malicious statements deliberately sent by the end user to the database, while JavaFX is the front-end from a user's point of view.
That said, let's assume you have a login screen to input user and password. Could you prevent the user to type one of the following sentences instead of their real user name?
DROP TABLE Users; --or
DELETE FROM Users WHERE 1=1;
You could validate the text looking for certain keywords like DROP, INSERT, UPDATE or DELETE. But is it worth? Maybe it does, depending on how probably is the users will try to go ahead with this kind of attacks.
However the best way to mitigate and frustrate SQL injection begins from the connection itself. Tipically you'll want to connect to the database with users that have the less necessary privileges to operate. A common practice is to create a dedicate user to do the login for example, with read-only access to the Users table and maybe INSERT and UPDATE granted to a Sessions table (if you are interested in keep a sessions log of course):
CREATE USER 'login_user'#'%' IDENTIFIED BY 'password';
GRANT USAGE ON MyDataBase.* TO 'login_user'#'%';
GRANT SELECT ON Users TO 'login_user'#'%';
GRANT INSERT, UPDATE ON Sessions TO 'login_user'#'%';
Note: the snippet is based on MySQL but the same concept applies to other RDBMS as well.
In this scenario, if the end user succeeds in sending one of the above sentences to the database, the db user which was established the connection wont' have enough privileges to perform none of those sentences and will cause an SQL exception. The same applies to other entities as well, just provide a db user with the less privileges to operate with sensistive data.
In addition, JDBC provides PreparedStatement interface which is intended to avoid SQL injection by using placeholders to build the statements. For example:
String sql = "SELECT * FROM Users WHERE username = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, userName);
The userName parameter will be wrapped into literals before sent the statement to the database so if the user types one of the above malicious sentences they won't have any effect. Plus, if you want to execute more than one sentence you have to use addBatch() and executeBatch() which is under developer's control, making it even safer.

How can I allow SQL Injection safely

So I wanted to know if there is an acceptable method to Allow SQL Injection.
Example:
Limit permissions on the table(s)/database(s)
Why you ask?
My employer wanted to devise a way to test the skills of applicants, one suggestion was to allow resume submissions via SQL Injection.
Any thoughts? suggestions?
You could use roles. Create a role for the web application (or whatever) that is used to connect to the database. Limit this role to only permit INSERT and access to necessary tables for applying. Applicants with access to your database through the application could then only use SQL injections to add their resume.
It may be possible for someone more talented in SQL to use injections in a way that increases the role's permission. But I think if the role had limited access to only specific tables and didn't have CREATE or GRANT privileges, the user wouldn't be able to create new roles.
Here is some information on roles to get you started:
Adding Roles to MySQL with MySQL Workbench
Creating Roles in PostgreSQL
GRANT command - used to add privileges to users on table, database, etc. This page is for PostgreSQL, but MySQL is very similar (see this SO answer)
Given that the reason behind this is to test people's ability, create a database with data you can afford to lose. Set up a form that posts to a coldfusion or php or java or .net or some other type of page which connects to that database.
On the form, put a textarea and submit button. On the form target page, log what they put in the textarea. Compare the log to the database to see how it turned out.
Then test to your heart's delight.

GRANT Database Permissions for specific tables and the validity of this as a security practice?

my question is rather simple.
Can i grant permissions on a database table wise? something in the lines:
User Management has permission to select, update, insert and delete on table Projects
User Supervisor has permission to select, update, insert on table Projects
User Colaborator has permission to select on table Projects
If so, I could set up a system to create database users based on the levels of access of my application, much like the examples above.
Is it a valid mechanism to use this to secure a application?
is it worth on a real world application?
i've used PHP with Oracle and MySQL, but I'm look for a database/language agnostic answer, but any example would be useful.
pushing my luck a bit, what about per record permission granting?
also, what about table schemas, are they a more acceptable then table based permissions?
The main problem with using database security would be that you need separate connections for each user rather than being able to use a "service user" for the connection from your application server to your DB server. That would mean that you would no longer be able to use database connection pooling have to "connect" and "disconnect" from the database for every user request, which is not very efficient as connections are relatively expensive.
Having said that, there is good reason for using separate users in the database, such as DATA_USER (which the application server connects as) and DATA_OWNER (which owns all the tables but is used only for DB maintenance) and then only give DATA_USER the permissions that it needs to, e.g. only select on a lookup table. By separating DATA_USER and DATA_OWNER you can add an additional level of confidence that your application won't issue DDL commands (e.g. dropping a table).
Answer to part 1:
Yes as long as you handle the responses correctly.
Part 2:
It's not as good as implementating security in the application layer, as most applications will need flexibility in the solution (what if you want a user to get increased privledges, have to code in lots of alter/deny/grant scripts)
Part 3: (Speaking from purely MSSQL) Row-level permissions aren't possible. Create custom views for this purpose.

Ensure that a SQL query is READ-only

What would be the best way to ensure that a SQL query won't alter the data of a database?
In my scenario, you don't have access to the database layer and can only do this logic on the application layer.
Would you recommend using a gem, a ruby custom script?
You can manage the permissions of the users so that they have access for reading the database but they don't have access to alter the database (i.e. not able to insert, update and delete). If you are using mysql, for instance, you can easily do this in phpmyadmin or equivalent tool.
Update based on your change. Even if you only have access through the application you are still connected to the database as a user who has or does not have privileges to update, delete, insert or select and as such the only way to ensure no such queries are executed is to alter that user's permissions.
A simple but far from foolproof method is to employ a blacklist of words that cannot be in the query, such as insert, update, etc.
Alternatively, you could use a parser on the sql query that will provide you with the necessary information to derive whether or not to allow the query.
I would take option 1 only as a last resort or if your checking needs are relatively simple.
On the database layer, make sure that the user the Rails app is accessing the database as only has the access that you desire, perhaps only SELECT.
Sequel has support for read only slave databases with a writable master database. Read-only slaves handle SELECT queries, other queries are done by the master database.
Maybe you can just setup master database as nil?
Another approach could be using hooks (before_save) to prevent writing to the database.

Disable all queries in SQL Server that don't use named parameters?

It seems that one could stop all threat of Sql injection once and for all by simply rejecting all queries that don't use named parameters. Any way to configure Sql server to do that? Or else any way to enforce that at the application level by inspecting each query without writing an entire SQL parser? Thanks.
Remove the grants for a role to be able to SELECT/UPDATE/INSERT/DELETE against the table(s) involved
Grant EXECUTE on the role for stored procedures/functions/etc
Associate the role to database user(s) you want to secure
It won't stop an account that also has the ability to GRANT access, but it will stop the users associated to the role (assuming no other grants on a per user basis) from being able to execute queries outside of the stored procedure/functions/etc that exist.
There are only a couple ways to do this. OMG Ponies has the best answer: don't allow direct sql statements against your database and instead leverage the tools and security sql server can provide.
An alternative way would be to add an additional tier which all queries would have to go through. In short you'd pass all queries (SOA architecture) to a new app which would evaluate the query for passing on to sql server. I've seen exactly one company do this in reaction to sql injection issues their site had.
Of course, this is a horrible way of doing things because SQL injection is only one potential problem.
Beyond SQL Injection, you also have issues of what happens when the site itself is cracked. Once you can write a new page to a web server it becomes trivial to pass any query you want to the associated database server. This would easily bypass any code level thing you could put in place. And it would allow the attacker to just write select * from ... or truncate table ... Heck, an internal person could potentially just directly connect to the sql server using the sites credentials and run any query they wanted.
The point is, if you leverage the security built into sql server to prevent direct table access then you can control through stored procedures the full range of actions availble to anyone attempting to connect to the server.
And how do you want to check for that? Queries sometimes have constant values that would just as easy be added to the query. For instance, I have a database that is prepared to be multi lingual, but not all code is, so my query looks like this:
SELECT NAME FROM SOMETABLE WHERE ID = :ID AND LANGUAGEID = 1
The ID is a parameter, but the language id isn't. Should this query be blocked?
You ask to block queries that don't use named parameters. That can be easily enforced. Just block any query that doesn't specify any parameters. You can do this in your application layer. But it will be hard to block queries like the one above, where one value is a parameter and the other one isn't. You'll need to parse that query to detect it, and it will be hard too.
I don't think sql server has any built in features to do this.