Pentest Journeys
Connect
  • Welcome!
  • Boxes
    • Categories
    • Starting Point
      • Unified
      • Three
    • Easy
      • Forest
      • Sauna
      • Active
      • Broker
      • Return
      • Timelapse
      • Support
      • Nibbles
      • Keeper
      • CozyHosting
      • Devvortex
      • Lame
      • FunBoxEasyEnum
      • Inclusiveness
      • Potato
      • Sumo
    • Medium
      • Resolute
      • Cascade
      • Monteverde
      • Intelligence
      • StreamIO
      • Loly
    • Hard
      • Mantis
      • Blackfield
      • Reel
    • Insane
      • Sizzle
      • Multimaster
      • Rebound
  • Cloud
    • Public Snapshots
  • TL;DR
    • Active Directory
      • AD Authentication
      • Access Controls
      • Recon
      • Groups
        • Account Operators
        • Backup Operators
        • DnsAdmins
        • Exchange Windows Permissions
        • Server Operators
      • Privileges
        • SeBackupPrivilege
        • SeImpersonatePrivilege
      • Permissions
        • AddSelf
        • DCSync
        • ForceChangePassword
        • FullControl
        • GenericAll
        • GenericWrite
        • Owns
        • ReadGMSAPassword
        • ReadLAPSPassword
        • WriteDACL
        • WriteOwner
      • Attacks
        • Password Spraying
        • ASREPRoasting
        • Kerberoasting
        • Silver Tickets
        • DCSync
        • Delegation
          • Unconstrained
          • Constrained
          • Resource-Based
        • Local SAM Dump
        • NTLMv2
        • Services
        • Scheduled Tasks
        • Exploits
      • Lateral Movement
        • WMI & WinRM
        • PsExec
        • Pass-the-Hash
        • Overpass-the-Hash
        • Pass-the-Ticket
        • DCOM
        • SSP Injection
      • Persistence
        • Golden Ticket
        • Shadow Copies
    • Web
      • Common Findings
        • Security Headers
        • Cookie Flags
        • SSL/TLS
      • Authentication
        • Broken Reset Logic
        • Brute Force Attacks
        • Rate Limiting
        • Session Tokens
        • MFA
        • JWTs
      • Authorization
        • IDOR / BOLA
        • IDOR / BFLA
        • Weak Access Controls
        • Automated A-B Testing
      • Injections
        • SQLi
          • SQLi 101
          • In Band
          • Blind
          • NoSQLi
          • Second Order
          • Other
        • XSS
          • XSS 101
          • Reflected
          • Stored
          • DOM-Based
          • Exploitation
          • Payloads
        • CI
          • CI
          • Filters
          • Examples
        • SSTI
          • SSTI 101
          • Twig
          • Freemarker
          • Pug
          • Jinja
          • Mustache
          • Handlebars
          • Mako
          • Case Study: Craft CMS
        • XXEI
          • XML 101
          • XXEI
      • File Inclusion
        • LFI & RFI
        • RCE
      • Cross-Origin
        • Cross-Origin 101
        • CSRF
        • CORS
      • File Uploads
      • Mass Assignment
      • WebSockets
      • Open Redirects
      • Race Conditions
      • SSRF
        • Exploitation
        • Examples
    • API
      • What is an API?
      • Useful Terms
      • Collection Creation
      • Enumeration
      • Tests
        • General
        • Security Misconfigurations
        • Authorization
          • BOLA
          • BFLA
        • Authentication
          • BFAs
          • Tokens
          • JWTs
            • Entropy Analysis
            • Signature Validation
            • Weak Signature
            • Header Injection
            • Algorithm Confusion
        • Excessive Data Exposure
        • HTTP Verb Tampering
        • Content Type Tampering
        • Improper Asset Management
        • Mass Assignment
        • SSRF
        • Unrestriced Resource Consumption
        • Unrestricted Access to Sensitive Business Flows
        • Unsafe API Consumption
    • Infra
      • Windows
      • Linux
      • FreeBSD
    • Pivoting
      • Networking 101
      • Port Foward
      • SSH Tunelling
      • Deep Packet Inspection
        • HTTP Tunneling
        • DNS Tunneling
    • Social Engineering
      • Phising
    • Cloud
      • AWS
        • Recon
    • Code Review
  • Tools
    • Web
      • Web Checklist
      • API
        • mitmweb
        • KiteRunner
        • Arjun
        • jwt_tool
      • Dirbusting
        • Fuff
        • Dirsearch
        • GoBuster
        • Wfuzz
      • Cloud
        • AWS
      • cURL
      • Hydra
      • Hakrawler
      • amass
      • WAFs
      • WhatWeb
      • Creds
      • SQLMap
      • GoWitness
      • Web Servers
        • Apache
        • Nginx
        • IIS
      • Frameworks
        • Spring
      • CMS
        • WordPress
        • Joomla
        • DNN
        • Umbraco
        • RiteCMS
      • DevOps
        • GitLab
        • Git Tools
      • BurpSuite
    • Infra
      • pspy
    • Port Scanners
      • Nmap
      • Rustscan
      • Arp-Scan
      • Netcat
      • PowerShell
    • Active Directory
      • netexec
      • impacket
      • mimikatz
      • Hounds
      • PowerView
      • SysInternals
      • net.exe
      • ldapsearch
      • BloodyAD
      • PowerView.py
      • Rubeus
      • DPAT
      • PingCastle
      • PowerUp
      • runas
      • Kerbrute
    • Passwords
      • HashID
      • Hashcat
      • John
      • DomainPasswordSpray
      • Credential Enum
    • Searchsploit
    • Metasploit
      • 101
      • Payloads
      • Post-Exploitation
      • Resource Scripts
    • Usernames
    • Vulnerability Scanners
      • Nuclei
      • Nikto
    • Text
      • jq
      • grep
      • awk
      • sed
      • tr
      • printf
    • Output
      • tee
    • Pivoting
      • Ligolo-ng
      • Sshuttle
    • Shells
      • Reverse Shells
      • Webshells
      • Upgrade
      • Listeners
        • Socat
        • Pwncat
        • Nc
    • Traffic Capture
    • File Transfers
    • Crypto
    • Files
    • Images
    • Evil-WinRM
    • KeePass
    • Random Scripts
  • Services
    • TCP
      • Remote Access
        • SSH (22)
        • RDP (3389)
        • WinRM (5985,5986)
      • Shares
        • FTP (21)
        • NFS (111, 2049)
        • SMB (139, 445)
      • LDAP (389, 636)
      • DNS (53)
      • SMTP (25,587)
      • DISTCC (3632)
      • AFS (1978)
      • DBMS
        • SQL
          • MSSQL (1433)
          • Oracle (1521)
          • MySQL (3306)
          • MariaDB (3306)
          • PostgreSQL (5432)
        • NoSQL
          • Aerospike (3000-3005)
          • MongoDB (27017)
    • UDP
      • SNMP (161)
  • OTHER
    • Exploits
      • Screen
    • CLIs
      • CMD
      • PowerShell
  • Package Managers
    • vevn
    • uv
  • Blue Team Stuff
    • Logs
      • System Logs
      • Apache2
      • Volatile Data
    • Traffic Analysis
      • Wireshark
Powered by GitBook
On this page
  • Educated Guesses
  • SQLi Types
  • Detection
  • String Delimiters
  • Closing Out Strings and Functions
  • Boundary Testing
  • Fuzzing
  • Prevention
  • Parameterized Queries
  • Prepared Statements

Was this helpful?

  1. TL;DR
  2. Web
  3. Injections
  4. SQLi

SQLi 101

PreviousSQLiNextIn Band

Last updated 9 months ago

Was this helpful?

SQL injection (SQLi) is a vulnerability where an attacker can manipulate a web application's database queries by injecting malicious SQL code through user inputs.

This can lead to unauthorized data access, data corruption, deletion of data, and potentially complete control over the database server.

Use and , validate and sanitize user inputs, and employ ORM (Object-Relational Mapping) frameworks to abstract database operations.

Educated Guesses

If we know the web server, we might infer what database is in use.

Web Server
Database
Db-specific SQLi

IIS

MSSQL

Apache/Nginx

MySQL

SQLi Types

Alex Olsen's Blind SQLi .

Detection

We can enumerate SQLi flaws via sending manual payloads, searching for dynamic SQL statements during a code review and/or fuzzing the request. The most common method for enumerating a SQLi flaw is to identify input fields that might be used in a database and submit characters that will break SQL queries. This might lead to verbose error messages or subtle differences in responses.

String Delimiters

Suppose we control an input field that asks for the parameter name. If our input is x7331 the query may look like this:

// normal query when the input is x7331
SELECT * FROM users WHERE name = 'x7331'

If our input is x7331' OR '1'='1 the query becomes:

// malicious query when the input is x7331' OR '1'='1
SELECT * FROM users WHERE name = 'x7331' OR '1'='1'
Payload
URL Encoded

'

%27

"

%22

#

%23

;

%3B

)

%29

We can also fuzz for pontially banned characters.

ffuf -k -u https://watch.streamio.htb/search.php -d 'q=FUZZ' -w /usr/share/seclists/Fuzzing/special-chars.txt -c -ic -ac -H 'Content-Type: application/x-www-form-urlencoded'

Closing Out Strings and Functions

There are various common functions used for string comparison, such as LOWER() and UPPER() to ensure consistency.

SELECT * FROM users WHERE LOWER(name) = LOWER('<userInput>');

In this case, the function should be closed out.

// injected payload
x7331') OR '1'='1
// resulting query
SELECT * FROM users WHERE LOWER(name) = LOWER('x7331') OR '1'='1')

We end up with a hanging ) at the end, thus, we will need to comment out whatever comes after our payload.

// injected payload
x7331') OR '1'='1'#
// resulting query
SELECT * FROM users WHERE LOWER(name) = LOWER('x7331') OR '1'='1'#)

Boundary Testing

Fuzzing

Prevention

Parameterized Queries

  1. Separation of SQL and Data: When you use a parameterized query, the SQL statement and the data are sent to the database as separate entities. The SQL statement is pre-compiled by the database, and the placeholders (?, %s, :value, etc.) are used to specify where the parameters will be substituted.

  2. Safe Binding: The database engine safely binds the user-provided input values to the placeholders. This means that the user input cannot alter the SQL command structure. Instead, it is strictly treated as data.

Here’s how an SQLi might happen with a normal query.

# Normal query with user input directly concatenated
user_id = "'; DROP TABLE users; --"
query = f"SELECT * FROM users WHERE id = '{user_id}'"
// resulting query
SELECT * FROM users WHERE id = ''; DROP TABLE users; --'

Here's how a parameterized query handles this.

# Parameterized query with user input
user_id = "'; DROP TABLE users; --"
query = "SELECT * FROM users WHERE id = %s"
cursor.execute(query, (user_id,))
// resulting query
SELECT * FROM users WHERE id = '''; DROP TABLE users; --'

Prepared Statements

Parameterized queries and prepared statements offer the same level of protection against SQLi. They both achieve the same goal of separating SQL logic from user input. However, prepared statements might be more explicitly linked to performance optimization through the process of compiling and reusing the SQL command.

# Prepared statement with user input
user_id = input("Enter the user ID: ")  # User enters: 1; DROP TABLE users;
query = "SELECT * FROM users WHERE id = %s"
cursor.execute(query, (user_id,))
// resulting query
SELECT * FROM users WHERE id = '1; DROP TABLE users;'

For MSSQL-specific SQLi info see .

For MySQL-specific SQLi info see .

is common software testing technique based on testing the boundary values of valid and invalid partitions. The behavior at the edge of the equivalence partition is more likely to be incorrect than the behavior within the partition, so boundaries are an area where testing is likely to yield defects.

Boundary testing within a SQLi context refers finding a parameter that takes a limited data set and submitting values that fall outside that set. One form of SQLi boundary testing is .

Automated tools, such as or Burp's Intruder, can be used to fuzz the suspected parameters with SQLi payloads and then assess the application's responses. The results of automated tools must always be validated manually.

Boundary Value Analysis
ffuf
payload examples
prepared statements
parameterized queries
using the ORDER BY clause to enumerate the number of columns displayed in a SQL statement
here
here
Figure 1: SQL Injection types (imaged adapted from ).
here