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.

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

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.