/

CVE-2026-26198

Severity:

CRITICAL RISK

(9.8)

SQL Injection in Ormar Aggregate Query Helpers (min/max)

CVE-2026-26198

Analyzed

Vulnerability type

Category:

SQL Injection

CWE:

CWE-89

Impact:

Arbitrary SQL Execution and Data Exfiltration

Severity:

CRITICAL RISK

(9.8)

CVSS version:

3.1

Catch this CVE while code is being written

Detect vulnerable code directly in pull requests, so CVEs are fixed before merge.

Summary

Ormar ORM versions 0.9.9 through 0.22.0 contain an SQL injection flaw in aggregate query helpers that build SQL using unvalidated, user-supplied column names with sqlalchemy.text().

Attackers who can influence the min() or max() column parameter can inject arbitrary SQL, potentially reading all database tables and bypassing model-level data boundaries.

Affected context

This vulnerability affects applications using Ormar (0.9.9–0.22.0) where:

  • Aggregate methods min() and max() are exposed directly or indirectly to user-controlled input (e.g., API query parameters, request bodies, filters).
  • The underlying database engine is accessed via SQLAlchemy, and Ormar composes SQL expressions with sqlalchemy.text().
  • Application logic assumes that aggregate helpers respect model boundaries and cannot query outside the associated table.

In such settings, any path that allows untrusted strings to reach the column parameter of these methods can become an SQL injection entry point.

Exploit preconditions

  • Attack surface: Application endpoints, services, or internal APIs that call QuerySet.min() or QuerySet.max() with a column name influenced by external input.
  • Required access: Ability to send crafted requests to the application (typically unauthenticated or low-privilege, depending on how aggregates are exposed).
  • Trigger point: Invocation of min(<attacker-controlled-string>) or max(<attacker-controlled-string>) on an Ormar queryset, which is translated into a raw SQL expression via sqlalchemy.text().
  • Why exploitation is possible: The column argument is interpolated directly into a textual SQL fragment without:
  • Name validation against the model fields, or
  • Proper parameterization/escaping.

This gives the attacker direct control over part of the SQL query structure and allows injection of subqueries or other SQL constructs.

Why this happens

The core issue is a direct instance of CWE-89: SQL Injection caused by dynamic query construction with untrusted data.

Ormar's QuerySet.min() and QuerySet.max() methods accept arbitrary strings as the column parameter and then embed this value into a sqlalchemy.text() call. Unlike sum() and avg(), which perform an is_numeric check to constrain the field, these methods do not verify that the column name:

  • Corresponds to a valid model attribute, or
  • Conforms to a safe identifier pattern.

By treating the user-supplied string as SQL instead of as data, the ORM blurs the boundary between query code and parameters, allowing the injected text to alter the query's semantics. This is the classic insecure pattern: constructing SQL from concatenated or interpolated user input instead of using parameterized queries and strict schema-based validation.

Potential impact

  • Attackers could read arbitrary data from other tables not associated with the queried model.
  • Application-level authorization boundaries could be bypassed by issuing injected subqueries.
  • Sensitive information such as user records, credentials (e.g., password hashes), tokens, or configuration values could be exfiltrated.
  • Business logic assumptions about "per-model" data access may be invalidated, impacting multi-tenant isolation or data partitioning strategies.
  • In some database environments, additional SQL injection primitives (e.g., union-based queries or stacked queries where allowed) could further escalate impact.

General mitigation guidance

Effective mitigation focuses on eliminating dynamic SQL construction from user-controlled input and enforcing strict schema-based constraints on aggregate operations:

  • Avoid passing raw strings into SQL builders:
  • Replace sqlalchemy.text() usage for column names with ORM-level column objects or whitelisted field descriptors.
  • Treat all user-originated values as parameters, never as query fragments.
  • Enforce strict column validation:
  • Restrict min() and max() to accept only:
  • Attribute references defined on the model, or
  • Predefined, whitelisted aggregate targets.
  • Reject or ignore any column parameter that does not map to a known model field.
  • Apply least-privilege at the data layer:
  • Use database roles that limit what the application account can read, ensuring that even if a query is manipulated, it cannot access unnecessary tables or schemas.
  • Segment especially sensitive tables into separate schemas or databases with stronger access controls.
  • Defensive application design:
  • Avoid designing APIs where clients can specify raw field or expression names for aggregates.
  • When flexibility is needed, provide a controlled vocabulary (e.g., "created_at", "price") mapped internally to safe fields.
  • Secure-by-default ORM patterns:
  • Prefer higher-level ORM query constructs over raw textual SQL whenever possible.
  • Establish coding guidelines that forbid unchecked text() calls or similar dynamic query construction in application and library code.

How teams detect issues like this

Organizations can identify and monitor for this vulnerability class using a combination of static, review-based, and runtime controls:

  • Static analysis and code scanning:
  • Search for uses of sqlalchemy.text() or other raw SQL entry points where any part of the argument is derived from non-constant input.
  • Configure SAST tools with rules specific to dynamic SQL construction (e.g., string concatenation or f-strings used to assemble queries).
  • Targeted code review:
  • Examine ORM helper methods that accept "field", "column", or "expression" strings, ensuring they:
  • Validate against model metadata.
  • Use parameter binding rather than direct interpolation.
  • Flag any logic that forwards request parameters directly into aggregate or filter functions without normalization.
  • Policy and linting rules:
  • Introduce linting or custom CI checks that:
  • Ban or require justification for sqlalchemy.text() and equivalent raw SQL interfaces.
  • Enforce usage of safe wrapper functions and centralized query helpers.
  • Runtime monitoring and logging:
  • Enable query logging to detect suspicious patterns (e.g., unexpected subqueries or references to unrelated tables in otherwise simple aggregate calls).
  • Use database activity monitoring to alert on anomalous cross-table reads or sudden spikes in exploratory queries.

Sources

SourceLink
github.comgithub.com/collerek/ormar/commit/a03bae14fe01358d3eaf7e319fcd5db2e4956b16
github.comgithub.com/collerek/ormar/releases/tag/0.23.0
github.comgithub.com/collerek/ormar/security/advisories/GHSA-xxh2-68g9-8jqr

Frequently asked

questions

Yes, if an application exposes endpoints that accept user input and pass it—directly or indirectly—into min() or max() as the column parameter. In typical web APIs, this makes the issue remotely exploitable whenever those paths are reachable.

Not inherently. Authentication requirements depend on how the application routes are configured. If aggregate endpoints are public or weakly protected, unauthenticated attackers could exploit the flaw; if they require login, only authenticated users with access to those routes can attempt exploitation.

The most robust fix is to remove any dynamic SQL built from raw strings and restrict aggregates to validated model fields. That usually means:

  • Mapping caller-specified field identifiers to known model attributes.
  • Using ORM column objects or parameterized constructs instead of sqlalchemy.text() for column names.
  • Rejecting any field value that does not resolve to a safe, whitelisted attribute.

Preventive strategies include:

  • Adopting a strict rule that untrusted input must never influence SQL structure—only parameter values.
  • Centralizing query construction in vetted helper modules instead of scattering raw SQL across the codebase.
  • Using automated checks to detect new uses of raw SQL APIs, and requiring security review for any exceptions.
  • Educating developers about ORM-safe patterns and the risks of treating user input as part of query logic.
Find out what's already
exploitable in your codebase.