SQL Injection when using native database logins/users - sql

When developing an application where users connect with their native database logins, I don't need to care about SQL injection right? The reason being the users can execute any SQL they want anyway. (There are places where admins execute CREATE LOGIN and CREATE USER statements and these have to be dynamically built.) I'm talking about a native Windows application on the LAN.

Well, SQL injection is a possibility to execute SQL, so with the SQL shell access, everything required for "SQL injection" is already authorized. However you still need to care if users run as non administrators, probably being restricted which tables they can access, and your system sends some additional SQL commands while logged in with higher rights (create user, etc). Use prepared statements for such a code.

If you mean that you are building a web application, and using users' database credentials to connect to the database, yes, you do need to worry about SQL injection.
Most databases restrict permissions based on objects - tables, views, stored procedures etc. So, a user logged in as "Bob" might have access to table "sales", but not table "payments".
The database does not restrict access to rows in tables (for instance). So, a user connected as "Bob" who can exploit a SQL injection bug in your code can delete every record in the "sales" table. You probably don't want that.
If user "Bob" also has direct SQL access, they could, of course, simply run that statement at a SQL command line - but usually, web applications are available where direct SQL access is not. Your web app may be put on the intranet to begin with, but you can't guarantee that won't be opened up in the future.
Given how easy it is to prevent SQL injection attacks when you're building the app, and what a pain it is to fix them later on, I see no real reason not to prevent them in the first place.

As a matter of fact, "SQL injection" is a common misconception.
Being unable to properly format their queries, folks invented an "sql injection" thing as an excuse.
While properly formatted query will serve 2 purposes at once:
it will always be syntactically correct, no matter what data sent in.
as a side effect it would be invulnerable to that notorious "SQL injection" thing.
I doubt you want your queries to fail because of some unexpected symbol. So, no matter of some "injection", you have to properly format it. But once formatted, there will be no injection anyway. So, you have to concern about format, not injections.
I also have a feeling that letting users to login with database credentials is not quite a good idea.

Related

SQL - is it bad practice to give Read-Only access to the entire company?

I work in my companies small IT department. I have been creating automation via VBA in Excel to pull data from SQL and put it into Excel, then dynamically format and summarize the data. The issue I am running into is the IT department does not want to give anyone outside the IT department SQL Read-Only Access. They view SQL as a privilege not a right...even if it is only Read-Only. They claim security reasons.
Just to be clear, we are NOT installing SQL on these peoples' computers nor do they have the technical understanding on how to write queries. Also, they can already view all the information on the front-end website.
I currently have to specify which database and which tables they can have access to and it takes about 1-2 weeks to give them access (they drag their feet doing the requests).
I am not trying to vent, I am actually wondering do they have a legit concern about security and is this actually a best practice on their part?
The worst thing that could happen is a user knows just enough to connect MS Access to the database, write some poor queries, and grind everything to a halt. You should always have non-IT users access data in a safe, structured way. Especially if this database is a transactional one, and not a reporting database.
Sure, they can access all the data per business process. So then, create a nice, safe query to read all the data and dump it to Excel - if that's what the users want.
Otherwise, IT-created queries - preferably in Stored Procedures - should be reading the data and presenting it to the users.
So it's not a security issue per se. It's more an issue of "we don't want non-IT users getting crafty and bringing down the database with poorly written queries."
I believe the connection properties to the SQL server is embedded in your VBA code, as long as the code is not visible to the user then there is no way they can query the SQL server directly.
Sounds like you need an SQL read only service account which you can use for Query connections. Create an Excel data connection that has the security details to connect to SQL, then your VBA hooks into that data connection.

How to prevent SQL injection attack when a sql query is passed in from the UI

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!

How to hide query statement while running in Firebird?

I have to execute some queries in Firebird, but I need to hide "query source" from viewing in mon$statements or any other log in database.
That's because the query has some business rules that I can't expose to other people.
Is there any way to do it? Or some "trick" that I can use?
There is no way to do this. However MON$STATEMENT only shows your own queries, unless you are SYSDBA, the owner of the database, or a user with the RDB$ADMIN role (then you can see all queries). Other then MON$STATEMENT, there is also the trace facility which allows people with sufficient access to see queries (either on the server or through the service api). People with insufficient access to the database can still see queries if they can see the network traffic between the application and the database server.
The only way is to not give any form of access to the database server to people who should not be able to see the queries. This can be done by hosting the application as a webapplication, or putting a webservice or other form of middleware between the database and the real application.

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.

Best practice on users/roles on SQL Server for a web application

I searched online a bit and couldn't find anything that really nailed the spot or covered the bases how to go about setting up users/roles on a database.
Basically, there would be a user that would be used to access the database from the application (web application in this case) that will need access to database for the regular database operations (select, insert, update, delete) and executing stored procedures (with exec to run stored procedures within other stored procedures/UDFs).
Then, we would also have a user that would be main admin (this is simple enough).
I currently have a development environment where we don't really manage the security too well in my opinion (application uses a user with db_owner role, though it is an intranet application). Even though it is an intranet application, we still have security in mind and would like to see what are some of the ways developers set up the users/roles for this type of environment.
EDIT: Web application and SQL Server reside on separate machines.
EDIT: Forgot to mention that an ORM is used that would need direct read/write access.
Question:
What are the "best practices" on setting up the user for application access? What roles would apply and what are some of the catches?
First, I tend to encapsulate permissions in database roles rather than attach them to single user principals. The big win here is roles are part of your database, so you can completely script security then tell the deployment types to "add a user and add him to this role" and they aren't fighting SQL permission boogeymen. Furthermore, this keeps things clean enough that you can avoid developing in db_owner mode and feel alot better about yourself--as well as practice like you play and generally avoid any issues.
Insofar as applying permissions for that role, I tend to cast the net wider these days, especially if one is using ORMs and handling security through the application. In T-SQL terms, it looks like this:
GRANT SELECT, UPDATE, INSERT, DELETE, EXECUTE on SCHEMA::DBO to [My DB Role]
This might seem a bit scary at first, but it really isn't -- that role can't do anything other than manipulate data. No access to extended procs or system procs or granting user access, etc. The other big advantage is that changing the schema--like adding a table or a procedure--requires no further security work so long as you remain within that schema.
Another thing to take into consideration for SQL 2005+ is to use database schemas to secure groups of objects. Now, the big trick here is that many ORMs and migration tools don't like them, but if you render the default schema [dbo] to the app, you can use alternative schemas for special secured stuff. Eg--create an ADMIN schema for special, brutal database cleanup procedures that should be manually run by admins. Or even a separate schema for a special, highly secured part of the application that needs more granular DB permissions.
Insofar as wiring in users where you have separate boxes, even without a domain you can use Windows authentication (in Sql Server terms integrated authentication). Just make a user with the same credentials (user/pass combo) on both boxes. Setup an app domain to run as that user on the web box and setup a Sql Server user backed by that principal on the sql box and profit. That said, using the database roles can pretty much divorce you from this decision as the deployment types should be able to handle creating sql users and modifying connection strings as required.
For a long time the SQL Server guidelines for application access to the database were to isolate access to data into stored procedures, group procedures into a schema and grant execute on the schema to the principal used by the application. Ownership chaining would guarantee data access to the procedure callers. The access can be reviewed by inspecting the stored procedures. This is a simple model, easy to understand, design, deploy and manage. Use of stored procedure can leverage code signing, the most granular and powerfull access control method, and the only one that is tamper evident (signature is lost if procedure is altered).
The problem is that every bit of technology comming out from the Visual Studio designers flies in the face of this recommendation. Developers are presented with models that are just hard to use exclusively with stored procedures. Developers love to design their class models first and generate the table structure from the logical model. The procedure based guidelines reuire the procedures to exists first, before the first line of the application is written, and this is actually problematic in development due to the iterative way of modern development. This is not unsolvable, as long as the team leadership is aware of the issue and addresses it (ie. have the procedures ready, even as mocks, when the dev cycle starts).
Create a user 'webuser' that the web application uses.
Only grant stored proc execute permissions to this user. Do not allow direct table read/write. If you need to read something from a table, write a proc. If you need to write data, write another proc.
This way everything is kept nice and simple. One app user, with only the relevant permissions. If security is compromised, then all the intruder can do is run the procs.