MongoDB · Create

Catch an injection attempt

A form whose fields become attributes, attacked in three ways: a field named like a MongoDB operator, a field named with SQL in it, and a value that looks like an operator.

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.

1 An operator as a field name

A posted field named "$where": ARX1017.

Already in scope: service (ArxMongoDbService)

C#
var contact = new ArxEntity("contact");
contact["email"] = "[email protected]";
contact["$where"] = "sleep(5000)";

try
{
    await service.CreateAsync(contact);
}
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.find({ email: "[email protected]" })

Expect: no documents.

2 SQL in a field name

A field name carrying SQL (an attack aimed at a SQL backend): ARX1017 too.

Already in scope: service (ArxMongoDbService)

C#
var contact = new ArxEntity("contact");
contact["email"] = "[email protected]";
contact["name'; DROP TABLE contact; --"] = "x";

try
{
    await service.CreateAsync(contact);
}
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.find({ email: "[email protected]" })

Expect: no documents.

3 An operator as a value

A value that looks like an operator is stored as text, never run.

Already in scope: service (ArxMongoDbService)

C#
var contact = new ArxEntity("contact");
contact["email"] = "[email protected]";
contact["first_name"] = "{ \"$ne\": null }";

await service.CreateAsync(contact);

Console.WriteLine("stored, as text");

Check it in the database

javascript

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

db.contact.find({ email: "[email protected]" }, { first_name: 1 })

Expect: 1 document, first_name the text "{ \"$ne\": null }".

Good to know

A name with $ or SQL syntax is ARX1017 SuspectedInjection, refused before anything is sent; alert on it. Values are never parsed: a value that looks like an operator is stored as the text it is.

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.Create.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 RealCase2_CatchAnInjectionAttempt().RunAsync(dbContext);
RealCase2_CatchAnInjectionAttempt.cs

The sample, as it is in the repository.

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

using static ArxSamples.MongoDb.SampleOutput;

namespace ArxSamples.MongoDb.Operations.Create.RealCases;

/// <summary>
/// A form whose fields become attributes, attacked in three ways: a field named like a MongoDB operator, a field named
/// with SQL in it, and a value that looks like an operator.
/// </summary>
/// <remarks>
/// A name with <c>$</c> or SQL syntax is <c>ARX1017 SuspectedInjection</c>, refused before anything is sent; alert on it.
/// Values are never parsed: a value that looks like an operator is stored as the text it is.
/// </remarks>
public sealed class RealCase2_CatchAnInjectionAttempt : ISample
{
    public string Name => "create-real-2-catch-an-injection-attempt";

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

    public async Task RunAsync(SampleContext dbContext)
    {
        await Scenario1_AnOperatorAsAFieldNameAsync(dbContext.Service);

        await Scenario2_SqlInAFieldNameAsync(dbContext.Service);

        await Scenario3_AnOperatorAsAValueAsync(dbContext.Service);
    }

    /// <summary>1. A posted field named "$where": ARX1017.</summary>
    private static async Task Scenario1_AnOperatorAsAFieldNameAsync(ArxMongoDbService service)
    {
        Step("1. An operator as a field name");

        var contact = new ArxEntity("contact");
        contact["email"] = "[email protected]";
        contact["$where"] = "sleep(5000)";

        try
        {
            await service.CreateAsync(contact);
        }
        catch (ArxValidationException exception) when (exception.Code == ArxErrorCode.SuspectedInjection)
        {
            ShowError(exception);
        }

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * db.contact.find({ email: "[email protected]" })
         * -- Expect: no documents.
         * ===========================================================
         */
    }

    /// <summary>2. A field name carrying SQL (an attack aimed at a SQL backend): ARX1017 too.</summary>
    private static async Task Scenario2_SqlInAFieldNameAsync(ArxMongoDbService service)
    {
        Step("2. SQL in a field name");

        var contact = new ArxEntity("contact");
        contact["email"] = "[email protected]";
        contact["name'; DROP TABLE contact; --"] = "x";

        try
        {
            await service.CreateAsync(contact);
        }
        catch (ArxValidationException exception) when (exception.Code == ArxErrorCode.SuspectedInjection)
        {
            ShowError(exception);
        }

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * db.contact.find({ email: "[email protected]" })
         * -- Expect: no documents.
         * ===========================================================
         */
    }

    /// <summary>3. A value that looks like an operator is stored as text, never run.</summary>
    private static async Task Scenario3_AnOperatorAsAValueAsync(ArxMongoDbService service)
    {
        Step("3. An operator as a value");

        var contact = new ArxEntity("contact");
        contact["email"] = "[email protected]";
        contact["first_name"] = "{ \"$ne\": null }";

        await service.CreateAsync(contact);

        Show("stored, as text");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * db.contact.find({ email: "[email protected]" }, { first_name: 1 })
         * -- Expect: 1 document, first_name the text "{ \"$ne\": null }".
         * ===========================================================
         */
    }
}

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 field name
      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. SQL in a field name
      caught ArxValidationException: ARX1017 SuspectedInjection: Attribute name 'name'; DROP TABLE contact; --' looks like an SQL injection attempt (contains '''). ARX refused it before sending anything to the database. Names must come from your code or a fixed list, never from user input.
  > 3. An operator as a value
      stored, as text