I am mid 'Pen Test' and trying to find the "most secure" way to use Entity Framework Core to Stored Procedures. You would think it would be obvious, but please read on.
Background
Using this document on using Raw SQL and having read Whats new in .NET Core 2.0 my initial code used string interpolation (showed as safe in the 'what's new' document).
However, the Pen Test successfully managed a sql injection attack against it.
Offending code example:
dbResults = _datacontext.Blogs.FromSql($"myStoredProcedure @parmeter1 = {parmeter1String}");
So, I changed the code to use params, but they also broke through this:
dbResults = _datacontext.Blogs.FromSql("myStoredProcedure @parmeter1 = {0}", parmeter1String);
and they broke this (though maybe I wasn't cleaning enough - at least I stopped exec):
dbResults = _datacontext.Blogs.FromSql("myStoredProcedure @parmeter1 = {0}", parmeter1String.ToCleanedSqlString());
So is the answer to use SqlParameter (not shown in any of the above docs/examples)?
dbResults = _datacontext.Blogs.FromSql("myStoredProcedure @parmeter1 = {0}", new SqlParameter("@parmeter1", parmeter1String));
or is there a better way?
Some definitive guidance would be appreciated please.
EDIT Following comment:
Important addition: The stored procedure does execute dynamic sql, but that procedure is not in my application and I don't have control over it. I have to call it.
$"? Both examples should most certainly not be vulnerable to injection, do you have an example input string that breaks the parameterization? Does the underlying SP use the given param in dynamic SQL in any way?@parmeter1to execute dynamic SQL. Can we see the SP in question?