Skip to content

ericescobar/MeshC2

Repository files navigation

MeshC2 - Remote Terminal Access

MeshC2 is a secure remote troubleshooting service that operates over Meshtastic mesh networks. It enables authorized system administrators to execute commands on remote systems and send notifications from local scripts via encrypted mesh radio communications, making it ideal for off-grid deployments, emergency scenarios, and distributed infrastructure management.

Features

Core Functionality

  • Remote Command Execution: Execute shell commands on remote systems via Meshtastic mesh network
  • Channel-Based Security: Operates on specific encrypted channels with PSK authentication
  • Real Device Integration: Full support for hardware Meshtastic devices via USB
  • Message Queuing: Reliable command queuing and response buffering
  • Status Monitoring: Real-time service status and connection monitoring

Channel Management

  • Multi-Channel Support: Create, configure, and switch between channels
  • QR Code Generation: Generate QR codes for easy channel sharing
  • Encryption Key Management: Support for custom or randomly generated PSK keys
  • Channel Discovery: List and inspect existing device channels

Device Compatibility

  • Heltec LoRa 32 boards (v1, v2, v3)
  • RAK WisBlock modules
  • ESP32-based Meshtastic devices
  • Generic devices with CP2102, CH340, or FTDI USB-to-serial chips

Local Messaging

  • Script Integration: Send messages from local scripts and programs via Unix socket IPC
  • Socket Communication: Uses running service to avoid device conflicts
  • Flexible Channels: Send to default service channel or specify custom channels
  • Message Splitting: Automatically splits long messages with proper sequencing
  • Timestamp Support: Optional timestamp prefixing for notifications
  • Retry Logic: Automatic retry with error logging for reliable delivery

Security Features

  • Encrypted Communications: All messages encrypted with channel-specific PSK
  • User Isolation: Runs as dedicated system user with minimal privileges
  • Resource Limits: CPU and memory usage constraints
  • Access Control: Limited to specific device groups and directories

🚀 What You Can Do

Remote Troubleshooting:

# On mesh network: send "ps aux" to target system
# Target system executes and responds with process list

Local Script Notifications:

# From any script on the system
meshc2 --message "Backup completed successfully" --timestamp
meshc2 --message "ALERT: Disk usage 95%" --channel "critical"

System Integration:

# In backup scripts
if backup_successful; then
    meshc2 --message "$(hostname): Backup OK" --timestamp
else
    meshc2 --message "$(hostname): BACKUP FAILED" --timestamp --channel "alerts"
fi

Quick Start

Installation

# Clone the repository
git clone https://github.com/your-org/meshc2.git
cd meshc2

# Interactive installation (recommended for first-time setup)
./install.sh

# Automated upgrade preserving existing configuration
./install.sh --upgrade-only --keep-existing-config

# Automated upgrade with fresh configuration
./install.sh --upgrade-only

# Show installer help and options
./install.sh --help

# Verify installation
./validate_install.sh

Installation Options:

  • Interactive Mode (default): Prompts for installation choices when existing installation detected
  • Automated Upgrade (--upgrade-only): Skips prompts, automatically upgrades existing installation
  • Config Preservation (--keep-existing-config): Preserves existing configuration during upgrade
  • Fresh Install: Available interactively for complete clean installation

Basic Usage

# List available Meshtastic devices
meshc2 --list-devices

# List channels on connected device
meshc2 --real-device --list-channels

# Create a new encrypted channel
meshc2 --real-device --create-channel "support-team"

# Start the service on a specific channel
sudo systemctl start meshc2

# Send messages from local scripts
meshc2 --message "backup completed successfully"
meshc2 --message "system rebooting" --timestamp
meshc2 --message "alert: disk space low" --channel "alerts"

Architecture

Components

MeshC2 Service
├── Meshtastic Listener    # Device communication and message reception
├── Command Queue          # Message queuing and ordering
├── Command Processor      # Command parsing and execution
├── Message Sender         # Response transmission
├── Output Manager         # Response buffering and formatting
└── Configuration Manager  # Settings and channel management

Communication Flow

  1. Message Reception: Meshtastic device receives encrypted messages via mesh network
  2. Channel Filtering: Messages filtered by configured channel index
  3. Command Processing: Valid commands parsed and queued for execution
  4. Execution: Commands executed in controlled environment
  5. Response Transmission: Results sent back via mesh network
  6. Logging: All activities logged for audit and debugging

Directory Structure

/opt/meshc2/              # Application installation
├── src/                  # Source code
├── config/               # Configuration templates
├── venv/                 # Python virtual environment
├── meshc2                # Command wrapper script
└── monitor_messages.sh   # Message monitoring utility

/etc/meshc2/              # Configuration files
└── config.yml            # Main configuration

/var/log/meshc2/          # Log files
└── meshc2.log

/var/lib/meshc2/          # Application data

Configuration

Service Configuration

Edit /etc/meshc2/config.yml:

# Meshtastic Configuration
meshtastic:
  channel: "remote-support"    # Default channel name
  use_real_device: true        # Use hardware device vs mock
  serial_port: null            # Auto-detect if null
  max_retries: 3               # Connection retry attempts
  retry_interval: 5            # Seconds between retries

# System Configuration  
system:
  command_timeout: 300         # Command execution timeout (seconds)
  max_message_length: 230      # Maximum message size (bytes)
  queue_max_size: 100          # Maximum queued commands

# Logging Configuration
logging:
  level: "INFO"                # DEBUG, INFO, WARNING, ERROR
  file: "/var/log/meshc2/meshc2.log"
  max_size: "10MB"             # Log rotation size
  backup_count: 5              # Number of log files to keep

Systemd Service

The service is configured as a systemd unit with the following features:

  • Automatic Startup: Starts on boot
  • Restart Policy: Automatic restart on failure
  • Security Sandbox: Runs with restricted permissions
  • Resource Limits: CPU and memory constraints
  • Logging Integration: Integrates with systemd journal

Channel Management

Creating Channels

# Create channel with random encryption key
meshc2 --real-device --create-channel "ops-team"

# Create channel with specific key
meshc2 --real-device --create-channel "secure-ops" --channel-key "your-base64-key"

# Create channel with specific preset
meshc2 --real-device --create-channel "long-range" --channel-preset "LONG_FAST"

Channel Information

Channels are created with the following properties:

  • Name: Human-readable channel identifier
  • Index: Numeric channel position (1-7, 0 reserved for primary)
  • PSK: 256-bit base64-encoded encryption key
  • Preset: Modulation settings (LONG_FAST default)
  • QR Code: Generated for easy sharing

Sharing Channels

When creating channels, QR codes are automatically generated:

  • URL Format: https://meshtastic.org/e/#channel-name?add=true&psk=key
  • Mobile App: Scan QR code to add channel without replacing existing channels
  • Manual Setup: Use displayed channel name and PSK key

Local Script Integration

MeshC2 allows local scripts and programs to send messages through the mesh network:

Basic Message Sending

# Send a simple notification
meshc2 --message "script completed"

# Send with timestamp
meshc2 --message "backup finished" --timestamp

# Send to specific channel
meshc2 --message "public announcement" --channel "general"

Script Examples

#!/bin/bash
# Backup script with mesh notifications

echo "Starting backup..."
meshc2 --message "Backup started" --timestamp

# Perform backup operations
rsync -av /home/ /backup/

if [ $? -eq 0 ]; then
    meshc2 --message "Backup completed successfully" --timestamp
else
    meshc2 --message "Backup failed - check logs" --timestamp --channel "alerts"
fi
# System monitoring script
#!/bin/bash
DISK_USAGE=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')

if [ $DISK_USAGE -gt 80 ]; then
    meshc2 --message "Warning: Disk usage at ${DISK_USAGE}%" --timestamp --channel "alerts"
fi

Message Features

  • Automatic Splitting: Long messages are automatically split into multiple parts
  • Channel Validation: Invalid channels show available options
  • Retry Logic: Failed sends are retried up to 3 times
  • Error Logging: All failures are logged to the main service log

Socket Communication Technical Details

MeshC2 uses Unix socket IPC to enable local message sending without device conflicts:

  • Socket Location: /var/lib/meshc2/meshc2.sock
  • Communication: JSON-based request/response protocol
  • Permissions: Socket accessible to all users (666), directory readable (755)
  • Automatic Detection: meshc2 command automatically uses socket when service is running
  • Fallback Behavior: Falls back to direct device access if socket unavailable
  • Service Integration: Socket server starts/stops with main service lifecycle

Benefits:

  • No Device Conflicts: Running service holds USB device, socket clients communicate via IPC
  • Better Performance: No device initialization overhead for quick messages
  • Reliable Delivery: Uses proven service connection and retry logic
  • Concurrent Access: Multiple scripts can send messages simultaneously

Service Management

Starting and Stopping

# Start service
sudo systemctl start meshc2

# Stop service  
sudo systemctl stop meshc2

# Restart service
sudo systemctl restart meshc2

# Enable auto-start
sudo systemctl enable meshc2

# Check status
sudo systemctl status meshc2

Monitoring

# View service logs
sudo journalctl -u meshc2 -f

# View application logs
tail -f /var/log/meshc2/meshc2.log

# Monitor incoming messages
/opt/meshc2/monitor_messages.sh

Manual Operation

For testing and debugging:

# Run interactively
meshc2 --real-device --channel "test-channel"

# List available devices
meshc2 --list-devices

# Validate configuration
meshc2 --validate-config

# Show service status
meshc2 --status

Security Considerations

Network Security

  • Encrypted Channels: All communications use AES encryption with channel-specific PSK
  • Channel Isolation: Commands only processed from configured channel
  • Mesh Network: No internet connectivity required, operates on local mesh

System Security

  • Dedicated User: Service runs as meshc2 system user, not root
  • Minimal Permissions: Limited file system access and capabilities
  • Resource Limits: CPU, memory, and process constraints
  • Audit Logging: All commands and responses logged

Physical Security

  • Device Access: Physical access to USB-connected device required for initial setup
  • Serial Port Protection: Device access limited to dialout group members

Operational Security

  • Channel Management: Regularly rotate encryption keys
  • Access Control: Limit physical access to devices running MeshC2
  • Log Monitoring: Regular review of command execution logs
  • Network Segmentation: Deploy on isolated or trusted networks only

Command Protocol

Message Format

Commands sent to MeshC2 follow this format:

<command> [arguments]

Supported Commands

Basic system commands are supported, including:

  • ls - List directory contents
  • ps - Show running processes
  • df - Display disk usage
  • free - Show memory usage
  • uptime - System uptime
  • whoami - Current user
  • pwd - Current directory

Response Format

Responses include:

  • Command Echo: Original command for confirmation
  • Output: Command execution results
  • Status: Success/failure indication
  • Timestamp: Execution time

Error Handling

  • Timeout: Commands that exceed configured timeout are terminated
  • Invalid Commands: Rejected with error message
  • System Errors: Execution failures reported with details
  • Queue Full: New commands rejected when queue is full

Troubleshooting

Installation Issues

Permission Denied

# Ensure sudo privileges
sudo -v

# Check installer permissions
chmod +x install.sh

Python Version Error

# Check Python version
python3 --version

# Update Python (Ubuntu/Debian)
sudo apt update
sudo apt install python3.8

Missing Dependencies

# Install system dependencies
sudo apt install python3-venv python3-dev build-essential

Service Issues

Service Won't Start

# Check detailed logs
sudo journalctl -u meshc2 -n 50

# Check configuration
meshc2 --validate-config

# Test device connection
meshc2 --list-devices

Device Not Found

# Check USB connection
lsusb | grep -i "cp210\|ch340\|ftdi"

# Check device permissions
ls -la /dev/ttyUSB*

# Reload udev rules
sudo udevadm control --reload-rules
sudo udevadm trigger

No Messages Received

# Check channel configuration
meshc2 --real-device --list-channels

# Verify service is listening
sudo systemctl status meshc2

# Monitor for any incoming packets
/opt/meshc2/monitor_messages.sh

Device Issues

Serial Port Access

# Add user to dialout group
sudo usermod -a -G dialout meshc2

# Check group membership
groups meshc2

# Restart service after group change
sudo systemctl restart meshc2

Device Connection Lost

# Check physical connection
ls /dev/ttyUSB* /dev/ttyACM*

# Check device power
# Reconnect USB cable
# Check for loose connections

Development

Building from Source

# Clone repository
git clone https://github.com/your-org/meshc2.git
cd meshc2

# Create virtual environment
python3 -m venv venv
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# Run tests
python -m pytest tests/

# Run development server
python -m src.meshtastic_troubleshoot.main --real-device --channel "dev"

Testing

# Run all tests
python -m pytest tests/

# Run specific test phases
python -m pytest tests/test_phase1.py

# Run with coverage
python -m pytest --cov=src tests/

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make changes with appropriate tests
  4. Submit a pull request

System Requirements

Hardware Requirements

  • CPU: ARM or x86_64 processor
  • RAM: Minimum 512MB available
  • Storage: 100MB for installation
  • USB Port: For Meshtastic device connection

Software Requirements

  • Operating System: Linux (Ubuntu 20.04+ recommended)
  • Python: Version 3.8 or higher
  • Systemd: For service management
  • Udev: For device management

Network Requirements

  • Meshtastic Device: LoRa radio for mesh communication
  • Mesh Network: Other Meshtastic devices in range
  • No Internet: No internet connectivity required

License

This project is licensed under the GPL-3.0 License - see the LICENSE file for details.

Support

Documentation

Community

  • Issues: Report bugs and request features via GitHub Issues
  • Discussions: Join community discussions
  • Contributing: See CONTRIBUTING.md for development guidelines

Security

To report security vulnerabilities, please email [email protected] instead of using public issues.

Acknowledgments

  • Meshtastic Project: For the excellent mesh networking platform
  • Community Contributors: For testing, feedback, and improvements
  • Security Researchers: For responsible disclosure of vulnerabilities

Disclaimer

MeshC2 enables remote command execution over mesh networks. Users are responsible for:

  • Securing encryption keys and access credentials
  • Ensuring compliance with local regulations
  • Implementing appropriate access controls
  • Monitoring and auditing system usage

Deploy only in trusted environments with proper security controls.

About

No description, website, or topics provided.

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published