Tutorial

Novas atualizações e melhorias para a Macfleet.

Aviso importante

Os exemplos de código e scripts fornecidos nestes tutoriais são apenas para fins educacionais. A Macfleet não é responsável por quaisquer problemas, danos ou vulnerabilidades de segurança que possam surgir do uso, modificação ou implementação destes exemplos. Sempre revise e teste o código em um ambiente seguro antes de usá-lo em sistemas de produção.

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

Novas atualizações e melhorias para a Macfleet.

Configurando um Runner do GitHub Actions em um Mac Mini (Apple Silicon)

Runner do GitHub Actions

GitHub Actions é uma plataforma poderosa de CI/CD que permite automatizar seus fluxos de trabalho de desenvolvimento de software. Embora o GitHub ofereça runners hospedados, runners auto-hospedados fornecem maior controle e personalização para sua configuração de CI/CD. Este tutorial o guia através da configuração e conexão de um runner auto-hospedado em um Mac mini para executar pipelines do macOS.

Pré-requisitos

Antes de começar, certifique-se de ter:

  • Um Mac mini (registre-se no Macfleet)
  • Um repositório GitHub com direitos de administrador
  • Um gerenciador de pacotes instalado (preferencialmente Homebrew)
  • Git instalado em seu sistema

Passo 1: Criar uma Conta de Usuário Dedicada

Primeiro, crie uma conta de usuário dedicada para o runner do GitHub Actions:

# Criar a conta de usuário '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

# Definir a senha para o usuário
sudo dscl . -passwd /Users/gh-runner sua_senha

# Adicionar 'gh-runner' ao grupo 'admin'
sudo dscl . -append /Groups/admin GroupMembership gh-runner

Mude para a nova conta de usuário:

su gh-runner

Passo 2: Instalar Software Necessário

Instale Git e Rosetta 2 (se estiver usando Apple Silicon):

# Instalar Git se ainda não estiver instalado
brew install git

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

Passo 3: Configurar o Runner do GitHub Actions

  1. Vá para seu repositório GitHub
  2. Navegue para Configurações > Actions > Runners

Runner do GitHub Actions

  1. Clique em "New self-hosted runner" (https://github.com/<username>/<repository>/settings/actions/runners/new)
  2. Selecione macOS como imagem do runner e ARM64 como arquitetura
  3. Siga os comandos fornecidos para baixar e configurar o runner

Runner do GitHub Actions

Crie um arquivo .env no diretório _work do runner:

# arquivo _work/.env
ImageOS=macos15
XCODE_15_DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
  1. Execute o script run.sh em seu diretório do runner para completar a configuração.
  2. Verifique se o runner está ativo e ouvindo por trabalhos no terminal e verifique as configurações do repositório GitHub para a associação do runner e status Idle.

Runner do GitHub Actions

Passo 4: Configurar Sudoers (Opcional)

Se suas ações requerem privilégios de root, configure o arquivo sudoers:

sudo visudo

Adicione a seguinte linha:

gh-runner ALL=(ALL) NOPASSWD: ALL

Passo 5: Usar o Runner em Fluxos de Trabalho

Configure seu fluxo de trabalho do GitHub Actions para usar o runner auto-hospedado:

name: Fluxo de trabalho de exemplo

on:
  workflow_dispatch:

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

O runner está autenticado em seu repositório e rotulado com self-hosted, macOS, e ARM64. Use-o em seus fluxos de trabalho especificando estes rótulos no campo runs-on:

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

Melhores Práticas

  • Mantenha seu software do runner atualizado
  • Monitore regularmente os logs do runner para problemas
  • Use rótulos específicos para diferentes tipos de runners
  • Implemente medidas de segurança adequadas
  • Considere usar múltiplos runners para balanceamento de carga

Solução de Problemas

Problemas comuns e soluções:

  1. Runner não conectando:

    • Verifique conectividade de rede
    • Verifique validade do token GitHub
    • Certifique-se de permissões adequadas
  2. Falhas de build:

    • Verifique instalação do Xcode
    • Verifique dependências necessárias
    • Revise logs do fluxo de trabalho
  3. Problemas de permissão:

    • Verifique permissões do usuário
    • Verifique configuração sudoers
    • Revise permissões do sistema de arquivos

Conclusão

Agora você tem um runner auto-hospedado do GitHub Actions configurado em seu Mac mini. Esta configuração fornece mais controle sobre seu ambiente CI/CD e permite executar fluxos de trabalho específicos do macOS de forma eficiente.

Lembre-se de manter regularmente seu runner e mantê-lo atualizado com os patches de segurança e versões de software mais recentes.

Aplicativo Nativo

Aplicativo nativo do Macfleet

Guia de Instalação do Macfleet

Macfleet é uma solução poderosa de gerenciamento de frota projetada especificamente para ambientes Mac Mini hospedados na nuvem. Como provedor de hospedagem na nuvem Mac Mini, você pode usar o Macfleet para monitorar, gerenciar e otimizar toda sua frota de instâncias Mac virtualizadas.

Este guia de instalação o conduzirá através da configuração do monitoramento do Macfleet em sistemas macOS, Windows e Linux para garantir supervisão abrangente de sua infraestrutura na nuvem.

🍎 macOS

  • Baixe o arquivo .dmg para Mac aqui
  • Clique duas vezes no arquivo .dmg baixado
  • Arraste o aplicativo Macfleet para a pasta Aplicativos
  • Ejete o arquivo .dmg
  • Abra Preferências do Sistema > Segurança e Privacidade
    • Aba Privacidade > Acessibilidade
    • Marque Macfleet para permitir monitoramento
  • Inicie o Macfleet a partir de Aplicativos
  • O rastreamento inicia automaticamente

🪟 Windows

  • Baixe o arquivo .exe para Windows aqui
  • Clique com o botão direito no arquivo .exe > "Executar como administrador"
  • Siga o assistente de instalação
  • Aceite os termos e condições
  • Permita no Windows Defender se solicitado
  • Conceda permissões de monitoramento de aplicativo
  • Inicie o Macfleet a partir do Menu Iniciar
  • O aplicativo começa o rastreamento automaticamente

🐧 Linux

  • Baixe o pacote .deb (Ubuntu/Debian) ou .rpm (CentOS/RHEL) aqui
  • Instale usando seu gerenciador de pacotes
    • Ubuntu/Debian: sudo dpkg -i Macfleet-linux.deb
    • CentOS/RHEL: sudo rpm -ivh Macfleet-linux.rpm
  • Permita permissões de acesso X11 se solicitado
  • Adicione o usuário aos grupos apropriados se necessário
  • Inicie o Macfleet a partir do menu Aplicativos
  • O aplicativo começa o rastreamento automaticamente

Nota: Após a instalação em todos os sistemas, faça login com suas credenciais do Macfleet para sincronizar dados com seu painel de controle.