58

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?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Bill Martin
  • 4,825
  • 9
  • 52
  • 86
  • 2
    Note for readers: the same goes for Entity Framework. See http://stackoverflow.com/questions/3473841/entity-framework-linqtosql-and-sql-injection – John Saunders Jul 03 '13 at 20:33

3 Answers3

82

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
  • 41,475
  • 16
  • 112
  • 158
  • 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 Jan 23 '09 at 15:17
  • 8
    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 Aug 13 '10 at 04:25
  • 1
    @KristoferA- How can one guard in the case that some of these procedures are necessary, and not readily translated into LINQ/Entity Framework? My instinct is to make sure that user text field input is not directly dropped into SQL statements without some kind of validation. Are there other vectors of attack that should be considered? – Scuba Steve Aug 15 '18 at 02:39
16

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;

Amy B
  • 108,202
  • 21
  • 135
  • 185
4

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

Jan Bannister
  • 4,859
  • 8
  • 38
  • 45