Will using LINQ to SQL help prevent SQL injection

C#asp.netLinqLinq to-Sql

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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;

Solution 3 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBill MartinView Question on Stackoverflow
Solution 1 - C#GalwegianView Answer on Stackoverflow
Solution 2 - C#Amy BView Answer on Stackoverflow
Solution 3 - C#Jan BannisterView Answer on Stackoverflow