<p align="center">
<pre>
██████╗ ██╗   ██╗███╗   ██╗
██╔══██╗╚██╗ ██╔╝████╗  ██║
███████║ ╚████╔╝ ██╔██╗ ██║
██╔══██║  ╚██╔╝  ██║╚██╗██║
██║  ██║   ██║   ██║ ╚████║
╚═╝  ╚═╝   ╚═╝   ╚═╝  ╚═══╝
⚔️ AYN ANTIVIRUS v1.0.0 ⚔️
Server Protection Suite
</pre>
</p>

<p align="center">
  <a href="https://www.python.org/downloads/"><img src="https://img.shields.io/badge/python-3.9%2B-blue?style=for-the-badge&logo=python&logoColor=white" alt="Python 3.9+"></a>
  <a href="#license"><img src="https://img.shields.io/badge/license-MIT-green?style=for-the-badge" alt="License: MIT"></a>
  <a href="#"><img src="https://img.shields.io/badge/platform-linux-lightgrey?style=for-the-badge&logo=linux&logoColor=white" alt="Platform: Linux"></a>
  <a href="#"><img src="https://img.shields.io/badge/version-1.0.0-orange?style=for-the-badge" alt="Version 1.0.0"></a>
</p>

---

# AYN Antivirus

**Comprehensive anti-virus, anti-malware, anti-spyware, and anti-cryptominer protection for Linux servers.**

AYN Antivirus is a purpose-built security suite designed for server environments. It combines signature-based detection, YARA rules, heuristic analysis, and live system inspection to catch threats that traditional AV tools miss — from cryptominers draining your CPU to rootkits hiding in kernel modules.

---

## Features

- 🛡️ **Real-time file system monitoring** — watches directories with inotify/FSEvents via watchdog, scans new and modified files instantly
- 🔍 **Deep file scanning with multiple detection engines** — parallel, multi-threaded scans across signature, YARA, and heuristic detectors
- 🧬 **YARA rule support** — load custom and community YARA rules for flexible pattern matching
- 📊 **Heuristic analysis** — Shannon entropy scoring, obfuscation detection, reverse-shell patterns, permission anomalies
- ⛏️ **Cryptominer detection** — process-level, network-level, and file-content analysis (stratum URLs, wallet addresses, pool domains)
- 🕵️ **Spyware & keylogger detection** — identifies keyloggers, screen/audio capture tools, data exfiltration, and shell-profile backdoors
- 🦠 **Rootkit detection** — hidden processes, hidden kernel modules, LD_PRELOAD hijacking, tampered logs, hidden network ports
- 🌐 **Auto-updating threat signatures** — pulls from abuse.ch feeds (MalwareBazaar, ThreatFox, URLhaus, Feodo Tracker) and Emerging Threats
- 🔒 **Encrypted quarantine vault** — isolates malicious files with Fernet (AES-128-CBC + HMAC-SHA256) encryption and JSON metadata
- 🔧 **Auto-remediation & patching** — kills rogue processes, fixes permissions, blocks IPs/domains, cleans cron jobs, restores system binaries
- 📝 **Reports in Text, JSON, HTML** — generate human-readable or machine-parseable reports from scan results
- ⏰ **Scheduled scanning** — built-in cron-style scheduler for unattended operation

---

## Quick Start

```bash
# Install
pip install .

# Update threat signatures
sudo ayn-antivirus update

# Run a full scan
sudo ayn-antivirus scan

# Quick scan (high-risk dirs only)
sudo ayn-antivirus scan --quick

# Check protection status
ayn-antivirus status
```

---

## Installation

### From pip (local)

```bash
pip install .
```

### Editable install (development)

```bash
pip install -e ".[dev]"
```

### From source with Make

```bash
make install        # production
make dev-install    # development (includes pytest, black, ruff)
```

### System dependencies

AYN uses [yara-python](https://github.com/VirusTotal/yara-python) for rule-based detection. On most systems pip handles this automatically, but you may need the YARA C library:

| Distro | Command |
|---|---|
| **Debian / Ubuntu** | `sudo apt install yara libyara-dev` |
| **RHEL / CentOS / Fedora** | `sudo dnf install yara yara-devel` |
| **Arch** | `sudo pacman -S yara` |
| **macOS (Homebrew)** | `brew install yara` |

After the system library is installed, `pip install yara-python` (or `pip install .`) will link against it.

---

## Usage

All commands accept `--verbose` / `-v` for detailed output and `--config <path>` to load a custom YAML config file.

### File System Scanning

```bash
# Full scan — all configured paths
sudo ayn-antivirus scan

# Quick scan — /tmp, /var/tmp, /dev/shm, crontabs
sudo ayn-antivirus scan --quick

# Deep scan — includes memory and hidden artifacts
sudo ayn-antivirus scan --deep

# Scan a single file
ayn-antivirus scan --file /tmp/suspicious.bin

# Targeted path with exclusions
sudo ayn-antivirus scan --path /home --exclude '*.log' --exclude '*.gz'
```

### Process Scanning

```bash
# Scan running processes for miners & suspicious CPU usage
sudo ayn-antivirus scan-processes
```

Checks every running process against known miner names (xmrig, minerd, ethminer, etc.) and flags anything above the CPU threshold (default 80%).

### Network Scanning

```bash
# Inspect active connections for mining pool traffic
sudo ayn-antivirus scan-network
```

Compares remote addresses against known mining pool domains and suspicious ports (3333, 4444, 5555, 14444, etc.).

### Update Signatures

```bash
# Fetch latest threat intelligence from all feeds
sudo ayn-antivirus update

# Force re-download even if signatures are fresh
sudo ayn-antivirus update --force
```

### Quarantine Management

```bash
# List quarantined items
ayn-antivirus quarantine list

# View details of a quarantined item
ayn-antivirus quarantine info 1

# Restore a quarantined file to its original location
sudo ayn-antivirus quarantine restore 1

# Permanently delete a quarantined item
ayn-antivirus quarantine delete 1
```

### Real-Time Monitoring

```bash
# Watch configured paths in the foreground (Ctrl+C to stop)
sudo ayn-antivirus monitor

# Watch specific paths
sudo ayn-antivirus monitor --paths /var/www --paths /tmp

# Run as a background daemon
sudo ayn-antivirus monitor --daemon
```

### Report Generation

```bash
# Plain text report to stdout
ayn-antivirus report

# JSON report to a file
ayn-antivirus report --format json --output /tmp/report.json

# HTML report
ayn-antivirus report --format html --output report.html
```

### Auto-Fix / Remediation

```bash
# Preview all remediation actions (no changes)
sudo ayn-antivirus fix --all --dry-run

# Apply all remediations
sudo ayn-antivirus fix --all

# Fix a specific threat by ID
sudo ayn-antivirus fix --threat-id 3
```

### Status Check

```bash
# View protection status at a glance
ayn-antivirus status
```

Displays signature freshness, last scan time, quarantine count, real-time monitor state, and engine toggles.

### Configuration

```bash
# Show active configuration
ayn-antivirus config

# Set a config value (persisted to ~/.ayn-antivirus/config.yaml)
ayn-antivirus config --set auto_quarantine true
ayn-antivirus config --set scan_schedule '0 3 * * *'
```

---

## Configuration

### Config file locations

AYN loads configuration from the first file found (in order):

| Priority | Path |
|---|---|
| 1 | Explicit `--config <path>` flag |
| 2 | `/etc/ayn-antivirus/config.yaml` |
| 3 | `~/.ayn-antivirus/config.yaml` |

### Config file options

```yaml
# Directories to scan
scan_paths:
  - /
exclude_paths:
  - /proc
  - /sys
  - /dev
  - /run
  - /snap

# Storage
quarantine_path: /var/lib/ayn-antivirus/quarantine
db_path: /var/lib/ayn-antivirus/signatures.db
log_path: /var/log/ayn-antivirus/

# Behavior
auto_quarantine: false
scan_schedule: "0 2 * * *"
max_file_size: 104857600  # 100 MB

# Engines
enable_yara: true
enable_heuristics: true
enable_realtime_monitor: false

# API keys (optional)
api_keys:
  malwarebazaar: ""
  virustotal: ""
```

### Environment variables

Environment variables override config file values. Copy `.env.sample` to `.env` and populate as needed.

| Variable | Description | Default |
|---|---|---|
| `AYN_SCAN_PATH` | Comma-separated scan paths | `/` |
| `AYN_QUARANTINE_PATH` | Quarantine vault directory | `/var/lib/ayn-antivirus/quarantine` |
| `AYN_DB_PATH` | Signature database path | `/var/lib/ayn-antivirus/signatures.db` |
| `AYN_LOG_PATH` | Log directory | `/var/log/ayn-antivirus/` |
| `AYN_AUTO_QUARANTINE` | Auto-quarantine on detection (`true`/`false`) | `false` |
| `AYN_SCAN_SCHEDULE` | Cron expression for scheduled scans | `0 2 * * *` |
| `AYN_MAX_FILE_SIZE` | Max file size to scan (bytes) | `104857600` |
| `AYN_MALWAREBAZAAR_API_KEY` | MalwareBazaar API key | — |
| `AYN_VIRUSTOTAL_API_KEY` | VirusTotal API key | — |

---

## Threat Intelligence Feeds

AYN aggregates indicators from multiple open-source threat intelligence feeds:

| Feed | Source | Data Type |
|---|---|---|
| **MalwareBazaar** | [bazaar.abuse.ch](https://bazaar.abuse.ch) | Malware sample hashes (SHA-256) |
| **ThreatFox** | [threatfox.abuse.ch](https://threatfox.abuse.ch) | IOCs — IPs, domains, URLs |
| **URLhaus** | [urlhaus.abuse.ch](https://urlhaus.abuse.ch) | Malware distribution URLs |
| **Feodo Tracker** | [feodotracker.abuse.ch](https://feodotracker.abuse.ch) | Botnet C2 IP addresses |
| **Emerging Threats** | [rules.emergingthreats.net](https://rules.emergingthreats.net) | Suricata / Snort IOCs |
| **YARA Rules** | Community & custom | Pattern-matching rules (`signatures/yara_rules/`) |

Signatures are stored in a local SQLite database (`signatures.db`) with separate tables for hashes, IPs, domains, and URLs. Run `ayn-antivirus update` to pull the latest data.

---

## Architecture

```
┌─────────────────────────────────────────────────────────────────┐
│                          CLI (cli.py)                           │
│                     Click commands + Rich UI                    │
└───────────────────────────────┬─────────────────────────────────┘
                                │
                    ┌───────────▼───────────┐
                    │    Core Scan Engine   │
                    │     (core/engine.py)  │
                    └───┬────┬────┬────┬───┘
                        │    │    │    │
          ┌─────────────┘    │    │    └─────────────┐
          ▼                  ▼    ▼                   ▼
 ┌─────────────────┐ ┌──────────────┐ ┌──────────────────────┐
 │    Detectors     │ │   Scanners   │ │    Monitor           │
 │ ┌─────────────┐ │ │ ┌──────────┐ │ │ ┌──────────────────┐ │
 │ │  Signature   │ │ │ │  File    │ │ │ │  Real-time       │ │
 │ │  YARA        │ │ │ │  Process │ │ │ │  (watchdog)      │ │
 │ │  Heuristic   │ │ │ │  Network │ │ │ └──────────────────┘ │
 │ │  Cryptominer │ │ │ │  Memory  │ │ └──────────────────────┘
 │ │  Spyware     │ │ │ └──────────┘ │
 │ │  Rootkit     │ │ └──────────────┘
 │ └─────────────┘ │
 └─────────────────┘
          │                              ┌──────────────────────┐
          │    ┌───────────────────┐     │     Signatures       │
          └───►│   Event Bus       │     │ ┌──────────────────┐ │
               │ (core/event_bus)  │     │ │  Feed Manager    │ │
               └──────┬────────────┘     │ │  Hash DB         │ │
                      │                  │ │  IOC DB          │ │
           ┌──────────┼──────────┐       │ │  YARA Rules      │ │
           ▼          ▼          ▼       │ └──────────────────┘ │
    ┌────────────┐ ┌────────┐ ┌───────┐  └──────────────────────┘
    │ Quarantine │ │Reports │ │Remedy │
    │   Vault    │ │  Gen.  │ │Patcher│
    │ (Fernet)   │ │txt/json│ │       │
    │            │ │  /html │ │       │
    └────────────┘ └────────┘ └───────┘
```

### Module summary

| Module | Path | Responsibility |
|---|---|---|
| **CLI** | `cli.py` | User-facing commands (Click + Rich) |
| **Config** | `config.py` | YAML & env-var configuration loader |
| **Engine** | `core/engine.py` | Orchestrates file/process/network scans |
| **Event Bus** | `core/event_bus.py` | Internal pub/sub for scan events |
| **Scheduler** | `core/scheduler.py` | Cron-based scheduled scans |
| **Detectors** | `detectors/` | Pluggable detection engines (signature, YARA, heuristic, cryptominer, spyware, rootkit) |
| **Scanners** | `scanners/` | File, process, network, and memory scanners |
| **Monitor** | `monitor/realtime.py` | Watchdog-based real-time file watcher |
| **Quarantine** | `quarantine/vault.py` | Fernet-encrypted file isolation vault |
| **Remediation** | `remediation/patcher.py` | Auto-fix engine (kill, block, clean, restore) |
| **Reports** | `reports/generator.py` | Text, JSON, and HTML report generation |
| **Signatures** | `signatures/` | Feed fetchers, hash DB, IOC DB, YARA rules |

---

## Auto-Patching Capabilities

The remediation engine (`ayn-antivirus fix`) can automatically apply the following fixes:

| Action | Description |
|---|---|
| **Fix permissions** | Strips SUID, SGID, and world-writable bits from compromised files |
| **Kill processes** | Sends SIGKILL to confirmed malicious processes (miners, reverse shells) |
| **Block IPs** | Adds `iptables` DROP rules for C2 and mining pool IP addresses |
| **Block domains** | Redirects malicious domains to `127.0.0.1` via `/etc/hosts` |
| **Clean cron jobs** | Removes entries matching suspicious patterns (curl\|bash, xmrig, etc.) |
| **Fix LD_PRELOAD** | Clears `/etc/ld.so.preload` entries injected by rootkits |
| **Clean SSH keys** | Removes `command=` forced-command entries from `authorized_keys` |
| **Remove startup entries** | Strips malicious lines from init scripts, systemd units, and `rc.local` |
| **Restore binaries** | Reinstalls tampered system binaries via `apt`/`dnf`/`yum` package manager |

> **Tip:** Always run with `--dry-run` first to preview changes before applying.

---

## Running as a Service

Create a systemd unit to run AYN as a persistent real-time monitor:

```ini
# /etc/systemd/system/ayn-antivirus.service
[Unit]
Description=AYN Antivirus Real-Time Monitor
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/ayn-antivirus monitor --daemon
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=10
User=root
Group=root

# Hardening
ProtectSystem=strict
ReadWritePaths=/var/lib/ayn-antivirus /var/log/ayn-antivirus
NoNewPrivileges=false
PrivateTmp=true

[Install]
WantedBy=multi-user.target
```

```bash
# Enable and start
sudo systemctl daemon-reload
sudo systemctl enable ayn-antivirus
sudo systemctl start ayn-antivirus

# Check status
sudo systemctl status ayn-antivirus

# View logs
sudo journalctl -u ayn-antivirus -f
```

Optionally add a timer unit for scheduled signature updates:

```ini
# /etc/systemd/system/ayn-antivirus-update.timer
[Unit]
Description=AYN Antivirus Signature Update Timer

[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true

[Install]
WantedBy=timers.target
```

```ini
# /etc/systemd/system/ayn-antivirus-update.service
[Unit]
Description=AYN Antivirus Signature Update

[Service]
Type=oneshot
ExecStart=/usr/local/bin/ayn-antivirus update
User=root
```

```bash
sudo systemctl enable --now ayn-antivirus-update.timer
```

---

## Development

### Prerequisites

- Python 3.9+
- [YARA](https://virustotal.github.io/yara/) C library (for yara-python)

### Setup

```bash
git clone <repo-url>
cd ayn-antivirus
pip install -e ".[dev]"
```

### Run tests

```bash
make test
# or directly:
pytest --cov=ayn_antivirus tests/
```

### Lint & format

```bash
make lint
# or directly:
ruff check ayn_antivirus/
black --check ayn_antivirus/
```

### Auto-format

```bash
black ayn_antivirus/
```

### Project layout

```
ayn-antivirus/
├── ayn_antivirus/
│   ├── __init__.py          # Package version
│   ├── __main__.py          # python -m ayn_antivirus entry point
│   ├── cli.py               # Click CLI commands
│   ├── config.py            # Configuration loader
│   ├── constants.py         # Thresholds, paths, known indicators
│   ├── core/
│   │   ├── engine.py        # Scan engine orchestrator
│   │   ├── event_bus.py     # Internal event system
│   │   └── scheduler.py     # Cron-based scheduler
│   ├── detectors/
│   │   ├── base.py          # BaseDetector ABC + DetectionResult
│   │   ├── signature_detector.py
│   │   ├── yara_detector.py
│   │   ├── heuristic_detector.py
│   │   ├── cryptominer_detector.py
│   │   ├── spyware_detector.py
│   │   └── rootkit_detector.py
│   ├── scanners/
│   │   ├── file_scanner.py
│   │   ├── process_scanner.py
│   │   ├── network_scanner.py
│   │   └── memory_scanner.py
│   ├── monitor/
│   │   └── realtime.py      # Watchdog-based file watcher
│   ├── quarantine/
│   │   └── vault.py         # Fernet-encrypted quarantine
│   ├── remediation/
│   │   └── patcher.py       # Auto-fix engine
│   ├── reports/
│   │   └── generator.py     # Report output (text/json/html)
│   ├── signatures/
│   │   ├── manager.py       # Feed orchestrator
│   │   ├── db/              # Hash DB + IOC DB (SQLite)
│   │   ├── feeds/           # Feed fetchers (abuse.ch, ET, etc.)
│   │   └── yara_rules/      # .yar rule files
│   └── utils/
│       ├── helpers.py
│       └── logger.py
├── tests/                   # pytest test suite
├── pyproject.toml           # Build config & dependencies
├── Makefile                 # Dev shortcuts
├── .env.sample              # Environment variable template
└── README.md
```

### Contributing

1. Fork the repo and create a feature branch
2. Write tests for new functionality
3. Ensure `make lint` and `make test` pass
4. Submit a pull request

---

## License

This project is licensed under the **MIT License**. See [LICENSE](LICENSE) for details.

---

<p align="center">
  <strong>⚔️ Stay protected. Stay vigilant. ⚔️</strong>
</p>
