Enterprise-grade macOS Endpoint Detection and Response
Real-time threat detection and response for macOS environments
Features β’ Quick Start β’ Documentation β’ Contributing
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.
- π 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
- β¨ Features
- ποΈ Architecture
- π Monitored Locations
- π Detection Capabilities
- π Quick Start
- βοΈ Detection Rules
- π Alert Format
- π§ͺ Testing & Validation
- π» Development
- π Backend Integration
- π Security Considerations
- β‘ Performance
β οΈ Limitations- π€ Contributing
- π License
- π Support & Community
- 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
- 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
- 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
- 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
/tmp- Temporary files and suspicious scripts/Users- User directories and profiles/Library/LaunchAgents- User-level persistence/Library/LaunchDaemons- System-level persistence
- New
.plistfiles in LaunchAgents/LaunchDaemons - Unauthorized system library modifications
- Executable scripts in
/tmpdirectory - Mass file operations (potential ransomware)
- Hidden file creation patterns
.plist- Launch services configuration.sh,.zsh- Shell scripts.py- Python scripts.command- macOS executable commands
| 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 |
git clone https://github.com/carlosparra/Mac-Guard.git
cd Mac-Guard
cargo build --releaseEdit 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# 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.yamlRules 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"]file_extensions: File extension filterspaths: Path substring matchingevent_types: Event type filters (FileCreated, FileModified, FileDeleted)frequency_threshold: Rate-based detection
{
"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": {...}
}
}MacGuard EDR includes comprehensive testing tools to validate functionality in both development and production environments.
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.pyThe 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
# 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 startMacGuard 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.sh launchagent- Creates a malicious
.plistfile in~/Library/LaunchAgents - Should trigger HIGH severity alert
- Simulates common macOS persistence technique
./test_scenarios.sh tmpscript- Creates
.shand.pyscripts in/tmpdirectory - Should trigger MEDIUM severity alerts
- Detects potential malware droppers
./test_scenarios.sh mass- Rapidly creates 20+ files in short time window
- Should trigger HIGH severity alert
- Simulates ransomware encryption patterns
./test_scenarios.sh system- Creates files in monitored system locations
- Tests unauthorized system modifications
- Validates directory monitoring scope
When tests run successfully, you should see:
- 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)
- 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)
- HTTP Requests in backend:
INFO: 127.0.0.1:54778 - "POST /v1/alerts HTTP/1.1" 200 OK
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# 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 .Visit http://localhost:8000/docs for:
- Interactive API documentation
- Test alert submission
- View received alerts
- Backend health status
# 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# 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"# CPU and memory usage
ps aux | grep macguard
# File descriptor usage
lsof -p $(pgrep macguard) | wc -l
# Network connections
netstat -an | grep :8000- Check agent is running:
./scripts/manage.sh status - Verify backend connectivity:
curl http://localhost:8000/health - Check configuration:
cat config/macguard.yaml - Review logs:
./scripts/manage.sh logs
- Ensure backend is running on port 8000
- Check firewall settings
- Verify endpoint in config matches backend URL
- Test with curl:
curl -v http://localhost:8000/health
- Check rules file:
cat policies/macguard_rules.yaml - Verify file extensions match
- Confirm paths are being monitored
- Test with known triggering files
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 cleanupFor 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.logThe 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#![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
# Run all tests
cargo test
# Run with output
cargo test -- --nocapture
# Test specific module
cargo test rules_testsMacGuard 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)}- 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
- 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
- User-mode monitoring only (no kernel-level visibility)
- macOS-specific implementation
- No real-time process monitoring (filesystem focus)
- Limited to configured watch paths
We welcome contributions! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Implement your changes with comprehensive tests
- Ensure code quality:
cargo fmt && cargo clippy && cargo test - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Submit a pull request
# 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 auditLicensed under the MIT License. See LICENSE file for details.
For issues and feature requests, please use the GitHub issue tracker.
- π 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