MongoDB · Delete

Catch an injection attempt

Two attacks on a "delete by" endpoint: a match field named like an operator, and a match value built to match every document. Neither deletes anything.

Set up for this page

The scenarios build on the sample application: SampleContext.cs (the dbContext every sample is given); SampleOutput.cs (Step and Show, which print); SampleContext.Application.cs (dbContext.Service, the application's ARX service); SampleCatalog.cs (the tables' ids, keys, lookups and display names); SampleContext.Direct.cs (dbContext.Direct); MongoDirectHelper.cs (the checks behind dbContext.Direct).

dbContext.Direct is the samples' own checking code on the plain driver, not part of ARX: leave it out of your application.

Before scenario 1 the sample runs this, so the service and the rows the scenarios use are there:

Set up
var contact = new ArxEntity("contact");
contact["email"] = "[email protected]";
contact["segment"] = "M92";
await service.CreateAsync(contact);

1 An operator as a match field

"Delete where $where": ARX1017 before anything is sent.

Already in scope: service (ArxMongoDbService)

C#
var match = new ArxEntity("contact");
match["$where"] = "true";

try
{
    await service.DeleteAsync(match, new ArxDeleteOptions { Match = ArxMatch.Columns("$where") });
}
catch (ArxValidationException exception) when (exception.Code == ArxErrorCode.SuspectedInjection)
{
    Console.WriteLine(exception.Message);
}

Check it in the database

javascript

Run it in mongosh connected to the database, after the code has run.

db.contact.countDocuments({ segment: "M92" })

Expect: 1.

2 A match built to find everything

A segment posted as { "$exists": true }: compared as data, it deletes nothing.

Already in scope: service (ArxMongoDbService)

C#
var match = new ArxEntity("contact");
match["segment"] = new ArxJsonB { SerializedValue = "{ \"$exists\": true }" };

int deleted = await service.DeleteAsync(match, new ArxDeleteOptions { Match = ArxMatch.Columns("segment") });

Console.WriteLine($"{deleted} documents deleted");

Check it in the database

javascript

Run it in mongosh connected to the database, after the code has run.

db.contact.countDocuments({ segment: "M92" })

Expect: 1: the victim is still there.

Good to know

A document with operator keys given as a match value would run as a query in MongoDB's shorthand equality; ARX wraps it in $eq, so it is compared as data and finds nothing.

See also

Run the complete sample

The code above comes from one program, built in a fresh project and run against the database. To run it yourself, here is every file and step.

The program, its files and how to run it

Run it locally

  1. .NET SDK: .NET SDK 10.0.100 or later 10.0.x (target net10.0).
  2. Create the project:
    Terminal
    dotnet new console -n ArxSample -f net10.0
    cd ArxSample
  3. Install the packages:
    Terminal
    dotnet add package ARX.SDK.MongoDb --version 1.0.0-rc.1
  4. Database: a MongoDB 7.0, a replica set (tested with 7.0.45, one node) database with the sample schema.
  5. Configuration: set ARX_SAMPLES_MONGODB to its connection string. Nothing is hard-coded.
  6. Source code: add the files of the sample application this sample uses (SampleContext.cs, SampleOutput.cs, SampleContext.Application.cs, SampleCatalog.cs, SampleContext.Direct.cs, MongoDirectHelper.cs), then replace Program.cs and add the other file below, with the file names shown.
  7. Run it:
    Terminal
    dotnet run
  8. Expected output: below.

The files

Program.cs

Runs the sample. Generated for this page; it reads the connection string from the environment and first remakes the sample database from sample-schema.json.

using ArxSamples.MongoDb;
using ArxSamples.MongoDb.Operations.Delete.RealCases;

// The connection string comes from the environment, never from the code (see "Configure the connection").
var connectionString = Environment.GetEnvironmentVariable("ARX_SAMPLES_MONGODB")
    ?? throw new InvalidOperationException("Set the ARX_SAMPLES_MONGODB environment variable to your MongoDB connection string.");

var dbContext = new SampleContext(connectionString);

// Every run starts from the sample data: this deletes and makes again what sample-schema.json lists
// (save the file in the project folder, see Get started).
await dbContext.Direct.ResetAsync();

await new RealCase1_CatchAnInjectionAttempt().RunAsync(dbContext);
RealCase1_CatchAnInjectionAttempt.cs

The sample, as it is in the repository.

using ARX.SDK;
using ARX.SDK.Models;
using ARX.SDK.MongoDb.Services;
using ARX.SDK.Services;

using static ArxSamples.MongoDb.SampleOutput;

namespace ArxSamples.MongoDb.Operations.Delete.RealCases;

/// <summary>
/// Two attacks on a "delete by" endpoint: a match field named like an operator, and a match value built to match every
/// document. Neither deletes anything.
/// </summary>
/// <remarks>
/// A document with operator keys given as a match value would run as a query in MongoDB's shorthand equality; ARX wraps it
/// in <c>$eq</c>, so it is compared as data and finds nothing.
/// </remarks>
public sealed class RealCase1_CatchAnInjectionAttempt : ISample
{
    public string Name => "delete-real-1-catch-an-injection-attempt";

    public string Title => "Catch an injection attempt";

    public async Task RunAsync(SampleContext dbContext)
    {
        var contact = new ArxEntity("contact");
        contact["email"] = "[email protected]";
        contact["segment"] = "M92";
        await dbContext.Service.CreateAsync(contact);

        await Scenario1_AnOperatorAsAMatchFieldAsync(dbContext.Service);

        await Scenario2_AMatchBuiltToFindEverythingAsync(dbContext.Service);
    }

    /// <summary>1. "Delete where $where": ARX1017 before anything is sent.</summary>
    private static async Task Scenario1_AnOperatorAsAMatchFieldAsync(ArxMongoDbService service)
    {
        Step("1. An operator as a match field");

        var match = new ArxEntity("contact");
        match["$where"] = "true";

        try
        {
            await service.DeleteAsync(match, new ArxDeleteOptions { Match = ArxMatch.Columns("$where") });
        }
        catch (ArxValidationException exception) when (exception.Code == ArxErrorCode.SuspectedInjection)
        {
            ShowError(exception);
        }

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * db.contact.countDocuments({ segment: "M92" })
         * -- Expect: 1.
         * ===========================================================
         */
    }

    /// <summary>2. A segment posted as <c>{ "$exists": true }</c>: compared as data, it deletes nothing.</summary>
    private static async Task Scenario2_AMatchBuiltToFindEverythingAsync(ArxMongoDbService service)
    {
        Step("2. A match built to find everything");

        var match = new ArxEntity("contact");
        match["segment"] = new ArxJsonB { SerializedValue = "{ \"$exists\": true }" };

        int deleted = await service.DeleteAsync(match, new ArxDeleteOptions { Match = ArxMatch.Columns("segment") });

        Show($"{deleted} documents deleted");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * db.contact.countDocuments({ segment: "M92" })
         * -- Expect: 1: the victim is still there.
         * ===========================================================
         */
    }
}

Expected output

What dotnet run printed when the sample was verified, on a freshly created sample schema. Ids differ when the tables already hold rows.

Output
  > 1. An operator as a match field
      caught ArxValidationException: ARX1017 SuspectedInjection: Attribute name '$where' looks like an SQL injection attempt (contains '$' (a MongoDB operator)). ARX refused it before sending anything to the database. Names must come from your code or a fixed list, never from user input.
  > 2. A match built to find everything
      0 documents deleted