-3

I have a dynamic price policy application in C# that execute T-SQL select statement and fetch value from query. but as you know, user can execute dangerous query like drop, update, delete, insert and etc.

So, how can I check a T-SQL query and ensure that the query is only a select statement?

I don't want to limit this with permission, because my user has a privilege to update or insert in other part of my application.

Really is this a hard question and Hasn't anyone faced this challenge before?

3 Answers3

2

It is not a good security practice to allow any SQL statement to be fed in via inputs as raw SQL from the front end.

You could provide a UI where they can create parameters so that in the back end, these could be fed to parameterised queries. Then you could create a condition builder that essentially allows them to build their query but through UI instead of SQL.

So for example, if one of the queries they might write is SELECT * FROM Products WHERE Id = 1, you could instead provide a UI on which they can create a parameter called Id and give it a value of 1. Then they could have a dropdown to pick from a list of available tables, followed by other UI which allows them to construct their WHERE clause.

It's pretty heavy compared to just passing through the raw SQL, but it would allow you to control what you put in your query in the back end, which would of course be using parameters.

Parameterised queries are standard security practice for any inbound requests to DBs using SQL from the front end. Here's a basic intro to them using SqlCommand in C# and VB.NET

Nick Proud
  • 355
  • 1
  • 3
  • 14
0

Can't you just check the sql query string to see if it conatains those dangerous commands (drop, update, delete, insert)?

Also, this approach sounds dangerous anyway. As has already been mentioned you should be using parametized queries or they can cause damage, even with just a select.

iKnowNothing
  • 920
  • 1
  • 10
  • 17
0

You could use execute to execute the query with an execute as clause that specifies a user account with readonly access to appropriate tables and views. If there are specific columns in a table that should not be accessible then deny access to the table and grant access to a view that provides only the allowable columns.

You are still depending on security settings to protect against hanky panky. A thorough examination of the query using a T SQL parser would be better, but a rigorous analysis of every possible coding trick in a query isn't trivial. You could check entities (tables, columns, functions, ...) against an allow list, restrict expressions, ... .

HABO
  • 15,314
  • 5
  • 39
  • 57