views:

977

answers:

4

I'm setting up a public site and the first thing on my mind is SQL injection. I have some text fields I'm saving and am using linq to update/write to the database. Am I safe using linq?

This example is creating the user account.

            Data.MemberRegistrationDataContext context = new MemberRegistrationDataContext();
            Data.tbl_Member_UserProfile profile = new tbl_Member_UserProfile();
            profile.SSN = Convert.ToDecimal(Session["tempMemberSSN_Registration"]);
            profile.UserName = userName;
            profile.Password = password;
            profile.EmailAddress = email;
            profile.QuestionID = qID;
            profile.QuestionResponse = securityAnswer;
            profile.LastModDt = DateTime.Now;
            profile.LastModBy = "web";
            context.tbl_Member_UserProfiles.InsertOnSubmit(profile);
            context.SubmitChanges();

This example is changing the password

   MemberRegistrationDataContext dc = new MemberRegistrationDataContext();
            var mProfileRecord = dc.tbl_Member_UserProfiles.Single(c => c.SSN == sSSN);
            mProfileRecord.Password = sNewPassword;
            dc.SubmitChanges();

Are these safe? Does LINQ parameterize the SQL it generates automatically?

+13  A: 

Yes, LINQ will help stop SQL injection.

LINQ to SQL passes all data to the database via SQL parameters. So, although the SQL query is composed dynamically, the values are substitued server side through parameters safeguarding against the most common cause of SQL injection attacks.

Also, see Eliminate SQL Injection Attacks Painlessly with LINQ for some info.

Galwegian
It should be noted that when they say "passes all data" they mean "all data" -- even hard-coded values: "db.Employees.Where(e=>e.Active == 1)" will pass the "1" as a parameter.
James Curran
With one minor exception: if you have a stored procedure or function that is SQL-injection vulnerable (due to dynamic SQL composition) then any calls to that SP/func are of course vulnerable.
KristoferA - Huagati.com
+5  A: 

You're good to go. Linq does parameterize the data it sends to the database.

Use the Log property to check out what's happening: dc.Log = Console.Out;

David B
+2  A: 

It should because the SQL emitted uses named parameters which cannot be exploited to execute arbitrary SQL.

Jan Bannister
A: 

Yes its very much possible to prevent SQL Injection by using LINQ, Please refer the article http://www.protalk.in/dotnet/eliminate-sql-injection-attacks-with-linq-part-1/ to kknow how to eliminate SQL Injection attack with LINQ

Thanks Nitin

Nitin