Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protect API from SQL Injection

I am creating an API the method below gets staff by their name in the query parameter or all staff. However, does the [FromQuery(Name = "name")] protect from SQL injection, unsure if this is a default feature of .NET core 2.2?

[HttpGet]
public IActionResult GetStaff([FromQuery(Name = "name")] string firstName)
{
    if (firstName == null)
    {
       //get all staff
       var staff = _repo.GetAllStaff().ToList();
       return Ok(staff);
    }

    if (firstName != null)
    {
       //get staff by firstName
       var staffByName = _repo.GetStaffByName(firstName).ToList();
       return Ok(staffByName);
    }

    return BadRequest("No staff found");
}

Method in Repository

    public IEnumerable<ApiStaff> GetStaffByName(string name)
    {
        var staffName = _context.ApiStaff.Where(k => k.FirstName == name);
        return staffName;
    }
like image 915
theJ Avatar asked Mar 04 '23 17:03

theJ


1 Answers

It's unclear from your question if you are using an ORM such as entity framework, however judging from naming conventions _context and the Where linq query, I'd guess you are.

ASP.net Core does not have built in SQL injection prevention as such, in fact Asp.net core does not have request validation built into it anymore.

However using an ORM has some natural SQL injection prevention:

LINQ to Entities injection attacks:

Although query composition is possible in LINQ to Entities, it is performed through the object model API. Unlike Entity SQL queries, LINQ to Entities queries are not composed by using string manipulation or concatenation, and they are not susceptible to traditional SQL injection attacks.

This is not the case if you chose to execute SQL directly within the ORM, so it depends on how your are using it.

Security should be considered as "defence in depth", adding mitigation techniques at each layer or boundary of your application.

A simple example for your use case could be constraining first name to sensible values, for example no longer than X characters (30?), no numerics etc, however this is easier said than done for internationalization therefore even if a weakness is found in Entity Framework, then you are thwarting an attacker by only giving them a limited character set to attack you with.

I'd recommend reading OWASP's cheat sheet

like image 187
Alex KeySmith Avatar answered Mar 15 '23 07:03

Alex KeySmith