TypeORM Prototype Pollution Leading To SQL Injection (CVE-2022-36531)
TypeORM's mergeDeep function did not block the __proto__ key, allowing prototype pollution that could alter SQL query parameters. An attacker could exploit this to inject SQL or cause a denial of service.
Published on doyensec.com
Security Advisory TypeORM Prototype Pollution Leading To SQL Injection Created by Norbert Szetei, Viktor Chuchurski 09/21/2022
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
TypeORM is an object-relational mapping (ORM) tool, and in this engagement it was used by the customer as a third-party library. The baseline expectation for any ORM is that it avoids SQL injection and passes every SQL query safely to the database. TypeORM is one of the most popular ORM solutions, with 960,405 weekly downloads on npmjs at the time of writing, so sanitising all potentially malicious user-supplied input is crucial.
The advisory covers a critical vulnerability in which a parameter used to compose SQL queries can be polluted. An attacker can exploit it either as a SQL injection or as a denial of service. The affected component is the TypeORM library, in versions 0.2.35 to 0.3.9, tracked as CVE-2022-36531. The credits are Norbert Szetei and Viktor Chuchurski.
Setup
The research was carried out against the TypeORM library as a dependency of the customer's application. The reproduction steps are the same as for a previously reported vulnerability, based on the example code at https://github.com/typeorm/typescript-example. To confirm the behaviour dynamically, a printing statement was added to https://github.com/typeorm/typeorm/blob/[redacted]/src/util/OrmUtils.ts#L119 to output the value argument.
The relevant version history is:
| Version | State |
|---|---|
| 0.2.24 and older | Affected by the earlier critical SQL injection |
| 0.2.25 | Fixed by rejecting the __proto__ key |
| 0.2.34 | Still fixed |
| 0.2.35 | Bug reintroduced by refactoring |
| 0.3.9 | Last affected version in the stated range |
| 0.3.10 | Fix deployed |
Finding it
Functions which internally called mergeDeep, such as connection.manager.save, were affected by prototype pollution. This allowed changing properties of different functions, which resulted in a SQL injection.
The bug had already been fixed once. Release 0.2.25 ensured that the user-supplied property with the prototype keyword __proto__ is not processed:
$ git clone https://github.com/typeorm/typeorm
$ cd typeorm
$ git diff 0.2.24 0.2.25 src/util/OrmUtils.ts
[ .. SNIP .. ]
if (value instanceof Promise)
if (key === "__proto__" || value instanceof Promise)
[ .. SNIP .. ]
The diff shows the added condition: a key equal to __proto__ is skipped, alongside values that are promises.
However, the refactoring of the code from release 0.2.34 to 0.2.35 reintroduced the same bug by removing the __proto__ check:
$ git diff 0.2.34 0.2.35 src/util/OrmUtils.ts
static mergeDeep(target: any, ...sources: any[]): any {
if (!sources.length) return target;
const source = sources.shift();
if (this.isObject(target) && this.isObject(source)) {
for (const key in source) {
const value = source[key];
if (key === "__proto__" || value instanceof Promise) continue;
Because the issue was reintroduced approximately one year after the initial fix, the same class of attack became possible again in the versions listed above.
Exploitation
Step 1: Confirm that parameters are polluted
Using the reproduction steps from the earlier report, a printing statement was added at OrmUtils.ts line 119 to output the value argument. This makes it possible to dynamically confirm that the parameters are polluted.
Step 2: Inject a payload through parsed JSON
With that instrumentation in place, the following input was injected:
const post = JSON.parse(`{"text":"a","title":{"__proto__": {"where":{"id":2,"where":null}}}}`)
The title property carries a nested __proto__ key whose value is an object with a where clause. When mergeDeep walks the parsed object, the __proto__ key is no longer skipped.
Step 3: Observe the polluted object
This causes pollution of the object with:
{ __proto__: { where: { id: 2, where: null } } }
Consequently, only the entry with id = 2 is outputted.
Root cause
The mistake is in mergeDeep in src/util/OrmUtils.ts. The function recursively merges source objects into a target, iterating with for (const key in source). The report says functions calling mergeDeep were affected by prototype pollution, allowing properties of different functions to be changed. Functions that internally call mergeDeep, such as connection.manager.save, then operate on polluted properties, and a polluted where clause ends up in the composed SQL.
The defence that existed was the explicit key === "__proto__" check added in 0.2.25. The refactoring between 0.2.34 and 0.2.35 removed that check.
Impact
Successful exploitation of the SQL injection can lead to the disclosure or modification of sensitive information to unauthorised users, compromising the confidentiality of the system. Exploitation using incorrect SQL syntax leads to denial of service, affecting the user experience and the general availability of the system. The vulnerability class is listed as injection flaws (SQL, XML, command, path, and similar), with severity critical.
Fix
The remediation is to reimplement the fix from version 0.2.25, so that objects with the prototype pollution payload are not merged. The advisory strongly recommends implementing a unit test to prevent regressions. TypeORM deployed a fix in TypeORM 0.3.10.
Disclosure timeline
| Date | Event |
|---|---|
| 07/07/2022 | Issue responsibly disclosed to the TypeORM dev team (Umed K.) |
| 09/19/2022 | TypeORM deployed a fix in TypeORM 0.3.10 |
| 09/21/2022 | Advisory public release |
The status of the issue is closed. The referenced prior report is "SQL Injection or Denial of Service due to a Prototype Pollution" at https://hackerone.com/reports/869574.
Variants to test
What happened, in plain words
A security research company called Doyensec was hired to look at a piece of software that one of its customers used inside their own application. That piece of software is called TypeORM. TypeORM is a library: a bundle of ready-made code that a programmer adds to a project instead of writing everything from scratch. TypeORM's job is to sit between an application and a database and translate the application's requests into SQL, the language databases understand. Software that does this translation is called an ORM, short for object-relational mapping.
The researchers found a serious flaw in TypeORM. An attacker could send specially crafted data to an application that uses TypeORM, and that data would quietly change a setting inside the library that is later used to build a database query. The result is that the attacker can influence the SQL that reaches the database. Depending on what they send, this can either leak or alter data (a SQL injection) or break the query so the application stops working properly (a denial of service).
The flaw is tracked publicly as CVE-2022-36531. A CVE is a catalogue number that the security community gives to a known vulnerability so that everyone can refer to the same issue. The affected versions are TypeORM 0.2.35 through 0.3.9. The issue was reported to the TypeORM developers on 7 July 2022, a fix shipped in TypeORM 0.3.10 on 19 September 2022, and the advisory became public on 21 September 2022. The credits go to Norbert Szetei and Viktor Chuchurski.
What makes the story interesting is that this exact bug had already been found and fixed once before, roughly a year earlier. A later round of code tidying, called refactoring, removed the protective check by accident, and the bug came back.
Background: what an ORM is and why it matters
Imagine a restaurant. You speak to the waiter, not to the kitchen. You say what you want in ordinary language, and the waiter translates it into whatever the kitchen needs to hear. An ORM is that waiter for databases. The application says "save this post" or "find the user with id 2", and the ORM writes the actual SQL statement and hands it to the database.
Because the ORM writes the SQL, it is also the place where safety has to be enforced. If it does, you get SQL injection: a class of attack where an attacker slips database instructions into data that was supposed to be treated as plain values. Injection flaws as a category also cover injecting into XML, operating system commands, file paths and similar, but here the target is SQL.
TypeORM is one of the most widely used ORMs in the JavaScript and TypeScript world. At the time of the advisory it had 960,405 weekly downloads on npmjs, the main package registry for JavaScript libraries. That number matters because a flaw in a library that popular spreads to every application that depends on it.
The setup: how the research was done
They worked with the TypeORM library as it was used by the customer's application, as a third-party dependency. To reproduce the behaviour they used the official example project published by the TypeORM team at https://github.com/typeorm/typescript-example. The reproduction steps were the same as those from an earlier report of the same bug.
To see what was happening inside the library, they added a printing statement to a specific line of TypeORM's source code, src/util/OrmUtils.ts line 119, so that the value argument passed through that line would be printed out. This is a common debugging technique: you make the program talk about what it is doing so you can watch the data flow. With that print in place, they could confirm in real time that the parameters used to build queries were being altered by their input.
The version history that matters is this:
| Version | State |
|---|---|
| 0.2.24 and older | Affected by the earlier critical SQL injection |
| 0.2.25 | Fixed by rejecting the __proto__ key |
| 0.2.34 | Still fixed |
| 0.2.35 | Bug reintroduced by refactoring |
| 0.3.9 | Last affected version in the stated range |
| 0.3.10 | Fix deployed |
Finding it: the bug that came back
The vulnerable functions are the ones that internally call a helper called mergeDeep, for example connection.manager.save. mergeDeep is a utility that takes two or more objects and combines them, copying the contents of one into another, going down into nested objects as it goes. The save function internally calls mergeDeep.
The problem is a concept called prototype pollution. In JavaScript, every object has a hidden parent object called its prototype, which supplies default properties. If you can write a property named __proto__ into an object, you are not adding a normal property to that object; you are changing the prototype that object inherits from. It is like being told to write your name on your own form, but instead finding a way to write it on the master template that every future form is copied from. From then on, everyone's form carries your change.
The bug had already been fixed once. Release 0.2.25 made sure that a user-supplied property named __proto__ is simply not processed. The researchers showed the fix by cloning the TypeORM source code and comparing the two releases:
$ git clone https://github.com/typeorm/typeorm
$ cd typeorm
$ git diff 0.2.24 0.2.25 src/util/OrmUtils.ts
[ .. SNIP .. ]
if (value instanceof Promise)
if (key === "__proto__" || value instanceof Promise)
[ .. SNIP .. ]
Line by line:
git clone https://github.com/typeorm/typeormdownloads a full copy of the TypeORM source code repository to the local machine. Git is the version control system that keeps every historical version of the code.cd typeormmoves into the downloaded folder.git diff 0.2.24 0.2.25 src/util/OrmUtils.tsasks Git to show what changed in the filesrc/util/OrmUtils.tsbetween release 0.2.24 and release 0.2.25. A diff is a side-by-side view of removed and added lines.[ .. SNIP .. ]marks places where the advisory cut out irrelevant lines.if (value instanceof Promise)is the old line: it only skips values that are promises (a JavaScript object representing a result that will arrive later).if (key === "__proto__" || value instanceof Promise)is the new line: it now also skips any key whose name is exactly__proto__. The||means "or", so the skip happens if either condition is true.
That single added condition was the whole defence. Then, when the code was refactored between releases 0.2.34 and 0.2.35, the check disappeared again:
$ git diff 0.2.34 0.2.35 src/util/OrmUtils.ts
static mergeDeep(target: any, ...sources: any[]): any {
if (!sources.length) return target;
const source = sources.shift();
if (this.isObject(target) && this.isObject(source)) {
for (const key in source) {
const value = source[key];
if (key === "__proto__" || value instanceof Promise) continue;
Line by line:
git diff 0.2.34 0.2.35 src/util/OrmUtils.tsshows what changed in the same file between 0.2.34 and 0.2.35.static mergeDeep(target: any, ...sources: any[]): any {declares the merge function. It takes atargetobject and any number ofsources, and returns an object.anyis TypeScript's way of saying "no type restriction".if (!sources.length) return target;stops early: if there are no sources left to merge, return the target as it is.const source = sources.shift();takes the first source off the list and stores it insource.shiftremoves and returns the first element of an array.if (this.isObject(target) && this.isObject(source)) {only proceeds if both the target and the source are objects, since merging only makes sense for objects.for (const key in source) {loops over every property name in the source object. This kind of loop is exactly where a__proto__key can slip in.const value = source[key];reads the value stored under that property name.if (key === "__proto__" || value instanceof Promise) continue;is the guard: skip this key if it is__proto__or if the value is a promise.continuejumps to the next iteration of the loop.
The advisory's point is that the refactoring reintroduced the same bug by removing the __proto__ check, and the affected range 0.2.35 to 0.3.9 reflects that. Because this happened about a year after the original fix, the same class of attack became possible again in those versions.
Exploitation: step by step
Step 1: Confirm that parameters are polluted
Before claiming a vulnerability, you want evidence. The researchers reused the reproduction steps from the earlier report and added the printing statement at OrmUtils.ts line 119 to output the value argument. That way, every value passing through the merge function is visible on screen, and they could dynamically confirm that the parameters used to compose queries were being polluted. This step is about observation, not attack: you are watching the program's own data.
Step 2: Inject a payload through parsed JSON
With the instrumentation in place, they injected the following input:
const post = JSON.parse(`{"text":"a","title":{"__proto__": {"where":{"id":2,"where":null}}}}`)
Line by line:
const post =creates a variable namedpostto hold the result.JSON.parse(...)takes a piece of text formatted as JSON and turns it into a real JavaScript object. JSON is a plain text format for data, the same format many web APIs use to send and receive information.- The text being parsed is
{"text":"a","title":{"__proto__": {"where":{"id":2,"where":null}}}}. It describes an object with atextproperty set to"a"and atitleproperty. - Inside
titlethere is a key literally named__proto__, whose value is an object containing awhereclause withidset to 2 andwhereset to null.
The title property is the vehicle. It carries a nested __proto__ key whose value is an object with a where clause. When mergeDeep walks through the parsed object, the __proto__ key is no longer skipped. In everyday terms: instead of adding a line to your own shopping list, you edited the template list that every list is copied from.
Step 3: Observe the polluted object
This causes pollution of the object with:
{ __proto__: { where: { id: 2, where: null } } }
Line by line:
{ __proto__: ... }shows that the prototype of the object now carries an entry.where: { id: 2, where: null }is the injected clause: it tells the query to select the row whereidequals 2, and the innerwhereis null.
Consequently, only the entry with id = 2 is outputted. The where clause that the attacker supplied through the prototype is the one that ends up composing the query.
Root cause: why it works
The mistake lives in mergeDeep in src/util/OrmUtils.ts. The function recursively merges source objects into a target, iterating with for (const key in source). The report says functions calling mergeDeep were affected by prototype pollution, allowing properties of different functions to be changed. Functions that internally call mergeDeep, such as connection.manager.save, then operate on polluted properties, and a polluted where clause ends up in the composed SQL.
The defence that existed was the explicit key === "__proto__" check added in 0.2.25. The refactoring between 0.2.34 and 0.2.35 removed that check.
Impact: what an attacker could do
Successful exploitation of the SQL injection can lead to the disclosure or modification of sensitive information to unauthorised users, compromising the confidentiality of the system. In plain terms: an attacker might read data they should not see, or change data they should not touch.
Exploitation using incorrect SQL syntax leads to denial of service, affecting the user experience and the general availability of the system. A denial of service means the application stops responding correctly, so legitimate users cannot use it. The vulnerability class is listed as injection flaws (SQL, XML, command, path, and similar), with severity critical.
Fix: what was done about it
The remediation is to reimplement the fix from version 0.2.25, so that objects with the prototype pollution payload are not merged. In other words, put the __proto__ check back. The advisory strongly recommends implementing a unit test to prevent regressions. A unit test is a small automated check that runs every time the code changes; if someone removes the guard again, the test fails and the mistake is caught before release. TypeORM deployed a fix in TypeORM 0.3.10.
Disclosure timeline
| Date | Event |
|---|---|
| 07/07/2022 | Issue responsibly disclosed to the TypeORM dev team (Umed K.) |
| 09/19/2022 | TypeORM deployed a fix in TypeORM 0.3.10 |
| 09/21/2022 | Advisory public release |
Responsible disclosure means telling the maintainers privately first, giving them time to fix the problem before the details become public, so that attackers do not get a head start. The status of the issue is closed. The referenced prior report is "SQL Injection or Denial of Service due to a Prototype Pollution" at https://hackerone.com/reports/869574.
Variants to test
If you want to check whether an application you are responsible for is affected, these are the directions the advisory points to:
Glossary
- API: a defined way for one piece of software to talk to another, like a menu of requests a service accepts and the answers it gives back.
- CVE: a public catalogue number assigned to a known vulnerability so everyone can refer to the same issue.
- Denial of service (DoS): an attack that makes a system stop working properly for legitimate users, for example by causing errors or exhausting resources.
- Dependency / third-party library: code written by someone else that your project includes and relies on.
- Diff: a view showing which lines were added, removed or changed between two versions of a file.
- Git: a version control system that records every change to source code and lets you compare and retrieve versions.
- Injection flaw: a class of vulnerability where attacker-supplied data is interpreted as instructions by a system (SQL, XML, operating system commands, file paths and so on).
- JSON: a plain text format for structured data, widely used by web APIs to send and receive information.
mergeDeep: a TypeORM helper that combines objects, including nested ones, copying values from sources into a target.- npmjs: the main public registry where JavaScript packages are published and downloaded.
- Object: in JavaScript, a collection of named properties and their values.
- ORM (object-relational mapping): software that translates an application's requests into database queries, so programmers work with objects instead of writing SQL by hand.
- Promise: a JavaScript object representing a result that will arrive later, used for asynchronous work.
- Prototype: the hidden parent object every JavaScript object inherits default properties from.
- Prototype pollution: a vulnerability where an attacker can write into an object's prototype, changing behaviour for other code that reads those properties.
- Refactoring: reorganising code without intending to change what it does; it can accidentally remove protections.
- Regression: when a bug that was previously fixed comes back.
- Responsible disclosure: reporting a vulnerability privately to the maintainers first, giving them time to fix it before details are published.
- SQL: the language used to query and modify relational databases.
- SQL injection: a vulnerability where attacker-supplied data becomes part of a SQL query, letting the attacker read or change data or break the query.
- TypeORM: a popular ORM library for JavaScript and TypeScript, affected here in versions 0.2.35 to 0.3.9.
- Unit test: a small automated check that verifies one piece of code behaves as expected, run whenever the code changes.
- Vulnerability: a weakness in software that an attacker can use to make it behave in ways its authors did not intend.
__proto__: the special property name in JavaScript that refers to an object's prototype; writing to it can pollute shared behaviour.