---
id: "CVE-2026-26198"
page: "https://infrastack.ai/live/CVE-2026-26198"
kind: "vulnerability"
aliases: ["CVE-2026-26198", "GHSA-xxh2-68g9-8jqr"]
title: "ormar is vulnerable to SQL Injection through aggregate functions min() and max()"
severity: "critical"
cvss: 9.8
epss: 0.01013
exploited: false
status: "open"
category: "package"
products: [{"name": "ormar", "fixed": ["0.23.0"], "affected": ">= 0.9.9, < 0.23.0", "ecosystem": "pypi"}, {"name": "collerek ormar", "fixed": ["0.23.0"], "affected": ">= 0.9.9, < 0.23.0", "ecosystem": "vendor"}]
ecosystems: ["pypi", "vendor"]
tags: ["cwe-89", "fastapi", "ormar", "package", "postgresql", "python", "sqlite"]
not_affected_if: ["fixed-column-names", "no-min-max-calls", "pre-0.9.9"]
published_at: "2026-02-23T22:12:17+00:00"
first_seen_at: "2026-11-16T15:48:11+00:00"
updated_at: "2026-11-16T16:08:50+00:00"
sources: [{"source": "ghsa", "url": "https://github.com/advisories/GHSA-xxh2-68g9-8jqr", "first_seen_at": "2026-11-16T15:48:11+00:00"}, {"source": "nvd", "url": "https://nvd.nist.gov/vuln/detail/CVE-2026-26198", "first_seen_at": "2026-11-16T16:08:50+00:00"}]
exploit_sources: [{"type": "epss", "score": 0.01013, "url": "https://api.first.org/data/v1/epss?cve=CVE-2026-26198"}]
---

# ormar is vulnerable to SQL Injection through aggregate functions min() and max()

Link for people: https://infrastack.ai/live/CVE-2026-26198 (this .md is for agents)

The ormar Python ORM passes the column name given to its min() and max() aggregate methods straight into raw SQL without validation. An attacker who can control that column name can run arbitrary subqueries and read any table in the database, including tables the API never exposes.

_Summary, check and fix written by a model from the sources; labelled as such._

## Affected

- pypi:ormar affected >= 0.9.9, < 0.23.0 fixed 0.23.0
- vendor:collerek ormar affected >= 0.9.9, < 0.23.0 fixed 0.23.0

## How to check

- Check the installed version with `pip show ormar` or `pip freeze | grep -i ormar`; versions from `0.9.9` up to but not including `0.23.0` are affected.
- Search the code for calls to `.min(` or `.max(` on an ormar QuerySet where the column argument comes from a request parameter.

## Fix

- `ormar` `0.23.0` (fixed version per the product data)

## Timeline

- 2026-11-16T15:48:11+00:00 ghsa https://github.com/advisories/GHSA-xxh2-68g9-8jqr
- 2026-11-16T16:08:50+00:00 nvd https://nvd.nist.gov/vuln/detail/CVE-2026-26198

## Documents

- [advisory] Maintainer's advisory: api.github.com https://api.github.com/repos/ormar-orm/ormar/security-advisories/GHSA-xxh2-68g9-8jqr
- [advisory] Maintainer's advisory: github.com https://github.com/collerek/ormar/security/advisories/GHSA-xxh2-68g9-8jqr
- [fix] Patch: github.com https://github.com/collerek/ormar/commit/a03bae14fe01358d3eaf7e319fcd5db2e4956b16
- [fix] Release: github.com https://github.com/collerek/ormar/releases/tag/0.23.0

## From the sources

# Report 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()`:

```python
#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:

```python
#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).
<h2>Start the vulnerable application</h2>
<ol>
<li>Install dependencies:</li>
</ol>
<pre><code class="language-bash">pip install ormar databases aiosqlite fastapi uvicorn httpx
</code></pre>
<ol>
<li>The vulnerable server (<code>poc_server.py</code>) is based on the <strong>official ormar FastAPI example</strong> (<a href="https://github.com/collerek/ormar/blob/master/examples/fastapi_quick_start.py">ormar/examples/fastapi_quick_start.py</a>). The only modification is the addition of a <code>/items/stats</code> endpoint — a common pattern for applications that provide aggregate statistics. This demonstrates that the vulnerability is easily triggered by natural API design.</li>
</ol>
<p>The server defines three models:</p>
<ul>
<li><code>Category</code> and <code>Item</code> — from the official ormar example (unchanged)</li>
<li><code>AdminUser</code> — simulates internal data (e.g., an admin_users table) that should NOT be accessible through the public API</li>
</ul>
<p>The vulnerable endpoint:</p>
<pre><code class="language-python"># 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=[&quot;year&quot;])
# See: &lt;https://collerek.github.io/ormar/queries/aggregations/&gt;

@app.get(&quot;/items/stats&quot;)
async def item_stats(
    metric: str = Query(&quot;max&quot;, description=&quot;max or min&quot;),
    column: str = Query(&quot;price&quot;, description=&quot;Column to aggregate&quot;),
):
    &quot;&quot;&quot;Return aggregate statistics for items.&quot;&quot;&quot;
    if metric == &quot;max&quot;:
        result = await Item.objects.max(column)
    elif metric == &quot;min&quot;:
        result = await Item.objects.min(column)
    else:
        return {&quot;error&quot;: &quot;Unsupported metric&quot;}
    return {&quot;metric&quot;: metric, &quot;column&quot;: column, &quot;result&quot;: result}
</code></pre>
<p>The database contains:</p>

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


<p>The <code>admin_users</code> table is <strong>NOT</strong> exposed via any API endpoint.</p>
<h2>The attack steps</h2>
<p>The PoC requires two terminals:</p>
<p><strong>Terminal 1</strong> — Start the vulnerable server:</p>
<pre><code class="language-bash">python poc_server.py
</code></pre>
<p><strong>Terminal 2</strong> — Run the attacker script:</p>
<pre><code class="language-bash">python poc_attacker.py
</code></pre>
<p>The attacker script (<code>poc_attacker.py</code>) sends HTTP requests to the running server. It has <strong>NO prior knowledge</strong> of the database schema — all information is discovered through the injection. The attacker executes 6 progressive attack stages through the single <code>/items/stats</code> endpoint.</p>
<h2>Principle of vulnerability exploitation</h2>
<h3>1. The attacker confirms injection by sending an arithmetic expression</h3>
<p>The attacker sends <code>GET /items/stats?metric=max&amp;column=1+1</code>. The data flow is:</p>
<pre><code>HTTP request: GET /items/stats?metric=max&amp;column=1+1
    ↓
item_stats(metric=&quot;max&quot;, column=&quot;1+1&quot;)                # poc_server.py
    ↓
Item.objects.max(&quot;1+1&quot;)                                # queryset.py:721
    ↓
_query_aggr_function(func_name=&quot;max&quot;, columns=[&quot;1+1&quot;]) # queryset.py:704
    ↓
SelectAction(select_str=&quot;1+1&quot;, model_cls=Item)          # select_action.py:22
    ↓
_split_value_into_parts(&quot;1+1&quot;)  →  self.field_name = &quot;1+1&quot;
    ↓
# min/max skip the is_numeric check (line 709 only checks sum/avg)
    ↓
get_text_clause()  →  sqlalchemy.text(&quot;1+1&quot;)            # select_action.py:43
    ↓
apply_func(sqlalchemy.func.max)  →  max(1+1)
</code></pre>
<p>Generated SQL:</p>
<pre><code class="language-sql">SELECT max(1+1) AS &quo

---

_Free to read, with fair use of about 60 pages a minute. For higher limits or API access: sales@infrastack.ai_
