Mori
Mori

Reputation: 2574

SQLInjection against CosmosDB in an Azure function

I have implemented an Azure function that is triggered by a HttpRequest. A parameter called name is passed as part of the HttpRequest. In Integration section, I have used the following query to retrieve data from CosmosDB (as an input):

SELECT * FROM c.my_collection pm 
WHERE
Contains(pm.first_name,{name}) 

As you see I am sending the 'name' without sanitizing it. Is there any SQLInjection concern here?

I searched and noticed that parameterization is available but that is not something I can do anything about here.

Upvotes: 5

Views: 4764

Answers (2)

jaybro
jaybro

Reputation: 1543

If you're using Microsoft.Azure.Cosmos instead of Microsoft.Azure.Documents:

public class MyContainerDbService : IMyContainerDbService
{
    private Container _container;

    public MyContainerDbService(CosmosClient dbClient)
    {
        this._container = dbClient.GetContainer("MyDatabaseId", "MyContainerId");
    }

    public async Task<IEnumerable<MyEntry>> GetMyEntriesAsync(string queryString, Dictionary<string, object> parameters)
    {
        if ((parameters?.Count ?? 0) < 1)
        {
            throw new ArgumentException("Parameters are required to prevent SQL injection.");
        }
        var queryDef = new QueryDefinition(queryString);
        foreach(var parm in parameters)
        {
            queryDef.WithParameter(parm.Key, parm.Value);
        }
        var query = this._container.GetItemQueryIterator<MyEntry>(queryDef);
        List<MyEntry> results = new List<MyEntry>();
        while (query.HasMoreResults)
        {
            var response = await query.ReadNextAsync();
            results.AddRange(response.ToList());
        }

        return results;
    }
}

Upvotes: 3

Matias Quaranta
Matias Quaranta

Reputation: 15603

When the binding occurs (the data from the HTTP Trigger gets sent to the Cosmos DB Input bind), it is passed through a SQLParameterCollection that will handle sanitization.

Please view this article:

Parameterized SQL provides robust handling and escaping of user input, preventing accidental exposure of data through “SQL injection”

This will cover any attempt to inject SQL through the name property.

Upvotes: 4

Related Questions