Summary
From 6.3.5-6.13.12, Mongoose 6 decides whether a value is a BSON type by checking only its bsontype property. A plain object such as {"bsontype":"ObjectID","id":""} therefore passes the ObjectId cast. bson 4.x then writes no id bytes but still advances 12 bytes in its serialization buffer, so the value sent to MongoDB is whatever the previous command left at that offset. Request bodies, cookies and Express 4 query strings can all produce such an object. sanitizeFilter doesn’t catch it because it has no $ keys.
Details
lib/helpers/isBsonType.js returned true for any object whose bsontype matched. This led to three problems:
1. Queries by id replay another request’s id. findById(forged) sends the id from the last command with the same layout, such as another request’s findById on the same collection. Likewise, findByIdAndDelete(forged) and findByIdAndUpdate(forged) act on the document another request just modified with findOneAndUpdate. This works with sanitizeFilter on. 2. Stored ObjectIds leak command bytes. create(), $set and other writes store 12 bytes of earlier commands, such as filter values and updated fields. Anyone who can read the document can read those bytes. This happens in the default configuration. 3. Forged regexes on String paths. {"bsontype":"BSONRegExp","pattern":"^a","options":""} passes the String query cast and is sent as a regular expression, bypassing sanitizeFilter.
mongoose.isObjectIdOrHexString() also returns true for the forged object.
The fix makes isBsonType() ignore bsontype when it is an own property. bson defines bsontype on the prototype (except for the Timestamp class, which Mongoose does not check), so real bson values still pass.
Proof of concept
javascript mongoose.set('sanitizeFilter', true); const User = mongoose.model('User', new mongoose.Schema({ email: String, password: String })); const Comment = mongoose.model('Comment', new mongoose.Schema({ post: mongoose.ObjectId })); const alice = await User.create({ email: 'alice@example.com', password: 'S3cret' }); const forged = () => JSON.parse('{"bsontype":"ObjectID","id":""}');
// 1. Query by id: replays the id from the previous command await User.findById(alice.id); // another request await User.findById(forged()); // alice's document
// 2. String path: forged BSONRegExp is sent as a regex await User.findOne({ password: JSON.parse('{"bsontype":"BSONRegExp","pattern":"^S3","options":""}') }); // alice's document
// 3. Stored value (default config): stores 12 bytes of the previous command await User.updateOne({ email: 'victim@example.com' }, { $set: { password: 'resetcode123' } }); // another request const c = await Comment.create({ post: forged() }); (await Comment.findById(c.id)).post.id.toString('latin1'); // 'il\x00\x13\x00\x00\x00victi'
Impact
Applications on 6.3.5 to 6.13.12 are affected if they pass request values into queries or writes on ObjectId or String paths without checking that the values are primitive values. An attacker can:
1. read, modify or delete documents that another request just accessed, even with sanitizeFilter, express-mongo-sanitize or mongo-sanitize enabled; 2. read fragments of other requests’ database commands, such as emails, reset codes or API keys, by storing forged ObjectIds and reading them back; 3. run regex matches against String fields despite sanitizeFilter.
Workaround: check that request values are strings, or use mongoose.isValidObjectId(), before passing them to Mongoose.
Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. From 8.5.0 until 8.24.10 and 9.12.2, Mongoose's sanitizeProjection can be bypassed by +path selections, object or array aggregation expressions, nested and parent projections, positional projections, $meta, discriminator-specific exclusions, an own proto key, and projection-cast error paths. Applications that pass attacker-controlled data to select(), find(filter, projection), or the projection option while relying on sanitizeProjection can return fields marked select: false, including password hashes, reset tokens, API keys, and nested secrets. Nested exclusion objects, $elemMatch combined with an exclusion or a cast error, and discriminator filters can also cause ordinary queries that do not enable sanitizeProjection to omit the select: false exclusions that Mongoose normally adds. This issue is fixed in versions 8.24.10 and 9.12.2.
Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. From 8.5.0 until 8.24.10 and 9.12.2, Mongoose's sanitizeProjection can be bypassed by +path selections, object or array aggregation expressions, nested and parent projections, positional projections, $meta, discriminator-specific exclusions, an own proto key, and projection-cast error paths. Applications that pass attacker-controlled data to select(), find(filter, projection), or the projection option while relying on sanitizeProjection can return fields marked select: false, including password hashes, reset tokens, API keys, and nested secrets. Nested exclusion objects, $elemMatch combined with an exclusion or a cast error, and discriminator filters can also cause ordinary queries that do not enable sanitizeProjection to omit the select: false exclusions that Mongoose normally adds. This issue is fixed in versions 8.24.10 and 9.12.2.
Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. From 6.0.0 until 6.13.13, 7.8.14, 8.24.10, and 9.12.2, Mongoose's sanitizeFilter rejects only a small named set of top-level operators and does not recursively inspect undocumented operators such as $internalSchemaXor and $internalSchemaCond. Applications that pass attacker-controlled filter keys to queries while relying on sanitizeFilter can therefore accept nested selectors such as $ne or $regex, allowing authentication bypass, disclosure of protected values through boolean queries, or unintended updates and deletions. Applications that construct filters from individual primitive values are not affected by this bypass. This issue is fixed in versions 6.13.13, 7.8.14, 8.24.10, and 9.12.2.
Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. From 6.0.0 until 6.13.13, 7.8.14, 8.24.10, and 9.12.2, Mongoose's sanitizeFilter rejects only a small named set of top-level operators and does not recursively inspect undocumented operators such as $internalSchemaXor and $internalSchemaCond. Applications that pass attacker-controlled filter keys to queries while relying on sanitizeFilter can therefore accept nested selectors such as $ne or $regex, allowing authentication bypass, disclosure of protected values through boolean queries, or unintended updates and deletions. Applications that construct filters from individual primitive values are not affected by this bypass. This issue is fixed in versions 6.13.13, 7.8.14, 8.24.10, and 9.12.2.
Summary
Three Mongoose code paths copy data into objects by property name without checking whether the property is the object's own or inherited from its prototype:
1. Loading a document from the database (init(), also used by Model.hydrate()) 2. Setting a dotted path on a document ($set, used by new Model(obj), doc.set() and doc.$set()) 3. Merging update documents (utils.mergeClone, used by findOneAndReplace(), chained update calls and Query.prototype.merge())
When a key names an inherited property, such as toString or valueOf, or a document internal such as $schema, Mongoose writes into the shared object behind that property. The data comes from the attacker.
- Denial of service. For example, { "toString": { "call": 1 } } overwrites Object.prototype.toString.call. Mongoose and most other libraries rely on Object.prototype.toString.call(). After the overwrite, every later query in the process throws TypeError: toString.call is not a function until the process restarts. This includes queries on unrelated models. - Changing shared schema state. Through a subdocument with strict: false, a path such as profile.$schema.paths.email.validators reaches the subdocument's schema, which every document shares. Setting it to [] removes the required validator for every document in the process.
Mongoose already blocked proto, constructor and prototype, so these bugs cannot add properties to Object.prototype itself. They can still overwrite methods and properties of shared built-in functions and of Mongoose's internal objects.
Details
1. Loading documents: init()
js if (!schemaType && utils.isPOJO(value)) { // assume nested object if (!doc[i]) { doc[i] = {}; ... } init(self, value, doc[i], opts, path + '.'); }
For a stored field named toString, doc[i] is the inherited Object.prototype.toString. It is truthy, so init() recurses into that function and copies the stored subfields onto it.
This runs for every document Mongoose loads: find(), findOne(), cursors, populated documents and Model.hydrate(). It runs whatever the strict setting, and it applies to top-level and nested paths alike. lean() queries are not affected.
A malicious document can get into the collection in several ways: - through a model with strict: false, for example new Model(req.body).save(); - through another application or the raw MongoDB driver; - through any update that writes arbitrary keys.
2. Setting dotted paths: $set
When it walks a dotted path, $set read obj[parts[i]] and descended into whatever it found. That included inherited functions, such as Object.prototype.toString on a plain object or Document.prototype.toObject on a subdocument. On subdocuments it also included non-function internals that are prototype getters, such as $schema, schema, $middleware and $schemaTypeOptions. Those point at objects that every document of the model shares.
Attacker-controlled input reaches this path through: - A Mixed path on a default, strict schema: new Model({ "mixed.toString.call": 1 }), or doc.set({ "mixed.toString.call": 1 }). Nothing needs to be saved. - Any root path on a schema with strict: false: for example doc.set('toString.call', 1). - A subdocument with strict: false, when the application passes a user-controlled path to doc.set(path, value): for example doc.set('profile.$schema.paths.email.validators', []).
3. Merging updates: utils.mergeClone
js if (typeof to[key] === 'undefined') { to[key] = clone(fromObj[key]); } else if (isObject(val)) { mergeClone(to[key], val); // to[key] may be an inherited built-in }
to[key] was read without an own-property check, so a key such as toString recursed into Object.prototype.toString. This affects:
- Model.findOneAndReplace(filter, replacement). It always merges the replacement into the query's update, so a single call with an untrusted replacement is enough. - Update calls chained onto a query that already has an update. For example Model.updateOne(filter, { $set: {...} }).updateOne({}, untrustedUpdate), the same pattern with findOneAndUpdate(), or middleware that calls this.updateOne(...). - Query.prototype.merge() with a source query whose update came from untrusted input.
Proof of concept
js const mongoose = require('mongoose'); const { Schema } = mongoose;
// 2. Setting dotted paths: a Mixed path on a default strict schema, nothing saved const Item = mongoose.model('Item', new Schema({ name: String, meta: {} })); new Item(JSON.parse('{"meta.toString.call": 1}')); // e.g. new Item(req.body) console.log(typeof Object.prototype.toString.call); // 'number' // From here on, every query in the process fails: // TypeError: toString.call is not a function
js // 1. Loading documents: a stored field named after an Object.prototype method const Loose = mongoose.model('Loose', new Schema({ name: String }, { strict: false })); await new Loose(JSON.parse('{"name":"evil","toString":{"call":1}}')).save(); await Loose.findOne({ name: 'evil' }); // any later read of this document await OtherModel.findOne(); // TypeError: toString.call is not a function
js // 3. Merging updates: a single findOneAndReplace() call with an untrusted replacement const Doc = mongoose.model('Doc', new Schema({ name: String })); Doc.findOneAndReplace({}, JSON.parse('{"toString":{"call":1}}')); console.log(typeof Object.prototype.toString.call); // 'number'
js // 2. Setting dotted paths: changing the shared subdocument schema const User = mongoose.model('User', new Schema({ profile: new Schema({ email: { type: String, required: true } }, { strict: false }) })); // e.g. JSON-patch style endpoint: doc.set(req.body.path, req.body.value) new User({ profile: { email: 'a@b.c' } }).set('profile.$schema.paths.email.validators', []); await new User({ profile: {} }).validate(); // resolves: required removed for every document
Impact
- Denial of service (paths 1, 2 and 3). One request overwrites Object.prototype.toString.call. After that, every query in the process fails, and so does much other code, until the process restarts. Ways in: - new Model(req.body) on any schema with a Mixed path; - findOneAndReplace() with an untrusted replacement; - reading one stored document that contains a field such as { "toString": { "call": 1 } }.
In the stored-document case, the attacker does not need any write path through Mongoose at the moment of the attack. Any later read of that document triggers the overwrite. If the document is read on startup or by a scheduled job, the application can be kept down. - Changes to shared state (path 2, strict: false subdocuments). An attacker who controls the path passed to doc.set(path, value) can change a subdocument schema that every document shares. For example, they can remove validators or change schema options for every later document in the process. - Properties on built-in functions. More generally, an attacker can attach properties they choose to built-in functions such as Object.prototype.toString, Object.prototype.valueOf and Function.prototype.call. Any other code that reads properties of those functions sees the attacker's values.
Summary
sanitizeFilter exists to stop query selector injection: it wraps operator objects such as { $ne: null } in filter values in $eq, so they are matched literally. Set on a connection with mongoose.connect() or createConnection(uri, { sanitizeFilter: true }), the connection reports it as enabled but queries never apply it. An application that relies on the connection-level option and passes an attacker-controlled object into a filter therefore remains open to selector injection, and a password value of { $ne: null } returns the account record without the password.
Details
NativeConnection#createClient() at lib/drivers/node-mongodb-native/connection.js:270-272 moves options.sanitizeFilter into Connection.config and deletes the original option. Query#castConditions() at lib/query.js:2413-2423 checks Connection.options, the global options, and the per-query options, but never Connection.config. The defense therefore does not run even though Connection#get('sanitizeFilter') returns true. This storage was introduced in Mongoose 6.0.0 and the same mismatch is present in 9.11.2.
Proof of concept
javascript import mongoose from 'mongoose'
const conn = await mongoose.createConnection('<MONGODBURI>', { sanitizeFilter: true }).asPromise() const User = conn.model('User', new mongoose.Schema({ username: String, password: String, marker: String }))
await User.create({ username: 'victim', password: 'correct-password', marker: 'PROTECTEDRECORD' })
const filter = { username: 'victim', password: { $ne: null } } console.log(conn.get('sanitizeFilter')) console.log((await User.findOne(filter).lean()).marker)
A control query with a literal wrong password returned no document in the same run, confirming the filter is otherwise enforced.
Impact
Connection-level sanitizeFilter option is not respected. Any user that relies on connection-level config and sanitizeFilter to defend against query selector injection is affected. Users that set sanitizeFilter globally using mongoose.set('sanitizeFilter') or on specific queries using Model.find().sanitizeFilter() are not affected.
Summary
sanitizeFilter exists to stop query selector injection: it wraps operator objects such as { $ne: null } in filter values in $eq, so they are matched literally. Set on a connection with mongoose.connect() or createConnection(uri, { sanitizeFilter: true }), the connection reports it as enabled but queries never apply it. An application that relies on the connection-level option and passes an attacker-controlled object into a filter therefore remains open to selector injection, and a password value of { $ne: null } returns the account record without the password.
Details
NativeConnection#createClient() at lib/drivers/node-mongodb-native/connection.js:270-272 moves options.sanitizeFilter into Connection.config and deletes the original option. Query#castConditions() at lib/query.js:2413-2423 checks Connection.options, the global options, and the per-query options, but never Connection.config. The defense therefore does not run even though Connection#get('sanitizeFilter') returns true. This storage was introduced in Mongoose 6.0.0 and the same mismatch is present in 9.11.2.
Proof of concept
javascript import mongoose from 'mongoose'
const conn = await mongoose.createConnection('<MONGODBURI>', { sanitizeFilter: true }).asPromise() const User = conn.model('User', new mongoose.Schema({ username: String, password: String, marker: String }))
await User.create({ username: 'victim', password: 'correct-password', marker: 'PROTECTEDRECORD' })
const filter = { username: 'victim', password: { $ne: null } } console.log(conn.get('sanitizeFilter')) console.log((await User.findOne(filter).lean()).marker)
A control query with a literal wrong password returned no document in the same run, confirming the filter is otherwise enforced.
Impact
Connection-level sanitizeFilter option is not respected. Any user that relies on connection-level config and sanitizeFilter to defend against query selector injection is affected. Users that set sanitizeFilter globally using mongoose.set('sanitizeFilter') or on specific queries using Model.find().sanitizeFilter() are not affected.
Summary
Three Mongoose code paths copy data into objects by property name without checking whether the property is the object's own or inherited from its prototype:
1. Loading a document from the database (init(), also used by Model.hydrate()) 2. Setting a dotted path on a document ($set, used by new Model(obj), doc.set() and doc.$set()) 3. Merging update documents (utils.mergeClone, used by findOneAndReplace(), chained update calls and Query.prototype.merge())
When a key names an inherited property, such as toString or valueOf, or a document internal such as $schema, Mongoose writes into the shared object behind that property. The data comes from the attacker.
- Denial of service. For example, { "toString": { "call": 1 } } overwrites Object.prototype.toString.call. Mongoose and most other libraries rely on Object.prototype.toString.call(). After the overwrite, every later query in the process throws TypeError: toString.call is not a function until the process restarts. This includes queries on unrelated models. - Changing shared schema state. Through a subdocument with strict: false, a path such as profile.$schema.paths.email.validators reaches the subdocument's schema, which every document shares. Setting it to [] removes the required validator for every document in the process.
Mongoose already blocked proto, constructor and prototype, so these bugs cannot add properties to Object.prototype itself. They can still overwrite methods and properties of shared built-in functions and of Mongoose's internal objects.
Details
1. Loading documents: init()
js if (!schemaType && utils.isPOJO(value)) { // assume nested object if (!doc[i]) { doc[i] = {}; ... } init(self, value, doc[i], opts, path + '.'); }
For a stored field named toString, doc[i] is the inherited Object.prototype.toString. It is truthy, so init() recurses into that function and copies the stored subfields onto it.
This runs for every document Mongoose loads: find(), findOne(), cursors, populated documents and Model.hydrate(). It runs whatever the strict setting, and it applies to top-level and nested paths alike. lean() queries are not affected.
A malicious document can get into the collection in several ways: - through a model with strict: false, for example new Model(req.body).save(); - through another application or the raw MongoDB driver; - through any update that writes arbitrary keys.
2. Setting dotted paths: $set
When it walks a dotted path, $set read obj[parts[i]] and descended into whatever it found. That included inherited functions, such as Object.prototype.toString on a plain object or Document.prototype.toObject on a subdocument. On subdocuments it also included non-function internals that are prototype getters, such as $schema, schema, $middleware and $schemaTypeOptions. Those point at objects that every document of the model shares.
Attacker-controlled input reaches this path through: - A Mixed path on a default, strict schema: new Model({ "mixed.toString.call": 1 }), or doc.set({ "mixed.toString.call": 1 }). Nothing needs to be saved. - Any root path on a schema with strict: false: for example doc.set('toString.call', 1). - A subdocument with strict: false, when the application passes a user-controlled path to doc.set(path, value): for example doc.set('profile.$schema.paths.email.validators', []).
3. Merging updates: utils.mergeClone
js if (typeof to[key] === 'undefined') { to[key] = clone(fromObj[key]); } else if (isObject(val)) { mergeClone(to[key], val); // to[key] may be an inherited built-in }
to[key] was read without an own-property check, so a key such as toString recursed into Object.prototype.toString. This affects:
- Model.findOneAndReplace(filter, replacement). It always merges the replacement into the query's update, so a single call with an untrusted replacement is enough. - Update calls chained onto a query that already has an update. For example Model.updateOne(filter, { $set: {...} }).updateOne({}, untrustedUpdate), the same pattern with findOneAndUpdate(), or middleware that calls this.updateOne(...). - Query.prototype.merge() with a source query whose update came from untrusted input.
Proof of concept
js const mongoose = require('mongoose'); const { Schema } = mongoose;
// 2. Setting dotted paths: a Mixed path on a default strict schema, nothing saved const Item = mongoose.model('Item', new Schema({ name: String, meta: {} })); new Item(JSON.parse('{"meta.toString.call": 1}')); // e.g. new Item(req.body) console.log(typeof Object.prototype.toString.call); // 'number' // From here on, every query in the process fails: // TypeError: toString.call is not a function
js // 1. Loading documents: a stored field named after an Object.prototype method const Loose = mongoose.model('Loose', new Schema({ name: String }, { strict: false })); await new Loose(JSON.parse('{"name":"evil","toString":{"call":1}}')).save(); await Loose.findOne({ name: 'evil' }); // any later read of this document await OtherModel.findOne(); // TypeError: toString.call is not a function
js // 3. Merging updates: a single findOneAndReplace() call with an untrusted replacement const Doc = mongoose.model('Doc', new Schema({ name: String })); Doc.findOneAndReplace({}, JSON.parse('{"toString":{"call":1}}')); console.log(typeof Object.prototype.toString.call); // 'number'
js // 2. Setting dotted paths: changing the shared subdocument schema const User = mongoose.model('User', new Schema({ profile: new Schema({ email: { type: String, required: true } }, { strict: false }) })); // e.g. JSON-patch style endpoint: doc.set(req.body.path, req.body.value) new User({ profile: { email: 'a@b.c' } }).set('profile.$schema.paths.email.validators', []); await new User({ profile: {} }).validate(); // resolves: required removed for every document
Impact
- Denial of service (paths 1, 2 and 3). One request overwrites Object.prototype.toString.call. After that, every query in the process fails, and so does much other code, until the process restarts. Ways in: - new Model(req.body) on any schema with a Mixed path; - findOneAndReplace() with an untrusted replacement; - reading one stored document that contains a field such as { "toString": { "call": 1 } }.
In the stored-document case, the attacker does not need any write path through Mongoose at the moment of the attack. Any later read of that document triggers the overwrite. If the document is read on startup or by a scheduled job, the application can be kept down. - Changes to shared state (path 2, strict: false subdocuments). An attacker who controls the path passed to doc.set(path, value) can change a subdocument schema that every document shares. For example, they can remove validators or change schema options for every later document in the process. - Properties on built-in functions. More generally, an attacker can attach properties they choose to built-in functions such as Object.prototype.toString, Object.prototype.valueOf and Function.prototype.call. Any other code that reads properties of those functions sees the attacker's values.
Summary
Mongoose chooses which discriminator model or schema to use by looking up the discriminator key value (t by default) in a plain object of registered discriminators, for example Model.discriminators[doc.t]. That value comes from user documents and query filters. Because the lookup did not check own properties, a value that names a property inherited from Object.prototype resolves to that inherited value instead of a discriminator. Examples are 'constructor', 'toString' and 'hasOwnProperty'.
- t: 'constructor' resolves to the global Object function. Mongoose then calls new Object(doc), which returns the raw user object where a Mongoose document is expected. - t: 'toString' and similar names resolve to built-in functions that throw when used as a constructor or schema.
The most serious effect: through bulkWrite() insertOne with skipValidation: true, the raw user object is stored as-is, without schema casting or strict filtering. After that, every query that returns the stored document throws, until the document is removed from the database.
Details
The registries that hold discriminators are plain objects: Model.discriminators, schema.discriminators, and the embedded discriminator registries on document arrays and single nested subdocuments. Several code paths indexed them directly with a value taken from the document or filter:
| Code path | Input | |---|---| | Model constructor (new Model(doc)) | document | | Model.create(), insertMany(), bulkWrite(), bulkSave() | documents | | Hydrating query results (find(), findOne(), etc.) and Model.hydrate() | stored documents | | Casting query filters, including flat paths such as 'events.t' and $elemMatch | query filter | | Casting updates and array filters | update filter, arrayFilters | | Document array push() / create(), document array and single nested casting | subdocuments | | Populate on embedded discriminators | stored subdocuments |
getDiscriminatorByValue() already iterated the registry's own keys safely. But most callers tried the direct lookup first and only fell back to it afterwards, so a truthy inherited value took precedence.
The lookups only read inherited properties. They do not write to Object.prototype or any other shared object, and they do not change in-memory state that affects other requests. This is NOT a prototype pollution vector.
Proof of concept
js const mongoose = require('mongoose');
const Base = mongoose.model('Base', new mongoose.Schema({ name: String, age: Number })); Base.discriminator('Child', new mongoose.Schema({ extra: String }));
// Type confusion: the "document" is the raw input object const doc = new Base({ name: 'x', t: 'constructor' }); console.log(doc instanceof mongoose.Document); // false
js // Schema bypass and persistent poison document via bulkWrite + skipValidation await Base.bulkWrite([{ insertOne: { document: { name: 'x', age: 'not a number', notInSchema: true, t: 'constructor' } } }], { skipValidation: true }); // Stored verbatim: { age: 'not a number', notInSchema: true, t: 'constructor', ... }
await Base.find(); // throws: Cannot read properties of undefined (reading 'eachPath')
Impact
- Crashing the request. An attacker who controls the discriminator key of a document or filter can make the request fail. In most code paths that sent the value, this means a TypeError or a non-document object returned to application code. Ways in include Model.create(req.body), new Model(req.body), Model.find(req.query)-style filters, and pushing user input onto embedded discriminator arrays. The effect is limited to the request carrying the value. - Schema bypass on bulkWrite({ skipValidation: true }). When an application passes untrusted documents to bulkWrite() insertOne with skipValidation: true, the raw object is stored without casting or strict filtering. Fields the schema would normally strip are persisted, such as an isAdmin that isn't in the schema. Fields with wrong types are also persisted. - Persistent denial of service for queries. A stored document with such a discriminator key value makes hydration throw. Every query that returns that document fails, for all users, until the document is deleted directly in the database. Besides the bulkWrite() path above, the document can get into the collection through another application, the raw MongoDB driver, or any other writer that does not go through Mongoose casting.
This issue doesn't let an attacker modify Object.prototype, built-in functions, schemas or other shared in-memory state. The schema bypass requires the application to opt in to skipValidation with untrusted input.
Summary
Mongoose chooses which discriminator model or schema to use by looking up the discriminator key value (t by default) in a plain object of registered discriminators, for example Model.discriminators[doc.t]. That value comes from user documents and query filters. Because the lookup did not check own properties, a value that names a property inherited from Object.prototype resolves to that inherited value instead of a discriminator. Examples are 'constructor', 'toString' and 'hasOwnProperty'.
- t: 'constructor' resolves to the global Object function. Mongoose then calls new Object(doc), which returns the raw user object where a Mongoose document is expected. - t: 'toString' and similar names resolve to built-in functions that throw when used as a constructor or schema.
The most serious effect: through bulkWrite() insertOne with skipValidation: true, the raw user object is stored as-is, without schema casting or strict filtering. After that, every query that returns the stored document throws, until the document is removed from the database.
Details
The registries that hold discriminators are plain objects: Model.discriminators, schema.discriminators, and the embedded discriminator registries on document arrays and single nested subdocuments. Several code paths indexed them directly with a value taken from the document or filter:
| Code path | Input | |---|---| | Model constructor (new Model(doc)) | document | | Model.create(), insertMany(), bulkWrite(), bulkSave() | documents | | Hydrating query results (find(), findOne(), etc.) and Model.hydrate() | stored documents | | Casting query filters, including flat paths such as 'events.t' and $elemMatch | query filter | | Casting updates and array filters | update filter, arrayFilters | | Document array push() / create(), document array and single nested casting | subdocuments | | Populate on embedded discriminators | stored subdocuments |
getDiscriminatorByValue() already iterated the registry's own keys safely. But most callers tried the direct lookup first and only fell back to it afterwards, so a truthy inherited value took precedence.
The lookups only read inherited properties. They do not write to Object.prototype or any other shared object, and they do not change in-memory state that affects other requests. This is NOT a prototype pollution vector.
Proof of concept
js const mongoose = require('mongoose');
const Base = mongoose.model('Base', new mongoose.Schema({ name: String, age: Number })); Base.discriminator('Child', new mongoose.Schema({ extra: String }));
// Type confusion: the "document" is the raw input object const doc = new Base({ name: 'x', t: 'constructor' }); console.log(doc instanceof mongoose.Document); // false
js // Schema bypass and persistent poison document via bulkWrite + skipValidation await Base.bulkWrite([{ insertOne: { document: { name: 'x', age: 'not a number', notInSchema: true, t: 'constructor' } } }], { skipValidation: true }); // Stored verbatim: { age: 'not a number', notInSchema: true, t: 'constructor', ... }
await Base.find(); // throws: Cannot read properties of undefined (reading 'eachPath')
Impact
- Crashing the request. An attacker who controls the discriminator key of a document or filter can make the request fail. In most code paths that sent the value, this means a TypeError or a non-document object returned to application code. Ways in include Model.create(req.body), new Model(req.body), Model.find(req.query)-style filters, and pushing user input onto embedded discriminator arrays. The effect is limited to the request carrying the value. - Schema bypass on bulkWrite({ skipValidation: true }). When an application passes untrusted documents to bulkWrite() insertOne with skipValidation: true, the raw object is stored without casting or strict filtering. Fields the schema would normally strip are persisted, such as an isAdmin that isn't in the schema. Fields with wrong types are also persisted. - Persistent denial of service for queries. A stored document with such a discriminator key value makes hydration throw. Every query that returns that document fails, for all users, until the document is deleted directly in the database. Besides the bulkWrite() path above, the document can get into the collection through another application, the raw MongoDB driver, or any other writer that does not go through Mongoose casting.
This issue doesn't let an attacker modify Object.prototype, built-in functions, schemas or other shared in-memory state. The schema bypass requires the application to opt in to skipValidation with untrusted input.
Impact
sanitizeFilter is Mongoose's mechanism for protecting against query selector injection attacks. In older versions of Mongoose, sanitizeFilter was not applied for countDocuments() queries.
Patches
Patches have been released for all supported Mongoose major release lines. Please upgrade to the following versions depending on which major version of Mongoose applications are using.
1. ^9.9.2 2. ^8.24.3 3. ^7.8.12 4. ^6.13.11
Workarounds
Middleware:
javascript mongoose.plugin(function() { schema.pre('countDocuments', function() { // This will always apply sanitizeFilter on countDocuments mongoose.sanitizeFilter(this.getFilter()); }); });
Impact
sanitizeFilter is Mongoose's mechanism for protecting against query selector injection attacks. In older versions of Mongoose, sanitizeFilter was not applied for countDocuments() queries.
Patches
Patches have been released for all supported Mongoose major release lines. Please upgrade to the following versions depending on which major version of Mongoose applications are using.
1. ^9.9.2 2. ^8.24.3 3. ^7.8.12 4. ^6.13.11
Workarounds
Middleware:
javascript mongoose.plugin(function() { schema.pre('countDocuments', function() { // This will always apply sanitizeFilter on countDocuments mongoose.sanitizeFilter(this.getFilter()); }); });
Summary
Prototype pollution via Schema.prototype.virtual() — the 2022 fix for CVE-2022-2564 / CVE-2022-24304 protected Schema.path()/add() but never virtual(), so the same class of bug is still exploitable in all maintained release lines.
Details
In lib/schema.js, Schema.prototype.virtual() (defined at line 2643) builds the virtual path via:
javascript virtuals[name] = parts.reduce(function(mem, part, i) { mem[part] || (mem[part] = (i === parts.length - 1) ? new VirtualType(options, name) : {}); return mem[part]; }, this.tree); // lines 2755-2759
Unlike path()/add(), virtual() never received the specialProperties check added for CVE-2022-2564/CVE-2022-24304 (lib/schema.js lines 806, 1308, 1331).
A path containing proto/constructor/prototype segments resolves through the prototype chain and writes onto Object.prototype / Function.prototype.
Proof of concept
javascript const mongoose = require('mongoose'); const schema = new mongoose.Schema({});
schema.virtual('proto.polluted'); console.log(({}).polluted); // VirtualType instance console.log(Object.prototype.hasOwnProperty('polluted')); // true console.log(Object.getOwnPropertyDescriptor( Object.prototype, 'polluted').enumerable); // true
schema.virtual('constructor.prototype.opol'); console.log(({}).opol); // true
schema.virtual('hasOwnProperty.proto.fpol'); console.log((function(){}).fpol); // Function.prototype polluted
Impact
Attacker-influenced schema field names (dynamic schemas, CMS form builders, schema-as-code) allow pollution of Object.prototype (own, enumerable keys visible on every object — e.g. ({}).isAdmin checks can be spoofed) and Function.prototype (a known gadget primitive in server-side JS).
Summary
Prototype pollution via Schema.prototype.virtual() — the 2022 fix for CVE-2022-2564 / CVE-2022-24304 protected Schema.path()/add() but never virtual(), so the same class of bug is still exploitable in all maintained release lines.
Details
In lib/schema.js, Schema.prototype.virtual() (defined at line 2643) builds the virtual path via:
javascript virtuals[name] = parts.reduce(function(mem, part, i) { mem[part] || (mem[part] = (i === parts.length - 1) ? new VirtualType(options, name) : {}); return mem[part]; }, this.tree); // lines 2755-2759
Unlike path()/add(), virtual() never received the specialProperties check added for CVE-2022-2564/CVE-2022-24304 (lib/schema.js lines 806, 1308, 1331).
A path containing proto/constructor/prototype segments resolves through the prototype chain and writes onto Object.prototype / Function.prototype.
Proof of concept
javascript const mongoose = require('mongoose'); const schema = new mongoose.Schema({});
schema.virtual('proto.polluted'); console.log(({}).polluted); // VirtualType instance console.log(Object.prototype.hasOwnProperty('polluted')); // true console.log(Object.getOwnPropertyDescriptor( Object.prototype, 'polluted').enumerable); // true
schema.virtual('constructor.prototype.opol'); console.log(({}).opol); // true
schema.virtual('hasOwnProperty.proto.fpol'); console.log((function(){}).fpol); // Function.prototype polluted
Impact
Attacker-influenced schema field names (dynamic schemas, CMS form builders, schema-as-code) allow pollution of Object.prototype (own, enumerable keys visible on every object — e.g. ({}).isAdmin checks can be spoofed) and Function.prototype (a known gadget primitive in server-side JS).