I need to allow users to enter SQL select statements in my web application; these select statements will be used to generate the options in a customized dropdownlist.
So I have a field on the UI where the user enters a select; how to prohibit the user of entering an insert/update/delete? I could check that the first statement word is select however they could enter multiple statements on the UI separated by semicolons.
I would do the following:
In your database create a user that only been granted SELECT privileges on the tables that you want the user to be accessible to.
In your server, use a separate data source using the read only user from above for the queries issued from the client.
Trust me, a user with malicious intent will find ways to bypass your checks and inject SQL. (Especially if you are using MS-SQL Server.)
So, do not do this.
Write a proper user interface, no matter how complex it needs to be, and make sure that absolutely no string entered by the user ends up un-quoted and un-escaped in an SQL query.
Construct your UI in such a way that the user types things like field1, field2 from table2 where this = that. Prepend the word select with your programming code.
You can use Connection.setReadonly(true) method to enable read-only transactions. But I would use that only if user input is trusted and we need to prevent an accidental change of data.
Related
I have a Java application that does a POST with the sql query that is typed in the UI and is executed using JDBC. Since the query is user defined, I'm unable to find a way to prevent the SQL injection issue. For instance if this is the query the user issues :
select * from test_table where id=123
a POST is done with this string to the servlet and this is executed as a query. Is there anyway to get around this since there is no restriction on what user can send in?
Thanks
Technically if the user is allowed to write the entire query, it's not an injection attack risk, it's simply an attack risk
Run the query using a database user that has permission only to carry out the types of operations you deem acceptable on the tables you're willing to give access to.
For example, only permit SELECT on tableX, tableY and tableZ. No DML, no DDL and no selecting from any other table
If your dbms of choice doesn't allow fine grained control in this way then instead execute a regular batch script that creates another database containing only a few tables. Permit your users to query this new db. If it does get wrecked it will soon be dropped and replaced by a working one with updated data, by the script. This is also beneficial if placed on another server, it stops your live system from being innocently DOSed by a user executing a duff query that takes up all resource on the server
SQL injection would be passing select * from test_table where id=123 in place of a parameter.
Not sure exactly what information you are letting the application use, but I would suggest granting access only to a specific schema. That would provide a consistent security model.
As others have suggested, this is not SQL injection - I call this a "designed in" SQL injection. How you deal with it depends on the use case:
Design a separate interface that does not require the full SQL statement
As Caius suggested, if you can limit the privs in the DB account to only do what the user can do, that would limit the damage
If this is an administrative interface, you may want to limit the usage of this interface to "trusted" users. If you go that route, you want to be very careful to document that users with this privilege have full access to the database, and provide an auditing mechanism to make sure that that list of users is well known.
It is not realistically possible to limit the SQL statement through validation - its a powerful language, especially in the context of modern databases.
See also this related question
Is there anyway to get around this since there is no restriction on what user can send in?
I'm not sure what you mean by "get around." Is it not the design of this application to allow users to run any query?
If you want to prevent them from running unauthorized queries, then you'll have to implement some Java code in the servlet to check the query and decide whether it's one they're authorized to run.
Some people do this by whitelisting a specific set of known queries. Just match the user's input query against the whitelist.
If they can run a given query with a variety of different constant values, then replace constant values with a ? in both the whitelisted form and in a copy of the user's input SQL query.
If they can run a variety of different queries, like with optional clauses and stuff, so that it's impossible to make a whitelist of finite length, then you'll have to implement a SQL parser in your Java servlet and some kind of business rule engine to decide if their query is authorized before you run it against the real database.
At this point, it seems easier to change the application front-end so that users are not allowed to submit arbitrary SQL queries!
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.
I want to allow SELECT queries to my database, but do not want to allow updates (or drops!).
Is it sufficient to ensure the query starts with SELECT and does not contain a semicolon?
I am using jdbc to execute the query, currently against MySQL, but hope not to limit it to that.
Edit:
I appreciate the caution of using a user who cannot update, but want to know if that is necessary, rather than just superstitious.
A better way to go about this is to create a new account and allow the account certain commands.
You must not execute code submitted by users. Allowing users to submit code is a great way to open yourself up to a denial of service attack, at the very least. For example, an attacker could easily submit a query with a huge Cartesian product guaranteed to bring down your server.
You can safely allow users to specify values, but not code. Then combine the values they enter into your SQL queries by using prepared statements with parameters.
Allowing users to submit SQL queries is as dangerous as shellexec($_GET["cmd"]);
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.
I've got a string containing an SQL statement. I want to find out whether the query will modify data or database structure, or if it will only read data. Is there some way to do this?
More info: In our application we need to let the users enter SQL-queries, mainly as part of the applications report system. These SQL queries should be allowed to read whatever they like from the databse, but they shouldn't be allowed to modify anything. No updates, deletes insert, table drops, constraint removals etc.
As of now I only test whether the first word in the string is "select", but this is too constricting and too insecure.
You should grant only select privileges on your tables for the login used by the application to be sure.
Create a new user for that part of the application that only has select privileges. Bear in mind that you'll also need to create synonyms for all the tables/views that that "read-only" user will be able to view.
The "regular" part of your application will still be able to do other operations (insert, update, delete). Just the reporting will use the read-only user.
As Horacio suggests, it is also a good idea/practice to add "wrapper" views that only expose what you want to expose. Some sort of "public API". This can give you flexibility if you need to change the underlying tables and don't want to/can't change the reports to the new definitions of said tables. This might, however, be seen as a lot of "extra work".
I agree with others that the right thing to do is use a separate schema with limited access & privileges for those queries that should be read-only.
Another option, however, is to set the transaction read-only before executing the statement entered by the user (SET TRANSACTION READ ONLY).
Create VIEWS to expose the data to end users, this is worthy because of three things:
The end user doesn't know how really your database look like.
You may can provide a simpler way to extract some pieces of data.
You can create the view with a read-only constraint:
CREATE VIEW items (name, price, tax)
AS SELECT name, price, tax_rate
FROM item
WITH READ ONLY;
Something that has worked well for me in the past, but may not fit your situation:
Use stored procedures to implement an API for the application. All modifications are done via that API. The procedures exposed to the front end are all complete units of work, and those procedures are responsible for rights enforcement.
The users running the front end application are only allowed to call the API stored procedures and read data.
Since the exposed API does complete units of work that correspond to actions the user could take via the GUI, letting them run the procedures directly doesn't get them any additional ability, nor allow them to corrupt the database accidently.
SELECT * FROM table FOR UPDATE works even with only SELECT privilege, and can still cause a lot of damage. If you want to be safe, the read only transactions are better.