ExportXMLWordPrintableJSON

    • Type: Bug
    • Resolution: Fixed
    • Priority: Minor - P4
    • 10.0.5, 9.1.5
    • Affects Version/s: 10.0.3, 9.1.3, 10.0.4, 9.1.4
    • Component/s: None
    • None
    • Dotnet Drivers
    • Not Needed
    • None
    • None
    • None
    • None
    • None
    • None

      HackerOne Report: https://hackerone.com/reports/4085459
      Report Date: 2026-10-04 19:33:24 UTC
      Reporter: phillnee
      Weakness: Code Injection

      Initial Report:

      Repository: github.com/mongodb/mongo-efcore-provider

      Summary

      When an ExecuteUpdate call contains a setter that references the entity being updated, the MongoDB EF Core provider builds the update as an aggregation pipeline with a single $set stage, and places the serialized value of each constant setter into that stage without wrapping it in $literal. In an aggregation $set stage a string value that begins with $ is evaluated as a field path, so a constant setter whose value is attacker-influenced (for example "$Email") is interpreted as a reference to another field rather than stored as text. The non-pipeline code path (no self-referencing setter) places the same value into a plain $set document, where it is stored literally. The result is that the literal-safety of a constant setter silently depends on whether some other setter in the same call self-references the entity, and in the pipeline case an attacker-controlled setter value becomes an arbitrary aggregation expression over the updated document: it can copy a field the write was never meant to read into a field the attacker controls, or set a field to an arbitrary expression. The provider's own method documentation states that constant setters contribute their serialized literal, so this is a divergence from the library's stated behavior, not an intended capability.

      Steps To Reproduce

      Reproduces with the published package and any local MongoDB instance.

      1. Create a .NET 10 console project with poc.csproj:
        <Project Sdk="Microsoft.NET.Sdk">
        <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net10.0</TargetFramework>
        <Nullable>disable</Nullable>
        <ImplicitUsings>enable</ImplicitUsings>
        </PropertyGroup>
        <ItemGroup>
        <PackageReference Include="MongoDB.EntityFrameworkCore" Version="10.0.4" />
        </ItemGroup>
        </Project>
        
      2. Program.cs (points DSN at any reachable mongod):
        Unable to find source-code formatter for language: csharp. Available languages are: actionscript, ada, applescript, bash, c, c#, c++, cpp, css, erlang, go, groovy, haskell, html, java, javascript, js, json, lua, none, nyan, objc, perl, php, python, r, rainbow, ruby, scala, sh, sql, swift, visualbasic, xml, yaml
        using Microsoft.EntityFrameworkCore;
        using MongoDB.EntityFrameworkCore.Extensions;
        using MongoDB.Driver;
        

      class Acct { public int Id

      Unknown macro: { get; set; }

      public string Name

      public string Email

      Unknown macro: { get; set; }

      public int Count

      }
      class Db : DbContext {
      public DbSet<Acct> Accts

      Unknown macro: { get; set; }

      protected override void OnConfiguring(DbContextOptionsBuilder o) =>
      o.UseMongoDB(new MongoClient(Environment.GetEnvironmentVariable("DSN")), "efcoretest");
      protected override void OnModelCreating(ModelBuilder b) => b.Entity<Acct>().ToCollection("accts");
      }
      class Program {
      static void Seed() {
      var col = new MongoClient(Environment.GetEnvironmentVariable("DSN")).GetDatabase("efcoretest")
      .GetCollection<MongoDB.Bson.BsonDocument>("accts");
      col.DeleteMany(MongoDB.Bson.BsonDocument.Parse("{}"));
      col.InsertOne(new MongoDB.Bson.BsonDocument {

      Unknown macro: {"_id",1}

      ,

      Unknown macro: {"Name","orig"}

      ,

      Unknown macro: {"Email","secret@x"}

      ,

      Unknown macro: {"Count",0}

      });
      }
      static string ReadName(Db db) => db.Accts.AsNoTracking().First(a => a.Id == 1).Name;
      static void Main() {
      using var db = new Db(); db.Database.EnsureCreated();
      string userInput = "$Email"; // attacker-influenced SetProperty value

          Seed();   // ATTACK: mixed update -> pipeline form (Count+1 self-references the entity)
          db.Accts.Where(a => a.Id == 1).ExecuteUpdate(s => s
              .SetProperty(e => e.Name, userInput)
              .SetProperty(e => e.Count, e => e.Count + 1));
          Console.WriteLine($"[ATTACK pipeline-form] Name = \"{ReadName(db)}\"  (\"$Email\" literal = safe; \"secret@x\" = Email COPIED = injection)");
      
          Seed();   // CONTROL: no self-referencing setter -> document form
          db.Accts.Where(a => a.Id == 1).ExecuteUpdate(s => s.SetProperty(e => e.Name, userInput));
          Console.WriteLine($"[CONTROL document-form] Name = \"{ReadName(db)}\"  (expect literal \"$Email\")");
      }
      

      }

      
      3. Run against a local mongod:
      

      DSN='mongodb://127.0.0.1:27017' dotnet run -c Release

      
      ## Supporting Material/References
      Observed run against the shipped `MongoDB.EntityFrameworkCore` 10.0.4 with EF Core 10 and MongoDB 7. The document is seeded `{_id:1, Name:"orig", Email:"secret@x", Count:0}` before each case:
      

      [ATTACK pipeline-form] Name = "secret@x" ("$Email" literal = safe; "secret@x" = Email COPIED = injection)
      [CONTROL document-form] Name = "$Email" (expect literal "$Email")

      In the attack case the setter value `"$Email"` was evaluated as a field path and the `Email` field value (`secret@x`) was copied into `Name`. In the control case, with no self-referencing setter, the identical value was stored literally as the string `"$Email"`. (A secondary observation during testing: a wrong-case `"$email"` setter returned an empty `Name` rather than the literal string, consistent with a non-existent field path resolving to a missing field; the primary attack/control transcript above is the load-bearing evidence.)
      
      Root cause, source at pin v10.0.4 (unchanged on the current default branch), in `src/MongoDB.EntityFrameworkCore/Query/Visitors/MongoShapedQueryCompilingExpressionVisitor.cs`:
      - The method documentation at lines 499 to 501 states: a `$set` document of serialized literal values, and "constant setters contribute their serialized literal (the two can mix freely)."
      - `BuildUpdate` (line 503). Line 511: `if (!setters.Any(s => s.IsSelfReferencing))` builds the document form, line 516 `setDoc[... ] = SerializeConstant(queryContext, setter)`, line 519 `new BsonDocument("$set", setDoc)`. Here the serialized value is stored literally.
      - Lines 522 to 542: the pipeline form, "required as soon as any setter references the document being updated." Line 536 `setStageDoc[...] = SerializeConstant(queryContext, setter)` places the same serialized value into a `$set` stage, lines 540 to 542 wrap it as `Builders<BsonDocument>.Update.Pipeline(...)`. There is no `$literal` wrapper on the constant value, so in the aggregation `$set` stage a `$`-prefixed string value is evaluated as a field path.
      - `SerializeConstant` (line 550) resolves the setter value (a captured closure value or a query parameter) to a `BsonValue`, so a user-supplied string reaches the stage verbatim.
      
      ## Impact
      
      ##Summary
      An application that forwards an attacker-influenced value as a `SetProperty` value in a bulk `ExecuteUpdate` call that also contains a self-referencing setter exposes an aggregation-expression injection. A realistic idiom that triggers the pipeline form is an ordinary bulk update that writes a user-editable field alongside a routine counter or version bump in the same call, for example `.SetProperty(x => x.DisplayName, userValue).SetProperty(x => x.Revision, x => x.Revision + 1)`: the self-referencing `Revision` setter forces the pipeline path, and the user-editable `DisplayName` value is then evaluated as an aggregation expression. The attacker can set the target field to a `$`-prefixed field reference and copy another field of the same document, including a field the update was never meant to read (for example a credential or secret field), into a field the attacker can subsequently read (demonstrated). It follows that the setter value is evaluated as an arbitrary aggregation expression over that document, so a field can also be set to an arbitrary expression (`$$ROOT` and similar); that broader integrity case is inferred from the demonstrated field-reference evaluation, not separately exercised (see Bounds). Because the same code is safe when no setter self-references the entity (the document form stores the value literally), an application behaves differently depending on an unrelated neighbouring setter, which the developer has no reason to expect from the documented literal-setter behavior.
      
      ## Bounds (what is and is not demonstrated)
      - Demonstrated, wire, against the shipped package: the field-copy disclosure (`"$Email"` copies `Email` into `Name`), the literal-vs-evaluated divergence between the pipeline and document forms (control), and the independent missing-field confirmation.
      - Delivery precondition, stated not asserted: the application forwards an attacker-influenced value as a `SetProperty` value in an `ExecuteUpdate` that also has a self-referencing setter (which triggers the pipeline form). A specific deployed application was not exercised.
      - Scope: the document(s) the `Where` matches and updates. Cross-document or cross-tenant impact was not demonstrated and is not claimed.
      - The arbitrary-aggregation-expression integrity impact beyond a same-document field copy (for example `$$ROOT`) was not separately exercised; only the field-reference copy was demonstrated.
      
      ## Remediation
      In the pipeline-form branch of `BuildUpdate`, wrap each constant setter value in `$literal` before placing it into the `$set` stage (as the document-form branch effectively does by storing it as a plain value), so a string value is never evaluated as a field path or operator. This restores the method's documented behavior (constant setters contribute a serialized literal) in both the document and the pipeline forms.
      
      Verified 2026-10-04 against the shipped `MongoDB.EntityFrameworkCore` 10.0.4 with EF Core 10 and a local MongoDB 7 server. No MongoDB-operated host was contacted.
      

      BugFiled by phillnee
      2026-10-04 19:33:24 UTC


      ReportPrioritisedNormal by intake-agent-45661
      2026-10-04 19:43:45 UTC


      ReportComplexityClassified by intake-agent-45661
      2026-10-04 19:43:45 UTC


      RecommendationCreated by intake-agent-45661
      2026-10-04 19:43:45 UTC


      TriageIntakeCompleted by hackerone-agent
      2026-10-04 19:43:45 UTC

      H1 Intake Process: (Initial assessment - Pending Validation from H1 Triage)
      Intake completed. Moving ahead for validation.
      Note For Program Team: The intake process involves an initial review of the report to identify and eliminate reports that are either out-of-scope, duplicates or have low/no impact. This report is yet to be validated by the HackerOne Triage Team.


      Comment by hackerone-agent
      2026-10-04 19:43:48 UTC

      Hello [@phillnee|/phillnee],
      Thank you for your submission!
      Your report has passed the preliminary review. Please note that this does not confirm validation, the status may change after further review.
      Next in the workflow is for our team to validate and reproduce the issue, evaluating its accuracy and security impact. You will be notified when the team has reviewed and made an assessment on your report.
      We'll keep you updated as the process moves forward. Have a great day!
      Thanks,
      hackerone-agent


      ReportTriageSummaryCreated by h1_analyst_ren
      2026-10-08 19:51:53 UTC


      GroupAssignedToBug by h1_analyst_ren
      2026-10-08 19:52:55 UTC

      Hey Team,
      When ExecuteUpdate contains at least one self-referencing setter (e.g., e => e.Count + 1), the MongoDB EF Core provider emits an aggregation pipeline $set stage. In that context, constant setter values pass through SerializeConstant without $literal wrapping, so a $-prefixed string (e.g., "$Email") is evaluated by MongoDB as a field path expression rather than stored as a literal.
      If someone exploited this in production, the concrete impact would be data disclosure within the same document. Consider a multi-tenant SaaS application using the MongoDB EF Core provider where users can edit their profile.
      Thnaks,
      [@h1_analyst_ren|/h1_analyst_ren]


      ReportSeverityUpdated by h1_analyst_ren
      2026-10-08 19:54:04 UTC

      • Application uses MongoDB EF Core provider ExecuteUpdate
      • At least one setter in the ExecuteUpdate call is self-referencing
      • At least one constant setter's value is attacker-influenced
      • Attacker can read the field they wrote to
      • Attacker knows or can guess BSON element names of sensitive fields

      BugPendingProgramReview by h1_analyst_ren
      2026-10-08 19:54:10 UTC

      Hi [@phillnee|/phillnee],
      I'm discussing this submission internally with the MongoDB team. You will be updated as soon as there is additional information to share. Thank you for your patience!
      [@h1_analyst_ren|/h1_analyst_ren]

            Assignee:
            Damien Guard
            Reporter:
            Boris Dogadov
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: