Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a SQL Server Stored Procedure Safe from SQL Injections

This can be easily injected here because the @ID param can be practically anything in this SQL statement by inputting it, however, how do you prevent this exploit?

I prefer to specifically prevent this exploit at this level rather than application level, any suggestions?

CREATE PROCEDURE [dbo].[GetDataByID]
@ID bigint,
@Table varchar(150)
AS
BEGIN

Declare @SQL Varchar(1000)

SELECT @SQL = 'SELECT * FROM ' + @Table + ' WHERE ID = ' + CONVERT(varchar,@ID)

SET NOCOUNT ON;

EXEC(@sql)  
END
like image 211
Control Freak Avatar asked Dec 19 '11 19:12

Control Freak


People also ask

How do stored procedures protect against SQL injection?

Using stored procedure prevents SQL injection from happening since input parameters are always treated as an actual text value, rather than as a command (see Image 1.3).

Which methods can be used to avoid SQL injection?

The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly. The developer must sanitize all input, not only web form inputs such as login forms.

What is the best defense against SQL injection?

You should always use parameterized statements where available, they are your number one protection against SQL injection. You can see more examples of parameterized statements in various languages in the code samples below.

How do I create a stored procedure secured?

Securing data using a Stored Procedure You can do that by granting that user the permission to call the stored procedure we created above. Let us create a role or user called John with only login privileges. Then we will grant him permission to call the stored procedure that inserts values into the Employees table.


2 Answers

Check this page, it has a wonderful guide to dynamic sql, and the options to execute them safely

In your case it should be like this:

SELECT @SQL =  N'SELECT * FROM ' + quotename(@Table) + N' WHERE ID = @xid' 
EXEC sp_executesql @SQL, N'@xid bigint', @ID
like image 176
Sebastian Piu Avatar answered Oct 06 '22 09:10

Sebastian Piu


1) create a new table that will have an identity PK and contain the string table names
2) insert all/only the valid tables you will allow in your procedure
3) use this int identity PK as the input parameter value (TableID) for the stored procedure
4) in the procedure, just look up the string value (table name) from the given identity PK and you are safe to concatenate that looked up string in your query. 5) your WHERE clause is fine since you pass in an int

like image 20
KM. Avatar answered Oct 06 '22 09:10

KM.