Convert string to FormattableString in Entity Framework
Asked Answered
W

2

11

I am trying to build a website vulnerable to SQL injections (for educational purposes) with an ASP.NET API. To do that, I would like to call FromSql with a previously prepared SQL query as such:

String query = "SELECT * FROM users WHERE email = '"+email
                  +"' AND password = '"+password+"'";
return RepositoryContext.Users.FromSql(query).FirstOrDefault();

But this code will not compile as FromSql is expecting a FormattableString, and not a String. I get the following error message:

Error CS1503 Argument 2: cannot convert from 'string' to 'System.FormattableString'

The following would compile, but then this code would not be vulnerable to SQL injections anymore as Entity Framework will perform a prepared SQL query and convert email and password to SQL query parameters :

return RepositoryContext.Users.FromSql(
   $"SELECT * FROM users WHERE email = {email} 
                           AND password = {password}").FirstOrDefault();

Is there a way to convert a String to a FormattableString?

Thank you for your help.

Whoosh answered 1/2, 2023 at 8:45 Comment(1)
Since you only want it for demonstration, I'd suggest to use a direct SQL connection. #21709805 You can directly manipulate the string and can put a malicious query there. I think EF does a good job in preventing SQL injection out of the boxFellmonger
J
20

using System.Runtime.CompilerServices;

...

var s = "...";
var fs = FormattableStringFactory.Create(s);
Jesicajeske answered 11/3, 2023 at 8:10 Comment(0)
D
3

What you see is Entity Framework doing a good job at preventing SQL injection by default.

You can teach SQL injection by using the FromSqlRaw method instead which takes a string that could be maliciously crafted.

See also Entity Framework Core SQL Queries → Passing parameters documentation:

Pay close attention to parameterization when using SQL queries

When introducing any user-provided values into a SQL query, care must be taken to avoid SQL injection attacks. SQL injection occurs when a program integrates a user-provided string value into a SQL query, and the user-provided value is crafted to terminate the string and perform another malicious SQL operation. To learn more about SQL injection, see this page.

The FromSql and FromSqlInterpolated methods are safe against SQL injection, and always integrate parameter data as a separate SQL parameter. However, the FromSqlRaw method can be vulnerable to SQL injection attacks, if improperly used. See below for more details.

Dimeter answered 1/2, 2023 at 9:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.