mTracker

Real-time Linux user activity monitoring with Slack notifications

Updated Jan 15, 2024
7 min read
Intermediate
tools

mTracker

mTracker is a real-time Linux user activity monitoring tool that provides comprehensive tracking of user sessions, commands, and system interactions. With instant Slack notifications and detailed logging, mTracker helps maintain security and compliance in Linux environments.

Overview

mTracker monitors and logs user activities in real-time, providing:

  • Real-time Monitoring: Live tracking of user sessions and commands
  • Slack Integration: Instant notifications for suspicious activities
  • Comprehensive Logging: Detailed audit trails for compliance
  • Security Alerts: Detection of unauthorized access and privilege escalation
  • Performance Monitoring: System resource usage tracking

Features

👥 User Activity Monitoring

  • Login/logout tracking
  • Command execution monitoring
  • File access logging
  • Network activity tracking
  • Privilege escalation detection

📱 Real-time Notifications

  • Slack Alerts: Instant notifications for critical events
  • Email Reports: Daily/weekly activity summaries
  • Webhook Support: Custom integrations
  • Dashboard: Real-time web interface

🔒 Security Features

  • Suspicious activity detection
  • Failed login attempt monitoring
  • Root privilege usage tracking
  • Unauthorized access alerts
  • Command pattern analysis

Installation

Quick Install Script

# Download and run install script
curl -sSL https://raw.githubusercontent.com/HarryTheDevOpsGuy/mTracker/main/install.sh | bash

# Or with custom configuration
curl -sSL https://raw.githubusercontent.com/HarryTheDevOpsGuy/mTracker/main/install.sh | bash -s -- --config /etc/mtracker

Manual Installation

# Clone repository
git clone https://github.com/HarryTheDevOpsGuy/mTracker.git
cd mTracker

# Install dependencies
sudo apt-get update
sudo apt-get install -y python3 python3-pip auditd audispd-plugins

# Install Python packages
pip3 install -r requirements.txt

# Install mTracker
sudo python3 setup.py install

# Create system user
sudo useradd -r -s /bin/false mtracker
sudo mkdir -p /var/log/mtracker
sudo chown mtracker:mtracker /var/log/mtracker

Docker Installation

# Run with Docker
docker run -d \
  --name mtracker \
  --privileged \
  -v /var/log:/var/log:ro \
  -v /etc/passwd:/etc/passwd:ro \
  -v /etc/shadow:/etc/shadow:ro \
  -e SLACK_WEBHOOK_URL="$SLACK_WEBHOOK_URL" \
  harrythedevopsguy/mtracker:latest

Configuration

Basic Configuration

Create /etc/mtracker/mtracker.yml:

# Global settings
global:
  log_level: "INFO"
  log_file: "/var/log/mtracker/mtracker.log"
  pid_file: "/var/run/mtracker.pid"
  check_interval: 1  # seconds

# User monitoring
users:
  monitor_all: true
  exclude_users:
    - "root"
    - "systemd-timesync"
    - "systemd-network"
  
  include_users:
    - "admin"
    - "developer"
    - "operator"

# Command monitoring
commands:
  monitor_all: true
  exclude_commands:
    - "ls"
    - "pwd"
    - "whoami"
    - "date"
  
  sensitive_commands:
    - "sudo"
    - "su"
    - "passwd"
    - "chmod"
    - "chown"
    - "rm"
    - "mv"
    - "cp"

# File monitoring
files:
  monitor_paths:
    - "/etc"
    - "/home"
    - "/var/log"
    - "/opt"
  
  exclude_paths:
    - "/tmp"
    - "/var/tmp"
    - "/proc"
    - "/sys"

# Network monitoring
network:
  enabled: true
  monitor_ports:
    - 22   # SSH
    - 80   # HTTP
    - 443  # HTTPS
    - 3306 # MySQL
    - 5432 # PostgreSQL
  
  alert_on_new_connections: true

# Security rules
security:
  failed_login_threshold: 5
  privilege_escalation_alert: true
  suspicious_command_patterns:
    - ".*rm.*-rf.*"
    - ".*chmod.*777.*"
    - ".*wget.*http.*"
    - ".*curl.*http.*"

# Notifications
notifications:
  slack:
    enabled: true
    webhook_url: "${SLACK_WEBHOOK_URL}"
    channel: "#security-alerts"
    username: "mTracker"
    icon_emoji: ":shield:"
    
  email:
    enabled: true
    smtp_server: "smtp.gmail.com"
    smtp_port: 587
    username: "${EMAIL_USERNAME}"
    password: "${EMAIL_PASSWORD}"
    to_addresses:
      - "security@company.com"
      - "admin@company.com"

Environment Variables

# Slack Configuration
export SLACK_WEBHOOK_URL="https://hooks.slack.com/services/..."

# Email Configuration
export EMAIL_USERNAME="mtracker@company.com"
export EMAIL_PASSWORD="your-app-password"

# Database Configuration (optional)
export DATABASE_URL="postgresql://user:password@localhost/mtracker"

Usage

Command Line Interface

# Start monitoring
sudo mtracker start

# Stop monitoring
sudo mtracker stop

# Restart monitoring
sudo mtracker restart

# Check status
sudo mtracker status

# View logs
sudo mtracker logs --tail 100

# Generate report
sudo mtracker report --format html --output activity-report.html

# Test configuration
sudo mtracker test-config

Systemd Service

# Enable and start service
sudo systemctl enable mtracker
sudo systemctl start mtracker

# Check service status
sudo systemctl status mtracker

# View service logs
sudo journalctl -u mtracker -f

Python API

from mtracker import UserMonitor, SecurityAnalyzer

# Initialize monitor
monitor = UserMonitor(config_file='/etc/mtracker/mtracker.yml')

# Start monitoring
monitor.start()

# Get current users
active_users = monitor.get_active_users()
print(f"Active users: {active_users}")

# Get recent commands
recent_commands = monitor.get_recent_commands(limit=10)
for cmd in recent_commands:
    print(f"{cmd['user']}: {cmd['command']}")

# Security analysis
analyzer = SecurityAnalyzer()
suspicious_activities = analyzer.analyze_recent_activity()
for activity in suspicious_activities:
    print(f"Alert: {activity['description']}")

Monitoring Features

User Session Tracking

class UserSession:
    def __init__(self, username, session_id, login_time):
        self.username = username
        self.session_id = session_id
        self.login_time = login_time
        self.commands = []
        self.files_accessed = []
        self.network_connections = []
    
    def add_command(self, command, timestamp):
        """Track command execution"""
        self.commands.append({
            'command': command,
            'timestamp': timestamp,
            'working_directory': os.getcwd()
        })
    
    def is_suspicious(self):
        """Check for suspicious activity patterns"""
        # Check for privilege escalation
        if any('sudo' in cmd['command'] for cmd in self.commands):
            return True
        
        # Check for destructive commands
        destructive_patterns = ['rm -rf', 'chmod 777', 'dd if=']
        if any(pattern in cmd['command'] for cmd in self.commands 
               for pattern in destructive_patterns):
            return True
        
        return False

Real-time Command Monitoring

import subprocess
import threading
import time

class CommandMonitor:
    def __init__(self, config):
        self.config = config
        self.running = False
        self.monitor_thread = None
    
    def start_monitoring(self):
        """Start real-time command monitoring"""
        self.running = True
        self.monitor_thread = threading.Thread(target=self._monitor_commands)
        self.monitor_thread.start()
    
    def _monitor_commands(self):
        """Monitor commands using auditd"""
        while self.running:
            try:
                # Read audit logs
                result = subprocess.run(
                    ['ausearch', '-m', 'EXECVE', '-ts', 'recent'],
                    capture_output=True, text=True
                )
                
                if result.returncode == 0:
                    self._process_audit_logs(result.stdout)
                
                time.sleep(self.config['global']['check_interval'])
            except Exception as e:
                logger.error(f"Error monitoring commands: {e}")
    
    def _process_audit_logs(self, audit_output):
        """Process audit log output"""
        for line in audit_output.split('\n'):
            if line.strip():
                self._parse_audit_line(line)

Security Analysis

class SecurityAnalyzer:
    def __init__(self):
        self.suspicious_patterns = [
            r'.*rm.*-rf.*',  # Destructive file operations
            r'.*chmod.*777.*',  # Overly permissive permissions
            r'.*wget.*http.*',  # Downloading from HTTP
            r'.*curl.*http.*',  # Downloading from HTTP
            r'.*nc.*-l.*',  # Netcat listener
            r'.*python.*-c.*',  # Python code execution
        ]
    
    def analyze_command(self, command, user, timestamp):
        """Analyze command for security risks"""
        alerts = []
        
        # Check for suspicious patterns
        for pattern in self.suspicious_patterns:
            if re.match(pattern, command):
                alerts.append({
                    'type': 'suspicious_command',
                    'severity': 'high',
                    'description': f'Suspicious command detected: {command}',
                    'user': user,
                    'timestamp': timestamp
                })
        
        # Check for privilege escalation
        if command.startswith('sudo') and user != 'root':
            alerts.append({
                'type': 'privilege_escalation',
                'severity': 'medium',
                'description': f'Privilege escalation: {command}',
                'user': user,
                'timestamp': timestamp
            })
        
        return alerts

Notification Examples

Slack Alert

def send_slack_alert(alert_data):
    """Send security alert to Slack"""
    color = "danger" if alert_data['severity'] == 'high' else "warning"
    
    payload = {
        "attachments": [
            {
                "color": color,
                "title": "🚨 Security Alert",
                "fields": [
                    {
                        "title": "User",
                        "value": alert_data['user'],
                        "short": True
                    },
                    {
                        "title": "Type",
                        "value": alert_data['type'],
                        "short": True
                    },
                    {
                        "title": "Description",
                        "value": alert_data['description'],
                        "short": False
                    },
                    {
                        "title": "Timestamp",
                        "value": alert_data['timestamp'],
                        "short": True
                    }
                ]
            }
        ]
    }
    
    requests.post(SLACK_WEBHOOK_URL, json=payload)

Email Report

def generate_email_report():
    """Generate daily activity report"""
    report_data = {
        'date': datetime.now().strftime('%Y-%m-%d'),
        'total_users': get_active_user_count(),
        'total_commands': get_command_count(),
        'security_alerts': get_security_alerts(),
        'top_users': get_top_users_by_activity(),
        'suspicious_activities': get_suspicious_activities()
    }
    
    html_template = """
    <html>
    <head><title>mTracker Daily Report</title></head>
    <body>
        <h2>Daily Activity Report - {date}</h2>
        
        <h3>Summary</h3>
        <ul>
            <li>Active Users: {total_users}</li>
            <li>Commands Executed: {total_commands}</li>
            <li>Security Alerts: {security_alerts}</li>
        </ul>
        
        <h3>Top Active Users</h3>
        <table border="1">
            <tr><th>User</th><th>Commands</th></tr>
            {top_users_rows}
        </table>
        
        <h3>Security Alerts</h3>
        {security_alerts_html}
    </body>
    </html>
    """
    
    return html_template.format(**report_data)

Web Dashboard

Real-time Dashboard

from flask import Flask, render_template, jsonify
import json

app = Flask(__name__)

@app.route('/')
def dashboard():
    """Main dashboard page"""
    return render_template('dashboard.html')

@app.route('/api/active-users')
def api_active_users():
    """API endpoint for active users"""
    users = get_active_users()
    return jsonify(users)

@app.route('/api/recent-commands')
def api_recent_commands():
    """API endpoint for recent commands"""
    commands = get_recent_commands(limit=50)
    return jsonify(commands)

@app.route('/api/security-alerts')
def api_security_alerts():
    """API endpoint for security alerts"""
    alerts = get_recent_security_alerts(limit=20)
    return jsonify(alerts)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

Dashboard HTML Template

<!DOCTYPE html>
<html>
<head>
    <title>mTracker Dashboard</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <h1>mTracker Real-time Dashboard</h1>
    
    <div class="stats">
        <div class="stat-card">
            <h3>Active Users</h3>
            <span id="active-users-count">0</span>
        </div>
        <div class="stat-card">
            <h3>Commands Today</h3>
            <span id="commands-count">0</span>
        </div>
        <div class="stat-card">
            <h3>Security Alerts</h3>
            <span id="alerts-count">0</span>
        </div>
    </div>
    
    <div class="charts">
        <canvas id="activity-chart"></canvas>
    </div>
    
    <div class="recent-activity">
        <h3>Recent Commands</h3>
        <div id="recent-commands"></div>
    </div>
    
    <script>
        // Real-time updates
        setInterval(updateDashboard, 5000);
        
        function updateDashboard() {
            fetch('/api/active-users')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('active-users-count').textContent = data.length;
                });
        }
    </script>
</body>
</html>

Integration Examples

Ansible Integration

# ansible-playbook.yml
- name: Deploy mTracker
  hosts: all
  tasks:
    - name: Install mTracker
      pip:
        name: mtracker
        state: present
    
    - name: Copy configuration
      template:
        src: mtracker.yml.j2
        dest: /etc/mtracker/mtracker.yml
        owner: root
        group: root
        mode: '0644'
    
    - name: Start mTracker service
      systemd:
        name: mtracker
        state: started
        enabled: yes

Prometheus Integration

from prometheus_client import Counter, Histogram, Gauge

# Metrics
user_commands = Counter('mtracker_user_commands_total', 'Total user commands', ['user'])
security_alerts = Counter('mtracker_security_alerts_total', 'Total security alerts', ['type'])
active_users = Gauge('mtracker_active_users', 'Number of active users')
command_duration = Histogram('mtracker_command_duration_seconds', 'Command execution time')

# Expose metrics
def expose_metrics():
    from prometheus_client import start_http_server
    start_http_server(8000)

Troubleshooting

Common Issues

Permission Denied

# Check auditd status
sudo systemctl status auditd

# Verify auditd rules
sudo auditctl -l

# Check mTracker permissions
sudo -u mtracker mtracker test-config

Missing Logs

# Check log file permissions
ls -la /var/log/mtracker/

# Verify auditd configuration
sudo auditctl -w /etc/passwd -p wa -k passwd_changes

# Test audit logging
sudo ausearch -k passwd_changes

Performance Issues

# Optimize configuration
global:
  check_interval: 5  # Increase interval
  max_log_size: 100MB
  log_rotation: true

# Reduce monitoring scope
users:
  monitor_all: false
  include_users:
    - "admin"
    - "developer"

API Reference

REST API Endpoints

Endpoint Method Description
/api/v1/users GET Get active users
/api/v1/commands GET Get recent commands
/api/v1/alerts GET Get security alerts
/api/v1/stats GET Get statistics
/api/v1/config GET/PUT Get/update configuration

WebSocket Events

// Connect to real-time updates
const ws = new WebSocket('ws://localhost:5000/ws');

ws.onmessage = function(event) {
    const data = JSON.parse(event.data);
    
    switch(data.type) {
        case 'user_login':
            console.log(`User logged in: ${data.user}`);
            break;
        case 'command_executed':
            console.log(`Command: ${data.user}@${data.host}: ${data.command}`);
            break;
        case 'security_alert':
            console.log(`Security alert: ${data.description}`);
            break;
    }
};

Contributing

We welcome contributions! Please see our Contributing Guidelines for details.

Development Setup

# Fork and clone repository
git clone https://github.com/your-username/mTracker.git
cd mTracker

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

# Install development dependencies
pip install -r requirements-dev.txt

# Run tests
pytest tests/

# Run linting
flake8 mtracker/
black mtracker/

License

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

Support


**Security Note**: mTracker requires elevated privileges to monitor system activities. Ensure proper access controls and regular security audits when deploying in production environments.

Found this helpful?

Help us improve this documentation by sharing your feedback or suggesting improvements.