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.

FileVault Encryption Management on macOS

Manage FileVault disk encryption across your MacFleet deployment with comprehensive monitoring, compliance reporting, and automated encryption management. This tutorial provides enterprise-grade solutions for maintaining data security through disk encryption.

Understanding FileVault Encryption

FileVault is Apple's full-disk encryption technology that protects data at rest on macOS devices:

  • Full Disk Encryption - Encrypts entire startup disk
  • XTS-AES-128 encryption algorithm with 256-bit key
  • Hardware acceleration on supported Mac devices
  • Recovery key management for enterprise deployment
  • Compliance requirements for data protection standards

Basic Encryption Status Monitoring

Check FileVault Status

#!/bin/bash

# Check current FileVault encryption status
sudo fdesetup status

echo "FileVault status check completed"

Verify Encryption State

#!/bin/bash

# Get detailed encryption information
echo "=== FileVault Status ==="
status=$(sudo fdesetup status)
echo "$status"

# Parse status for automation
if echo "$status" | grep -q "FileVault is On"; then
    echo "✅ Encryption: ENABLED"
    exit 0
elif echo "$status" | grep -q "FileVault is Off"; then
    echo "❌ Encryption: DISABLED"
    exit 1
else
    echo "⚠️ Encryption: UNKNOWN STATE"
    exit 2
fi

Encryption Progress Monitoring

macOS 10.11 and 10.12 (Core Storage)

#!/bin/bash

# Monitor encryption/decryption progress for older macOS versions
echo "=== Core Storage Encryption Progress ==="
progress=$(diskutil cs list | grep "Conversion Progress")

if [[ -n "$progress" ]]; then
    echo "Encryption in progress:"
    echo "$progress"
else
    echo "No encryption/decryption operation in progress"
fi

macOS 10.13+ (APFS)

#!/bin/bash

# Monitor encryption progress for APFS (macOS 10.13+)
echo "=== APFS Encryption Progress ==="

# Check encryption progress
enc_progress=$(diskutil apfs list | grep "Encryption Progress")
if [[ -n "$enc_progress" ]]; then
    echo "Encryption in progress:"
    echo "$enc_progress"
fi

# Check decryption progress
dec_progress=$(diskutil apfs list | grep "Decryption Progress")
if [[ -n "$dec_progress" ]]; then
    echo "Decryption in progress:"
    echo "$dec_progress"
fi

if [[ -z "$enc_progress" && -z "$dec_progress" ]]; then
    echo "No encryption/decryption operation in progress"
fi

Universal Progress Monitor

#!/bin/bash

# Universal encryption progress monitor
check_encryption_progress() {
    local macos_version
    macos_version=$(sw_vers -productVersion | cut -d. -f1-2)
    
    echo "=== Encryption Progress Monitor ==="
    echo "macOS Version: $macos_version"
    
    case "$macos_version" in
        "10.11"|"10.12")
            echo "Using Core Storage monitoring..."
            diskutil cs list | grep "Conversion Progress" || echo "No progress detected"
            ;;
        *)
            echo "Using APFS monitoring..."
            local enc_progress dec_progress
            enc_progress=$(diskutil apfs list | grep "Encryption Progress")
            dec_progress=$(diskutil apfs list | grep "Decryption Progress")
            
            if [[ -n "$enc_progress" ]]; then
                echo "Encryption: $enc_progress"
            elif [[ -n "$dec_progress" ]]; then
                echo "Decryption: $dec_progress"
            else
                echo "No encryption/decryption operation in progress"
            fi
            ;;
    esac
}

check_encryption_progress

Advanced Enterprise Management

Comprehensive Encryption Audit

#!/bin/bash

# MacFleet FileVault Enterprise Audit Tool
# Comprehensive encryption status and compliance checking

# Configuration
LOG_FILE="/var/log/macfleet_encryption.log"
REPORT_DIR="/var/log/macfleet_reports"
CONFIG_FILE="/etc/macfleet/encryption_policy.conf"

# Create directories if they don't exist
mkdir -p "$(dirname "$LOG_FILE")" "$REPORT_DIR" "$(dirname "$CONFIG_FILE")"

# Default configuration
cat > "$CONFIG_FILE" 2>/dev/null << 'EOF' || true
# MacFleet Encryption Policy Configuration
REQUIRE_FILEVAULT=true
ALERT_ON_DISABLED=true
MONITOR_PROGRESS=true
COMPLIANCE_REPORTING=true
AUTO_REMEDIATION=false
NOTIFICATION_EMAIL=""
EOF

# Source configuration
source "$CONFIG_FILE" 2>/dev/null || true

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

# Get system information
get_system_info() {
    echo "=== System Information ==="
    echo "Hostname: $(hostname)"
    echo "macOS Version: $(sw_vers -productVersion)"
    echo "Build: $(sw_vers -buildVersion)"
    echo "Hardware: $(system_profiler SPHardwareDataType | grep "Model Name" | awk -F: '{print $2}' | xargs)"
    echo "Serial: $(system_profiler SPHardwareDataType | grep "Serial Number" | awk -F: '{print $2}' | xargs)"
    echo "Audit Date: $(date)"
    echo ""
}

# Check FileVault status
check_filevault_status() {
    echo "=== FileVault Status Analysis ==="
    
    local status
    status=$(sudo fdesetup status 2>/dev/null)
    
    if echo "$status" | grep -q "FileVault is On"; then
        echo "✅ FileVault Status: ENABLED"
        log_action "FileVault encryption is properly enabled"
        
        # Get enabled users
        local enabled_users
        enabled_users=$(sudo fdesetup list 2>/dev/null)
        if [[ -n "$enabled_users" ]]; then
            echo "Enabled Users:"
            echo "$enabled_users"
        fi
        
        return 0
    elif echo "$status" | grep -q "FileVault is Off"; then
        echo "❌ FileVault Status: DISABLED"
        log_action "SECURITY ALERT: FileVault encryption is disabled"
        
        if [[ "$ALERT_ON_DISABLED" == "true" ]]; then
            echo "⚠️  COMPLIANCE VIOLATION: Encryption required by policy"
        fi
        
        return 1
    else
        echo "⚠️  FileVault Status: UNKNOWN"
        log_action "WARNING: Cannot determine FileVault status"
        return 2
    fi
}

# Check encryption progress
check_encryption_progress() {
    echo "=== Encryption Progress ==="
    
    local macos_version
    macos_version=$(sw_vers -productVersion | cut -d. -f1-2)
    
    case "$macos_version" in
        "10.11"|"10.12")
            local cs_progress
            cs_progress=$(diskutil cs list | grep "Conversion Progress")
            if [[ -n "$cs_progress" ]]; then
                echo "Core Storage Progress: $cs_progress"
                log_action "Encryption/Decryption in progress: $cs_progress"
            else
                echo "No Core Storage conversion in progress"
            fi
            ;;
        *)
            local enc_progress dec_progress
            enc_progress=$(diskutil apfs list | grep "Encryption Progress")
            dec_progress=$(diskutil apfs list | grep "Decryption Progress")
            
            if [[ -n "$enc_progress" ]]; then
                echo "APFS Encryption Progress: $enc_progress"
                log_action "APFS encryption in progress: $enc_progress"
            elif [[ -n "$dec_progress" ]]; then
                echo "APFS Decryption Progress: $dec_progress"
                log_action "APFS decryption in progress: $dec_progress"
            else
                echo "No APFS encryption/decryption in progress"
            fi
            ;;
    esac
}

# Check disk information
check_disk_info() {
    echo "=== Disk Information ==="
    
    # Boot disk info
    local boot_disk
    boot_disk=$(diskutil info / | grep "Device Node" | awk '{print $3}')
    echo "Boot Disk: $boot_disk"
    
    # Disk size and usage
    echo "Disk Usage:"
    df -h /
    
    # APFS information (macOS 10.13+)
    if command -v diskutil >/dev/null && diskutil apfs list >/dev/null 2>&1; then
        echo -e "\nAPFS Container Info:"
        diskutil apfs list | grep -E "(Container|Volume|Encryption)"
    fi
}

# Generate compliance report
generate_compliance_report() {
    local report_file="$REPORT_DIR/encryption_compliance_$(date +%Y%m%d_%H%M%S).json"
    
    echo "=== Generating Compliance Report ==="
    
    # Get FileVault status
    local filevault_enabled=false
    local status_detail=""
    
    if sudo fdesetup status 2>/dev/null | grep -q "FileVault is On"; then
        filevault_enabled=true
        status_detail="enabled"
    else
        status_detail="disabled"
    fi
    
    # Create JSON report
    cat > "$report_file" << EOF
{
  "report_type": "encryption_compliance",
  "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "hostname": "$(hostname)",
  "serial_number": "$(system_profiler SPHardwareDataType | grep "Serial Number" | awk -F: '{print $2}' | xargs)",
  "macos_version": "$(sw_vers -productVersion)",
  "encryption": {
    "filevault_enabled": $filevault_enabled,
    "status_detail": "$status_detail",
    "compliance_status": "$([ "$filevault_enabled" == "true" ] && echo "compliant" || echo "non_compliant")",
    "policy_required": $REQUIRE_FILEVAULT
  },
  "disk_info": {
    "boot_disk": "$(diskutil info / | grep "Device Node" | awk '{print $3}')",
    "file_system": "$(diskutil info / | grep "File System" | awk -F: '{print $2}' | xargs)"
  },
  "audit_details": {
    "audit_date": "$(date)",
    "policy_version": "1.0",
    "remediation_required": $([ "$filevault_enabled" != "true" ] && echo "true" || echo "false")
  }
}
EOF
    
    echo "Compliance report saved to: $report_file"
    log_action "Compliance report generated: $report_file"
}

# Remediation actions
perform_remediation() {
    echo "=== Automated Remediation ==="
    
    if [[ "$AUTO_REMEDIATION" != "true" ]]; then
        echo "Auto-remediation disabled in policy"
        return 0
    fi
    
    # Check if FileVault is disabled
    if ! sudo fdesetup status 2>/dev/null | grep -q "FileVault is On"; then
        echo "⚠️  FileVault is disabled - remediation required"
        log_action "REMEDIATION: FileVault encryption is disabled"
        
        echo "Manual remediation steps:"
        echo "1. Open System Preferences > Security & Privacy"
        echo "2. Click the FileVault tab"
        echo "3. Click Turn On FileVault"
        echo "4. Follow the setup wizard"
        echo ""
        echo "Or use MDM to enforce FileVault encryption policy"
        
        # Create remediation ticket (placeholder)
        echo "Creating remediation ticket for device: $(hostname)"
    fi
}

# Main audit function
main() {
    log_action "=== MacFleet FileVault Audit Started ==="
    
    get_system_info
    check_filevault_status
    local filevault_status=$?
    
    echo ""
    check_encryption_progress
    echo ""
    check_disk_info
    echo ""
    
    if [[ "$COMPLIANCE_REPORTING" == "true" ]]; then
        generate_compliance_report
        echo ""
    fi
    
    if [[ $filevault_status -ne 0 ]]; then
        perform_remediation
    fi
    
    log_action "=== FileVault audit completed with status: $filevault_status ==="
    return $filevault_status
}

# Execute main function
main "$@"

Enterprise Policy Management

Policy Configuration Template

#!/bin/bash

# Create comprehensive encryption policy
cat > /etc/macfleet/encryption_policy.conf << 'EOF'
# MacFleet Enterprise Encryption Policy
# Version: 2.0

# Core Requirements
REQUIRE_FILEVAULT=true
ENFORCE_IMMEDIATE_ENCRYPTION=true
ALLOW_PERSONAL_RECOVERY_KEY=false
REQUIRE_INSTITUTIONAL_RECOVERY_KEY=true

# Monitoring Configuration
ALERT_ON_DISABLED=true
MONITOR_PROGRESS=true
PROGRESS_CHECK_INTERVAL=3600  # seconds
COMPLIANCE_REPORTING=true
AUDIT_FREQUENCY=86400  # daily

# Remediation Settings
AUTO_REMEDIATION=false
ESCALATION_THRESHOLD=72  # hours
NOTIFICATION_EMAIL="security@company.com"
HELP_DESK_CONTACT="+1-555-0123"

# Security Policies
MIN_RECOVERY_KEY_LENGTH=24
RECOVERY_KEY_ROTATION_DAYS=90
ENCRYPTION_ALGORITHM="XTS-AES-128"

# Compliance Standards
COMPLIANCE_FRAMEWORKS="SOC2,HIPAA,PCI-DSS"
DATA_CLASSIFICATION_REQUIRED=true
AUDIT_TRAIL_RETENTION_DAYS=2555  # 7 years
EOF

echo "Enterprise encryption policy configured"

Recovery Key Management

#!/bin/bash

# Enterprise recovery key management
manage_recovery_keys() {
    echo "=== Recovery Key Management ==="
    
    # Check if institutional recovery key is set
    local has_institutional_key=false
    if sudo fdesetup list 2>/dev/null | grep -q "institutional"; then
        has_institutional_key=true
        echo "✅ Institutional recovery key configured"
    else
        echo "❌ No institutional recovery key found"
    fi
    
    # Validate recovery key
    if [[ "$has_institutional_key" == "true" ]]; then
        echo "Recovery key validation:"
        sudo fdesetup validaterecovery 2>/dev/null && echo "✅ Recovery key valid" || echo "❌ Recovery key invalid"
    fi
    
    # Escrow recovery key (MDM integration)
    echo "Recovery key escrow status:"
    if system_profiler SPConfigurationProfileDataType | grep -q "FDERecoveryKeyEscrow"; then
        echo "✅ Recovery key escrowed to MDM"
    else
        echo "⚠️  Recovery key not escrowed"
    fi
}

manage_recovery_keys

Monitoring and Alerting

Continuous Monitoring Script

#!/bin/bash

# Continuous FileVault monitoring daemon
DAEMON_NAME="macfleet-encryption-monitor"
PID_FILE="/var/run/${DAEMON_NAME}.pid"
CHECK_INTERVAL=300  # 5 minutes

# Daemon functions
start_monitoring() {
    if [[ -f "$PID_FILE" ]]; then
        echo "Monitoring daemon already running (PID: $(cat "$PID_FILE"))"
        return 1
    fi
    
    echo "Starting FileVault monitoring daemon..."
    
    # Background monitoring loop
    (
        while true; do
            # Quick status check
            if ! sudo fdesetup status 2>/dev/null | grep -q "FileVault is On"; then
                logger -t "$DAEMON_NAME" "ALERT: FileVault encryption disabled on $(hostname)"
                
                # Send notification (customize for your environment)
                osascript -e 'display notification "FileVault encryption is disabled!" with title "MacFleet Security Alert"' 2>/dev/null || true
            fi
            
            sleep "$CHECK_INTERVAL"
        done
    ) &
    
    echo $! > "$PID_FILE"
    echo "Monitoring daemon started (PID: $!)"
}

stop_monitoring() {
    if [[ -f "$PID_FILE" ]]; then
        local pid
        pid=$(cat "$PID_FILE")
        kill "$pid" 2>/dev/null
        rm -f "$PID_FILE"
        echo "Monitoring daemon stopped"
    else
        echo "Monitoring daemon not running"
    fi
}

# Execute based on argument
case "${1:-start}" in
    start)
        start_monitoring
        ;;
    stop)
        stop_monitoring
        ;;
    restart)
        stop_monitoring
        sleep 2
        start_monitoring
        ;;
    status)
        if [[ -f "$PID_FILE" ]]; then
            echo "Monitoring daemon running (PID: $(cat "$PID_FILE"))"
        else
            echo "Monitoring daemon not running"
        fi
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
        ;;
esac

Important Security Notes

FileVault Best Practices

  • Enable before deployment - Encrypt devices before user deployment
  • Escrow recovery keys - Use MDM for centralized key management
  • Regular key rotation - Rotate institutional recovery keys periodically
  • Monitor compliance - Continuous monitoring for policy violations
  • Test recovery procedures - Regularly test key recovery processes

Enterprise Considerations

  • Performance impact - Minimal on modern Mac hardware with T2/Apple Silicon
  • Initial encryption time - Can take several hours for large drives
  • Recovery planning - Ensure recovery key availability for support
  • User training - Educate users on encryption benefits and recovery
  • Compliance reporting - Regular audits for regulatory requirements

Apple Silicon Considerations

  • Hardware acceleration - Optimized encryption performance
  • Secure Enclave - Enhanced key protection
  • Progress monitoring limitations - Some monitoring tools may not work
  • Boot security - Additional security features beyond FileVault

Remember to test these scripts thoroughly in your environment before deploying to production devices.

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.