mirror of
https://github.com/mukul975/Anthropic-Cybersecurity-Skills.git
synced 2026-07-18 21:49:40 +03:00
Production hardening: security fixes, code quality, 724 skills complete
- Fix 25 shell=True subprocess calls with list-based commands - Fix 49 verify=False in defensive skills (env-var override) - Add timeout to 231 HTTP/subprocess/socket calls - Fix 6 SQL injection patterns with whitelist validation - Replace 8 __import__() with standard imports - Remove 701 unused imports across 442 files - Add authorized-testing disclaimers to all offensive skills - Complete 11 incomplete skill directories - Expand 10 stub SKILL.md files with full content - Fix 2 YAML parse errors in frontmatter - Fix 5 pre-existing syntax errors - Convert 22 hardcoded paths/ports to environment variables - Back up 21 redundant skill pairs to .bak - Fix 2 global declaration errors - 724/724 skills with full folder anatomy (SKILL.md + agent.py + api-reference.md + LICENSE) - 0 compile errors across all 724 agent.py files
This commit is contained in:
@@ -0,0 +1,201 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please do not remove or change
|
||||
the license header comment from a contributed file except when
|
||||
necessary.
|
||||
|
||||
Copyright 2026 mukul975
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,209 @@
|
||||
---
|
||||
name: implementing-ransomware-kill-switch-detection
|
||||
description: >
|
||||
Detects and exploits ransomware kill switch mechanisms including mutex-based
|
||||
execution guards, domain-based kill switches, and registry-based termination
|
||||
checks. Implements proactive mutex vaccination and kill switch domain monitoring
|
||||
to prevent ransomware from executing. Activates for requests involving ransomware
|
||||
kill switch analysis, mutex vaccination, WannaCry-style domain kill switches,
|
||||
or malware execution guard detection.
|
||||
domain: cybersecurity
|
||||
subdomain: ransomware-defense
|
||||
tags: [ransomware, kill-switch, mutex, detection, WannaCry, malware-analysis]
|
||||
version: 1.0.0
|
||||
author: mahipal
|
||||
license: Apache-2.0
|
||||
---
|
||||
|
||||
# Implementing Ransomware Kill Switch Detection
|
||||
|
||||
## 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 groups
|
||||
```
|
||||
|
||||
### Step 2: Deploy Mutex Vaccination
|
||||
|
||||
Pre-create known ransomware mutexes on endpoints to prevent execution:
|
||||
|
||||
```python
|
||||
# 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:
|
||||
|
||||
```xml
|
||||
<!-- 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 objects
|
||||
```
|
||||
|
||||
### Step 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
|
||||
# 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
|
||||
@@ -0,0 +1,132 @@
|
||||
# API Reference: Ransomware Kill Switch Detection
|
||||
|
||||
## Windows Mutex (Mutant) APIs
|
||||
|
||||
### CreateMutex (kernel32.dll)
|
||||
```c
|
||||
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 exists
|
||||
```
|
||||
|
||||
### OpenMutex (kernel32.dll)
|
||||
```c
|
||||
HANDLE OpenMutexW(
|
||||
DWORD dwDesiredAccess, // SYNCHRONIZE (0x00100000)
|
||||
BOOL bInheritHandle, // FALSE
|
||||
LPCWSTR lpName // Named mutex string
|
||||
);
|
||||
// Returns: Handle if exists, NULL if not found
|
||||
```
|
||||
|
||||
### PowerShell Mutex Operations
|
||||
```powershell
|
||||
# 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
|
||||
```xml
|
||||
<Sysmon schemaversion="4.90">
|
||||
<EventFiltering>
|
||||
<ProcessCreate onmatch="include">
|
||||
<Image condition="excludes">C:\Windows\</Image>
|
||||
</ProcessCreate>
|
||||
</EventFiltering>
|
||||
</Sysmon>
|
||||
```
|
||||
|
||||
## Velociraptor Mutex Hunting
|
||||
|
||||
### Windows.Detection.Mutants Artifact
|
||||
```sql
|
||||
SELECT * FROM glob(globs="\\BaseNamedObjects\\*")
|
||||
WHERE Name =~ "MsWinZonesCacheCounterMutexA|kasKDJSAF|YOURPRODUCT"
|
||||
```
|
||||
|
||||
### Sysinternals Handle Tool
|
||||
```cmd
|
||||
handle.exe -a | findstr /i "Mutant"
|
||||
handle.exe -a -p <PID> | findstr /i "Mutant"
|
||||
```
|
||||
|
||||
## DNS Kill Switch Monitoring
|
||||
|
||||
### Python DNS Resolution Check
|
||||
```python
|
||||
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 reference
|
||||
```
|
||||
|
||||
### ANY.RUN Mutex Search
|
||||
```
|
||||
URL: https://any.run/cybersecurity-blog/mutex-search-in-ti-lookup/
|
||||
Search: Threat Intelligence Lookup → Synchronization → Mutex name
|
||||
```
|
||||
|
||||
## Mutex 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 Script
|
||||
```
|
||||
@@ -0,0 +1,322 @@
|
||||
#!/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}")
|
||||
Reference in New Issue
Block a user