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()andmax()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()orQuerySet.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>)ormax(<attacker-controlled-string>)on an Ormar queryset, which is translated into a raw SQL expression viasqlalchemy.text(). - Why exploitation is possible: The
columnargument 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()andmax()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.

