Reputation: 10687
I have a method that inserts records into the database using normal parameterized SQL query.
public static void Add(string name, string friendlyName)
{
using (var db = Database.Open(_connectionString))
{
var sql = "INSERT INTO Tags(Name, UrlFriendlyName) " +
"VALUES(@0,@1)";
db.Execute(sql, name, friendlyName);
}
}
I changed the method so that it uses a stored procedure instead
public static void Add(string name, string friendlyName)
{
using (var db = Database.Open(_connectionString))
{
// USE STORED PROCEDURE
var query = "Exec insertTags @name='" + name + "', @urlFriendlyName= '" + friendlyName + "'";
db.Execute(query);
}
}
The stored procedure looks like the following
CREATE PROCEDURE insertTags
@name nvarchar(25),
@urlFriendlyName nvarchar(25)
AS
BEGIN
BEGIN Transaction
BEGIN TRY
INSERT INTO dbo.Tags(Name, UrlFriendlyName)
VALUES(@name, @urlFriendlyName)
IF @@TRANCOUNT > 0
BEGIN COMMIT TRANSACTION;
END
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
BEGIN ROLLBACK TRANSACTION;
END
END CATCH
END
Both of these methods work just fine. My question is, does the method that utilize the stored procedure provide security against SQL injections like the first one does? Thanks.
EDIT
I changed the second method to use parameters instead of string concatenation and it works. Is this safe against SQL injections?
public static void Add(string name, string friendlyName)
{
using (var db = Database.Open(_connectionString))
{
// USE STORED PROCEDURE
var query = "Exec insertTags @0, @1";
db.Execute(query, name, friendlyName);
}
}
Upvotes: 0
Views: 1353
Reputation: 7944
Any use of string concatenation in your application even when using a stored procedure automatically makes the execution of that code vulnerable to SQL injection.
In ADO.NET, the correct method of executing a stored procedure is to use the DbCommand
classes with the CommandType
set to CommandType.StoredProcedure
and providing the stored procedure parameters in the Parameters
collection.
Link to MSDN: System.Data.Common.DbCommand
Upvotes: 0
Reputation: 3002
No, it doesn't. As soon as you construct a SQL statement by concatenating strings together, you are at risk of SQL injection.
For example:
"Exec insertTags @name='" + name
Someone could pass: "Anything'; DROP TABLE xxx;" for name, and potentially break your database. You can still use parameterized queries with stored procedures, so they can offer the same protection, just not in the way you're calling it in your example.
Upvotes: 0
Reputation: 1054
You need to use parameters instead of string concatenations. In this case you will be safe
Upvotes: 1