How to prevent sql injection in dynamic SQL - sql

This is a old topic, but I am still having problem with it, so want to get some new idea here.
I used to check | in parameter, but it seems now ; is a separator to check too.
It suggests to use sp_executesql with parameters to prevent SQL injection, but I am not sure if I can do that.
What I try to do is collect filters from client side and run dynamic SQL to get result, for example, from client side, I could send a request with the below filters to SQL:
id=1234 name=david date=2014/01/01
I will create dynamic sql like
select *
from members
where id = 1234
and name like 'david%'
and crea_date = '2014/01/01'
The search column could be any random list of field of a table, so I cannot run sp_executesql like
sp_executesql N'select * from members where id=#id and name like #name and crea_date=#crea_date',N'#id int,#name nvachar(100),#crea_date datetime', ....
Any suggestions?

You can use parameters, no problem. Make the SQL dynamic, but make the generated SQL refer to parameters. Unconditionally pass in a #name parameter if you need to, just make the name like #name part of your where clause dynamic. If you don't search on name, simply ignore the parameter in your SQL.
If you do not want to hard code the parameter names, name them param1, param2 etc.
Depending on how you are executing it, you may even be able to get rid of the dummy parameters when you aren't using them.

Default answer: Use prepared statements.

Related

Removing possibility of injecting dangerous SQL queries

There is a function having a parameter. The function internally invokes a stored procedure with the parameter. And clients can pass a string to the function through HTTP requests.
I'm trying to add a method to remove any possibilities of injecting dangerous SQL statement through the parameter. The method name is IsSQLParameterSafe() and it returns boolean values depending on the parameter. If the value is safe to execute, then the method will return true, otherwise it returns false.
In my case, the parameter doesn't have to have blanks so if there are any whitespaces, then it'll return false. Also, I'm going to limit the length of the input up to 64 because its the maximum length of the parameter.
Do you think that my idea will work? If not, can you suggest ideas?
Thanks
You can use a parameterized query even with stored procedures. This is the best way to deal with SQL injection risks. It's difficult to be more specific without knowing what language you're using, but in Java, for example, you'd use something similar to this:
String callStmt = "CALL PROC(?)";
PreparedStatement prepStmt = con.prepareStatement(callStmt);
prepStmt.setString(1, parameter);
ResultSet rs = prepStmt.executeQuery();
You might also be interested in the OWASP SQL Injection Prevention Cheat Sheet, which goes into more detail.
You won't need to worry, unless you are stitching the SQL together manually and then executing it with the EXEC command.
For example, this is a simple Stored Procedure:
CREATE PROCEDURE DeleteRecord
(
#name VARCHAR(64)
)
AS
BEGIN
DELETE FROM Records WHERE [Name] = #name
END
If you attempt to pass this string into the procedure...
name OR 1=1
...then the Procedure will Delete 0 records, because no one has this exact name.
Why doesn't it delete everything?
The Stored Procedure doesn't stitch the SQL together into a big string (you often see this sort of thing in tutorials for beginners in PHP). Instead, it passes the original SQL statement, then each parameter as a distinct argument. I don't know the technical details of how this works, but I know from experience that adding slashes and quotes and garbled characters will not break this query.
But...
If you are writing Dynamic SQL, and if you parameter represents a Table or Column name, then you need to be more careful. I would use a white list for that.
http://www.sommarskog.se/dynamic_sql.html

Dynamic sql - Is this a good approach?

I have a table that has a column named category. The column category has values like "6,7,9,22,44". I would like to know if this approach is an efficient approach for SQL Server 2005 or 2008. I basically pass in the "6,7,9,22,44" value to the stored procedure. I am open links/suggestions for a better approach.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Note: I should clarify that I am maintaining an app written by someone else and the category column already has comma separated values. I would have placed the data in a separate table but I won't be able to do that in the short term. With regards to SQL Injection - The column is populated by values checked from a checkbox list. Users cannot type in or enter any data that would affect that specific stored proc. Is SQL injection still possible with that scenario? Please explain how. Thanks.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CREATE PROCEDURE [dbo].[GetCategories]
-- Add the parameter that contain the string that is passed in
#catstring varchar(300)
AS
DECLARE #SQLQuery nvarchar(500);
BEGIN
/* Build Transact-SQL String with parameter value */
SET #SQLQuery = 'select id,category from categoryTable where id in ('+ #catstring +')'
/* Execute Transact-SQL String */
EXECUTE(#SQLQuery)
END
GO
This is a very bad idea because it leaves your system open to SQL injection. A malicious user might be able to pass in a string like "') DROP TABLE categoryTable --" (notice the single quote at the beginning of the string), or something worse.
There are plenty of ways to protect yourself against SQL injection, and there are plenty of resources out there. I would suggest you research it on your own since it's too large an area to cover in a single question.
But for your particular problem, I would suggest this website to learn how to create a Table Valued Parameter to pass in a list of integer IDs: http://www.sommarskog.se/arrays-in-sql-2008.html
It's only valid for SQL Server 2008, you should follow the links in that article for solutions for SQL Server 2005 if you need to.
As Jack said, this creates a possibility of SQL injection. Sommarskog has an excellent look at different ways of handling this at: The Curse and Blessing of Dynamic SQL.

nvarchar as query argument

I am trying to create a stored procedure that has a table and as an argument and executes some queries on that table.
So...
CREATE PROCEDURE blabla
#TableName nvarchar(50)
AS
DROP TABLE #TableName -- just an example, real queries are much longer
GO
This query gives me incorrect syntax error.
I know I can always use sp_executesql procedure, but I want a neater way where I don't need to worry about building an endless sql string.
Thanks
Here is a good article on why not to use Dynamic SQL in most cases as well as how to use it properly when it is the best solution:
http://www.sommarskog.se/dynamic_sql.html
Basically, doing what you are looking to do has a number of issues, including not allowing the system to properly check for permission issues before executing, not being able to optimize the stored procedure, and (most importantly) opening yourself up to SQL injection. You can mitigate this last issue somewhat but it involves a much more complex statement. Here is a quote from the above article:
Passing table and column names as parameters to a procedure with dynamic SQL is rarely a good idea for application code. (It can make perfectly sense for admin tasks). As I've said, you cannot pass a table or a column name as a parameter to sp_executesql, but you must interpolate it into the SQL string. Still you should protect it against SQL injection, as a matter of routine. It could be that bad it comes from user input.
To this end, you should use the built-in function quotename() (added in SQL 7). quotename() takes two parameters: the first is a string, and the second is a pair of delimiters to wrap the string in. The default for the second parameter is []. Thus, quotename('Orders') returns [Orders]. quotename() takes care of nested delimiters, so if you have a really crazy table name like Left]Bracket, quotename() will return [Left]]Bracket].
Note that when you work with names with several components, each component should be quoted separately. quotename('dbo.Orders') returns [dbo.Orders], but that is a table in an unknown schema of which the first four characters are d, b, o and a dot. As long as you only work with the dbo schema, best practice is to add dbo in the dynamic SQL and only pass the table name. If you work with different schemas, pass the schema as a separate parameter. (Although you could use the built-in function parsename() to split up a #tblname parameter in parts.)
I know you want a "neater" way of creating a dynamic statement but the reality is that no only is that not possible for how you want to do this, really you need to make the statement even more complex in order to ensure that the stored procedure is safe. I would try very hard to look at a different way to solve this issue (the article had a few suggestions). If you can avoid making this statement into dynamic SQL, you really should.
There are very few places that parameters can be used in T-SQL. Usually, it's exactly the places where you would find a quoted string - not just any arbitrary place within the query (where the query is necessarily in a string form anyway)
E.g., you could use a parameter or variable to replace 'hello' below:
SELECT * from Table2 where ColA = 'hello'
But you couldn't use it where Table2 appears. I don't know why people seem to expect such things to be possible in T-SQL, when it's generally not possible in most other programming languages either, outside of exec/eval style functions.
If you have multiple tables that share the same structure (names and types of columns), it generally suggests that what you should actually have is a single table, with possibly additional column(s) that distinguish between rows that would originally be in different tables. E.g. if you currently have:
CREATE TABLE MaleEmployees (
EmployeeNo int not null,
Name varchar(50) not null,
)
and
CREATE TABLE FemaleEmployees (
EmployeeNo int not null,
Name varchar(50) not null
)
You should instead have:
CREATE TABLE Employees (
EmployeeNo int not null,
Name varchar(50) not null,
Gender char(1) not null,
constraint CK_Gender_Valid CHECK (Gender in ('M','F'))
)
You can then query this Employees table, regardless of gender, rather than trying to parametrize the table name within your query. Of course, the above is an exaggerated example.
set #l = 'DROP TABLE ' + #TableName
exec #l
But if that's what you mean by 'endless string', not sure what you want
The correct syntax(notice the begin):
CREATE PROCEDURE blabla
#TableName nvarchar(50)
AS
begin
DROP TABLE #TableName -- just an example, real queries are much longer
END
GO

check select statement is valid or not in c#.net

i want to check select statement(string) is valid or not in c#.net, if select statement is right then retrieve data and fill dropdown list box else drop down should be empty
How often would the select statement be invalid? Seems like a simple try/catch block around the execution of the SQL might be sufficient.
As an aside, I hope you aren't making an app that would allow someone to type in arbitrary SQL into a box which you would then execute...
One approach which covers most scenarios is to execute the SQL with SET FMTONLY ON
e.g.
SET FMTONLY ON;
SELECT SomeField FROM ExampleQuery
From BOL, SET FMTONLY :
Returns only metadata to the client.
Can be used to test the format of the
response without actually running the
query.query.
That will error if the query is invalid. You can also check the result to determine what the schema of the resultset that is returned would be (i.e. no schema = not a SELECT statement).
Update:
In general terms when dealing with SQL that you want to protect against SQL injection there are other things you should be thinking about:
Avoid dynamic sql (concatenating user-entered values into an SQL string to be executed). Use parameterised SQL instead.
Encapsulate the query as a nested query. e.g.
SELECT * FROM (SELECT Something FROM ADynamicQueryThatsBeenGenerated) x
So if the query contains multiple commands, this would result in an error. i.e. this would result in an invalid query when encapsulated as a nested query:
SELECT SomethingFrom FROM MyTable;TRUNCATE TABLE MyTable

How do I supply the FROM clause of a SELECT statement from a UDF parameter

In the application I'm working on porting to the web, we currently dynamically access different tables at runtime from run to run, based on a "template" string that is specified. I would like to move the burden of doing that back to the database now that we are moving to SQL server, so I don't have to mess with a dynamic GridView. I thought of writing a Table-valued UDF with a parameter for the table name and one for the query WHERE clause.
I entered the following for my UDF but obviously it doesn't work. Is there any way to take a varchar or string of some kind and get a table reference that can work in the FROM clause?
CREATE FUNCTION TemplateSelector
(
#template varchar(40),
#code varchar(80)
)
RETURNS TABLE
AS
RETURN
(
SELECT * FROM #template WHERE ProductionCode = #code
)
Or some other way of getting a result set similar in concept to this. Basically all records in the table indicated by the varchar #template with the matching ProductionCode of the #code.
I get the error "Must declare the table variable "#template"", so SQL server probably things I'm trying to select from a table variable.
On Edit: Yeah I don't need to do it in a function, I can run Stored Procs, I've just not written any of them before.
CREATE PROCEDURE TemplateSelector
(
#template varchar(40),
#code varchar(80)
)
AS
EXEC('SELECT * FROM ' + #template + ' WHERE ProductionCode = ' + #code)
This works, though it's not a UDF.
The only way to do this is with the exec command.
Also, you have to move it out to a stored proc instead of a function. Apparently functions can't execute dynamic sql.
The only way that this would be possible is with dynamic SQL, however, dynamic SQL is not supported by SqlServer within a function.
I'm sorry to say that I'm quite sure that it is NOT possible to do this within a function.
If you were working with stored procedures it would be possible.
Also, it should be noted that, be replacing the table name in the query, you've destroyed SQL Server's ability to cache the execution plan for the query. This pretty much reduces the advantage of using a UDF or SP to nil. You might as well just call the SQL query directly.
I have a finite number of tables that I want to be able to address, so I could writing something using IF, that tests #template for matches with a number of values and for each match runs
SELECT * FROM TEMPLATENAME WHERE ProductionCode = #code
It sounds like that is a better option
If you have numerous tables with identical structure, it usually means you haven't designed your database in a normal form. You should unify these into one table. You may need to give this table one more attribute column to distinguish the data sets.