prevent sql injection in proc in linq c# - c#

I have a search form with 3 textboxes (stud_name, stud_city, stud_state). When I enter this vaue ' drop table users in the name textbox, it will drop the table successfully. Here is my c# code for calling stored procedure. How to prevent this type of injection using linq in c#
using (iDataContext db = new iDataContext(connectionString))
{
var statusList = db.SP_Student_LOOKUP(name, city, state);
return statusList.ToList<SP_Student_LOOKUPResult>();
}
here is my sp
CREATE proc SP_Student_LOOKUP #name varchar(50),
#city varchar(50),
#state varchar(2)
as
declare #sql varchar(2048)
begin
set #sql = 'select * from student where ';
if (((#name is not null)) and (len(#name) > 0))
set #sql = #sql + ' studentname like ''%'+#name+'%'' and '
if (((#city is not null)) and (len(#city) > 0))
set #sql = #sql + ' studentcity like ''%'+#city+'%'' and '
if (((#state is not null)) and (len(#state) > 0))
set #sql = #sql + ' studentstate like ''%'+#state+'%'' and '
print #sql
exec( #sql )

Your stored proc is susceptible to sql injection because you're (needlessly) using dynamic sql to build up your query. Don't do this.
Your stored procedure should be
CREATE proc SP_Student_LOOKUP
#name varchar(50),
#city varchar(50),
#state varchar(2)
as
select * from student
where
(#name is null or len(#name) = 0 or studentname LIKE #name)
and (#city is null or len(#city) = 0 or studentcity like #city)
and (#state is null or len(#state) = 0 or studentstate like #state)
This has the same behaviour as your dynamic sql, with 1 caveat - to fully stop the sql injection vulnerability you need to wrap % and % around your inputs - by doing this inside the stored proc you will re-introoduce the same problem

If you're using Entity Framework, as I'm guessing, you shouldn't be using stored procedures to retrieve data, unless your query is really beyond the capabilities of LINQ (and it isn't). You should build your query in LINQ, like that:
using (iDataContext db = new iDataContext(connectionString))
{
var statusList = from s in db.Set<student>()
select s;
if (!String.IsNullOrEmpty(name))
{
statusList = statusList.Where(s => s.studentname.Contains(name));
}
if (!String.IsNullOrEmpty(city))
{
studentList = studentList.Where(s => s.studentcity.Contains(city));
}
if (!String.IsNullOrEmpty(state))
{
studentList = studentList.Where(s => s.studentstate.Contains(state));
}
return statusList.ToList();
}
and if you're really using the old DataContext object, please read a more recent EF tutorial. This has been superceeded by DbContext (where you will find the .Set<>() method I used).

I agree with #TsahiAsher and #Jamiec
but clearly you are adamant to stick to the dynamic sql,
Given the constraints, I'd suggest that you parameterize your dynamic sql and execute it with the parameters you got.
(note i've also changed the position of "And" statements because if all 3 parameters are empty, you'd get an incomplete sql statement)
db fiddle Here
-- If I recall correct, it has to be NVARCHAR
declare #sql nvarchar(2048)
set #sql = 'select * from student where 1=1 ';
if ((#name is not null) and (len(#name) > 0))
set #sql = #sql + 'AND studentname like ''%''+#name+''%'' '
if ((#city is not null) and (len(#city) > 0))
set #sql = #sql + 'AND studentcity like ''%''+#city+''%'' '
if ((#state is not null) and (len(#state) > 0))
set #sql = #sql + 'AND studentstate like ''%''+#state+''%'' '
print (#sql)
exec sp_executesql #sql, N'#name VARCHAR(50),#city VARCHAR(50),#state VARCHAR(2)', #name = #name, #city = #city, #state=#state

Sanitize the input strings by escaping single quotes within it:
using (iDataContext db = new iDataContext(connectionString))
{
var statusList = db.SP_Student_LOOKUP(name.Replace("'", #"\'"), city.Replace("'", #"\'"), state.Replace("'", #"\'")
return statusList.ToList<SP_Student_LOOKUPResult>();
}

Related

SqlCommand Parameters.AddWithValue return # instead of variable [duplicate]

I am trying to execute this query:
declare #tablename varchar(50)
set #tablename = 'test'
select * from #tablename
This produces the following error:
Msg 1087, Level 16, State 1, Line 5
Must declare the table variable "#tablename".
What's the right way to have the table name populated dynamically?
For static queries, like the one in your question, table names and column names need to be static.
For dynamic queries, you should generate the full SQL dynamically, and use sp_executesql to execute it.
Here is an example of a script used to compare data between the same tables of different databases:
Static query:
SELECT * FROM [DB_ONE].[dbo].[ACTY]
EXCEPT
SELECT * FROM [DB_TWO].[dbo].[ACTY]
Since I want to easily change the name of table and schema, I have created this dynamic query:
declare #schema sysname;
declare #table sysname;
declare #query nvarchar(max);
set #schema = 'dbo'
set #table = 'ACTY'
set #query = '
SELECT * FROM [DB_ONE].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table) + '
EXCEPT
SELECT * FROM [DB_TWO].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table);
EXEC sp_executesql #query
Since dynamic queries have many details that need to be considered and they are hard to maintain, I recommend that you read: The curse and blessings of dynamic SQL
Change your last statement to this:
EXEC('SELECT * FROM ' + #tablename)
This is how I do mine in a stored procedure. The first block will declare the variable, and set the table name based on the current year and month name, in this case TEST_2012OCTOBER. I then check if it exists in the database already, and remove if it does. Then the next block will use a SELECT INTO statement to create the table and populate it with records from another table with parameters.
--DECLARE TABLE NAME VARIABLE DYNAMICALLY
DECLARE #table_name varchar(max)
SET #table_name =
(SELECT 'TEST_'
+ DATENAME(YEAR,GETDATE())
+ UPPER(DATENAME(MONTH,GETDATE())) )
--DROP THE TABLE IF IT ALREADY EXISTS
IF EXISTS(SELECT name
FROM sysobjects
WHERE name = #table_name AND xtype = 'U')
BEGIN
EXEC('drop table ' + #table_name)
END
--CREATES TABLE FROM DYNAMIC VARIABLE AND INSERTS ROWS FROM ANOTHER TABLE
EXEC('SELECT * INTO ' + #table_name + ' FROM dbo.MASTER WHERE STATUS_CD = ''A''')
Use:
CREATE PROCEDURE [dbo].[GetByName]
#TableName NVARCHAR(100)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #sSQL nvarchar(500);
SELECT #sSQL = N'SELECT * FROM' + QUOTENAME(#TableName);
EXEC sp_executesql #sSQL
END
You can't use a table name for a variable. You'd have to do this instead:
DECLARE #sqlCommand varchar(1000)
SET #sqlCommand = 'SELECT * from yourtable'
EXEC (#sqlCommand)
You'll need to generate the SQL content dynamically:
declare #tablename varchar(50)
set #tablename = 'test'
declare #sql varchar(500)
set #sql = 'select * from ' + #tablename
exec (#sql)
Use sp_executesql to execute any SQL, e.g.
DECLARE #tbl sysname,
#sql nvarchar(4000),
#params nvarchar(4000),
#count int
DECLARE tblcur CURSOR STATIC LOCAL FOR
SELECT object_name(id) FROM syscolumns WHERE name = 'LastUpdated'
ORDER BY 1
OPEN tblcur
WHILE 1 = 1
BEGIN
FETCH tblcur INTO #tbl
IF ##fetch_status <> 0
BREAK
SELECT #sql =
N' SELECT #cnt = COUNT(*) FROM dbo.' + quotename(#tbl) +
N' WHERE LastUpdated BETWEEN #fromdate AND ' +
N' coalesce(#todate, ''99991231'')'
SELECT #params = N'#fromdate datetime, ' +
N'#todate datetime = NULL, ' +
N'#cnt int OUTPUT'
EXEC sp_executesql #sql, #params, '20060101', #cnt = #count OUTPUT
PRINT #tbl + ': ' + convert(varchar(10), #count) + ' modified rows.'
END
DEALLOCATE tblcur
You need to use the SQL Server dynamic SQL:
DECLARE #table NVARCHAR(128),
#sql NVARCHAR(MAX);
SET #table = N'tableName';
SET #sql = N'SELECT * FROM ' + #table;
Use EXEC to execute any SQL:
EXEC (#sql)
Use EXEC sp_executesql to execute any SQL:
EXEC sp_executesql #sql;
Use EXECUTE sp_executesql to execute any SQL:
EXECUTE sp_executesql #sql
Declare #tablename varchar(50)
set #tablename = 'Your table Name'
EXEC('select * from ' + #tablename)
Also, you can use this...
DECLARE #SeqID varchar(150);
DECLARE #TableName varchar(150);
SET #TableName = (Select TableName from Table);
SET #SeqID = 'SELECT NEXT VALUE FOR ' + #TableName + '_Data'
exec (#SeqID)
Declare #fs_e int, #C_Tables CURSOR, #Table varchar(50)
SET #C_Tables = CURSOR FOR
select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%'
OPEN #C_Tables
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
WHILE ( #fs_e <> -1)
BEGIN
exec('Select * from ' + #Table)
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
END

Unable to get Dynamic SQL to pass a dynamic table parameter

Not worried about SQL Injection or anything of the like, just trying to get this to work. Using SSMS and Visual Studio.
I have C# code that passes a variable, GlobalVariables.username, to an SQL parameter.
private void btnNext_Click(object sender, EventArgs e)
{
if (checkIntrotoPublicSpeaking.Checked || checkEffectiveOralCommunication.Checked || checkProfComm.Checked)
{
List<SqlParameter> sqlOralComm = new List<SqlParameter>();
sqlOralComm.Add(new SqlParameter("Username", GlobalVariables.username));
sqlOralComm.Add(new SqlParameter("IntrotoPublicSpeaking", cboxIntrotoPublicSpeaking.Text));
sqlOralComm.Add(new SqlParameter("EffectiveOralCommunication", cboxEffectiveOralCommunication.Text));
sqlOralComm.Add(new SqlParameter("ProfComm", cboxProfComm.Text));
DAL.ExecSP("CreateOralComm", sqlOralComm);
}
}
I've been reading into Dynamic SQL and saw that to pass the table name as a parameter, you have to construct it manually and execute it as "SET..." etc, etc. I've been trying slightly different modifications of the last 3 lines below. Each time, I'm greeted with an "invalid syntax near ..." exception pertaining to different parts of that line. In stack exchange it's broken into 3 lines but in SSMS it's one line, a little easier to read.
Status is nvarchar column and Course is an int column.
ALTER PROCEDURE [dbo].[CreateOralComm]
-- Add the parameters for the stored procedure here
#Username nvarchar(30),
#IntrotoPublicSpeaking nvarchar(3),
#EffectiveOralCommunication nvarchar(3),
#ProfComm nvarchar(3)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
DECLARE #sql as nvarchar(max)
SET #sql = 'UPDATE ' + #Username + ' SET Grade = ' +
#IntrotoPublicSpeaking + ' Status = "Completed" WHERE Course = 7600105';
EXEC sp_executesql #sql;
END
GO
I know that global variable works, I have another line of code that's just a MessageBox displaying the value and it's correct. Just can't get those last few lines of SQL to work. I'm trying out just this first part, #IntrotoPublicSpeaking, before I move onto the other 2.
Any help would be really appreciated.
Two things here:
DECLARE #sql as nvarchar(max)
SET #sql = 'UPDATE ' + #Username + ' SET Grade = ' +
#IntrotoPublicSpeaking + ' Status = "Completed" WHERE Course = 7600105';
EXEC sp_executesql #sql;
Missing comma before Status and I think you do need to use single quotes
DECLARE #sql as nvarchar(max)
SET #sql = 'UPDATE ' + #Username + ' SET Grade = ' +
#IntrotoPublicSpeaking + ', Status = ''Completed'' WHERE Course = 7600105';
EXEC sp_executesql #sql;

Best way to write Combination logic in SQL or MVC for multiple select options

I, want to write the best combination login either SQL store procedure or ASP.net for the following combination diagram.
Each field in the diagram has 4 combinations. So, total it will be 20 combinations. I, don't want to write 20 if else statement in SQL server or c#.
Here is the UI for the logic.
The user can either select Quotation no or combination of 20 etc. I, don't want to write 20 if else statement.
Is their any better way to write a statement in SQL or C# to make it better.
For example
the user can select from either Quotation no or agency name or start date or end date or combination of two or more field.
What is the best way to write the algorithm?
Here is the combination
1- Search By only Quotation No
2- Search By only Agency No
3- Search By only Start Date
4- Search By only End Date
5- Search By only contract No
6 - Quotation No + Agency No
7 - Quotation No + Start Date
8 - Quotation No + End Date
9 - Select by All fields
I stumbled upon a similar problem some time ago while trying to perform a search using many filters. The best solution I found was to use a dynamic SQL query, in which the statement is built based on the parameters.
The select clause of the sql statement is static but the from clause and the where clause is based on the parameters.
CREATE PROCEDURE dbo.SearchQuotation
(
#QuotationNo INT,
#AgencyName VARCHAR(50),
#StartDate DATETIME,
#EndDate DATETIME,
#Term INT
)
AS
BEGIN
DECLARE #SQL NVARCHAR(4000)
SELECT #SQL = N'SELECT * FROM Quotations WHERE 1 = 1'
DECLARE #ParametersDefinition NVARCHAR(4000)
SELECT #ParametersDefinition = N'#QuotationNoParameter INT,
#AgencyNameParameter VARCHAR(50),
#StartDateParameter DATETIME,
#EndDateParameter DATETIME,
#TermParameter INT'
IF #QuotationNo IS NOT NULL
SELECT #SQL = #SQL + N' AND QuotationNo = #QuotationNoParameter '
IF #AgencyName IS NOT NULL
SELECT #SQL = #SQL + N' AND AgencyName = #AgencyNameParameter '
IF #StartDate IS NOT NULL
SELECT #SQL = #SQL + N' AND StartDate = #StartDateParameter '
IF #EndDate IS NOT NULL
SELECT #SQL = #SQL + N' AND EndDate = #EndDateParameter '
IF #Term IS NOT NULL
SELECT #SQL = #SQL + N' AND Term = #TermParameter '
EXECUTE sp_executesql
#SQL,
#ParametersDefinition,
#QuotationNoParameter = #QuotationNo,
#AgencyNameParameter = #AgencyName,
#StartDateParameter = #StartDate,
#EndDateParameter = #EndDate,
#TermParameter = #Term
END
From the SQL side you can achieve by this way:
SELECT * FROM Qoutes AS q
WHERE (q.QoutationNo = #QoutationNo OR #QoutationNo IS NULL)
AND (q.AgencyName = #AgencyName OR #AgencyName IS NULL)
AND (q.StartDate = #StartDate OR #StartDate IS NULL)
AND (q.EndDate = #EndDate OR #EndDate IS NULL)
AND (q.Term = #Term OR #Term IS NULL)
Pass NULL value if it is not selected from the web page.

Adding conditions in where statement

I have this Linq query:
IQueryable<SPR> query = db.SPRs;
if (!string.IsNullOrEmpty(search.accountNumber))
{
query = query.Where(b => b.CustomerAccountNumber.Contains(search.accountNumber));
}
if (!string.IsNullOrEmpty(search.accountName))
{
query = query.Where(b => b.CustomerNumber.Contains(search.accountName));
}
if (!string.IsNullOrEmpty(search.submittedBy))
{
query = query.Where(b => b.SubmittedBy.Contains(search.submittedBy));
}
if (!string.IsNullOrEmpty(search.smName))
{
query = query.Where(b => b.SMUserName == search.smName);
}
var result = query.ToList();
I am just appending the where clause if conditions are true. The issue is that it is not just adding a And in the generated SQL where clause like I want it to.
Here is the generated SQL if I have the SubmittedBy and SMUserName filled with data.
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[CustomerNumber] AS [CustomerNumber],
[Extent1].[CustomerAccountNumber] AS [CustomerAccountNumber],
[Extent1].[SMUserName] AS [SMUserName],
[Extent1].[SubmittedBy] AS [SubmittedBy],
[Extent1].[Notes] AS [Notes]
FROM
[dbo].[SPRs] AS [Extent1]
WHERE
([Extent1].[SubmittedBy] LIKE #p__linq__0 ESCAPE N'~')
AND (([Extent1].[SMUserName] = #p__linq__1) OR (([Extent1].[SMUserName] IS NULL)
AND (#p__linq__1 IS NULL)))
Not sure how this last line OR (([Extent1].[SMUserName] IS NULL) AND (#p__linq__1 IS NULL))) is getting added which is messing the query up.
Can someone please tell me how I can have just AND in the eventual query when the if conditions are satisfied?
Since you are working with sql server a more performance efficient and sleek way would be to handle the optional parameters inside a stored procedure and make use of Dynamic sql with sp_executesql to benefit from Parameterised Execution Plans.
CREATE PROCEDURE getSPR
#SubmittedBy Varchar(100) = NULL --<--- Use appropriate datatypes
,#CustomerAccountNumber Varchar(100) = NULL
,#CustomerNumber Varchar(100) = NULL
,#SMUserName Varchar(100) = NULL
AS
BEGIN
SET NOCOUNT ON;
Declare #Sql Nvarchar(max);
SET #Sql = N'SELECT [Id]
,[CustomerNumber]
,[CustomerAccountNumber]
,[SMUserName]
,[SubmittedBy]
,[Notes]
FROM [dbo].[SPRs]
WHERE 1 = 1 '
+ CASE WHEN #SubmittedBy IS NOT NULL THEN
N' AND [SubmittedBy] LIKE ''%'' + #SubmittedBy + ''%''' ELSE N' ' END
+ CASE WHEN #CustomerAccountNumber IS NOT NULL THEN
N' AND [CustomerAccountNumber] LIKE ''%'' + #CustomerAccountNumber + ''%''' ELSE N' ' END
+ CASE WHEN #CustomerNumber IS NOT NULL THEN
N' AND [CustomerNumber] LIKE ''%'' + #CustomerNumber + ''%''' ELSE N' ' END
+ CASE WHEN #SMUserName IS NOT NULL THEN
N' AND [SMUserName] = #SMUserName ' ELSE N' ' END
Exec sp_executesql #sql
,N' #SubmittedBy Varchar(100),#CustomerAccountNumber Varchar(100)
,#CustomerNumber Varchar(100), #SMUserName Varchar(100)'
,#SubmittedBy
,#CustomerAccountNumber
,#CustomerNumber
,#SMUserName
END

how to set return type of a stored procedure according to a specific table

I had made a dynamic stored procedure like this
CREATE PROCEDURE [dbo].[MyProcedure]
#pSelect nvarchar(max)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQL nvarchar(max)
SET #SQL = 'select ' + #pSelect + ' from tabel1';
EXEC (#SQL)
END
And on updating my entitydatamodel the in context.cs the above stored procedure is in the form of
virtual int MyProcedure(string pSelect)
{
var pSelectParameter = pSelect != null ?
new ObjectParameter("pSelect", pSelect) :
new ObjectParameter("pSelect", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("MyProcedure", pSelectParameter);
}
on calling the stored procedure from c# code
var result = myDataModel.MyProcedure("Select * From table1").tolist();
the above code is showing error because MyProcedure is returning a integer return type
so how could i set the return type of the stored procedure according to tje select query I am passing to it
HOW DO I MODIFY MY STORED PROCEDURE SO THAT ITS RETURN TYPE IS OF ANY SPECIFIC TABLE TYPE
In this case you have to trick the code.
CREATE PROCEDURE [dbo].[MyProcedure]
#pSelect nvarchar(max)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQL nvarchar(max)
SET #SQL = 'select ' + #pSelect + ' from tabel1';
EXEC (#SQL)
--Remove the below line once you have added the stored procedure to the dbml file.
select * from table1
END
After creating the sp, drag and drop to the c# dbml file. then you can alter the sp by removing the line " select * from table1".
NOTE : if you dont have those columns in the table1, the direct values(any datatype) in the select statement like "select 1 as colmumn1, 'string' as colmumn2, cast('10/01/1900' as datetime) as colmumn3 from table1"
just add # sign in your parameter.
var pSelectParameter = pSelect != null ?
new ObjectParameter("#pSelect", pSelect) :
new ObjectParameter("#pSelect", typeof(string));
may be this should work and i believe your are passing only column name in this parameter.

Categories

Resources