Varol Cagdas Tok

Personal notes and articles.

Error-Based SQL Injection

Error-based SQL injection is a data extraction technique that works by constructing queries that cause the database to embed query results inside an error message. The error message travels back to the attacker through the application's error response. It requires that the application return database error text to the client, either directly or through a mechanism where errors are logged and accessible.


Why Errors Contain Data

Database engines generate errors when a type conversion or operation fails, and some of those error messages include the value that caused the failure. If an attacker controls the value inside a failing expression, they can arrange for data retrieved from the database to be that value, causing it to appear in the error text.

In MySQL, the EXTRACTVALUE() function raises an error when its XPath argument is invalid, and the error message includes the XPath string that caused the error. By constructing an XPath argument that concatenates a valid-but-invalid-XPath prefix with a subquery result, the subquery output appears in the error:

EXTRACTVALUE(1, CONCAT(0x7e, (SELECT version())))

This raises an error containing the database version string. The 0x7e is the tilde character, which makes the XPath invalid while clearly delimiting the data in the error output. The same pattern works with UPDATEXML().


SQL Server: Converting Types to Force Errors

SQL Server's CONVERT() and implicit casting will raise an error when a non-numeric string is converted to an integer. The error includes the string value. An injected expression that converts a subquery result to an integer forces the result into an error message:

CONVERT(int, (SELECT TOP 1 table_name FROM information_schema.tables))

SQL Server's error text reads: Conversion failed when converting the nvarchar value 'users' to data type int. The table name is returned directly in the error.


PostgreSQL: Division and Casting

PostgreSQL does not include arbitrary data in most arithmetic errors, but the CAST() function and certain aggregate functions can be coerced into error messages. The more common PostgreSQL out-of-band channel is the || concatenation operator combined with intentional type mismatches in subqueries passed to functions expecting specific types.


The Precondition: Visible Errors

Error-based extraction requires that database error messages reach the attacker. Applications that suppress all database errors and return a generic response prevent this technique. The error does not need to be shown in the browser; if errors are written to a log that the attacker can read (a world-readable log file, a logging endpoint, an email report), the channel still exists.

When errors are not visible, the technique falls back to blind SQL injection, which infers data without requiring error output.