Search code examples
.netazure-cognitive-searchazure-search-.net-sdk

SQL-like injection in filters


I'm building this method which allows to build SearchParameters object. One of methods allows to specify Filter field of this object. It looks like this (simplified version)

public SearchParameters CreateWithFilter(string fieldName, string operator, string value)
{
    var filterString = $"{fieldName} {operator} '{value}'";

    return new SearchParameters{ Filter = filterString };
}

so I can use it like this

var searchParameters = this.CreateWithFilter("manufacturer", "eq", "volvo");

Now, the issue is that this code is sql-injection-like vulnerable. If I'll call

var searchParameters = this.CreateWithFilter("manufacturer", "eq", "volvo' or someField eq 1 or manufacturer eq 'volvo");

I'll become a great Azure Search Hacker ;)

My question:

Are there any specific techniques within Azure Search similar to ones known from SQL world that would allow me to secure code against those types of injections?


Solution

  • Great point, if you're taking strings from external/untrusted sources, building a query string with those is never safe.

    In SQL the recommended approach is to use parameterized queries whenever possible (e.g. SELECT * FROM Table WHERE field > @param). Unfortunately Azure Search doesn't have parameters in queries like that.

    The alternative approach for Azure Search is to carefully escape special characters that enable injection. A simple starting point is to:

    1. For string fields, escape single quotes (repeat the quotes).
    2. For numbers, booleans and dates, fully parse the literal (e.g. with int.parse, float.parse, bool.parse, etc.) and re-convert it to a string before adding it to the filter. This not only helps with injection, but also allows you to take inputs in locales and formats other than what the OData assumes (e.g. "," vs "." as decimal separators, date formats, etc.).