Why ORMs and Prepared Statements Can't (Always) Win
The Soko package search feature built SQL queries by concatenating user input into ORM query builder calls, leading to SQL injection. An attacker could exploit this to read the PostgreSQL version and, because the database user was a superuser, execute arbitrary commands on the server.
Published on sonarsource.com
We were told to use ORMs and prepared statements to avoid SQL injections for a long time now. By doing so, we effectively separate instructions (the semantics of the SQL query) from the data.
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Not written yet. The AI write-up for this write-up has not been written yet. The Original tab links to the source.
How it worked
Root cause
The application concatenated user-controlled input into the first argument of ORM query builder methods (OrderExpr and Where), which is meant to be a constant string with placeholders, so the input was not escaped.
Impact
An attacker could read the PostgreSQL version and, because the database user was a superuser, execute arbitrary commands on the server; however, the service only displays package information, so a supply chain attack was not possible and users were not at risk.
What the attacker needed
Access to the Soko search feature; no authentication required
The fix
The maintainers refactored the query builder calls to pass the query builder object and use constant strings with placeholders, so user input is properly escaped.
How it was found
- Send a search request containing a single quote to break the SQL syntax and confirm an error.
- Craft a payload that closes the string and WHERE clause, adds a UNION SELECT with matching column types, and comments out the rest.
- Use the payload in the search field to retrieve the PostgreSQL version in the results.
- Use stacked queries to execute additional SQL statements, such as COPY FROM PROGRAM, to run arbitrary commands on the server.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this write-up has not been written yet. The Original tab links to the source.
SQL injection is when user input is inserted into a database query without proper separation, letting an attacker change the query's meaning. Here, the developers used an ORM (a library that builds queries) but still pasted the search term directly into parts of the query, so the protection was bypassed. The database also ran with too many privileges, so the attacker could run system commands.
What is SQL injection?
Input reaches a database query as code, letting an attacker read or change data the application never meant to expose.