npx skills add mukul975/Anthropic-Cybersecurity-SkillsMITRE ATT&CK
When to Use
- Analyzing a ransomware sample to determine if it contains a kill switch mechanism (mutex, domain, registry)
- Deploying proactive mutex vaccination across endpoints to prevent known ransomware families from executing
- Monitoring DNS for kill switch domain lookups that indicate ransomware attempting to check before encrypting
- During incident response to quickly determine if a ransomware variant can be stopped by activating its kill switch
- Building detection signatures for ransomware mutex creation events using Sysmon or EDR telemetry
Do not use kill switch vaccination as a primary defense. Not all ransomware families implement kill switches, and those that do may remove them in newer versions. This is a supplementary detection and prevention layer.
Prerequisites
- Python 3.8+ with
ctypes(Windows) for mutex creation and enumeration - Sysmon installed with Event ID 1 (process creation) and Event ID 17/18 (pipe/mutex events) configured
- Access to malware analysis sandbox for identifying kill switch mechanisms in samples
- DNS monitoring capability for detecting kill switch domain resolution attempts
- Familiarity with Windows internals: mutexes (mutants), kernel objects, named pipes
- Reference database of known ransomware mutexes (github.com/albertzsigovits/malware-mutex)
Workflow
Step 1: Identify Kill Switch Mechanisms in Ransomware
Analyze samples for common kill switch patterns:
Kill Switch Types Found in Ransomware:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1. MUTEX-BASED (most common):
- Ransomware creates a named mutex at startup
- If mutex already exists → another instance is running → exit
- Defense: Pre-create the mutex to prevent execution
- Examples:
WannaCry: Global\MsWinZonesCacheCounterMutexA
Conti: kasKDJSAFJauisiudUASIIQWUA82
REvil: Global\{GUID-based-on-machine}
Ryuk: Global\YOURPRODUCT_MUTEX
2. DOMAIN-BASED:
- Ransomware resolves a hardcoded domain before executing
- If domain resolves → security sandbox detected → exit
- Defense: Register/sinkhole the domain to activate kill switch
- Examples:
WannaCry v1: iuqerfsodp9ifjaposdfjhgosurijfaewrwergwea.com
WannaCry v1: fferfsodp9ifjaposdfjhgosurijfaewrwergwea.com
3. REGISTRY-BASED:
- Check for specific registry key/value before executing
- If key exists → exit (anti-analysis or kill switch)
- Defense: Create the registry key proactively
4. FILE-BASED:
- Check for existence of specific file or directory
- If marker file exists → exit
- Defense: Create the marker file on all endpoints
5. LANGUAGE-BASED:
- Check system language/keyboard layout
- Exit if Russian/CIS country keyboard detected
- Common in Eastern European ransomware groupsStep 2: Deploy Mutex Vaccination
Pre-create known ransomware mutexes on endpoints to prevent execution:
# Windows mutex vaccination using ctypes
import ctypes
from ctypes import wintypes
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
def create_mutex(name):
"""Create a named mutex to vaccinate against ransomware."""
handle = kernel32.CreateMutexW(None, False, name)
error = ctypes.get_last_error()
if handle == 0:
return False, f"Failed to create mutex: error {error}"
if error == 183: # ERROR_ALREADY_EXISTS
return True, f"Mutex already exists (already vaccinated): {name}"
return True, f"Mutex created successfully: {name}"
KNOWN_RANSOMWARE_MUTEXES = [
"Global\\MsWinZonesCacheCounterMutexA", # WannaCry
"Global\\kasKDJSAFJauisiudUASIIQWUA82", # Conti
"Global\\YOURPRODUCT_MUTEX", # Ryuk variant
"Global\\JhbGjhBsSQjz", # Maze
"Global\\sdjfhksjdhfsd", # Generic ransomware
]Step 3: Monitor for Mutex Creation Events
Use Sysmon to detect when ransomware creates its characteristic mutexes:
<!-- Sysmon configuration for mutex monitoring -->
<Sysmon schemaversion="4.90">
<EventFiltering>
<!-- Event ID 1: Process creation with mutex indicators -->
<ProcessCreate onmatch="include">
<CommandLine condition="contains">mutex</CommandLine>
<CommandLine condition="contains">CreateMutex</CommandLine>
</ProcessCreate>
</EventFiltering>
</Sysmon>Detection via Event Logs:
━━━━━━━━━━━━━━━━━━━━━━━━
Windows Security Log:
Event ID 4688: Process creation (enable command line logging)
Sysmon:
Event ID 1: Process create (includes command line and hashes)
Event ID 17: Pipe created (named pipes, similar to mutexes)
PowerShell detection:
Event ID 4104: Script block logging (detect mutex creation in scripts)
Velociraptor artifact:
Windows.Detection.Mutants - Enumerates all named mutant objectsStep 4: Monitor DNS for Kill Switch Domains
Detect ransomware domain-based kill switch resolution attempts:
DNS Monitoring for Kill Switch Domains:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1. Monitor DNS queries for known kill switch domains
2. High-entropy domain names (>4.0 entropy in domain label) may indicate
ransomware kill switch domains or DGA-generated C2 domains
3. Queries to newly registered domains from endpoints that typically
only access well-established domains
Indicators:
- Domain with no prior resolution history
- Domain registered in last 24-72 hours
- High character entropy in domain name
- Resolution attempt followed by either mass encryption (kill switch failed)
or process termination (kill switch activated)Step 5: Enumerate Active Mutexes for Incident Response
During an active incident, scan endpoints for ransomware-associated mutexes:
# PowerShell: List all named mutant objects using Sysinternals Handle
# handle.exe -a -p <PID> | findstr "Mutant"
# Velociraptor query for mutex hunting:
# SELECT * FROM glob(globs="\\BaseNamedObjects\\*") WHERE Name =~ "mutex_pattern"
# Python-based enumeration (requires pywin32):
# import win32event
# handle = win32event.OpenMutex(0x00100000, False, "Global\\MutexName")Verification
- Verify mutex vaccination by attempting to create the same mutex (should get ERROR_ALREADY_EXISTS)
- Test that vaccinated mutexes survive system reboot (they do not; re-apply at startup via scheduled task)
- Confirm DNS monitoring detects test queries for known kill switch domains
- Validate Sysmon event generation for mutex creation by running a test script
- Check that vaccination does not interfere with legitimate applications using similar mutex names
- Test against actual ransomware samples in an isolated sandbox to confirm kill switch activation
Key Concepts
| Term | Definition |
|---|---|
| Mutex (Mutant) | A Windows kernel synchronization object used to ensure only one instance of a program runs; ransomware uses named mutexes to prevent re-infection |
| Kill Switch | A mechanism in ransomware that causes it to terminate without encrypting if a specific condition is met (mutex exists, domain resolves, file present) |
| Mutex Vaccination | Proactively creating named mutexes on endpoints that match known ransomware mutex names, preventing the ransomware from executing |
| Domain Sinkhole | Registering or redirecting a malicious domain to a controlled server; used to activate domain-based kill switches |
| DGA (Domain Generation Algorithm) | Algorithm used by malware to generate pseudo-random domain names for C2 communication, sometimes incorporating kill switch checks |
Tools & Systems
- Sysmon: Microsoft system monitor providing Event ID 17/18 for named pipe and mutex creation monitoring
- Velociraptor: Endpoint visibility tool with built-in artifacts for enumerating mutant (mutex) objects on Windows
- Sysinternals Handle: Command-line tool for listing open handles including named mutexes per process
- malware-mutex (GitHub): Community-maintained database of mutexes used by known malware families
- ANY.RUN: Interactive malware sandbox that reports mutex creation during dynamic analysis
- PassiveDNS: DNS monitoring infrastructure for detecting kill switch domain resolution attempts
References and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 1
api-reference.md3.7 KB
API Reference: Ransomware Kill Switch Detection
Windows Mutex (Mutant) APIs
CreateMutex (kernel32.dll)
HANDLE CreateMutexW(
LPSECURITY_ATTRIBUTES lpMutexAttributes, // NULL for default
BOOL bInitialOwner, // TRUE to own immediately
LPCWSTR lpName // Named mutex string
);
// Returns: Handle to mutex, or NULL on failure
// GetLastError() == ERROR_ALREADY_EXISTS (183) if mutex already existsOpenMutex (kernel32.dll)
HANDLE OpenMutexW(
DWORD dwDesiredAccess, // SYNCHRONIZE (0x00100000)
BOOL bInheritHandle, // FALSE
LPCWSTR lpName // Named mutex string
);
// Returns: Handle if exists, NULL if not foundPowerShell Mutex Operations
# Create a named mutex
$created = $false
$m = New-Object System.Threading.Mutex($true, "Global\MutexName", [ref]$created)
# Check if mutex exists
try {
$m = [System.Threading.Mutex]::OpenExisting("Global\MutexName")
"EXISTS"
} catch { "NOT_FOUND" }Known Ransomware Kill Switch Mutexes
| Mutex Name | Family | Notes |
|---|---|---|
| Global\MsWinZonesCacheCounterMutexA | WannaCry | Single-instance guard |
| Global\kasKDJSAFJauisiudUASIIQWUA82 | Conti | Instance mutex |
| Global\YOURPRODUCT_MUTEX | Ryuk variant | Instance guard |
| Global\JhbGjhBsSQjz | Maze | Single-instance check |
| Global{GUID-based} | LockBit | Machine-specific GUID |
| Global\sdjfhksjdhfsd | Generic builders | Common in kits |
Known Kill Switch Domains
| Domain | Family | Discovered By |
|---|---|---|
| iuqerfsodp9ifjaposdfjhgosurijfaewrwergwea.com | WannaCry v1 | MalwareTech (2017) |
| fferfsodp9ifjaposdfjhgosurijfaewrwergwea.com | WannaCry v1 | Secondary switch |
Sysmon Configuration for Mutex Detection
Event ID 1 - Process Creation
<Sysmon schemaversion="4.90">
<EventFiltering>
<ProcessCreate onmatch="include">
<Image condition="excludes">C:\Windows\</Image>
</ProcessCreate>
</EventFiltering>
</Sysmon>Velociraptor Mutex Hunting
Windows.Detection.Mutants Artifact
SELECT * FROM glob(globs="\\BaseNamedObjects\\*")
WHERE Name =~ "MsWinZonesCacheCounterMutexA|kasKDJSAF|YOURPRODUCT"Sysinternals Handle Tool
handle.exe -a | findstr /i "Mutant"
handle.exe -a -p <PID> | findstr /i "Mutant"DNS Kill Switch Monitoring
Python DNS Resolution Check
import socket
def check_domain(domain):
try:
ip = socket.gethostbyname(domain)
return {"resolves": True, "ip": ip}
except socket.gaierror:
return {"resolves": False}Passive DNS Services
| Service | URL | Notes |
|---|---|---|
| VirusTotal | virustotal.com | Domain resolution history |
| PassiveTotal | community.riskiq.com | DNS record history |
| SecurityTrails | securitytrails.com | Domain intelligence |
Malware Mutex Database
albertzsigovits/malware-mutex (GitHub)
URL: https://github.com/albertzsigovits/malware-mutex
Format: JSON with mutex name, malware family, source referenceANY.RUN Mutex Search
URL: https://any.run/cybersecurity-blog/mutex-search-in-ti-lookup/
Search: Threat Intelligence Lookup → Synchronization → Mutex nameMutex Vaccination Deployment Methods
| Method | Persistence | Scope |
|---|---|---|
| GPO Startup Script | Survives reboot | Domain-wide |
| Scheduled Task (at logon) | Survives reboot | Per-machine |
| Windows Service | Survives reboot | Per-machine |
| Manual PowerShell | Until reboot | Current session |
GPO Startup Script Path
Computer Configuration → Policies → Windows Settings →
Scripts (Startup/Shutdown) → Startup → Add ScriptScripts 1
agent.py12.0 KB
#!/usr/bin/env python3
"""Ransomware kill switch detection and mutex vaccination agent.
Detects ransomware kill switch mechanisms (mutexes, domains, registry keys)
and can proactively deploy mutex vaccinations to prevent known ransomware
families from executing. Monitors for kill switch domain DNS queries.
"""
import json
import logging
import platform
import socket
import subprocess
import sys
from datetime import datetime
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
)
logger = logging.getLogger("killswitch_agent")
KNOWN_KILL_SWITCH_MUTEXES = {
"Global\\MsWinZonesCacheCounterMutexA": {
"family": "WannaCry",
"type": "instance_guard",
"notes": "Prevents multiple WannaCry instances from running",
},
"Global\\kasKDJSAFJauisiudUASIIQWUA82": {
"family": "Conti",
"type": "instance_guard",
"notes": "Conti ransomware single-instance mutex",
},
"Global\\YOURPRODUCT_MUTEX": {
"family": "Ryuk variant",
"type": "instance_guard",
"notes": "Ryuk variant instance check",
},
"Global\\JhbGjhBsSQjz": {
"family": "Maze",
"type": "instance_guard",
"notes": "Maze ransomware single-instance mutex",
},
"Global\\{A7FE5338-4DDE-8CDE-9F54-FE88C3B8B532}": {
"family": "LockBit",
"type": "instance_guard",
"notes": "LockBit variant mutex (GUID-based)",
},
"Global\\MsWinZonesCacheCounterMutexA0": {
"family": "WannaCry variant",
"type": "instance_guard",
"notes": "WannaCry variant with appended zero",
},
"Global\\55a42b46-43dc-4e6c-abef-2529ddd744c7": {
"family": "BlackCat/ALPHV",
"type": "instance_guard",
"notes": "ALPHV ransomware instance mutex",
},
"Global\\sdjfhksjdhfsd": {
"family": "Generic ransomware",
"type": "instance_guard",
"notes": "Common in several ransomware builders",
},
}
KNOWN_KILL_SWITCH_DOMAINS = {
"iuqerfsodp9ifjaposdfjhgosurijfaewrwergwea.com": {
"family": "WannaCry v1",
"type": "domain_kill_switch",
"notes": "Primary WannaCry kill switch domain registered by MalwareTech",
},
"fferfsodp9ifjaposdfjhgosurijfaewrwergwea.com": {
"family": "WannaCry v1 (alternate)",
"type": "domain_kill_switch",
"notes": "Secondary WannaCry kill switch domain",
},
"ayloginilider.com": {
"family": "Emotet (ransomware loader)",
"type": "c2_sinkhole",
"notes": "Emotet C2 domain sinkholed by law enforcement",
},
}
KNOWN_KILL_SWITCH_REGISTRY = {
"HKLM\\SOFTWARE\\WannaDecrypt0r": {
"family": "WannaCry",
"type": "registry_marker",
"key": "HKLM\\SOFTWARE\\WannaDecrypt0r",
},
}
def check_mutex_exists_windows(mutex_name):
"""Check if a named mutex exists on Windows using PowerShell."""
ps_script = (
f'try {{ $m = [System.Threading.Mutex]::OpenExisting("{mutex_name}"); '
f'"EXISTS" }} catch {{ "NOT_FOUND" }}'
)
try:
result = subprocess.run(
["powershell", "-Command", ps_script],
capture_output=True, text=True, timeout=10,
)
return result.stdout.strip() == "EXISTS"
except (FileNotFoundError, subprocess.TimeoutExpired):
return None
def create_mutex_windows(mutex_name):
"""Create a named mutex on Windows for vaccination."""
ps_script = (
f'$created = $false; '
f'$m = New-Object System.Threading.Mutex($true, "{mutex_name}", [ref]$created); '
f'if ($created) {{ "CREATED" }} else {{ "ALREADY_EXISTS" }}; '
f'Start-Sleep -Seconds 2'
)
try:
result = subprocess.run(
["powershell", "-Command", ps_script],
capture_output=True, text=True, timeout=15,
)
output = result.stdout.strip()
return output == "CREATED" or output == "ALREADY_EXISTS", output
except (FileNotFoundError, subprocess.TimeoutExpired) as e:
return False, str(e)
def check_kill_switch_domain(domain):
"""Check if a kill switch domain resolves (indicating it is active)."""
try:
ip = socket.gethostbyname(domain)
return {
"domain": domain,
"resolves": True,
"ip": ip,
"kill_switch_active": True,
"notes": "Domain resolves - kill switch is ACTIVE (ransomware should abort)",
}
except socket.gaierror:
return {
"domain": domain,
"resolves": False,
"ip": None,
"kill_switch_active": False,
"notes": "Domain does NOT resolve - kill switch INACTIVE (ransomware would proceed)",
}
def scan_all_kill_switches():
"""Scan for all known kill switch mechanisms."""
report = {
"scan_time": datetime.now().isoformat(),
"hostname": platform.node(),
"platform": platform.system(),
"mutex_checks": [],
"domain_checks": [],
"registry_checks": [],
"summary": {"total_checked": 0, "active_vaccinations": 0, "active_domains": 0},
}
# Check mutexes (Windows only)
if platform.system() == "Windows":
logger.info("Checking %d known ransomware mutexes...", len(KNOWN_KILL_SWITCH_MUTEXES))
for mutex_name, info in KNOWN_KILL_SWITCH_MUTEXES.items():
exists = check_mutex_exists_windows(mutex_name)
check = {
"mutex": mutex_name,
"family": info["family"],
"exists": exists,
"vaccinated": exists is True,
}
report["mutex_checks"].append(check)
report["summary"]["total_checked"] += 1
if exists:
report["summary"]["active_vaccinations"] += 1
logger.warning("Mutex EXISTS: %s (%s)", mutex_name, info["family"])
else:
logger.info("Mutex checking is Windows-only. Skipping on %s.", platform.system())
# Check kill switch domains
logger.info("Checking %d known kill switch domains...", len(KNOWN_KILL_SWITCH_DOMAINS))
for domain, info in KNOWN_KILL_SWITCH_DOMAINS.items():
result = check_kill_switch_domain(domain)
result["family"] = info["family"]
report["domain_checks"].append(result)
report["summary"]["total_checked"] += 1
if result["resolves"]:
report["summary"]["active_domains"] += 1
return report
def vaccinate_endpoint(mutex_list=None):
"""Deploy mutex vaccinations to prevent ransomware execution."""
if platform.system() != "Windows":
return {"error": "Mutex vaccination is only supported on Windows"}
if mutex_list is None:
mutex_list = list(KNOWN_KILL_SWITCH_MUTEXES.keys())
results = {"vaccinated": [], "failed": [], "already_exists": []}
for mutex_name in mutex_list:
info = KNOWN_KILL_SWITCH_MUTEXES.get(mutex_name, {"family": "Custom"})
success, status = create_mutex_windows(mutex_name)
record = {"mutex": mutex_name, "family": info.get("family", "Custom"), "status": status}
if status == "CREATED":
results["vaccinated"].append(record)
logger.info("Vaccinated: %s (%s)", mutex_name, info.get("family"))
elif status == "ALREADY_EXISTS":
results["already_exists"].append(record)
logger.info("Already vaccinated: %s", mutex_name)
else:
results["failed"].append(record)
logger.error("Failed to vaccinate: %s - %s", mutex_name, status)
results["summary"] = {
"total_attempted": len(mutex_list),
"newly_vaccinated": len(results["vaccinated"]),
"already_vaccinated": len(results["already_exists"]),
"failed": len(results["failed"]),
}
return results
def generate_vaccination_script():
"""Generate a PowerShell script for persistent mutex vaccination."""
lines = [
"# Ransomware Mutex Vaccination Script",
"# Deploy via Group Policy Startup Script or Scheduled Task",
f"# Generated: {datetime.now().isoformat()}",
"# This script creates named mutexes that prevent known ransomware from executing",
"",
"$mutexHandles = @()",
"",
]
for mutex_name, info in KNOWN_KILL_SWITCH_MUTEXES.items():
lines.append(f"# {info['family']} - {info['notes']}")
lines.append(f'$created = $false')
lines.append(f'$m = New-Object System.Threading.Mutex($true, "{mutex_name}", [ref]$created)')
lines.append(f'if ($created) {{ Write-Host "Vaccinated: {mutex_name}" }}')
lines.append(f'$mutexHandles += $m')
lines.append("")
lines.append("# Keep script running to maintain mutex handles")
lines.append("Write-Host 'Mutex vaccination active. Press Ctrl+C to stop.'")
lines.append("while ($true) { Start-Sleep -Seconds 60 }")
return "\n".join(lines)
if __name__ == "__main__":
print("=" * 60)
print("Ransomware Kill Switch Detection & Vaccination Agent")
print("Mutex vaccination, domain monitoring, kill switch analysis")
print("=" * 60)
if len(sys.argv) < 2:
print("\nUsage:")
print(" python agent.py scan Scan for all known kill switches")
print(" python agent.py vaccinate Deploy mutex vaccinations")
print(" python agent.py domains Check kill switch domain status")
print(" python agent.py generate-script Generate PowerShell vaccination script")
print(" python agent.py list List all known kill switches")
sys.exit(0)
command = sys.argv[1]
if command == "scan":
report = scan_all_kill_switches()
print(f"\n--- Kill Switch Scan Results ---")
print(f" Total checked: {report['summary']['total_checked']}")
print(f" Active mutex vaccinations: {report['summary']['active_vaccinations']}")
print(f" Active kill switch domains: {report['summary']['active_domains']}")
for mc in report["mutex_checks"]:
status = "VACCINATED" if mc["vaccinated"] else "not vaccinated"
print(f" [{status:15s}] {mc['family']:20s} {mc['mutex']}")
for dc in report["domain_checks"]:
status = "ACTIVE" if dc["resolves"] else "INACTIVE"
print(f" [{status:15s}] {dc['family']:20s} {dc['domain']}")
print(f"\n{json.dumps(report, indent=2, default=str)}")
elif command == "vaccinate":
print("\n[*] Deploying mutex vaccinations...")
results = vaccinate_endpoint()
print(f"\n--- Vaccination Results ---")
print(f" Newly vaccinated: {results['summary']['newly_vaccinated']}")
print(f" Already vaccinated: {results['summary']['already_vaccinated']}")
print(f" Failed: {results['summary']['failed']}")
elif command == "domains":
print("\n--- Kill Switch Domain Status ---")
for domain, info in KNOWN_KILL_SWITCH_DOMAINS.items():
result = check_kill_switch_domain(domain)
status = "ACTIVE (resolves)" if result["resolves"] else "INACTIVE (no DNS)"
print(f" [{status}] {info['family']}: {domain}")
if result["resolves"]:
print(f" Resolves to: {result['ip']}")
elif command == "generate-script":
script = generate_vaccination_script()
output_file = "mutex_vaccination.ps1"
with open(output_file, "w") as f:
f.write(script)
print(f"\n[+] Vaccination script saved to: {output_file}")
print(f"[+] Deploy via GPO startup script or scheduled task")
print(f"\n{script[:500]}...")
elif command == "list":
print(f"\n--- Known Ransomware Kill Switches ---")
print(f"\nMutexes ({len(KNOWN_KILL_SWITCH_MUTEXES)}):")
for name, info in KNOWN_KILL_SWITCH_MUTEXES.items():
print(f" {info['family']:20s} {name}")
print(f"\nDomains ({len(KNOWN_KILL_SWITCH_DOMAINS)}):")
for domain, info in KNOWN_KILL_SWITCH_DOMAINS.items():
print(f" {info['family']:20s} {domain}")
else:
print(f"[!] Unknown command: {command}")