MongoDB · Update
Catch an injection attempt
Two attacks on an update endpoint: an operator as a field name, and a match value built to match every document.
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:
var account = new ArxEntity("account");
account["name"] = "Trey Research";
account["account_number"] = "ACC-M821";
account["credit_limit"] = 5000m;
await service.CreateAsync(account);1 An operator as a field name
A posted field named "$set": ARX1017.
Already in scope: service (ArxMongoDbService)
var change = new ArxEntity("account");
change["account_number"] = "ACC-M821";
change["$set"] = "{ credit_limit: 1000000 }";
try
{
await service.UpdateAsync(change, new ArxUpdateOptions { Match = ArxMatch.Key("account_number") });
}
catch (ArxValidationException exception) when (exception.Code == ArxErrorCode.SuspectedInjection)
{
Console.WriteLine(exception.Message);
}Check it in the database
Run it in mongosh connected to the database, after the code has run.
db.account.find({ account_number: "ACC-M821" }, { credit_limit: 1 })Expect: 1 document, credit_limit NumberDecimal("5000").
2 A match built to find everything
An account number posted as JSON { "$ne": null }: compared as data, it matches nothing (ARX2002).
Already in scope: service (ArxMongoDbService)
var change = new ArxEntity("account");
change["account_number"] = new ArxJsonB { SerializedValue = "{ \"$ne\": null }" };
change["credit_limit"] = 1_000_000m;
try
{
await service.UpdateAsync(change, new ArxUpdateOptions { Match = ArxMatch.Columns("account_number") });
}
catch (ArxException exception) when (exception.Code == ArxErrorCode.RecordNotFound)
{
Console.WriteLine(exception.Message);
}Check it in the database
Run it in mongosh connected to the database, after the code has run.
db.account.countDocuments({ credit_limit: NumberDecimal("1000000") })Expect: 0.
Good to know
A field name with $ is ARX1017 before anything is sent. A match value that is a document with operator keys ({ "$ne": null }) is compared as data: ARX wraps it in $eq, so it finds no document instead of all of them.
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
- .NET SDK: .NET SDK 10.0.100 or later 10.0.x (target
net10.0). - Create the project:
Terminal dotnet new console -n ArxSample -f net10.0 cd ArxSample - Install the packages:
Terminal dotnet add package ARX.SDK.MongoDb --version 1.0.0-rc.1 - Database: a MongoDB 7.0, a replica set (tested with 7.0.45, one node) database with the sample schema.
- Configuration: set
ARX_SAMPLES_MONGODBto its connection string. Nothing is hard-coded. - 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 replaceProgram.csand add the other file below, with the file names shown. - Run it:
Terminal dotnet run - Expected output: below.
The files
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.Update.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);
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.Update.RealCases;
/// <summary>
/// Two attacks on an update endpoint: an operator as a field name, and a match value built to match every document.
/// </summary>
/// <remarks>
/// A field name with <c>$</c> is ARX1017 before anything is sent. A match value that is a document with operator keys
/// (<c>{ "$ne": null }</c>) is compared as data: ARX wraps it in <c>$eq</c>, so it finds no document instead of all of them.
/// </remarks>
public sealed class RealCase1_CatchAnInjectionAttempt : ISample
{
public string Name => "update-real-1-catch-an-injection-attempt";
public string Title => "Catch an injection attempt";
public async Task RunAsync(SampleContext dbContext)
{
var account = new ArxEntity("account");
account["name"] = "Trey Research";
account["account_number"] = "ACC-M821";
account["credit_limit"] = 5000m;
await dbContext.Service.CreateAsync(account);
await Scenario1_AnOperatorAsAFieldNameAsync(dbContext.Service);
await Scenario2_AMatchBuiltToFindEverythingAsync(dbContext.Service);
}
/// <summary>1. A posted field named "$set": ARX1017.</summary>
private static async Task Scenario1_AnOperatorAsAFieldNameAsync(ArxMongoDbService service)
{
Step("1. An operator as a field name");
var change = new ArxEntity("account");
change["account_number"] = "ACC-M821";
change["$set"] = "{ credit_limit: 1000000 }";
try
{
await service.UpdateAsync(change, new ArxUpdateOptions { Match = ArxMatch.Key("account_number") });
}
catch (ArxValidationException exception) when (exception.Code == ArxErrorCode.SuspectedInjection)
{
ShowError(exception);
}
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* db.account.find({ account_number: "ACC-M821" }, { credit_limit: 1 })
* -- Expect: 1 document, credit_limit NumberDecimal("5000").
* ===========================================================
*/
}
/// <summary>2. An account number posted as JSON <c>{ "$ne": null }</c>: compared as data, it matches nothing (ARX2002).</summary>
private static async Task Scenario2_AMatchBuiltToFindEverythingAsync(ArxMongoDbService service)
{
Step("2. A match built to find everything");
var change = new ArxEntity("account");
change["account_number"] = new ArxJsonB { SerializedValue = "{ \"$ne\": null }" };
change["credit_limit"] = 1_000_000m;
try
{
await service.UpdateAsync(change, new ArxUpdateOptions { Match = ArxMatch.Columns("account_number") });
}
catch (ArxException exception) when (exception.Code == ArxErrorCode.RecordNotFound)
{
ShowError(exception);
}
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* db.account.countDocuments({ credit_limit: NumberDecimal("1000000") })
* -- Expect: 0.
* ===========================================================
*/
}
}
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.
> 1. An operator as a field name
caught ArxValidationException: ARX1017 SuspectedInjection: Attribute name '$set' 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
caught ArxException: ARX2002 RecordNotFound: Update of 'account': no document matched the entity's columns (account_number).