ransomware defense

Implementing Honeypot for Ransomware Detection

Deploys canary files, honeypot shares, and decoy systems to detect ransomware activity at the earliest possible stage. Configures canary tokens embedded in strategic file locations that trigger alerts when ransomware attempts encryption, uses honeypot network shares that mimic high-value targets, and deploys Thinkst Canary appliances for comprehensive deception-based detection. Activates for requests involving ransomware honeypots, canary files, deception technology for ransomware, or early ransomware alerting.

canarydeceptiondefensedetectionhoneypotransomware
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

When to Use

  • Deploying early-warning detection for ransomware encryption attempts using canary files
  • Creating honeypot file shares that detect lateral movement and data staging before encryption
  • Supplementing EDR and SIEM-based detection with deception-layer alerts that have near-zero false positives
  • Detecting ransomware variants that evade signature-based detection by triggering on file modification behavior
  • Validating that ransomware detection capabilities work by testing with controlled encryption tools

Do not use as the sole ransomware detection mechanism. Honeypots are a high-confidence supplementary layer, not a replacement for EDR, network monitoring, and backup protection.

Prerequisites

  • File server or NAS infrastructure where canary files can be deployed
  • Windows File Server Resource Manager (FSRM) or equivalent file activity monitoring
  • Thinkst Canary or similar deception platform (optional, for advanced deployment)
  • SIEM platform for centralizing honeypot alerts
  • Administrative access to deploy canary files across file shares
  • Network segment for honeypot systems (if deploying full honeypot servers)

Workflow

Step 1: Deploy Canary Files on File Shares

Place canary files in strategic locations that ransomware will encounter during encryption:

# Deploy canary files across all file shares
# Files are named to appear early in alphabetical and directory order
# Ransomware typically encrypts alphabetically or by directory traversal
 
$shares = @("\\fileserver01\finance", "\\fileserver01\hr", "\\fileserver01\engineering")
$canaryNames = @(
    "!_IMPORTANT_DO_NOT_DELETE.docx",
    "000_Budget_2026_FINAL.xlsx",
    "_Confidential_Employee_Records.pdf",
    "AAAA_Quarterly_Report.docx"
)
 
foreach ($share in $shares) {
    foreach ($name in $canaryNames) {
        $targetPath = Join-Path $share $name
        # Create a legitimate-looking file with canary content
        # The file contains a unique token that triggers on access
        $content = "This document contains confidential financial data.`n"
        $content += "Q4 2025 Revenue: $42.3M | Q1 2026 Forecast: $45.1M`n"
        $content += "Prepared by: Finance Department`n"
        Set-Content -Path $targetPath -Value $content
        # Set file as hidden system to avoid user interaction
        $file = Get-Item $targetPath
        $file.Attributes = [System.IO.FileAttributes]::Hidden
    }
}
 
# Also deploy in subdirectories (ransomware traverses recursively)
$subDirs = Get-ChildItem -Path "\\fileserver01\finance" -Directory -Recurse | Select-Object -First 20
foreach ($dir in $subDirs) {
    $canaryPath = Join-Path $dir.FullName "!_Budget_Summary.xlsx"
    Set-Content -Path $canaryPath -Value "Canary file for ransomware detection"
    (Get-Item $canaryPath).Attributes = [System.IO.FileAttributes]::Hidden
}

Step 2: Configure File Integrity Monitoring on Canary Files

Windows FSRM approach:

# Configure FSRM to monitor for ransomware file extensions
# and canary file modifications
 
Install-WindowsFeature -Name FS-Resource-Manager -IncludeManagementTools
 
# Create file screen for known ransomware extensions
$ransomExtensions = @(
    "*.encrypted", "*.locked", "*.crypto", "*.crypt",
    "*.locky", "*.cerber", "*.zepto", "*.thor",
    "*.aesir", "*.zzzzz", "*.wallet", "*.onion",
    "*.wncry", "*.wcry", "*.lockbit", "*.BlackCat",
    "*.ALPHV", "*.rhysida", "*.play"
)
 
# Create file group for ransomware extensions
New-FsrmFileGroup -Name "Ransomware_Extensions" -IncludePattern $ransomExtensions
 
# Create file screen template
New-FsrmFileScreenTemplate -Name "Ransomware_Screen" `
    -IncludeGroup "Ransomware_Extensions" `
    -Active:$false  # Passive mode: alert without blocking
 
# Apply to all monitored shares
$monitoredPaths = @("D:\Shares\Finance", "D:\Shares\HR", "D:\Shares\Engineering")
foreach ($path in $monitoredPaths) {
    New-FsrmFileScreen -Path $path -Template "Ransomware_Screen"
}

Canary file modification monitoring with PowerShell FileSystemWatcher:

# Real-time canary file monitoring service
$canaryPaths = @(
    "D:\Shares\Finance\!_IMPORTANT_DO_NOT_DELETE.docx",
    "D:\Shares\HR\000_Budget_2026_FINAL.xlsx",
    "D:\Shares\Engineering\_Confidential_Employee_Records.pdf"
)
 
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "D:\Shares"
$watcher.Filter = "*"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
 
$action = {
    $path = $Event.SourceEventArgs.FullPath
    $changeType = $Event.SourceEventArgs.ChangeType
    $timestamp = $Event.TimeGenerated
 
    # Check if modified file is a canary
    $isCanary = $false
    foreach ($canary in $canaryPaths) {
        if ($path -eq $canary) { $isCanary = $true; break }
    }
 
    if ($isCanary -or $changeType -eq "Renamed") {
        $alertMsg = "RANSOMWARE ALERT: Canary file modified! Path: $path | Change: $changeType | Time: $timestamp"
        # Log to Windows Event Log
        Write-EventLog -LogName Application -Source "RansomwareCanary" `
            -EventID 9999 -EntryType Error -Message $alertMsg
        # Send SIEM alert via syslog
        # Trigger automated containment
    }
}
 
Register-ObjectEvent $watcher "Changed" -Action $action
Register-ObjectEvent $watcher "Deleted" -Action $action
Register-ObjectEvent $watcher "Renamed" -Action $action

Step 3: Deploy Honeypot Network Shares

Create decoy file shares that appear to contain high-value data:

# Create honeypot share on dedicated server
# This server monitors ALL file access and alerts on any activity
 
New-Item -Path "D:\HoneypotShares\Executive_Compensation" -ItemType Directory
New-Item -Path "D:\HoneypotShares\M&A_Documents" -ItemType Directory
New-Item -Path "D:\HoneypotShares\Board_Meeting_Notes" -ItemType Directory
New-Item -Path "D:\HoneypotShares\Customer_Database_Exports" -ItemType Directory
 
# Share with broad read access (enticing to attackers)
New-SmbShare -Name "Executive_Compensation" `
    -Path "D:\HoneypotShares\Executive_Compensation" `
    -FullAccess "DOMAIN\Domain Users" `
    -Description "Executive Compensation Files - Restricted"
 
# Populate with realistic-looking but fake documents
# Use document templates that look legitimate
$docContent = @"
CONFIDENTIAL - Executive Compensation Summary
FY 2026 Base Salary and Bonus Structures
CEO: [REDACTED] | CFO: [REDACTED] | CTO: [REDACTED]
Total Compensation Package: See Appendix A
"@
Set-Content -Path "D:\HoneypotShares\Executive_Compensation\FY2026_Comp_Summary.txt" -Value $docContent
 
# Enable detailed audit logging on honeypot share
$acl = Get-Acl "D:\HoneypotShares"
$auditRule = New-Object System.Security.AccessControl.FileSystemAuditRule(
    "Everyone", "ReadAndExecute,Write,Delete", "ContainerInherit,ObjectInherit",
    "None", "Success,Failure"
)
$acl.AddAuditRule($auditRule)
Set-Acl "D:\HoneypotShares" $acl
 
# Enable object access auditing via GPO
auditpol /set /subcategory:"File System" /success:enable /failure:enable

Step 4: Deploy Thinkst Canary Tokens

For organizations using Thinkst Canary or the free canarytokens.org service:

# Generate canary tokens via API (Thinkst Canary)
# These trigger alerts when documents are opened or URLs are accessed
 
# Word document token
curl -X POST "https://CONSOLE.canary.tools/api/v1/canarytoken/create" \
  -d "auth_token=YOUR_API_TOKEN" \
  -d "memo=Finance_Share_Canary" \
  -d "kind=doc-msword" \
  -o /tmp/canary_budget_report.docx
 
# PDF document token
curl -X POST "https://CONSOLE.canary.tools/api/v1/canarytoken/create" \
  -d "auth_token=YOUR_API_TOKEN" \
  -d "memo=HR_Share_Canary" \
  -d "kind=pdf-acrobat-reader" \
  -o /tmp/canary_employee_handbook.pdf
 
# Windows folder token (alerts when folder is browsed)
curl -X POST "https://CONSOLE.canary.tools/api/v1/canarytoken/create" \
  -d "auth_token=YOUR_API_TOKEN" \
  -d "memo=Executive_Folder_Browse" \
  -d "kind=windows-dir"
 
# Deploy Canary appliance (emulates a file server)
# Configure via web console to appear as:
# - Windows file server with SMB shares
# - Contains realistic-looking directories
# - Any access triggers immediate alert with source IP and activity details

Step 5: Integrate Alerts with SIEM and Automated Response

# siem_integration.py - Forward honeypot alerts to SIEM and trigger containment
 
import json
import requests
import logging
from datetime import datetime
 
SIEM_WEBHOOK = "https://siem.company.com/api/alerts"
NAC_API = "https://nac.company.com/api/v1/quarantine"
EDR_API = "https://edr.company.com/api/v1/isolate"
 
def send_ransomware_alert(source_ip: str, canary_path: str, action: str):
    """Send high-priority alert to SIEM and trigger automated containment."""
    alert = {
        "timestamp": datetime.utcnow().isoformat(),
        "severity": "CRITICAL",
        "category": "Ransomware - Canary File Triggered",
        "source_ip": source_ip,
        "canary_file": canary_path,
        "action_detected": action,
        "automated_response": "Host isolation initiated",
        "mitre_technique": "T1486 - Data Encrypted for Impact",
    }
 
    # Send to SIEM
    try:
        requests.post(SIEM_WEBHOOK, json=alert, timeout=5)
    except requests.RequestException as e:
        logging.error(f"SIEM alert failed: {e}")
 
    # Automated containment - isolate host via NAC
    try:
        requests.post(f"{NAC_API}/{source_ip}",
                      json={"action": "quarantine", "reason": "Ransomware canary triggered"},
                      timeout=5)
    except requests.RequestException as e:
        logging.error(f"NAC quarantine failed: {e}")
 
    # Automated containment - isolate host via EDR
    try:
        requests.post(EDR_API,
                      json={"ip": source_ip, "action": "isolate"},
                      timeout=5)
    except requests.RequestException as e:
        logging.error(f"EDR isolation failed: {e}")
 
    logging.critical(f"RANSOMWARE CANARY ALERT: {source_ip} modified {canary_path} ({action})")

Key Concepts

Term Definition
Canary File A decoy file placed in strategic locations that triggers an alert when modified, renamed, or deleted by ransomware
Honeypot Share A decoy network share designed to attract attackers, where any access is suspicious and triggers alerts
Canary Token A trackable token embedded in a document or URL that reports back when accessed, revealing the accessor's IP and time
FSRM File Server Resource Manager - Windows Server role that monitors file operations and can screen for ransomware extensions
Deception Layer Security architecture layer using decoy assets to detect threats with near-zero false positive rates
File System Watcher System service that monitors real-time file system changes (creation, modification, deletion, rename)

Tools & Systems

  • Thinkst Canary: Commercial deception platform providing canary appliances (emulate servers) and canary tokens (trackable documents)
  • Canarytokens.org: Free service from Thinkst for generating basic canary tokens (Word docs, PDFs, URLs, DNS)
  • OpenCanary: Open-source honeypot daemon that emulates common services (SMB, RDP, SSH) and logs access attempts
  • FSRM (File Server Resource Manager): Windows Server built-in tool for file screening, quota management, and ransomware extension detection
  • Elastic Endpoint: Uses canary files internally for ransomware protection, triggering behavioral alerts on canary modification

Common Scenarios

Scenario: Early Detection of BlackByte Ransomware via Canary Files

Context: A retail company deploys canary files across 200 file shares and 3 honeypot shares. At 3:00 AM on a Saturday, the canary monitoring system generates 47 alerts in rapid succession as canary files across 12 shares are modified within 90 seconds.

Approach:

  1. Canary file alert triggers automated containment: source workstation (10.2.8.55) quarantined via NAC within 30 seconds
  2. SIEM correlation shows the source workstation had EDR alerts for PsExec execution 2 hours earlier (missed by overnight SOC)
  3. Additional canary alerts from 3 other workstations indicate the ransomware is spreading via scheduled tasks
  4. IR team isolates the affected VLAN, preventing encryption of the remaining 188 file shares
  5. The 12 affected shares are restored from immutable backups within 4 hours
  6. Estimated damage prevented: $2.3M in downtime and recovery costs based on the 95% of shares protected

Pitfalls:

  • Placing canary files only in root directories where ransomware may skip them by targeting subdirectories first
  • Using obvious canary names that sophisticated ransomware may recognize and avoid
  • Not testing canary alerting end-to-end, discovering during an actual incident that alerts are not reaching the SOC
  • Generating excessive canary alerts during legitimate file migrations or antivirus scans, causing alert fatigue

Output Format

## Ransomware Honeypot Deployment Report
 
**Organization**: [Name]
**Deployment Date**: [Date]
 
### Canary File Deployment
| Share | Files Deployed | Naming Convention | Alert Method |
|-------|---------------|-------------------|--------------|
| [Share path] | [Count] | [Pattern] | [FSRM/Watcher/Token] |
 
### Honeypot Shares
| Share Name | Location | Apparent Content | Monitoring |
|-----------|----------|-----------------|------------|
| [Name] | [Server] | [Description] | [Audit/Canary] |
 
### Alert Integration
- SIEM: [Connected/Not Connected]
- Automated Containment: [EDR Isolation/NAC Quarantine/None]
- Alert SLA: [Expected response time]
 
### Testing Results
| Test Date | Test Type | Canary Triggered | Alert Received | Containment Executed | Time to Alert |
|-----------|----------|-----------------|----------------|---------------------|---------------|
Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 3

api-reference.md1.7 KB

API Reference: Implementing Honeypot for Ransomware Detection

Canary File Strategy

Name Pattern Extension Purpose
!Accounting_* .docx, .xlsx Sorted first alphabetically
~$Confidential_* .pdf, .csv Mimics temp/open Office files
!Payroll_* .xlsx, .bak High-value bait

Integrity Monitoring

import hashlib
from pathlib import Path
content = Path("canary.docx").read_bytes()
sha256 = hashlib.sha256(content).hexdigest()

Ransomware Extension Indicators

Extension Ransomware Family
.encrypted Generic
.locked LockBit, GandCrab
.crypto CryptoLocker variants
.ransom Generic
.enc Various

Samba Honeypot Share (full_audit VFS)

[FinanceArchive]
    path = /srv/honeypot
    vfs objects = full_audit
    full_audit:success = open opendir write rename unlink
    full_audit:failure = open
    full_audit:facility = LOCAL7
    full_audit:priority = NOTICE

Thinkst Canary API

# List incidents
curl "https://DOMAIN.canary.tools/api/v1/incidents/all" \
  -d auth_token=TOKEN
 
# Acknowledge incident
curl "https://DOMAIN.canary.tools/api/v1/incident/acknowledge" \
  -d auth_token=TOKEN -d incident=INC_ID

Detection Thresholds

Metric Threshold Severity
Files modified in 60s > 50 CRITICAL
Canary file deleted Any CRITICAL
Canary hash changed Any CRITICAL
Known ransom extensions Any CRITICAL

References

standards.md1.0 KB

Standards & References - Honeypot for Ransomware Detection

MITRE ATT&CK

  • T1486: Data Encrypted for Impact (detection via canary file modification)
  • T1021.002: SMB/Windows Admin Shares (detection via honeypot share access)
  • T1083: File and Directory Discovery (detection via honeypot folder browsing)

NIST SP 800-53 Rev 5

  • SI-4: System Monitoring (honeypots as monitoring component)
  • AU-6: Audit Record Review, Analysis, and Reporting (canary file audit logging)

CIS Controls v8

  • Control 13.1: Centralize security event alerting (integrate honeypot alerts into SIEM)
  • Control 13.8: Deploy intrusion detection/prevention systems

Tools Documentation

workflows.md1.4 KB

Workflows - Honeypot for Ransomware Detection

Workflow 1: Canary File Deployment

Start
  |
  v
[Inventory all file shares] --> Map share names, paths, user population
  |
  v
[Select canary file placement strategy]
  |-- Root of each share (first files encrypted)
  |-- Key subdirectories (finance, HR, executive)
  |-- Alphabetically early names (!_, 000_, AAA_)
  |
  v
[Generate canary files with realistic content]
  |-- .docx, .xlsx, .pdf formats
  |-- Realistic filenames matching share context
  |-- Hidden attribute to prevent user interaction
  |
  v
[Deploy monitoring]
  |-- FSRM file screens for ransomware extensions
  |-- FileSystemWatcher for canary file changes
  |-- Audit logging on canary files
  |
  v
[Integrate with SIEM and automated containment]
  |
  v
[Test with controlled encryption tool]
  |
  v
End

Workflow 2: Honeypot Alert Response

Canary Alert Triggered
  |
  v
[Identify source IP and user from alert]
  |
  v
[Automated containment (within 30 seconds)]
  |-- NAC: Quarantine source IP
  |-- EDR: Isolate endpoint
  |-- AD: Disable user account
  |
  v
[SOC validates alert]
  |-- Check for legitimate activity (file migration, AV scan)
  |-- If FP --> Restore access, tune alerting
  |-- If TP --> Escalate to IR team
  |
  v
[IR team assesses scope]
  |-- How many canary files triggered?
  |-- How many endpoints involved?
  |-- Is encryption spreading?
  |
  v
[Full incident response activation]
  |
  v
End

Scripts 2

agent.py8.6 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Agent for deploying and monitoring ransomware honeypot canary files."""

import os
import json
import argparse
import hashlib
import time
from datetime import datetime
from pathlib import Path
from collections import Counter


CANARY_EXTENSIONS = [".docx", ".xlsx", ".pdf", ".pptx", ".csv", ".txt",
                     ".jpg", ".png", ".sql", ".bak"]
CANARY_PREFIX_NAMES = [
    "!Accounting_Report_2024", "!Budget_Final", "!Confidential_HR",
    "!Employee_SSN_List", "!Financial_Audit", "!Payroll_Records",
    "~$Customer_Database", "~$Executive_Compensation",
]


def create_canary_files(target_dir, count=10):
    """Create canary files in strategic locations for ransomware detection."""
    canaries = []
    target = Path(target_dir)
    for i in range(min(count, len(CANARY_PREFIX_NAMES))):
        for ext in CANARY_EXTENSIONS[:3]:
            name = f"{CANARY_PREFIX_NAMES[i]}{ext}"
            path = target / name
            content = os.urandom(1024 * (i + 1))
            path.write_bytes(content)
            file_hash = hashlib.sha256(content).hexdigest()
            canaries.append({
                "path": str(path),
                "hash": file_hash,
                "size": len(content),
                "created": datetime.utcnow().isoformat(),
            })
    return canaries


def generate_canary_manifest(canaries, manifest_path):
    """Save canary file manifest for integrity monitoring."""
    manifest = {
        "created_at": datetime.utcnow().isoformat(),
        "canary_count": len(canaries),
        "canaries": canaries,
    }
    with open(manifest_path, "w") as f:
        json.dump(manifest, f, indent=2)
    return manifest_path


def check_canary_integrity(manifest_path):
    """Check canary files against manifest to detect tampering/encryption."""
    with open(manifest_path) as f:
        manifest = json.load(f)
    alerts = []
    for canary in manifest.get("canaries", []):
        path = Path(canary["path"])
        if not path.exists():
            alerts.append({
                "type": "DELETED",
                "path": canary["path"],
                "severity": "CRITICAL",
                "detail": "Canary file deleted - possible ransomware wiper",
            })
            continue
        current_hash = hashlib.sha256(path.read_bytes()).hexdigest()
        if current_hash != canary["hash"]:
            alerts.append({
                "type": "MODIFIED",
                "path": canary["path"],
                "severity": "CRITICAL",
                "original_hash": canary["hash"],
                "current_hash": current_hash,
                "detail": "Canary file modified - possible ransomware encryption",
            })
        current_size = path.stat().st_size
        if abs(current_size - canary["size"]) > canary["size"] * 0.1:
            alerts.append({
                "type": "SIZE_CHANGE",
                "path": canary["path"],
                "severity": "HIGH",
                "original_size": canary["size"],
                "current_size": current_size,
            })
    checked = len(manifest.get("canaries", []))
    return {
        "checked": checked,
        "alerts": alerts,
        "alert_count": len(alerts),
        "status": "ALERT" if alerts else "CLEAN",
    }


def detect_ransomware_indicators(watch_dir, window_seconds=60):
    """Detect rapid file modifications indicative of ransomware."""
    watch_path = Path(watch_dir)
    now = time.time()
    recently_modified = []
    extension_changes = Counter()
    new_extensions = Counter()

    for fp in watch_path.rglob("*"):
        if not fp.is_file():
            continue
        try:
            mtime = fp.stat().st_mtime
            if now - mtime < window_seconds:
                recently_modified.append(str(fp))
                ext = fp.suffix.lower()
                if ext in (".encrypted", ".locked", ".crypto", ".crypt",
                           ".enc", ".pay", ".ransom"):
                    new_extensions[ext] += 1
        except (OSError, PermissionError):
            continue

    indicators = []
    if len(recently_modified) > 50:
        indicators.append({
            "indicator": "Mass file modification",
            "count": len(recently_modified),
            "severity": "CRITICAL",
            "detail": f"{len(recently_modified)} files modified in {window_seconds}s",
        })
    if new_extensions:
        indicators.append({
            "indicator": "Ransomware file extensions detected",
            "extensions": dict(new_extensions),
            "severity": "CRITICAL",
        })
    return {
        "files_checked_window": window_seconds,
        "recently_modified": len(recently_modified),
        "indicators": indicators,
        "status": "ALERT" if indicators else "CLEAN",
    }


def generate_honeypot_share_config(share_name="FinanceArchive", share_path="/srv/honeypot"):
    """Generate SMB honeypot share configuration."""
    return {
        "samba_config": {
            "share_name": share_name,
            "path": share_path,
            "comment": "Financial Archive (Read Only)",
            "read_only": False,
            "browseable": True,
            "guest_ok": False,
            "valid_users": "@domain_users",
            "vfs_objects": "full_audit",
            "full_audit_prefix": f"%u|%I|%S",
            "full_audit_success": "open opendir write rename unlink mkdir rmdir",
            "full_audit_failure": "open",
            "full_audit_facility": "LOCAL7",
            "full_audit_priority": "NOTICE",
        },
        "monitoring": {
            "log_path": "/var/log/samba/audit.log",
            "alert_on": ["write", "rename", "unlink"],
            "siem_integration": "syslog -> SIEM",
        },
    }


def analyze_honeypot_logs(log_path):
    """Analyze honeypot access logs for suspicious activity."""
    with open(log_path) as f:
        events = json.load(f)
    items = events if isinstance(events, list) else events.get("events", [])
    by_user = Counter(e.get("user", "unknown") for e in items)
    by_action = Counter(e.get("action", "unknown") for e in items)
    write_events = [e for e in items if e.get("action") in ("write", "rename", "delete")]
    return {
        "total_events": len(items),
        "by_user": dict(by_user.most_common(10)),
        "by_action": dict(by_action),
        "write_events": len(write_events),
        "suspicious": len(write_events) > 5,
        "severity": "CRITICAL" if len(write_events) > 20 else
                    "HIGH" if len(write_events) > 5 else "INFO",
    }


def main():
    parser = argparse.ArgumentParser(description="Ransomware Honeypot Agent")
    parser.add_argument("--deploy", help="Directory to deploy canary files")
    parser.add_argument("--manifest", help="Canary manifest JSON for integrity check")
    parser.add_argument("--watch", help="Directory to watch for ransomware indicators")
    parser.add_argument("--honeypot-log", help="Honeypot access log JSON")
    parser.add_argument("--action", choices=["deploy", "check", "detect", "analyze",
                                              "share-config", "full"], default="full")
    parser.add_argument("--output", default="ransomware_honeypot_report.json")
    args = parser.parse_args()

    report = {"generated_at": datetime.utcnow().isoformat(), "results": {}}

    if args.action in ("deploy", "full") and args.deploy:
        canaries = create_canary_files(args.deploy)
        manifest = generate_canary_manifest(canaries, args.deploy + "/canary_manifest.json")
        report["results"]["deployed"] = {"count": len(canaries), "manifest": manifest}
        print(f"[+] Deployed {len(canaries)} canary files")

    if args.action in ("check", "full") and args.manifest:
        result = check_canary_integrity(args.manifest)
        report["results"]["integrity"] = result
        print(f"[+] Integrity: {result['status']} ({result['alert_count']} alerts)")

    if args.action in ("detect", "full") and args.watch:
        result = detect_ransomware_indicators(args.watch)
        report["results"]["detection"] = result
        print(f"[+] Detection: {result['status']}")

    if args.action in ("share-config", "full"):
        config = generate_honeypot_share_config()
        report["results"]["share_config"] = config
        print("[+] Honeypot share config generated")

    if args.action in ("analyze", "full") and args.honeypot_log:
        result = analyze_honeypot_logs(args.honeypot_log)
        report["results"]["log_analysis"] = result
        print(f"[+] Honeypot events: {result['total_events']}, writes: {result['write_events']}")

    with open(args.output, "w") as f:
        json.dump(report, f, indent=2, default=str)
    print(f"[+] Report saved to {args.output}")


if __name__ == "__main__":
    main()
process.py11.3 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
Ransomware Honeypot Deployment and Monitoring Tool

Deploys canary files across file shares and monitors for modifications
that indicate ransomware activity. Supports:
- Canary file generation with realistic content
- File system monitoring with immediate alerting
- Integration with SIEM via syslog
- Automated containment via API calls
"""

import hashlib
import json
import logging
import os
import sys
import time
from dataclasses import dataclass, field, asdict
from datetime import datetime
from pathlib import Path
from typing import Optional

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger("ransomware_honeypot")


@dataclass
class CanaryFile:
    path: str
    original_hash: str
    file_type: str
    deploy_time: str
    share_name: str
    status: str = "active"
    last_check: Optional[str] = None
    alert_triggered: bool = False


@dataclass
class CanaryAlert:
    timestamp: str
    canary_path: str
    change_type: str  # modified, deleted, renamed, extension_changed
    source_info: str
    severity: str = "CRITICAL"
    automated_response: str = ""


CANARY_TEMPLATES = {
    "finance": [
        ("!_Budget_FY2026_FINAL.xlsx", "FY2026 Budget Summary\nTotal Revenue: $142.3M\nTotal Expenses: $98.7M\nNet Income: $43.6M"),
        ("000_Quarterly_Earnings.docx", "Q4 2025 Earnings Report\nRevenue: $38.2M\nGross Margin: 67%\nEBITDA: $12.1M"),
        ("_Executive_Compensation.pdf", "Executive Compensation Committee Report\nCEO Total Comp: $2.1M\nCFO Total Comp: $1.4M"),
    ],
    "hr": [
        ("!_Employee_SSN_List.xlsx", "Employee ID | Name | SSN\n10001 | Smith, John | XXX-XX-1234\n10002 | Johnson, Mary | XXX-XX-5678"),
        ("000_Salary_Database_2026.csv", "Employee,Department,Base Salary,Bonus\nSmith J,Engineering,$145000,$29000"),
        ("_Termination_List_Q1.docx", "Planned Workforce Reduction Q1 2026\nDepartment: Operations\nHeadcount Impact: 45 positions"),
    ],
    "engineering": [
        ("!_Product_Roadmap_Confidential.docx", "Product Roadmap 2026-2028\nProject Phoenix: AI-powered analytics\nProject Titan: Next-gen platform"),
        ("000_Source_Code_Access_Keys.txt", "Repository Access Tokens\nGitHub Enterprise: ghp_XXXXXXXXXXXX\nAWS CodeCommit: AKIAIOSFODNN7EXAMPLE"),
        ("_Patent_Application_Draft.pdf", "US Patent Application\nTitle: Method for Distributed Computing\nInventor: Dr. Jane Smith"),
    ],
    "executive": [
        ("!_Board_Meeting_Minutes.docx", "Board of Directors Meeting Minutes\nDate: January 15, 2026\nAttendees: Full board present"),
        ("000_MA_Target_Analysis.xlsx", "M&A Target Analysis\nTarget: AcmeTech Inc\nValuation: $450M\nSynergies: $80M annual"),
        ("_Strategic_Plan_2026.pdf", "Strategic Plan 2026-2030\nVision: Market leader in three verticals\nCapEx Budget: $200M"),
    ],
}


class CanaryDeployer:
    """Deploys and manages canary files for ransomware detection."""

    def __init__(self, state_file: str = "canary_state.json"):
        self.state_file = state_file
        self.canaries: list[CanaryFile] = []
        self._load_state()

    def _load_state(self):
        if os.path.exists(self.state_file):
            with open(self.state_file, "r") as f:
                data = json.load(f)
                self.canaries = [CanaryFile(**c) for c in data.get("canaries", [])]

    def _save_state(self):
        with open(self.state_file, "w") as f:
            json.dump({"canaries": [asdict(c) for c in self.canaries],
                       "last_updated": datetime.now().isoformat()}, f, indent=2)

    def _compute_hash(self, filepath: str) -> str:
        if not os.path.exists(filepath):
            return ""
        h = hashlib.sha256()
        with open(filepath, "rb") as f:
            for chunk in iter(lambda: f.read(8192), b""):
                h.update(chunk)
        return h.hexdigest()

    def deploy_canaries(self, base_path: str, share_type: str = "finance") -> list:
        """Deploy canary files to a target directory."""
        templates = CANARY_TEMPLATES.get(share_type, CANARY_TEMPLATES["finance"])
        deployed = []

        base = Path(base_path)
        if not base.exists():
            logger.error(f"Target path does not exist: {base_path}")
            return deployed

        for filename, content in templates:
            filepath = base / filename
            try:
                filepath.write_text(content, encoding="utf-8")
                file_hash = self._compute_hash(str(filepath))

                canary = CanaryFile(
                    path=str(filepath),
                    original_hash=file_hash,
                    file_type=filepath.suffix,
                    deploy_time=datetime.now().isoformat(),
                    share_name=share_type,
                )
                self.canaries.append(canary)
                deployed.append(canary)
                logger.info(f"Deployed canary: {filepath}")
            except OSError as e:
                logger.error(f"Failed to deploy canary {filepath}: {e}")

        self._save_state()
        return deployed

    def check_canaries(self) -> list:
        """Check all deployed canaries for modifications."""
        alerts = []

        for canary in self.canaries:
            if canary.status != "active":
                continue

            canary.last_check = datetime.now().isoformat()

            if not os.path.exists(canary.path):
                # File deleted - strong ransomware indicator
                alert = CanaryAlert(
                    timestamp=datetime.now().isoformat(),
                    canary_path=canary.path,
                    change_type="deleted",
                    source_info="File no longer exists",
                    severity="CRITICAL",
                )
                alerts.append(alert)
                canary.alert_triggered = True
                canary.status = "triggered"
                logger.critical(f"CANARY DELETED: {canary.path}")
                continue

            current_hash = self._compute_hash(canary.path)
            if current_hash != canary.original_hash:
                # File modified - likely encryption
                alert = CanaryAlert(
                    timestamp=datetime.now().isoformat(),
                    canary_path=canary.path,
                    change_type="modified",
                    source_info=f"Hash changed: {canary.original_hash[:16]}... -> {current_hash[:16]}...",
                    severity="CRITICAL",
                )
                alerts.append(alert)
                canary.alert_triggered = True
                canary.status = "triggered"
                logger.critical(f"CANARY MODIFIED: {canary.path}")

            # Check for ransomware extension appended
            parent = Path(canary.path).parent
            base_name = Path(canary.path).name
            for f in parent.iterdir():
                if f.name.startswith(base_name) and f.name != base_name:
                    # Possible encrypted version (e.g., file.docx.lockbit)
                    alert = CanaryAlert(
                        timestamp=datetime.now().isoformat(),
                        canary_path=canary.path,
                        change_type="extension_changed",
                        source_info=f"Possible encrypted copy: {f.name}",
                        severity="CRITICAL",
                    )
                    alerts.append(alert)
                    canary.alert_triggered = True
                    logger.critical(f"CANARY EXTENSION CHANGE: {f.name}")

        self._save_state()
        return alerts

    def generate_report(self) -> str:
        """Generate deployment status report."""
        lines = []
        lines.append("=" * 60)
        lines.append("RANSOMWARE CANARY DEPLOYMENT REPORT")
        lines.append("=" * 60)
        lines.append(f"Report Time: {datetime.now().isoformat()}")
        lines.append(f"Total Canaries: {len(self.canaries)}")

        active = sum(1 for c in self.canaries if c.status == "active")
        triggered = sum(1 for c in self.canaries if c.status == "triggered")
        lines.append(f"Active: {active}")
        lines.append(f"Triggered: {triggered}")

        by_share = {}
        for c in self.canaries:
            by_share.setdefault(c.share_name, []).append(c)

        lines.append("\nDeployment by Share:")
        for share, canaries in by_share.items():
            lines.append(f"\n  {share.upper()}:")
            for c in canaries:
                status_icon = "OK" if c.status == "active" else "ALERT"
                lines.append(f"    [{status_icon}] {c.path}")

        lines.append("\n" + "=" * 60)
        return "\n".join(lines)

    def continuous_monitor(self, interval_seconds: int = 10):
        """Run continuous monitoring loop."""
        logger.info(f"Starting continuous canary monitoring (interval: {interval_seconds}s)")
        logger.info(f"Monitoring {len(self.canaries)} canary files")

        try:
            while True:
                alerts = self.check_canaries()
                if alerts:
                    logger.critical(f"!!! {len(alerts)} CANARY ALERTS DETECTED !!!")
                    for alert in alerts:
                        logger.critical(f"  {alert.change_type}: {alert.canary_path}")
                        # In production: trigger SIEM alert, NAC quarantine, EDR isolation
                time.sleep(interval_seconds)
        except KeyboardInterrupt:
            logger.info("Monitoring stopped by user")


def main():
    deployer = CanaryDeployer(
        state_file=str(Path(__file__).parent / "canary_state.json")
    )

    if len(sys.argv) > 1:
        command = sys.argv[1]

        if command == "deploy" and len(sys.argv) >= 4:
            target_path = sys.argv[2]
            share_type = sys.argv[3]
            deployed = deployer.deploy_canaries(target_path, share_type)
            print(f"Deployed {len(deployed)} canary files to {target_path}")

        elif command == "check":
            alerts = deployer.check_canaries()
            if alerts:
                print(f"\n!!! {len(alerts)} ALERTS !!!")
                for alert in alerts:
                    print(f"  [{alert.severity}] {alert.change_type}: {alert.canary_path}")
            else:
                print("All canaries intact - no alerts")

        elif command == "monitor":
            interval = int(sys.argv[2]) if len(sys.argv) > 2 else 10
            deployer.continuous_monitor(interval)

        elif command == "report":
            print(deployer.generate_report())

        else:
            print("Usage:")
            print("  python process.py deploy <path> <type>  - Deploy canaries (finance/hr/engineering/executive)")
            print("  python process.py check                 - Check all canaries for modifications")
            print("  python process.py monitor [interval]    - Continuous monitoring")
            print("  python process.py report                - Generate deployment report")
    else:
        # Demo mode
        print("Ransomware Honeypot - Demo Mode")
        print("=" * 40)
        demo_dir = Path(__file__).parent / "demo_share"
        demo_dir.mkdir(exist_ok=True)

        deployed = deployer.deploy_canaries(str(demo_dir), "finance")
        print(f"\nDeployed {len(deployed)} canary files")

        alerts = deployer.check_canaries()
        print(f"Initial check: {len(alerts)} alerts (expected: 0)")

        print("\n" + deployer.generate_report())


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 1.0 KB
Keep exploring