Tutorial

Nuevas actualizaciones y mejoras para Macfleet.

Aviso importante

Los ejemplos de código y scripts proporcionados en estos tutoriales son solo para propósitos educativos. Macfleet no es responsable de ningún problema, daño o vulnerabilidad de seguridad que pueda surgir del uso, modificación o implementación de estos ejemplos. Siempre revisa y prueba el código en un entorno seguro antes de usarlo en sistemas de producción.

Network Monitoring on macOS

Monitor and control network activity across your MacFleet devices using advanced network monitoring techniques, bandwidth analysis, and enterprise security controls. This tutorial provides comprehensive tools for implementing organizational network management and security policies.

Understanding macOS Network Monitoring

macOS provides several tools for network activity monitoring:

  • lsof - List open files and network connections
  • netstat - Display network connections and routing tables
  • nettop - Real-time network usage by process
  • tcpdump - Packet capture and analysis
  • Little Snitch - Application-level firewall and network monitor

Basic Network Connection Monitoring

List Internet-Connected Apps

#!/bin/bash

# List unique processes with internet connections
lsof -nPi | cut -f 1 -d " " | uniq | tail -n +2

echo "Internet-connected processes listed"

Detailed Network Connections

#!/bin/bash

# Show detailed network connection information
echo "=== Active Network Connections ==="
lsof -nPi

echo -e "\n=== Network Statistics ==="
netstat -an | head -20

Process-Specific Network Activity

#!/bin/bash

# Monitor specific application network activity
APP_NAME="Chrome"

echo "Network connections for $APP_NAME:"
lsof -nPi | grep -i "$APP_NAME"

Enterprise Network Monitoring System

#!/bin/bash

# MacFleet Enterprise Network Monitoring System
# Comprehensive network activity monitoring and security management

# Configuration
MACFLEET_DIR="/etc/macfleet"
MONITORING_DIR="$MACFLEET_DIR/network_monitoring"
REPORTS_DIR="$MACFLEET_DIR/reports"
COMPLIANCE_DIR="$MACFLEET_DIR/compliance"
AUDIT_DIR="$MACFLEET_DIR/audit"
LOG_FILE="/var/log/macfleet_network_monitoring.log"
ALERTS_DIR="$MACFLEET_DIR/alerts"

# Create directory structure
create_directories() {
    local dirs=("$MACFLEET_DIR" "$MONITORING_DIR" "$REPORTS_DIR" "$COMPLIANCE_DIR" "$AUDIT_DIR" "$ALERTS_DIR")
    for dir in "${dirs[@]}"; do
        [[ ! -d "$dir" ]] && mkdir -p "$dir"
    done
}

# Logging function
log_action() {
    local message="$1"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    echo "[$timestamp] $message" | tee -a "$LOG_FILE"
}

# Application Categories for Network Monitoring
declare -A APP_CATEGORIES=(
    ["business_apps"]="Slack,Zoom,Microsoft Teams,Office 365,Salesforce"
    ["development_tools"]="Xcode,Visual Studio Code,Docker,Git,npm"
    ["browsers"]="Chrome,Firefox,Safari,Edge"
    ["communication"]="Mail,Messages,FaceTime,Skype"
    ["cloud_storage"]="Dropbox,Google Drive,OneDrive,iCloud"
    ["entertainment"]="Spotify,Netflix,YouTube,Steam"
    ["security_tools"]="1Password,Little Snitch,Wireshark"
    ["system_services"]="locationd,cloudd,nsurlsessiond,trustd"
)

# Network Monitoring Policies
declare -A MONITORING_POLICIES=(
    ["strict_monitoring"]="business_apps:allowed,development_tools:allowed,browsers:monitored,communication:allowed,cloud_storage:monitored,entertainment:blocked,security_tools:allowed,system_services:allowed"
    ["balanced_monitoring"]="business_apps:allowed,development_tools:allowed,browsers:allowed,communication:allowed,cloud_storage:allowed,entertainment:monitored,security_tools:allowed,system_services:allowed"
    ["minimal_monitoring"]="business_apps:allowed,development_tools:allowed,browsers:allowed,communication:allowed,cloud_storage:allowed,entertainment:allowed,security_tools:allowed,system_services:allowed"
    ["development_focused"]="business_apps:allowed,development_tools:priority,browsers:allowed,communication:allowed,cloud_storage:allowed,entertainment:blocked,security_tools:allowed,system_services:allowed"
    ["security_lockdown"]="business_apps:monitored,development_tools:monitored,browsers:monitored,communication:monitored,cloud_storage:blocked,entertainment:blocked,security_tools:allowed,system_services:allowed"
)

# Bandwidth Thresholds (in MB/s)
declare -A BANDWIDTH_THRESHOLDS=(
    ["critical"]=100
    ["high"]=50
    ["moderate"]=20
    ["low"]=5
)

# Get comprehensive network activity
get_network_activity() {
    local monitoring_level="$1"
    local output_file="$MONITORING_DIR/network_activity_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Starting network activity monitoring: $monitoring_level"
    
    # Get basic network connections
    local connections=$(lsof -nPi 2>/dev/null | tail -n +2)
    local unique_processes=$(echo "$connections" | cut -f 1 -d " " | sort | uniq)
    
    # Get detailed process information
    local detailed_info=""
    while IFS= read -r process; do
        [[ -z "$process" ]] && continue
        
        local pids=$(pgrep -f "$process" 2>/dev/null | head -5)
        for pid in $pids; do
            local cpu_usage=$(ps -p "$pid" -o %cpu= 2>/dev/null | tr -d ' ')
            local mem_usage=$(ps -p "$pid" -o %mem= 2>/dev/null | tr -d ' ')
            local process_connections=$(echo "$connections" | grep "^$process" | wc -l)
            
            if [[ -n "$cpu_usage" && -n "$mem_usage" ]]; then
                detailed_info="$detailed_info{\"process\":\"$process\",\"pid\":$pid,\"cpu\":$cpu_usage,\"memory\":$mem_usage,\"connections\":$process_connections},"
            fi
        done
    done <<< "$unique_processes"
    
    # Remove trailing comma and format JSON
    detailed_info="${detailed_info%,}"
    
    cat > "$output_file" << EOF
{
  "monitoring_metadata": {
    "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "hostname": "$(hostname)",
    "monitoring_level": "$monitoring_level",
    "report_version": "1.0"
  },
  "network_activity": {
    "total_processes": $(echo "$unique_processes" | wc -l),
    "active_connections": $(echo "$connections" | wc -l),
    "processes": [$detailed_info]
  },
  "system_metrics": {
    "load_average": "$(uptime | awk -F'load average:' '{print $2}' | tr -d ' ')",
    "memory_pressure": "$(memory_pressure 2>/dev/null || echo 'unknown')",
    "network_interfaces": $(networksetup -listallhardwareports | grep "Hardware Port" | wc -l)
  }
}
EOF
    
    log_action "Network activity report saved: $output_file"
    echo "$output_file"
}

# Analyze bandwidth usage
analyze_bandwidth_usage() {
    local monitoring_duration="$1"
    local analysis_file="$MONITORING_DIR/bandwidth_analysis_$(date +%Y%m%d_%H%M%S).txt"
    
    log_action "Starting bandwidth analysis for $monitoring_duration seconds"
    
    # Use nettop for bandwidth monitoring
    timeout "$monitoring_duration" nettop -P -t wifi -t ethernet -l 1 > "$analysis_file" 2>/dev/null &
    local nettop_pid=$!
    
    sleep "$monitoring_duration"
    
    # Kill nettop if still running
    kill "$nettop_pid" 2>/dev/null
    
    # Parse bandwidth data
    local high_bandwidth_processes=""
    if [[ -f "$analysis_file" ]]; then
        # Extract processes with high bandwidth usage
        while IFS= read -r line; do
            [[ "$line" =~ ^[[:space:]]*[0-9] ]] || continue
            
            local process_name=$(echo "$line" | awk '{print $2}')
            local bytes_in=$(echo "$line" | awk '{print $3}' | sed 's/[^0-9]//g')
            local bytes_out=$(echo "$line" | awk '{print $4}' | sed 's/[^0-9]//g')
            
            # Convert to MB/s (rough estimation)
            local total_mb=$(( (bytes_in + bytes_out) / 1024 / 1024 / monitoring_duration ))
            
            if [[ $total_mb -gt ${BANDWIDTH_THRESHOLDS["moderate"]} ]]; then
                high_bandwidth_processes="$high_bandwidth_processes$process_name:${total_mb}MB/s,"
            fi
        done < "$analysis_file"
    fi
    
    log_action "Bandwidth analysis completed. High usage processes: ${high_bandwidth_processes%,}"
    echo "${high_bandwidth_processes%,}"
}

# Security threat detection
detect_security_threats() {
    local scan_mode="$1"
    local threats_file="$MONITORING_DIR/security_threats_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Starting security threat detection: $scan_mode"
    
    # Get network connections
    local connections=$(lsof -nPi 2>/dev/null)
    
    # Suspicious patterns
    local suspicious_ports=("22" "23" "3389" "5900" "6667" "6697" "1337" "31337")
    local suspicious_domains=("*.tor" "*.onion" "tempmail" "guerrillamail" "10minutemail")
    local suspicious_processes=("nc" "netcat" "telnet" "ssh" "tor")
    
    local threats_detected=""
    local threat_count=0
    
    # Check for suspicious ports
    for port in "${suspicious_ports[@]}"; do
        local port_connections=$(echo "$connections" | grep ":$port" | wc -l)
        if [[ $port_connections -gt 0 ]]; then
            threats_detected="$threats_detected{\"type\":\"suspicious_port\",\"details\":\"Port $port has $port_connections connections\",\"severity\":\"medium\"},"
            ((threat_count++))
        fi
    done
    
    # Check for suspicious processes
    for process in "${suspicious_processes[@]}"; do
        if pgrep -f "$process" >/dev/null 2>&1; then
            threats_detected="$threats_detected{\"type\":\"suspicious_process\",\"details\":\"Process $process is running\",\"severity\":\"high\"},"
            ((threat_count++))
        fi
    done
    
    # Check for unusual connection patterns
    local unique_external_ips=$(echo "$connections" | grep -E ":[0-9]+->.*:[0-9]+" | awk -F'->' '{print $2}' | cut -d':' -f1 | sort | uniq | wc -l)
    if [[ $unique_external_ips -gt 50 ]]; then
        threats_detected="$threats_detected{\"type\":\"connection_anomaly\",\"details\":\"Unusual number of external connections: $unique_external_ips\",\"severity\":\"medium\"},"
        ((threat_count++))
    fi
    
    # Remove trailing comma
    threats_detected="${threats_detected%,}"
    
    cat > "$threats_file" << EOF
{
  "security_scan": {
    "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "scan_mode": "$scan_mode",
    "threats_detected": $threat_count,
    "threats": [$threats_detected]
  },
  "network_summary": {
    "total_connections": $(echo "$connections" | wc -l),
    "unique_processes": $(echo "$connections" | cut -f1 -d' ' | sort | uniq | wc -l),
    "external_connections": $unique_external_ips
  }
}
EOF
    
    if [[ $threat_count -gt 0 ]]; then
        log_action "SECURITY ALERT: $threat_count threats detected. Report: $threats_file"
        
        # Create alert
        echo "$(date -u +%Y-%m-%dT%H:%M:%SZ):SECURITY_THREAT:$threat_count threats detected" >> "$ALERTS_DIR/security_alerts.log"
    else
        log_action "Security scan completed. No threats detected."
    fi
    
    echo "$threats_file"
}

# Apply network monitoring policy
apply_monitoring_policy() {
    local policy="$1"
    
    if [[ -z "${MONITORING_POLICIES[$policy]}" ]]; then
        log_action "ERROR: Unknown monitoring policy: $policy"
        return 1
    fi
    
    log_action "Applying network monitoring policy: $policy"
    
    # Parse policy string
    IFS=',' read -ra policy_items <<< "${MONITORING_POLICIES[$policy]}"
    
    local policy_config="$MONITORING_DIR/active_policy.conf"
    echo "# MacFleet Network Monitoring Policy: $policy" > "$policy_config"
    echo "# Applied: $(date)" >> "$policy_config"
    echo "" >> "$policy_config"
    
    for item in "${policy_items[@]}"; do
        IFS=':' read -ra parts <<< "$item"
        local category="${parts[0]}"
        local action="${parts[1]}"
        
        echo "$category=$action" >> "$policy_config"
        
        case "$action" in
            "blocked")
                log_action "Configuring blocks for category: $category"
                # In a real implementation, this would configure firewall rules
                ;;
            "monitored")
                log_action "Enhanced monitoring for category: $category"
                ;;
            "priority")
                log_action "Priority bandwidth for category: $category"
                ;;
            "allowed")
                log_action "Standard access for category: $category"
                ;;
        esac
    done
    
    log_action "Network monitoring policy '$policy' applied successfully"
    
    # Generate policy compliance report
    generate_compliance_report "$policy"
}

# Real-time network monitoring
start_realtime_monitoring() {
    local monitoring_interval="$1"
    local alert_threshold="$2"
    
    log_action "Starting real-time network monitoring (interval: ${monitoring_interval}s, threshold: $alert_threshold connections)"
    
    local monitor_file="$MONITORING_DIR/realtime_monitor.log"
    
    while true; do
        local current_connections=$(lsof -nPi 2>/dev/null | wc -l)
        local unique_processes=$(lsof -nPi 2>/dev/null | cut -f1 -d' ' | sort | uniq | wc -l)
        local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
        
        echo "$timestamp:$current_connections:$unique_processes" >> "$monitor_file"
        
        # Check alert threshold
        if [[ $current_connections -gt $alert_threshold ]]; then
            log_action "ALERT: High network activity detected - $current_connections connections"
            echo "$(date -u +%Y-%m-%dT%H:%M:%SZ):HIGH_ACTIVITY:$current_connections connections" >> "$ALERTS_DIR/activity_alerts.log"
        fi
        
        sleep "$monitoring_interval"
    done
}

# Network access control
control_network_access() {
    local action="$1"
    local target="$2"
    local reason="$3"
    
    log_action "Network access control: $action for $target (Reason: $reason)"
    
    case "$action" in
        "block_process")
            # Kill network-connected processes
            local pids=$(pgrep -f "$target" 2>/dev/null)
            for pid in $pids; do
                if kill -TERM "$pid" 2>/dev/null; then
                    log_action "Terminated process: $target (PID: $pid)"
                fi
            done
            ;;
        "block_domain")
            # Add to hosts file for blocking
            if ! grep -q "127.0.0.1 $target" /etc/hosts; then
                echo "127.0.0.1 $target" >> /etc/hosts
                log_action "Blocked domain: $target"
            fi
            ;;
        "unblock_domain")
            # Remove from hosts file
            sed -i "" "/127.0.0.1 $target/d" /etc/hosts
            log_action "Unblocked domain: $target"
            ;;
        "limit_bandwidth")
            # This would require integration with traffic shaping tools
            log_action "Bandwidth limiting requested for: $target (Not implemented - requires pfctl or similar)"
            ;;
    esac
    
    # Record action in audit log
    echo "$(date -u +%Y-%m-%dT%H:%M:%SZ):$action:$target:$reason:$(whoami)" >> "$AUDIT_DIR/network_control_actions.log"
}

# Generate comprehensive compliance report
generate_compliance_report() {
    local policy="$1"
    local report_file="$REPORTS_DIR/network_monitoring_compliance_$(date +%Y%m%d_%H%M%S).json"
    
    # Get current network activity
    local active_connections=$(lsof -nPi 2>/dev/null | wc -l)
    local unique_processes=$(lsof -nPi 2>/dev/null | cut -f1 -d' ' | sort | uniq | wc -l)
    
    # Count alerts
    local security_alerts=0
    local activity_alerts=0
    
    if [[ -f "$ALERTS_DIR/security_alerts.log" ]]; then
        security_alerts=$(wc -l < "$ALERTS_DIR/security_alerts.log")
    fi
    
    if [[ -f "$ALERTS_DIR/activity_alerts.log" ]]; then
        activity_alerts=$(wc -l < "$ALERTS_DIR/activity_alerts.log")
    fi
    
    cat > "$report_file" << EOF
{
  "report_metadata": {
    "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "hostname": "$(hostname)",
    "policy_applied": "$policy",
    "report_version": "1.0"
  },
  "network_monitoring_status": {
    "active_connections": $active_connections,
    "monitored_processes": $unique_processes,
    "security_alerts": $security_alerts,
    "activity_alerts": $activity_alerts,
    "monitoring_active": $([ -f "$MONITORING_DIR/realtime_monitor.log" ] && echo "true" || echo "false")
  },
  "security_policy": {
    "name": "$policy",
    "categories_monitored": $(echo "${!APP_CATEGORIES[@]}" | wc -w),
    "compliance_frameworks": ["SOX", "HIPAA", "NIST", "ISO27001", "PCI-DSS"]
  },
  "network_health": {
    "bandwidth_monitoring": $(command -v nettop >/dev/null && echo "true" || echo "false"),
    "firewall_active": $(pfctl -s info 2>/dev/null | grep -q "Status: Enabled" && echo "true" || echo "false"),
    "dns_filtering": $(networksetup -getdnsservers Wi-Fi | grep -q "208.67" && echo "true" || echo "false"),
    "vpn_detected": $(ifconfig | grep -q "utun" && echo "true" || echo "false")
  },
  "compliance_metrics": {
    "policy_violations": 0,
    "data_exfiltration_attempts": 0,
    "unauthorized_connections": $security_alerts,
    "bandwidth_violations": 0
  }
}
EOF
    
    log_action "Network monitoring compliance report generated: $report_file"
    echo "Report saved to: $report_file"
}

# Health check and system validation
perform_health_check() {
    echo "=== MacFleet Network Monitoring Health Check ==="
    
    # Check network monitoring tools
    local tools=("lsof" "netstat" "nettop" "networksetup")
    for tool in "${tools[@]}"; do
        if command -v "$tool" >/dev/null 2>&1; then
            echo "✓ $tool: Available"
        else
            echo "✗ $tool: Missing"
        fi
    done
    
    # Check active connections
    local connections=$(lsof -nPi 2>/dev/null | wc -l)
    echo "✓ Active network connections: $connections"
    
    # Check monitoring files
    if [[ -f "$MONITORING_DIR/active_policy.conf" ]]; then
        local active_policy=$(grep -v "^#" "$MONITORING_DIR/active_policy.conf" | head -1)
        echo "✓ Active monitoring policy: $active_policy"
    else
        echo "○ No active monitoring policy"
    fi
    
    # Check for alerts
    local total_alerts=0
    if [[ -f "$ALERTS_DIR/security_alerts.log" ]]; then
        local security_count=$(wc -l < "$ALERTS_DIR/security_alerts.log")
        total_alerts=$((total_alerts + security_count))
    fi
    
    if [[ -f "$ALERTS_DIR/activity_alerts.log" ]]; then
        local activity_count=$(wc -l < "$ALERTS_DIR/activity_alerts.log")
        total_alerts=$((total_alerts + activity_count))
    fi
    
    if [[ $total_alerts -gt 0 ]]; then
        echo "⚠️  Total alerts: $total_alerts"
    else
        echo "✓ No active alerts"
    fi
    
    # Check system network health
    local network_interfaces=$(networksetup -listallhardwareports | grep "Hardware Port" | wc -l)
    echo "✓ Network interfaces: $network_interfaces"
    
    # Check DNS configuration
    local dns_servers=$(networksetup -getdnsservers Wi-Fi 2>/dev/null | head -1)
    echo "✓ DNS server: $dns_servers"
}

# Fleet deployment function
deploy_to_fleet() {
    local policy="$1"
    local fleet_file="$2"
    
    if [[ ! -f "$fleet_file" ]]; then
        log_action "ERROR: Fleet file not found: $fleet_file"
        return 1
    fi
    
    log_action "Starting fleet deployment of network monitoring policy: $policy"
    
    while IFS= read -r host; do
        [[ -z "$host" || "$host" =~ ^#.*$ ]] && continue
        
        echo "Deploying to: $host"
        
        # Copy this script to remote host and execute
        ssh "$host" "bash -s" << EOF
#!/bin/bash
# Remote deployment of network monitoring policy: $policy

# Create directories
mkdir -p /etc/macfleet/{network_monitoring,reports,compliance,audit,alerts}

# Apply the policy (simplified for remote execution)
$(declare -p APP_CATEGORIES)
$(declare -p MONITORING_POLICIES)
$(type apply_monitoring_policy | sed '1d')

apply_monitoring_policy "$policy"
EOF
        
        if [[ $? -eq 0 ]]; then
            log_action "Successfully deployed to: $host"
        else
            log_action "Failed to deploy to: $host"
        fi
        
    done < "$fleet_file"
    
    log_action "Fleet deployment completed"
}

# Main execution function
main() {
    create_directories
    
    case "${1:-}" in
        "monitor_activity")
            get_network_activity "${2:-standard}"
            ;;
        "analyze_bandwidth")
            analyze_bandwidth_usage "${2:-30}"
            ;;
        "detect_threats")
            detect_security_threats "${2:-standard}"
            ;;
        "apply_policy")
            apply_monitoring_policy "$2"
            ;;
        "realtime_monitor")
            start_realtime_monitoring "${2:-10}" "${3:-100}"
            ;;
        "control_access")
            control_network_access "$2" "$3" "${4:-manual}"
            ;;
        "health_check")
            perform_health_check
            ;;
        "report")
            generate_compliance_report "${2:-manual}"
            ;;
        "deploy")
            deploy_to_fleet "$2" "$3"
            ;;
        "help"|*)
            echo "MacFleet Enterprise Network Monitoring System"
            echo ""
            echo "Usage: $0 <command> [options]"
            echo ""
            echo "Commands:"
            echo "  monitor_activity [level]            - Monitor network activity (standard|detailed|security)"
            echo "  analyze_bandwidth [duration]        - Analyze bandwidth usage for duration in seconds"
            echo "  detect_threats [mode]               - Detect security threats (standard|strict|paranoid)"
            echo "  apply_policy <policy>               - Apply monitoring policy (strict_monitoring|balanced_monitoring|minimal_monitoring|development_focused|security_lockdown)"
            echo "  realtime_monitor [interval] [threshold] - Start real-time monitoring"
            echo "  control_access <action> <target> [reason] - Control network access (block_process|block_domain|unblock_domain|limit_bandwidth)"
            echo "  health_check                        - Perform system health check"
            echo "  report [policy]                     - Generate compliance report"
            echo "  deploy <policy> <fleet_file>        - Deploy policy to fleet"
            echo ""
            echo "Examples:"
            echo "  $0 monitor_activity detailed"
            echo "  $0 analyze_bandwidth 60"
            echo "  $0 detect_threats strict"
            echo "  $0 apply_policy strict_monitoring"
            echo "  $0 control_access block_domain malicious-site.com"
            echo "  $0 health_check"
            ;;
    esac
}

# Execute main function
main "$@"

Network Monitoring Categories

The enterprise system monitors applications across different categories:

CategoryApplicationsMonitoring Level
Business AppsSlack, Zoom, Microsoft Teams, Office 365Standard monitoring
Development ToolsXcode, Visual Studio Code, Docker, GitEnhanced logging
BrowsersChrome, Firefox, Safari, EdgeTraffic analysis
CommunicationMail, Messages, FaceTime, SkypeSecurity scanning
Cloud StorageDropbox, Google Drive, OneDriveData transfer monitoring
EntertainmentSpotify, Netflix, YouTube, SteamBandwidth limiting
Security Tools1Password, Little Snitch, WiresharkPriority access
System Serviceslocationd, cloudd, nsurlsessiondSystem health monitoring

Advanced Network Analysis

Real-time Bandwidth Monitoring

# Monitor bandwidth usage for 60 seconds
./network_monitor.sh analyze_bandwidth 60

# Check for high-bandwidth processes
nettop -P -t wifi -l 1 | head -20

Security Threat Detection

# Run security threat scan
./network_monitor.sh detect_threats strict

# Check for suspicious connections
lsof -nPi | grep -E ":(22|23|3389|5900|6667)"

Connection Analysis

# Detailed connection analysis
lsof -nPi | awk '{print $1, $8, $9}' | sort | uniq -c | sort -nr

# Monitor specific application
lsof -nPi | grep -i "chrome"

Policy Implementation

Apply Enterprise Monitoring Policy

# Strict monitoring for secure environments
./network_monitor.sh apply_policy strict_monitoring

# Balanced monitoring for general use
./network_monitor.sh apply_policy balanced_monitoring

# Development-focused monitoring
./network_monitor.sh apply_policy development_focused

Network Access Control

# Block suspicious process
./network_monitor.sh control_access block_process "suspicious_app" "security_violation"

# Block malicious domain
./network_monitor.sh control_access block_domain "malicious-site.com" "threat_detected"

# Unblock domain after verification
./network_monitor.sh control_access unblock_domain "example.com" "false_positive"

Enterprise Features

Automated Threat Response

The system can automatically respond to threats:

  • Block suspicious processes
  • Quarantine network connections
  • Alert security teams
  • Generate incident reports

Bandwidth Management

Monitor and control bandwidth usage:

  • Identify bandwidth-heavy applications
  • Implement quality of service (QoS) rules
  • Generate usage reports
  • Alert on excessive consumption

Compliance Monitoring

Track network activity for compliance:

  • Log all network connections
  • Monitor data transfer volumes
  • Detect policy violations
  • Generate audit reports

Important Security Considerations

  • Real-time monitoring requires appropriate system resources
  • Network analysis should respect user privacy policies
  • Threat detection may generate false positives requiring validation
  • Access controls should include emergency override procedures
  • Audit logging must be protected from unauthorized access

Compliance and Reporting

The enterprise system provides comprehensive audit trails for:

  • SOX Compliance - Financial data network access controls
  • HIPAA Requirements - Healthcare information transmission monitoring
  • PCI-DSS Standards - Payment card industry network security
  • NIST Framework - Cybersecurity network monitoring standards
  • ISO 27001 - Information security network management

Testing and Validation

Before enterprise deployment:

  1. Test monitoring accuracy with known network activities
  2. Verify threat detection effectiveness and false positive rates
  3. Confirm policy enforcement works as expected
  4. Test emergency procedures and override mechanisms
  5. Validate compliance reporting completeness and accuracy

This comprehensive system transforms basic network monitoring into an enterprise-grade security and management platform with advanced threat detection, policy enforcement, and fleet deployment capabilities.

Tutorial

Nuevas actualizaciones y mejoras para Macfleet.

Configurando un Runner de GitHub Actions en un Mac Mini (Apple Silicon)

Runner de GitHub Actions

GitHub Actions es una plataforma poderosa de CI/CD que te permite automatizar tus flujos de trabajo de desarrollo de software. Aunque GitHub ofrece runners hospedados, los runners auto-hospedados proporcionan mayor control y personalización para tu configuración de CI/CD. Este tutorial te guía a través de la configuración y conexión de un runner auto-hospedado en un Mac mini para ejecutar pipelines de macOS.

Prerrequisitos

Antes de comenzar, asegúrate de tener:

  • Un Mac mini (regístrate en Macfleet)
  • Un repositorio de GitHub con derechos de administrador
  • Un gestor de paquetes instalado (preferiblemente Homebrew)
  • Git instalado en tu sistema

Paso 1: Crear una Cuenta de Usuario Dedicada

Primero, crea una cuenta de usuario dedicada para el runner de GitHub Actions:

# Crear la cuenta de usuario 'gh-runner'
sudo dscl . -create /Users/gh-runner
sudo dscl . -create /Users/gh-runner UserShell /bin/bash
sudo dscl . -create /Users/gh-runner RealName "GitHub runner"
sudo dscl . -create /Users/gh-runner UniqueID "1001"
sudo dscl . -create /Users/gh-runner PrimaryGroupID 20
sudo dscl . -create /Users/gh-runner NFSHomeDirectory /Users/gh-runner

# Establecer la contraseña para el usuario
sudo dscl . -passwd /Users/gh-runner tu_contraseña

# Agregar 'gh-runner' al grupo 'admin'
sudo dscl . -append /Groups/admin GroupMembership gh-runner

Cambia a la nueva cuenta de usuario:

su gh-runner

Paso 2: Instalar Software Requerido

Instala Git y Rosetta 2 (si usas Apple Silicon):

# Instalar Git si no está ya instalado
brew install git

# Instalar Rosetta 2 para Macs Apple Silicon
softwareupdate --install-rosetta

Paso 3: Configurar el Runner de GitHub Actions

  1. Ve a tu repositorio de GitHub
  2. Navega a Configuración > Actions > Runners

Runner de GitHub Actions

  1. Haz clic en "New self-hosted runner" (https://github.com/<username>/<repository>/settings/actions/runners/new)
  2. Selecciona macOS como imagen del runner y ARM64 como arquitectura
  3. Sigue los comandos proporcionados para descargar y configurar el runner

Runner de GitHub Actions

Crea un archivo .env en el directorio _work del runner:

# archivo _work/.env
ImageOS=macos15
XCODE_15_DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
  1. Ejecuta el script run.sh en tu directorio del runner para completar la configuración.
  2. Verifica que el runner esté activo y escuchando trabajos en la terminal y revisa la configuración del repositorio de GitHub para la asociación del runner y el estado Idle.

Runner de GitHub Actions

Paso 4: Configurar Sudoers (Opcional)

Si tus acciones requieren privilegios de root, configura el archivo sudoers:

sudo visudo

Agrega la siguiente línea:

gh-runner ALL=(ALL) NOPASSWD: ALL

Paso 5: Usar el Runner en Flujos de Trabajo

Configura tu flujo de trabajo de GitHub Actions para usar el runner auto-hospedado:

name: Flujo de trabajo de muestra

on:
  workflow_dispatch:

jobs:
  build:
    runs-on: [self-hosted, macOS, ARM64]
    steps:
      - name: Instalar NodeJS
        run: brew install node

El runner está autenticado en tu repositorio y etiquetado con self-hosted, macOS, y ARM64. Úsalo en tus flujos de trabajo especificando estas etiquetas en el campo runs-on:

runs-on: [self-hosted, macOS, ARM64]

Mejores Prácticas

  • Mantén tu software del runner actualizado
  • Monitorea regularmente los logs del runner para problemas
  • Usa etiquetas específicas para diferentes tipos de runners
  • Implementa medidas de seguridad apropiadas
  • Considera usar múltiples runners para balanceo de carga

Solución de Problemas

Problemas comunes y soluciones:

  1. Runner no conectando:

    • Verifica conectividad de red
    • Verifica validez del token de GitHub
    • Asegúrate de permisos apropiados
  2. Fallas de construcción:

    • Verifica instalación de Xcode
    • Verifica dependencias requeridas
    • Revisa logs del flujo de trabajo
  3. Problemas de permisos:

    • Verifica permisos de usuario
    • Verifica configuración de sudoers
    • Revisa permisos del sistema de archivos

Conclusión

Ahora tienes un runner auto-hospedado de GitHub Actions configurado en tu Mac mini. Esta configuración te proporciona más control sobre tu entorno de CI/CD y te permite ejecutar flujos de trabajo específicos de macOS de manera eficiente.

Recuerda mantener regularmente tu runner y mantenerlo actualizado con los últimos parches de seguridad y versiones de software.

Aplicación Nativa

Aplicación nativa de Macfleet

Guía de Instalación de Macfleet

Macfleet es una solución poderosa de gestión de flota diseñada específicamente para entornos de Mac Mini alojados en la nube. Como proveedor de hosting en la nube de Mac Mini, puedes usar Macfleet para monitorear, gestionar y optimizar toda tu flota de instancias Mac virtualizadas.

Esta guía de instalación te llevará a través de la configuración del monitoreo de Macfleet en sistemas macOS, Windows y Linux para asegurar una supervisión integral de tu infraestructura en la nube.

🍎 macOS

  • Descarga el archivo .dmg para Mac aquí
  • Haz doble clic en el archivo .dmg descargado
  • Arrastra la aplicación Macfleet a la carpeta Aplicaciones
  • Expulsa el archivo .dmg
  • Abre Preferencias del Sistema > Seguridad y Privacidad
    • Pestaña Privacidad > Accesibilidad
    • Marca Macfleet para permitir el monitoreo
  • Inicia Macfleet desde Aplicaciones
  • El seguimiento comienza automáticamente

🪟 Windows

  • Descarga el archivo .exe para Windows aquí
  • Haz clic derecho en el archivo .exe > "Ejecutar como administrador"
  • Sigue el asistente de instalación
  • Acepta los términos y condiciones
  • Permite en Windows Defender si se solicita
  • Concede permisos de monitoreo de aplicaciones
  • Inicia Macfleet desde el Menú Inicio
  • La aplicación comienza el seguimiento automáticamente

🐧 Linux

  • Descarga el paquete .deb (Ubuntu/Debian) o .rpm (CentOS/RHEL) aquí
  • Instala usando tu gestor de paquetes
    • Ubuntu/Debian: sudo dpkg -i Macfleet-linux.deb
    • CentOS/RHEL: sudo rpm -ivh Macfleet-linux.rpm
  • Permite permisos de acceso X11 si se solicita
  • Agrega el usuario a los grupos apropiados si es necesario
  • Inicia Macfleet desde el menú de Aplicaciones
  • La aplicación comienza el seguimiento automáticamente

Nota: Después de la instalación en todos los sistemas, inicia sesión con tus credenciales de Macfleet para sincronizar datos con tu panel de control.