Skip to content
carlosparraPublic

About

Rust-based macOS endpoint detection agent. Real-time filesystem monitoring with YAML rules for threat detection (LaunchAgents, malicious scripts, ransomware). Sends structured alerts to backend APIs. Zero unsafe code, async Tokio runtime

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

πŸ›‘οΈ MacGuard EDR

Enterprise-grade macOS Endpoint Detection and Response

Rust macOS License: MIT Security

Real-time threat detection and response for macOS environments

Features β€’ Quick Start β€’ Documentation β€’ Contributing


🎯 Overview

MacGuard EDR is a high-performance, Rust-based endpoint detection and response agent specifically designed for macOS environments. It provides enterprise-grade security monitoring through intelligent filesystem surveillance, behavioral analysis, and real-time threat detection.

🎯 Key Highlights

  • πŸš€ High Performance: Built with Rust for maximum efficiency and safety
  • πŸ”’ Enterprise Security: Production-ready threat detection and response
  • πŸ“Š Real-time Analytics: Instant behavioral analysis and alerting
  • πŸ› οΈ Easy Integration: RESTful API and comprehensive documentation
  • πŸ§ͺ Battle-tested: Comprehensive testing suite and validation tools

πŸ“š Table of Contents


✨ Features

πŸ” Core Security Features

  • Real-time Filesystem Monitoring - Advanced surveillance of critical system directories
  • Behavioral Analysis - Intelligent detection of suspicious activity patterns
  • Persistence Detection - Identifies malware installation and persistence mechanisms
  • Mass File Activity Detection - Ransomware and bulk operation detection

βš™οΈ Technical Features

  • YAML-based Configuration - Flexible, human-readable rule definitions
  • Structured Alerts - JSON-formatted alerts with rich contextual data
  • HTTP Transport - RESTful API integration with configurable endpoints
  • Offline Queuing - Local persistence when backend services are unavailable
  • Graceful Degradation - Continuous operation despite component failures

πŸš€ Performance & Reliability

  • Zero-copy Operations - Memory-efficient file monitoring
  • Async Architecture - Non-blocking I/O with Tokio runtime
  • Rate Limiting - Built-in frequency analysis prevents alert storms
  • Resource Management - Bounded queues and automatic cleanup

πŸ—οΈ Architecture

Core Components

  • Config: YAML-based configuration management
  • Device: System information and device identification
  • Events: Event structures and alert definitions
  • Filesystem: Real-time file system monitoring using notify
  • Rules: Detection rule engine with frequency analysis
  • Alerts: Alert management and queuing
  • Transport: HTTP client for backend communication
  • Storage: Local persistence for offline alerts

πŸ“‚ Monitored Locations

  • /tmp - Temporary files and suspicious scripts
  • /Users - User directories and profiles
  • /Library/LaunchAgents - User-level persistence
  • /Library/LaunchDaemons - System-level persistence

πŸ” Detection Capabilities

Persistence Detection

  • New .plist files in LaunchAgents/LaunchDaemons
  • Unauthorized system library modifications

Suspicious Activity

  • Executable scripts in /tmp directory
  • Mass file operations (potential ransomware)
  • Hidden file creation patterns

File Extensions Monitored

  • .plist - Launch services configuration
  • .sh, .zsh - Shell scripts
  • .py - Python scripts
  • .command - macOS executable commands

πŸš€ Quick Start

πŸ“‹ Prerequisites

Requirement Version Notes
Rust 1.70+ 2021 edition required
macOS 10.15+ Catalina or later
Python 3.8+ For test backend only
Git 2.0+ For cloning repository

πŸ“¦ Installation

git clone https://github.com/carlosparra/Mac-Guard.git
cd Mac-Guard
cargo build --release

βš™οΈ Configuration

Edit config/macguard.yaml:

agent:
  device_id: null  # Auto-generated
  log_level: "info"
  scan_interval_seconds: 5

monitoring:
  watch_paths:
    - "/tmp"
    - "/Users"
    - "/Library/LaunchAgents"
    - "/Library/LaunchDaemons"
  rules_file: "policies/macguard_rules.yaml"

backend:
  endpoint: "http://localhost:8000/v1/alerts"
  timeout_seconds: 30
  retry_attempts: 3

πŸƒ Running

# Interactive mode with health checks
./target/release/macguard

# Daemon mode
./target/release/macguard --daemon

# Verbose logging
./target/release/macguard --verbose

# Custom config
./target/release/macguard --config /path/to/config.yaml

βš™οΈ Detection Rules

Rules are defined in policies/macguard_rules.yaml. Example rule:

rules:
  - name: "LaunchAgent Persistence"
    description: "Detects creation of new plist files in LaunchAgents directories"
    severity: "High"
    enabled: true
    conditions:
      file_extensions: [".plist"]
      paths: ["/Library/LaunchAgents", "LaunchAgents"]
      event_types: ["FileCreated"]
    actions: ["alert"]

Rule Conditions

  • file_extensions: File extension filters
  • paths: Path substring matching
  • event_types: Event type filters (FileCreated, FileModified, FileDeleted)
  • frequency_threshold: Rate-based detection

πŸ“‹ Alert Format

{
  "alert_id": "uuid-v4",
  "device_id": "device-uuid",
  "hostname": "macbook-pro.local",
  "event_type": "FileCreated",
  "severity": "High",
  "path": "/Library/LaunchAgents/malicious.plist",
  "reason": "LaunchAgent Persistence: Detected creation of new plist file",
  "timestamp": "2024-01-01T12:00:00Z",
  "evidence": {
    "file_info": {...},
    "additional_context": {...}
  }
}

πŸ§ͺ Testing & Validation

Quick Test Setup

MacGuard EDR includes comprehensive testing tools to validate functionality in both development and production environments.

1. Setup Test Backend

First, start the included FastAPI test backend to receive alerts:

# Setup Python environment
cd backend
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -r requirements.txt

# Start test backend
python main.py

The backend will start on http://localhost:8000 with:

  • Health endpoint: GET /health
  • Alerts endpoint: POST /v1/alerts
  • Dashboard: http://localhost:8000/docs (Swagger UI)
  • Statistics: GET /v1/alerts/stats

2. Build and Run MacGuard

# Build release version
cargo build --release

# Run with verbose logging (in another terminal)
./target/release/macguard --config config/macguard.yaml --verbose

# Or use management script
./scripts/manage.sh start

3. Run Automated Tests

MacGuard includes a comprehensive test suite that simulates real threat scenarios:

# Make test script executable
chmod +x test_scenarios.sh

# Run all test scenarios
./test_scenarios.sh all

# Run specific tests
./test_scenarios.sh launchagent    # Test LaunchAgent persistence detection
./test_scenarios.sh tmpscript      # Test suspicious scripts in /tmp
./test_scenarios.sh mass           # Test mass file activity (ransomware simulation)
./test_scenarios.sh system         # Test system directory monitoring
./test_scenarios.sh alerts         # Check generated alerts
./test_scenarios.sh stats          # View backend statistics

Test Scenarios Explained

πŸ” LaunchAgent Persistence Test

./test_scenarios.sh launchagent
  • Creates a malicious .plist file in ~/Library/LaunchAgents
  • Should trigger HIGH severity alert
  • Simulates common macOS persistence technique

πŸ•·οΈ Suspicious Script Test

./test_scenarios.sh tmpscript
  • Creates .sh and .py scripts in /tmp directory
  • Should trigger MEDIUM severity alerts
  • Detects potential malware droppers

πŸ’₯ Mass File Activity Test

./test_scenarios.sh mass
  • Rapidly creates 20+ files in short time window
  • Should trigger HIGH severity alert
  • Simulates ransomware encryption patterns

πŸ›‘οΈ System Directory Test

./test_scenarios.sh system
  • Creates files in monitored system locations
  • Tests unauthorized system modifications
  • Validates directory monitoring scope

Expected Test Results

When tests run successfully, you should see:

  1. Backend Logs showing received alerts:
🚨 ALERT: High - LaunchAgent Persistence: Detected creation of new plist file (device-uuid)
🚨 ALERT: Medium - Suspicious Script in /tmp: Detected creation of executable script (device-uuid)
  1. Agent Logs showing detections:
INFO Alert generated: 550e8400-e29b-41d4-a716-446655440000 - LaunchAgent Persistence (High)
INFO Alert generated: 550e8400-e29b-41d4-a716-446655440001 - Suspicious Script in /tmp (Medium)
  1. HTTP Requests in backend:
INFO: 127.0.0.1:54778 - "POST /v1/alerts HTTP/1.1" 200 OK

Manual Testing

You can also test manually by creating suspicious files:

# Test LaunchAgent detection
cat > ~/Library/LaunchAgents/com.test.malicious.plist << 'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.test.malicious</string>
    <key>ProgramArguments</key>
    <array>
        <string>/tmp/backdoor.sh</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>
EOF

# Test script detection
echo '#!/bin/bash' > /tmp/suspicious.sh
echo 'echo "Malicious payload"' >> /tmp/suspicious.sh

# Test Python script
echo '#!/usr/bin/env python3' > /tmp/keylogger.py
echo 'print("Fake keylogger")' >> /tmp/keylogger.py

Viewing Results

Real-time Monitoring

# MacGuard agent logs
./scripts/manage.sh logs

# System logs (if installed as service)
tail -f /var/log/macguard/macguard.log

# Backend statistics
curl -s http://localhost:8000/v1/alerts/stats | jq .

Web Dashboard

Visit http://localhost:8000/docs for:

  • Interactive API documentation
  • Test alert submission
  • View received alerts
  • Backend health status

Command Line Queries

# Get recent alerts
curl -s http://localhost:8000/v1/alerts?limit=10 | jq '.alerts[] | {severity, reason, path, timestamp}'

# Clear test alerts
curl -X DELETE http://localhost:8000/v1/alerts

# Health check
curl http://localhost:8000/health

Performance Testing

High Volume Test

# Generate many events quickly
for i in {1..50}; do
  echo "test file $i" > /tmp/bulk_test_$i.txt
  sleep 0.1
done

# Check if frequency-based detection triggers
./scripts/manage.sh logs | grep "Mass File Activity"

Resource Monitoring

# CPU and memory usage
ps aux | grep macguard

# File descriptor usage  
lsof -p $(pgrep macguard) | wc -l

# Network connections
netstat -an | grep :8000

Troubleshooting Tests

No Alerts Generated

  1. Check agent is running: ./scripts/manage.sh status
  2. Verify backend connectivity: curl http://localhost:8000/health
  3. Check configuration: cat config/macguard.yaml
  4. Review logs: ./scripts/manage.sh logs

Backend Connection Failed

  1. Ensure backend is running on port 8000
  2. Check firewall settings
  3. Verify endpoint in config matches backend URL
  4. Test with curl: curl -v http://localhost:8000/health

Rules Not Triggering

  1. Check rules file: cat policies/macguard_rules.yaml
  2. Verify file extensions match
  3. Confirm paths are being monitored
  4. Test with known triggering files

Test Environment Cleanup

After testing, clean up test files:

# Run cleanup (automatically done by test script)
rm -f ~/Library/LaunchAgents/com.test.malicious.plist
rm -f /tmp/suspicious.sh /tmp/keylogger.py
rm -f /tmp/bulk_test_*.txt

# Or use test script cleanup
./test_scenarios.sh cleanup

Continuous Testing

For ongoing validation:

# Set up automated testing (cron job example)
# Run tests every hour and log results
0 * * * * cd /path/to/macguard && ./test_scenarios.sh all >> /var/log/macguard-tests.log 2>&1

# Monitor test results
tail -f /var/log/macguard-tests.log

πŸ’» Development

Code Quality

The project enforces strict code quality standards:

# Format code
cargo fmt

# Lint with pedantic rules
cargo clippy --all-targets --all-features -- -D warnings

# Run tests
cargo test

# Security audit
cargo audit

Project Guidelines

  • #![deny(clippy::all)] and #![deny(clippy::pedantic)]
  • #![deny(unsafe_code)] - No unsafe code allowed
  • Comprehensive error handling with anyhow
  • Structured logging with tracing
  • Async-first design with tokio

Testing

# Run all tests
cargo test

# Run with output
cargo test -- --nocapture

# Test specific module
cargo test rules_tests

πŸ”— Backend Integration

MacGuard sends alerts to a configurable HTTP endpoint:

  • Endpoint: POST /v1/alerts
  • Format: JSON array of alerts
  • Authentication: Bearer token (optional)
  • Retry Logic: Exponential backoff with configurable attempts

Example FastAPI backend endpoint:

from fastapi import FastAPI
from typing import List

app = FastAPI()

@app.post("/v1/alerts")
async def receive_alerts(alerts: List[dict]):
    for alert in alerts:
        print(f"Alert: {alert['reason']} - {alert['path']}")
    return {"status": "ok", "received": len(alerts)}

πŸ”’ Security Considerations

  • User-mode only: No kernel extensions or privileged operations
  • Read-only monitoring: No file modification capabilities
  • Safe Rust: No unsafe code blocks
  • Input validation: All external inputs validated
  • Error isolation: Individual component failures don't crash agent

⚑ Performance

  • Low overhead: Efficient file watching with system notifications
  • Batched processing: Alerts sent in configurable batches
  • Rate limiting: Built-in frequency analysis prevents alert spam
  • Memory efficient: Bounded queues and cleanup routines

⚠️ Limitations

  • User-mode monitoring only (no kernel-level visibility)
  • macOS-specific implementation
  • No real-time process monitoring (filesystem focus)
  • Limited to configured watch paths

🀝 Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Implement your changes with comprehensive tests
  4. Ensure code quality: cargo fmt && cargo clippy && cargo test
  5. Commit your changes (git commit -m 'Add amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Submit a pull request

Development Setup

# Clone your fork
git clone https://github.com/your-username/Mac-Guard.git
cd Mac-Guard

# Install development dependencies
rustup component add rustfmt clippy
cargo install cargo-audit

# Run the full development workflow
cargo fmt
cargo clippy --all-targets --all-features -- -D warnings
cargo test
cargo audit

πŸ“„ License

Licensed under the MIT License. See LICENSE file for details.

πŸ“ž Support & Community

For issues and feature requests, please use the GitHub issue tracker.

Getting Help

  • πŸ› Bug Reports: Use our bug report template
  • πŸ’‘ Feature Requests: Submit enhancement proposals
  • ❓ Questions: Check existing issues or start a discussion
  • πŸ”’ Security Issues: Please report privately to the maintainers

Built with ❀️ for macOS Security

Made by Carlos Alberto β€’ MIT License

About

Rust-based macOS endpoint detection agent. Real-time filesystem monitoring with YAML rules for threat detection (LaunchAgents, malicious scripts, ransomware). Sends structured alerts to backend APIs. Zero unsafe code, async Tokio runtime

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages