npm package: @modular-intelligence/yara-scanner
Description: MCP server wrapping YARA for malware detection and pattern matching
Latest version: 1.0.2

# YARA Scanner MCP Server

MCP server wrapping YARA for malware detection, pattern matching, and security analysis. Provides comprehensive tools for scanning files, directories, and processes with YARA rules.

## Features

- **File Scanning**: Scan individual files with custom or built-in YARA rules
- **Directory Scanning**: Recursively scan directories with file extension filtering
- **Process Scanning**: Scan running process memory (requires root)
- **Rule Management**: Compile, validate, and generate YARA rules
- **Built-in Rulesets**: Use curated rulesets for malware, webshells, exploits, and more
- **Security**: Path validation, rule content validation, sandboxed execution

## Prerequisites

### Required

- **YARA CLI**: Install the YARA command-line tool
  ```bash
  # macOS
  brew install yara

  # Ubuntu/Debian
  sudo apt-get install yara

  # From source
  git clone https://github.com/VirusTotal/yara.git
  cd yara
  ./bootstrap.sh
  ./configure
  make
  sudo make install
  ```

### Optional

- **Built-in Rulesets**: For `yara_scan_with_builtin` tool
  - Set `YARA_RULES_PATH` environment variable, or
  - Install rules to `/opt/yara-rules/`
  - Recommended: [Awesome YARA rules](https://github.com/InQuest/awesome-yara)

  ```bash
  # Example: Install common rulesets
  sudo mkdir -p /opt/yara-rules
  cd /opt/yara-rules

  # Download popular rule repositories
  git clone https://github.com/Yara-Rules/rules.git yara-rules-repo

  # Organize by category
  cp yara-rules-repo/malware/*.yar malware.yar
  cp yara-rules-repo/webshells/*.yar webshell.yar
  # ... etc
  ```

## Installation

```bash
cd yara-scanner
bun install
bun run build
```

## Configuration

Add to your MCP settings file:

### Claude Desktop

**macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
**Windows**: `%APPDATA%\Claude\claude_desktop_config.json`

```json
{
  "mcpServers": {
    "yara-scanner": {
      "command": "bun",
      "args": ["run", "/absolute/path/to/yara-scanner/src/index.ts"],
      "env": {
        "YARA_RULES_PATH": "/opt/yara-rules"
      }
    }
  }
}
```

### Environment Variables

- `YARA_RULES_PATH`: Base directory for built-in rulesets (default: `/opt/yara-rules`)

## Tools

### yara_scan_file

Scan a single file with YARA rules.

**Parameters:**
- `file_path` (required): Absolute path to file to scan
- `rule_path` (optional): Path to YARA rule file (.yar/.yara)
- `rule_content` (optional): YARA rule content (alternative to rule_path)
- `timeout` (optional): Maximum scan duration in seconds (default: 60, max: 300)

**Note**: Must provide either `rule_path` or `rule_content`, not both.

**Example:**
```typescript
{
  "file_path": "/home/user/suspicious.exe",
  "rule_path": "/opt/yara-rules/malware.yar",
  "timeout": 60
}
```

**Returns:**
```json
{
  "file": "/home/user/suspicious.exe",
  "matches": [
    {
      "rule": "Win32_Trojan_Generic",
      "tags": ["trojan", "win32"],
      "strings": [
        {
          "offset": "0x1234",
          "identifier": "$suspicious_string",
          "data": "malicious payload"
        }
      ]
    }
  ],
  "match_count": 1
}
```

### yara_scan_directory

Scan a directory (optionally recursive) with YARA rules.

**Parameters:**
- `dir_path` (required): Absolute path to directory to scan
- `rule_path` (optional): Path to YARA rule file
- `rule_content` (optional): YARA rule content
- `recursive` (optional): Scan directories recursively (default: false)
- `file_extensions` (optional): Filter by file extensions (e.g., [".exe", ".dll"])
- `timeout` (optional): Maximum scan duration in seconds (default: 60)

**Example:**
```typescript
{
  "dir_path": "/var/www/html",
  "rule_path": "/opt/yara-rules/webshell.yar",
  "recursive": true,
  "file_extensions": [".php", ".jsp", ".asp"]
}
```

**Returns:**
```json
{
  "directory": "/var/www/html",
  "files_scanned": 42,
  "matches": [
    {
      "file": "/var/www/html/upload/shell.php",
      "rule": "PHP_Webshell",
      "tags": ["webshell", "php"],
      "strings": [...]
    }
  ],
  "total_matches": 1
}
```

### yara_scan_process

Scan a running process memory with YARA rules. **Requires root privileges.**

**Parameters:**
- `pid` (required): Process ID to scan (positive integer)
- `rule_path` (optional): Path to YARA rule file
- `rule_content` (optional): YARA rule content
- `timeout` (optional): Maximum scan duration in seconds (default: 60)

**Example:**
```typescript
{
  "pid": 1234,
  "rule_content": "rule suspicious { strings: $a = \"malware\" condition: $a }"
}
```

**Returns:**
```json
{
  "pid": 1234,
  "matches": [
    {
      "rule": "suspicious",
      "tags": [],
      "strings": [...]
    }
  ],
  "match_count": 1
}
```

### yara_compile_rules

Compile and validate YARA rules without executing a scan.

**Parameters:**
- `rule_content` (required): YARA rule content to validate (max 500KB)

**Example:**
```typescript
{
  "rule_content": "rule test { strings: $a = \"test\" condition: $a }"
}
```

**Returns:**
```json
{
  "valid": true,
  "errors": [],
  "warnings": []
}
```

### yara_rule_info

Extract metadata and information from a YARA rule file.

**Parameters:**
- `rule_path` (required): Path to YARA rule file

**Example:**
```typescript
{
  "rule_path": "/opt/yara-rules/malware.yar"
}
```

**Returns:**
```json
{
  "rules": [
    {
      "name": "Win32_Trojan_Generic",
      "tags": ["trojan", "win32"],
      "meta": {
        "author": "Security Researcher",
        "description": "Generic trojan detection",
        "date": "2024-01-01"
      },
      "strings_count": 5,
      "condition": "3 of them"
    }
  ],
  "total_rules": 1
}
```

### yara_generate_rule

Generate a YARA rule from components and validate by compiling.

**Parameters:**
- `name` (required): Rule name
- `strings` (required): Array of string definitions
  - `identifier`: String identifier (e.g., "$s1")
  - `value`: String value or hex pattern
  - `type`: "text", "hex", or "regex" (default: "text")
- `condition` (optional): YARA condition expression (default: "any of them")
- `tags` (optional): Array of rule tags
- `meta` (optional): Metadata key-value pairs

**Example:**
```typescript
{
  "name": "Custom_Malware_Detector",
  "tags": ["malware", "custom"],
  "meta": {
    "author": "Security Team",
    "description": "Detects custom malware variant"
  },
  "strings": [
    {
      "identifier": "$s1",
      "value": "malicious string",
      "type": "text"
    },
    {
      "identifier": "$hex1",
      "value": "6D 61 6C 77 61 72 65",
      "type": "hex"
    }
  ],
  "condition": "all of them"
}
```

**Returns:**
```json
{
  "rule_content": "rule Custom_Malware_Detector : malware custom\n{\n    meta:\n        author = \"Security Team\"\n        description = \"Detects custom malware variant\"\n    strings:\n        $s1 = \"malicious string\"\n        $hex1 = { 6D 61 6C 77 61 72 65 }\n    condition:\n        all of them\n}",
  "valid": true,
  "compilation_errors": []
}
```

### yara_scan_with_builtin

Scan a file using curated built-in YARA rulesets.

**Parameters:**
- `file_path` (required): Absolute path to file to scan
- `ruleset` (required): Built-in ruleset category
  - `malware`: General malware detection
  - `suspicious`: Suspicious patterns and behaviors
  - `crypto`: Cryptographic algorithms and ransomware
  - `webshell`: Web shell detection
  - `exploit`: Exploit code patterns
  - `packer`: Executable packers
  - `ransomware`: Ransomware-specific signatures
- `timeout` (optional): Maximum scan duration in seconds (default: 60)

**Example:**
```typescript
{
  "file_path": "/home/user/suspicious.exe",
  "ruleset": "malware",
  "timeout": 120
}
```

**Returns:**
```json
{
  "file": "/home/user/suspicious.exe",
  "ruleset": "malware",
  "matches": [
    {
      "rule": "Generic_Malware",
      "tags": ["malware"],
      "strings": [...]
    }
  ],
  "match_count": 1
}
```

## Security Features

### Path Validation
- All paths must be absolute
- No path traversal (`..`) allowed
- No null bytes in paths
- Access to `/proc`, `/sys`, `/dev` is blocked

### Rule Content Validation
- Maximum rule size: 500KB
- Must contain at least one `rule` definition
- Only safe YARA modules allowed:
  - Allowed: `pe`, `elf`, `math`, `hash`, `console`, `time`, `string`
  - Blocked: `cuckoo`, `dotnet`, and other potentially dangerous modules

### Process Scanning
- Requires root privileges (UID 0)
- Process ID must be positive integer
- Validates process exists before scanning

### Execution Safety
- Command timeout enforcement (10-300 seconds)
- SIGKILL safety timer (timeout + 5 seconds)
- Maximum output buffer: 10MB
- Temporary files cleaned up automatically

## Example YARA Rules

### Simple Text Match
```yara
rule Simple_Text_Match {
    strings:
        $text = "malicious"
    condition:
        $text
}
```

### Hex Pattern Match
```yara
rule Hex_Pattern {
    strings:
        $hex = { 4D 5A 90 00 }  // PE header
    condition:
        $hex at 0
}
```

### Complex Rule with Metadata
```yara
rule Advanced_Detection {
    meta:
        author = "Security Team"
        description = "Detects advanced threat"
        severity = "high"

    strings:
        $s1 = "suspicious_function" ascii wide
        $s2 = /http:\/\/[a-z]+\.evil\.com/
        $hex1 = { E8 [4] 83 C4 ?? }

    condition:
        2 of them and filesize < 1MB
}
```

### Using PE Module
```yara
import "pe"

rule PE_Characteristics {
    condition:
        pe.is_pe and
        pe.number_of_sections > 5 and
        pe.imports("kernel32.dll", "CreateRemoteThread")
}
```

## Troubleshooting

### YARA not found
```
Error: spawn yara ENOENT
```
**Solution**: Install YARA CLI and ensure it's in your PATH.

### Permission denied (process scanning)
```
Error: Process scanning requires root privileges
```
**Solution**: Run with sudo or as root user.

### Built-in ruleset not found
```
Error: Failed to scan with built-in ruleset 'malware'
```
**Solution**: Set `YARA_RULES_PATH` environment variable or install rules to `/opt/yara-rules/`.

### Rule compilation errors
```json
{
  "valid": false,
  "errors": ["syntax error, unexpected $end"],
  "warnings": []
}
```
**Solution**: Check YARA rule syntax. Use `yara_compile_rules` to debug.

### Dangerous module import blocked
```
Error: Dangerous module import detected: "cuckoo"
```
**Solution**: Remove unsafe module imports or use only allowed modules (pe, elf, math, hash, console, time, string).

## Performance Tips

1. **Use specific rules**: More specific rules = faster scanning
2. **Set appropriate timeouts**: Large files may need longer timeouts
3. **Filter by extension**: When scanning directories, use `file_extensions` filter
4. **Avoid deep recursion**: Deep directory trees can be slow
5. **Optimize rule conditions**: Simple conditions are faster than complex ones

## Best Practices

1. **Test rules first**: Use `yara_compile_rules` to validate before scanning
2. **Use metadata**: Add author, description, date to rules
3. **Tag appropriately**: Use tags for categorization (malware, trojan, ransomware, etc.)
4. **Start specific**: Scan individual files before scanning directories
5. **Monitor performance**: Use appropriate timeouts for large scans
6. **Keep rules updated**: Regularly update built-in rulesets
7. **Document custom rules**: Use metadata fields for documentation

## Use Cases

- **Malware Detection**: Scan files for known malware signatures
- **Incident Response**: Scan compromised systems for IOCs
- **Threat Hunting**: Search for suspicious patterns across filesystems
- **Web Security**: Detect webshells in web application directories
- **Memory Forensics**: Scan running processes for malicious code
- **File Analysis**: Analyze unknown files with custom rules
- **Automated Scanning**: Integrate with CI/CD for security scanning

## License

MIT

## References

- [YARA Official Documentation](https://yara.readthedocs.io/)
- [YARA GitHub Repository](https://github.com/VirusTotal/yara)
- [Awesome YARA Rules](https://github.com/InQuest/awesome-yara)
- [YARA Rule Writing Guide](https://yara.readthedocs.io/en/stable/writingrules.html)