<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: implementing-canary-file-detection
description: >-
  Deploy canary files (honeypot files) across network shares and endpoints
  to detect ransomware encryption in its earliest stages. Covers canary
  file placement strategies, monitoring with auditd/Sysmon, alerting
  pipelines, and integration with SIEM platforms for sub-minute detection
  of mass file encryption events.
domain: cybersecurity
subdomain: ransomware-defense
tags:
  - canary-files
  - honeypot
  - early-detection
  - file-integrity-monitoring
  - auditd
  - sysmon
  - ransomware-detection
  - tripwire
version: '1.0'
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1486"]
---

# Implementing Canary File Detection

## Overview

Canary files are decoy files strategically placed in directories where
ransomware will encounter them early during encryption. When a canary is
modified, renamed, or deleted, it triggers an immediate alert — often
providing detection within seconds of encryption starting, before
significant data loss occurs.

Design goal: detect encryption within 60 seconds of it starting on any
monitored endpoint or share.

## Prerequisites

| Tool | Purpose | Install |
|------|---------|---------|
| auditd | Linux file monitoring | `apt install auditd` |
| Sysmon | Windows file monitoring | `sysmon64 -i config.xml` |
| inotifywait | Linux real-time FS events | `apt install inotify-tools` |
| OSSEC/Wazuh | FIM agent | Platform agent install |
| PowerShell | Windows canary deploy | Built-in |

## Key Concepts

### Canary Placement Strategy

```
Placement rules (maximize early detection):
├── Name: starts with symbols to sort first (! # 0 _ ~)
│   Examples: !IMPORTANT_DOCS.xlsx, #Budget_2026.docx
├── Location: every monitored share root + 2 levels deep
├── Size: realistic (10KB-5MB) — not empty or suspiciously uniform
├── Types: .docx, .xlsx, .pdf, .pptx — targeted by all ransomware
├── Density: 3-5 canaries per share/volume root
├── Hidden attribute: NOT set — must be visible to encryption
└── Content: realistic dummy data (not random bytes)

Naming strategy (sort order exploitation):
├── ! prefix  → sorts before A-Z in most file systems
├── ~ prefix  → sorts after Z in many enumerators
├── 000_ prefix → numeric sort first
└── Mix: place at beginning AND end of sort order
```

### Detection Architecture

```
Canary File Modified/Renamed/Deleted
  ├── auditd rule fires (Linux) / Sysmon Event 11/23 (Windows)
  ├── Log forwarded to SIEM (< 5 seconds)
  ├── Correlation rule triggers (< 10 seconds)
  ├── Alert fires to SOC (< 30 seconds)
  └── Automated containment (< 60 seconds total)
      ├── EDR isolate endpoint
      ├── Disable user account
      └── Block network segment
```

## Workflow

### Step 1 — Deploy Canary Files (Linux)

```bash
#!/bin/bash
# deploy-canaries.sh — Place canary files across monitored paths
set -euo pipefail

CANARY_DIRS=("/srv/shares/finance" "/srv/shares/hr" "/srv/shares/engineering"
             "/data/projects" "/data/backups")
CANARY_MARKER="CANARY-$(hostname)-$(date +%s)"

for dir in "${CANARY_DIRS[@]}"; do
  [ -d "$dir" ] || continue

  # Create realistic-looking canary files
  dd if=/dev/urandom bs=1K count=50 2>/dev/null | \
    base64 > "$dir/!Budget_Report_2026.xlsx"
  echo "$CANARY_MARKER" >> "$dir/!Budget_Report_2026.xlsx"

  dd if=/dev/urandom bs=1K count=30 2>/dev/null | \
    base64 > "$dir/#Employee_Directory.docx"
  echo "$CANARY_MARKER" >> "$dir/#Employee_Directory.docx"

  dd if=/dev/urandom bs=1K count=80 2>/dev/null | \
    base64 > "$dir/~Quarterly_Financials.pdf"
  echo "$CANARY_MARKER" >> "$dir/~Quarterly_Financials.pdf"

  # Set permissions (readable but track access)
  chmod 644 "$dir"/{"!Budget_Report_2026.xlsx","#Employee_Directory.docx","~Quarterly_Financials.pdf"}
done
```

### Step 2 — Configure auditd Monitoring (Linux)

```bash
# /etc/audit/rules.d/canary-files.rules
# Monitor canary files for any modification
-w /srv/shares/finance/!Budget_Report_2026.xlsx -p wa -k canary_triggered
-w /srv/shares/finance/#Employee_Directory.docx -p wa -k canary_triggered
-w /srv/shares/finance/~Quarterly_Financials.pdf -p wa -k canary_triggered
-w /srv/shares/hr/!Budget_Report_2026.xlsx -p wa -k canary_triggered
-w /srv/shares/hr/#Employee_Directory.docx -p wa -k canary_triggered

# Reload audit rules
auditctl -R /etc/audit/rules.d/canary-files.rules

# Verify rules loaded
auditctl -l | grep canary
```

### Step 3 — Real-Time Detection with inotifywait

```bash
#!/bin/bash
# canary-monitor.sh — Real-time canary file monitoring daemon
CANARY_PATTERN="!Budget_Report|#Employee_Directory|~Quarterly_Financials"
ALERT_WEBHOOK="https://hooks.slack.com/services/TEAM/CHANNEL/TOKEN"
WATCH_DIRS="/srv/shares /data"

inotifywait -m -r --format '%T %w%f %e' --timefmt '%FT%T' \
  -e modify -e delete -e moved_from -e moved_to \
  $WATCH_DIRS 2>/dev/null | while read -r timestamp filepath event; do

  if echo "$filepath" | grep -qE "$CANARY_PATTERN"; then
    ALERT="{\"text\":\"🚨 RANSOMWARE CANARY TRIGGERED\\nFile: $filepath\\nEvent: $event\\nTime: $timestamp\\nHost: $(hostname)\"}"

    # Alert via webhook
    curl -s -X POST "$ALERT_WEBHOOK" \
      -H 'Content-type: application/json' -d "$ALERT"

    # Log locally
    logger -p auth.crit "CANARY_TRIGGERED: $filepath $event"
  fi
done
```

### Step 4 — Deploy Canary Files (Windows)

```powershell
# Deploy-CanaryFiles.ps1
$shares = Get-SmbShare | Where-Object { $_.ShareType -eq 'FileSystemDirectory' }
$canaryContent = [byte[]](1..50000 | ForEach-Object { Get-Random -Max 256 })

foreach ($share in $shares) {
    $path = $share.Path
    if (-not (Test-Path $path)) { continue }

    $files = @(
        "!Important_Contracts_2026.docx",
        "#Budget_Forecast_Q2.xlsx",
        "~Executive_Summary.pdf"
    )
    foreach ($file in $files) {
        $fullPath = Join-Path $path $file
        [System.IO.File]::WriteAllBytes($fullPath, $canaryContent)
        # Set audit ACL
        $acl = Get-Acl $fullPath
        $rule = New-Object System.Security.AccessControl.FileSystemAuditRule(
            "Everyone", "Write,Delete", "Success,Failure")
        $acl.AddAuditRule($rule)
        Set-Acl $fullPath $acl
    }
}
```

### Step 5 — Sysmon Configuration for Canary Monitoring

```xml
<Sysmon schemaversion="4.90">
  <EventFiltering>
    <!-- File creation/modification of canary files -->
    <FileCreate onmatch="include">
      <TargetFilename condition="contains any">!Budget_Report;#Employee_Directory;~Quarterly_Financials;!Important_Contracts;#Budget_Forecast;~Executive_Summary</TargetFilename>
    </FileCreate>
    <FileDelete onmatch="include">
      <TargetFilename condition="contains any">!Budget_Report;#Employee_Directory;~Quarterly_Financials</TargetFilename>
    </FileDelete>
  </EventFiltering>
</Sysmon>
```

### Step 6 — SIEM Correlation Rule

```yaml
# Sigma: Canary File Modification Detected
title: Ransomware Canary File Triggered
id: e5a3f8b2-4c1d-4e9a-a7b6-3d2c1f8e5a4b
status: stable
description: Detects modification or deletion of planted canary files
logsource:
  category: file_change
  product: windows
detection:
  selection:
    TargetFilename|contains:
      - '!Budget_Report'
      - '#Employee_Directory'
      - '~Quarterly_Financials'
      - '!Important_Contracts'
  condition: selection
falsepositives:
  - User accidentally editing canary file (restrict write access)
level: critical
tags:
  - attack.impact
  - attack.t1486
```

## Verification

- [ ] Canary files deployed to all monitored shares and volumes
- [ ] auditd/Sysmon rules active and generating events on canary access
- [ ] Real-time monitoring daemon running and alerting
- [ ] SIEM correlation rule tested with simulated canary modification
- [ ] End-to-end detection time measured (target: < 60 seconds)
- [ ] Automated containment response tested
- [ ] Canary files not discoverable by naming pattern analysis

## References

- MITRE ATT&CK T1486: Data Encrypted for Impact
- NIST SP 800-83: Guide to Malware Incident Prevention
- CIS Control 8: Audit Log Management
- Thinkst Canary: https://canary.tools (commercial canary platform)
