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.

Screen Lock Security on macOS

Implement comprehensive screen lock security policies across your MacFleet devices using AppleScript automation and advanced security configurations. This tutorial covers password enforcement, sleep security management, and enterprise-grade lock mechanisms.

Understanding macOS Screen Lock Security

macOS provides multiple layers of screen lock security:

  • Screen Saver Password - Requires password when returning from screen saver
  • Sleep Password - Requires password when waking from sleep mode
  • Immediate Lock - Sets password requirement timing to immediate
  • Security Preferences - System-level security configuration management

Basic Screen Lock Configuration

Enable Password for Screen Lock

#!/bin/bash

# Basic screen lock password enablement
enable_screen_lock_password() {
    echo "=== Enabling Screen Lock Password ==="
    
    # Enable password requirement for screen lock using AppleScript
    if osascript -e 'tell application "System Events" to set require password to wake of security preferences to true'; then
        echo "✅ Screen lock password enabled successfully"
        
        # Verify the setting
        local current_setting=$(osascript -e 'tell application "System Events" to get require password to wake of security preferences')
        if [[ "$current_setting" == "true" ]]; then
            echo "✅ Password requirement verified: enabled"
        else
            echo "⚠️  Password requirement verification failed"
        fi
    else
        echo "❌ Failed to enable screen lock password"
        return 1
    fi
}

enable_screen_lock_password

Check Current Screen Lock Status

#!/bin/bash

# Check current screen lock password status
check_screen_lock_status() {
    echo "=== Screen Lock Status Check ==="
    
    # Get current password requirement status
    local password_required=$(osascript -e 'tell application "System Events" to get require password to wake of security preferences' 2>/dev/null)
    
    if [[ "$password_required" == "true" ]]; then
        echo "✅ Screen lock password: ENABLED"
    elif [[ "$password_required" == "false" ]]; then
        echo "❌ Screen lock password: DISABLED"
    else
        echo "⚠️  Screen lock password status: UNKNOWN"
    fi
    
    # Get screen saver timeout settings
    local saver_timeout=$(defaults read com.apple.screensaver idleTime 2>/dev/null || echo "Unknown")
    echo "Screen saver timeout: $saver_timeout seconds"
    
    # Get display sleep timeout
    local display_sleep=$(pmset -g | grep displaysleep | awk '{print $2}')
    echo "Display sleep timeout: $display_sleep minutes"
    
    # Get system sleep timeout
    local system_sleep=$(pmset -g | grep sleep | grep -v displaysleep | awk '{print $2}')
    echo "System sleep timeout: $system_sleep minutes"
}

check_screen_lock_status

Advanced Security Configuration

Comprehensive Screen Lock Setup

#!/bin/bash

# Advanced screen lock security configuration
configure_advanced_screen_lock() {
    local timeout_minutes="${1:-5}"
    local grace_period="${2:-0}"
    
    echo "=== Advanced Screen Lock Configuration ==="
    echo "Timeout: $timeout_minutes minutes"
    echo "Grace period: $grace_period seconds"
    
    # Enable password requirement for screen lock
    echo "Enabling password requirement..."
    if osascript -e 'tell application "System Events" to set require password to wake of security preferences to true'; then
        echo "✅ Password requirement enabled"
    else
        echo "❌ Failed to enable password requirement"
        return 1
    fi
    
    # Set password delay (grace period)
    echo "Setting password delay..."
    if osascript -e "tell application \"System Events\" to set delay interval of security preferences to $grace_period"; then
        echo "✅ Password delay set to $grace_period seconds"
    else
        echo "⚠️  Password delay setting may have failed"
    fi
    
    # Configure screen saver timeout
    echo "Configuring screen saver timeout..."
    local timeout_seconds=$((timeout_minutes * 60))
    defaults write com.apple.screensaver idleTime -int $timeout_seconds
    
    # Enable screen saver password immediately
    defaults write com.apple.screensaver askForPassword -int 1
    defaults write com.apple.screensaver askForPasswordDelay -int $grace_period
    
    # Configure system sleep settings
    echo "Configuring power management..."
    sudo pmset -a displaysleep $timeout_minutes
    sudo pmset -a sleep $((timeout_minutes + 5))
    
    # Apply hot corners for immediate lock (optional)
    configure_hot_corners
    
    echo "✅ Advanced screen lock configuration completed"
}

# Configure hot corners for security
configure_hot_corners() {
    echo "Configuring security hot corners..."
    
    # Bottom right corner: Start screen saver
    defaults write com.apple.dock wvous-br-corner -int 5
    defaults write com.apple.dock wvous-br-modifier -int 0
    
    # Top right corner: Put display to sleep
    defaults write com.apple.dock wvous-tr-corner -int 10
    defaults write com.apple.dock wvous-tr-modifier -int 0
    
    # Restart Dock to apply changes
    killall Dock
    
    echo "✅ Hot corners configured for enhanced security"
}

# Usage: configure_advanced_screen_lock 3 0
configure_advanced_screen_lock

Security Policy Enforcement

#!/bin/bash

# Enforce enterprise security policies
enforce_security_policies() {
    echo "=== Security Policy Enforcement ==="
    
    # Disable automatic login
    echo "Disabling automatic login..."
    sudo defaults delete /Library/Preferences/com.apple.loginwindow autoLoginUser 2>/dev/null || true
    
    # Enable fast user switching menu
    echo "Configuring user switching..."
    sudo defaults write /Library/Preferences/.GlobalPreferences MultipleSessionEnabled -bool YES
    defaults write .GlobalPreferences userMenuExtraStyle -int 2
    
    # Disable guest account
    echo "Disabling guest account..."
    sudo defaults write /Library/Preferences/com.apple.loginwindow GuestEnabled -bool NO
    
    # Set login window to show name and password fields
    sudo defaults write /Library/Preferences/com.apple.loginwindow SHOWFULLNAME -bool YES
    
    # Hide admin users from login window
    sudo defaults write /Library/Preferences/com.apple.loginwindow Hide500Users -bool YES
    
    # Disable password hints
    sudo defaults write /Library/Preferences/com.apple.loginwindow RetriesUntilHint -int 0
    
    # Enable secure virtual memory
    sudo defaults write /Library/Preferences/com.apple.virtualMemory UseEncryptedSwap -bool YES
    
    echo "✅ Security policies enforced"
}

enforce_security_policies

Screen Saver and Lock Management

Screen Saver Configuration

#!/bin/bash

# Configure screen saver with security settings
configure_secure_screensaver() {
    local module_name="${1:-Flurry}"
    local timeout_minutes="${2:-5}"
    
    echo "=== Secure Screen Saver Configuration ==="
    echo "Module: $module_name"
    echo "Timeout: $timeout_minutes minutes"
    
    # Set screen saver module
    defaults -currentHost write com.apple.screensaver moduleDict -dict \
        moduleName "$module_name" \
        path "/System/Library/Screen Savers/$module_name.saver" \
        type 0
    
    # Set timeout
    local timeout_seconds=$((timeout_minutes * 60))
    defaults write com.apple.screensaver idleTime -int $timeout_seconds
    
    # Enable password immediately
    defaults write com.apple.screensaver askForPassword -int 1
    defaults write com.apple.screensaver askForPasswordDelay -int 0
    
    # Disable screen saver preview
    defaults write com.apple.screensaver showClock -bool NO
    
    # Set message on lock screen (optional)
    set_lock_screen_message
    
    echo "✅ Secure screen saver configured"
}

# Set custom lock screen message
set_lock_screen_message() {
    local message="${1:-This device is managed by MacFleet. Unauthorized access is prohibited.}"
    
    echo "Setting lock screen message..."
    defaults write /Library/Preferences/com.apple.loginwindow LoginwindowText "$message"
    
    echo "✅ Lock screen message set"
}

# Usage: configure_secure_screensaver "Flurry" 3
configure_secure_screensaver

Manual Lock Mechanisms

#!/bin/bash

# Immediate lock mechanisms
immediate_lock_functions() {
    echo "=== Immediate Lock Mechanisms ==="
    
    # Method 1: Using pmset to sleep display
    lock_display_pmset() {
        echo "Locking display using pmset..."
        pmset displaysleepnow
    }
    
    # Method 2: Using osascript to activate screen saver
    lock_screensaver() {
        echo "Activating screen saver lock..."
        osascript -e 'tell application "System Events" to start current screen saver'
    }
    
    # Method 3: Using CGSession for fast user switching
    lock_fast_user_switch() {
        echo "Switching to login window..."
        /System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend
    }
    
    # Method 4: Using open command with screen saver
    lock_open_screensaver() {
        echo "Opening screen saver module..."
        open -a ScreenSaverEngine
    }
    
    # Default lock method
    lock_display_pmset
}

immediate_lock_functions

Enterprise Lock Management System

#!/bin/bash

# MacFleet Enterprise Screen Lock Management System
# Comprehensive security policy enforcement and monitoring

# Configuration
SECURITY_CONFIG_FILE="/etc/macfleet/screen_lock_config.conf"
LOG_FILE="/var/log/macfleet_screen_lock.log"
STATUS_FILE="/var/log/macfleet_security_status.json"

# Default security settings
DEFAULT_SCREEN_TIMEOUT=300    # 5 minutes
DEFAULT_GRACE_PERIOD=0        # Immediate
DEFAULT_DISPLAY_SLEEP=5       # 5 minutes
DEFAULT_SYSTEM_SLEEP=10       # 10 minutes

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

# Load security configuration
load_security_config() {
    if [[ -f "$SECURITY_CONFIG_FILE" ]]; then
        source "$SECURITY_CONFIG_FILE"
        log_action "Loaded security configuration from $SECURITY_CONFIG_FILE"
    else
        log_action "Using default security configuration"
    fi
}

# Apply enterprise screen lock policies
apply_enterprise_policies() {
    log_action "Applying enterprise screen lock policies"
    
    # Enable password requirement for screen lock
    log_action "Enabling screen lock password requirement"
    if osascript -e 'tell application "System Events" to set require password to wake of security preferences to true'; then
        log_action "✅ Screen lock password requirement enabled"
    else
        log_action "❌ Failed to enable screen lock password requirement"
        return 1
    fi
    
    # Set password delay
    local grace_period="${GRACE_PERIOD:-$DEFAULT_GRACE_PERIOD}"
    log_action "Setting password grace period to $grace_period seconds"
    osascript -e "tell application \"System Events\" to set delay interval of security preferences to $grace_period" 2>/dev/null
    
    # Configure screen saver settings
    local screen_timeout="${SCREEN_TIMEOUT:-$DEFAULT_SCREEN_TIMEOUT}"
    log_action "Setting screen saver timeout to $screen_timeout seconds"
    defaults write com.apple.screensaver idleTime -int $screen_timeout
    defaults write com.apple.screensaver askForPassword -int 1
    defaults write com.apple.screensaver askForPasswordDelay -int $grace_period
    
    # Configure power management
    local display_sleep="${DISPLAY_SLEEP:-$DEFAULT_DISPLAY_SLEEP}"
    local system_sleep="${SYSTEM_SLEEP:-$DEFAULT_SYSTEM_SLEEP}"
    
    log_action "Configuring power management: display=$display_sleep min, system=$system_sleep min"
    sudo pmset -a displaysleep $display_sleep
    sudo pmset -a sleep $system_sleep
    sudo pmset -a halfdim 1
    
    # Apply additional security settings
    apply_additional_security_settings
    
    log_action "screen lock policies applied successfully"
}

# Apply additional security settings
apply_additional_security_settings() {
    log_action "Applying additional security settings"
    
    # Disable automatic login
    sudo defaults delete /Library/Preferences/com.apple.loginwindow autoLoginUser 2>/dev/null || true
    
    # Disable guest account
    sudo defaults write /Library/Preferences/com.apple.loginwindow GuestEnabled -bool NO
    
    # Set login window to show name and password fields
    sudo defaults write /Library/Preferences/com.apple.loginwindow SHOWFULLNAME -bool YES
    
    # Hide admin users from login window
    sudo defaults write /Library/Preferences/com.apple.loginwindow Hide500Users -bool YES
    
    # Disable password hints
    sudo defaults write /Library/Preferences/com.apple.loginwindow RetriesUntilHint -int 0
    
    # Enable secure virtual memory
    sudo defaults write /Library/Preferences/com.apple.virtualMemory UseEncryptedSwap -bool YES
    
    # Set lock screen message if configured
    if [[ -n "${LOCK_SCREEN_MESSAGE}" ]]; then
        defaults write /Library/Preferences/com.apple.loginwindow LoginwindowText "$LOCK_SCREEN_MESSAGE"
        log_action "Set lock screen message"
    fi
    
    log_action "Additional security settings applied"
}

# Monitor screen lock compliance
monitor_screen_lock_compliance() {
    log_action "Monitoring screen lock compliance"
    
    local compliance_issues=0
    local timestamp=$(date -u +%Y-%m-%dT%H:%M:%SZ)
    
    # Check password requirement
    local password_required=$(osascript -e 'tell application "System Events" to get require password to wake of security preferences' 2>/dev/null)
    local password_compliant=false
    
    if [[ "$password_required" == "true" ]]; then
        password_compliant=true
        log_action "✅ Password requirement: compliant"
    else
        ((compliance_issues++))
        log_action "❌ Password requirement: non-compliant"
    fi
    
    # Check screen saver timeout
    local current_timeout=$(defaults read com.apple.screensaver idleTime 2>/dev/null || echo "0")
    local timeout_compliant=false
    local max_allowed_timeout="${MAX_SCREEN_TIMEOUT:-600}"  # 10 minutes default
    
    if [[ "$current_timeout" -le "$max_allowed_timeout" && "$current_timeout" -gt 0 ]]; then
        timeout_compliant=true
        log_action "✅ Screen saver timeout: compliant ($current_timeout seconds)"
    else
        ((compliance_issues++))
        log_action "❌ Screen saver timeout: non-compliant ($current_timeout seconds)"
    fi
    
    # Check password delay
    local password_delay=$(defaults read com.apple.screensaver askForPasswordDelay 2>/dev/null || echo "300")
    local delay_compliant=false
    local max_allowed_delay="${MAX_PASSWORD_DELAY:-60}"  # 1 minute default
    
    if [[ "$password_delay" -le "$max_allowed_delay" ]]; then
        delay_compliant=true
        log_action "✅ Password delay: compliant ($password_delay seconds)"
    else
        ((compliance_issues++))
        log_action "❌ Password delay: non-compliant ($password_delay seconds)"
    fi
    
    # Check guest account status
    local guest_enabled=$(sudo defaults read /Library/Preferences/com.apple.loginwindow GuestEnabled 2>/dev/null || echo "true")
    local guest_compliant=false
    
    if [[ "$guest_enabled" == "0" || "$guest_enabled" == "false" ]]; then
        guest_compliant=true
        log_action "✅ Guest account: disabled (compliant)"
    else
        ((compliance_issues++))
        log_action "❌ Guest account: enabled (non-compliant)"
    fi
    
    # Generate compliance report
    local compliance_status='{
        "timestamp": "'$timestamp'",
        "device_id": "'$(system_profiler SPHardwareDataType | grep "Hardware UUID" | awk '{print $3}')'",
        "hostname": "'$(hostname)'",
        "compliance_score": '$((4 - compliance_issues))'/4,
        "total_issues": '$compliance_issues',
        "checks": {
            "password_required": '$password_compliant',
            "timeout_compliant": '$timeout_compliant',
            "delay_compliant": '$delay_compliant',
            "guest_disabled": '$guest_compliant'
        },
        "settings": {
            "current_timeout": '$current_timeout',
            "current_delay": '$password_delay',
            "guest_account": "'$guest_enabled'"
        }
    }'
    
    # Save compliance status
    echo "$compliance_status" | jq . > "$STATUS_FILE"
    
    if [[ $compliance_issues -eq 0 ]]; then
        log_action "✅ Screen lock compliance check passed (4/4)"
    else
        log_action "⚠️  Screen lock compliance issues found: $compliance_issues/4"
    fi
    
    return $compliance_issues
}

# Auto-remediate compliance issues
auto_remediate_compliance() {
    log_action "Starting auto-remediation for compliance issues"
    
    # Check current compliance
    monitor_screen_lock_compliance
    local issues=$?
    
    if [[ $issues -eq 0 ]]; then
        log_action "No compliance issues found, skipping remediation"
        return 0
    fi
    
    log_action "Found $issues compliance issues, attempting remediation"
    
    # Re-apply enterprise policies
    apply_enterprise_policies
    
    # Wait and re-check compliance
    sleep 5
    monitor_screen_lock_compliance
    local remaining_issues=$?
    
    if [[ $remaining_issues -lt $issues ]]; then
        log_action "✅ Remediation successful: reduced issues from $issues to $remaining_issues"
    else
        log_action "⚠️  Remediation incomplete: $remaining_issues issues remain"
    fi
    
    return $remaining_issues
}

# Generate security report
generate_security_report() {
    log_action "Generating comprehensive security report"
    
    local report_file="/var/log/macfleet_security_report_$(date +%Y%m%d_%H%M%S).txt"
    
    {
        echo "MacFleet Screen Lock Security Report"
        echo "Generated: $(date)"
        echo "Device: $(hostname)"
        echo "Hardware UUID: $(system_profiler SPHardwareDataType | grep "Hardware UUID" | awk '{print $3}')"
        echo "macOS Version: $(sw_vers -productVersion)"
        echo "====================================="
        echo ""
        
        echo "Screen Lock Configuration:"
        echo "Password Required: $(osascript -e 'tell application "System Events" to get require password to wake of security preferences' 2>/dev/null || echo 'Unknown')"
        echo "Screen Saver Timeout: $(defaults read com.apple.screensaver idleTime 2>/dev/null || echo 'Not set') seconds"
        echo "Password Delay: $(defaults read com.apple.screensaver askForPasswordDelay 2>/dev/null || echo 'Not set') seconds"
        echo ""
        
        echo "Power Management Settings:"
        pmset -g | grep -E "(sleep|displaysleep|halfdim)"
        echo ""
        
        echo "Login Window Security:"
        echo "Guest Account: $(sudo defaults read /Library/Preferences/com.apple.loginwindow GuestEnabled 2>/dev/null || echo 'Unknown')"
        echo "Show Full Name: $(sudo defaults read /Library/Preferences/com.apple.loginwindow SHOWFULLNAME 2>/dev/null || echo 'Unknown')"
        echo "Hide Admin Users: $(sudo defaults read /Library/Preferences/com.apple.loginwindow Hide500Users 2>/dev/null || echo 'Unknown')"
        echo ""
        
        echo "Security Compliance Status:"
        if [[ -f "$STATUS_FILE" ]]; then
            cat "$STATUS_FILE"
        else
            echo "No compliance data available"
        fi
        
    } > "$report_file"
    
    log_action "Security report saved to: $report_file"
}

# Emergency lock function
emergency_lock() {
    log_action "Emergency lock initiated"
    
    # Method 1: Immediate display sleep
    pmset displaysleepnow
    
    # Method 2: Activate screen saver
    osascript -e 'tell application "System Events" to start current screen saver' 2>/dev/null
    
    # Method 3: Switch to login window
    /System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend 2>/dev/null
    
    log_action "Emergency lock completed"
}

# Main screen lock management function
main() {
    local action="${1:-apply}"
    
    log_action "=== MacFleet Screen Lock Management Started ==="
    
    case "$action" in
        "apply")
            load_security_config
            apply_enterprise_policies
            ;;
        "monitor")
            monitor_screen_lock_compliance
            ;;
        "remediate")
            auto_remediate_compliance
            ;;
        "report")
            generate_security_report
            ;;
        "lock")
            emergency_lock
            ;;
        "status")
            monitor_screen_lock_compliance
            ;;
        *)
            echo "Usage: $0 [apply|monitor|remediate|report|lock|status]"
            echo "  apply     - Apply enterprise screen lock policies (default)"
            echo "  monitor   - Monitor compliance status"
            echo "  remediate - Auto-remediate compliance issues"
            echo "  report    - Generate comprehensive security report"
            echo "  lock      - Emergency lock device immediately"
            echo "  status    - Check current compliance status"
            exit 1
            ;;
    esac
    
    log_action "=== MacFleet Screen Lock Management Completed ==="
}

# Execute main function
main "$@"

Security Configuration File

Create a configuration file for enterprise security policies:

#!/bin/bash

# Create screen lock security configuration file
create_security_config() {
    local config_dir="/etc/macfleet"
    local config_file="$config_dir/screen_lock_config.conf"
    
    # Create directory if it doesn't exist
    sudo mkdir -p "$config_dir"
    
    # Create configuration file
    sudo tee "$config_file" > /dev/null << 'EOF'
# MacFleet Screen Lock Security Configuration
# All timeout values are in seconds unless specified

# Screen saver timeout (default: 300 seconds = 5 minutes)
SCREEN_TIMEOUT=300

# Password grace period after screen lock (default: 0 = immediate)
GRACE_PERIOD=0

# Display sleep timeout in minutes (default: 5 minutes)
DISPLAY_SLEEP=5

# System sleep timeout in minutes (default: 10 minutes)
SYSTEM_SLEEP=10

# Maximum allowed screen timeout for compliance (default: 600 seconds = 10 minutes)
MAX_SCREEN_TIMEOUT=600

# Maximum allowed password delay for compliance (default: 60 seconds)
MAX_PASSWORD_DELAY=60

# Lock screen message (optional)
LOCK_SCREEN_MESSAGE="This device is managed by MacFleet. Unauthorized access is prohibited."

# Hot corners configuration (optional)
ENABLE_HOT_CORNERS=true
HOT_CORNER_BR=5    # Bottom right: Start screen saver
HOT_CORNER_TR=10   # Top right: Put display to sleep

# Security enforcement options
DISABLE_GUEST_ACCOUNT=true
DISABLE_AUTO_LOGIN=true
HIDE_ADMIN_USERS=true
DISABLE_PASSWORD_HINTS=true
ENABLE_SECURE_VM=true

# Monitoring settings
COMPLIANCE_CHECK_INTERVAL=3600  # 1 hour
AUTO_REMEDIATION=true
GENERATE_REPORTS=true
EOF

    echo "Screen lock security configuration created at: $config_file"
    echo "Please review and modify settings according to your security policies"
}

create_security_config

Integration with MacFleet Management

#!/bin/bash

# MacFleet screen lock security integration
macfleet_security_integration() {
    echo "=== MacFleet Screen Lock Security Integration ==="
    
    # Device information
    local device_id=$(system_profiler SPHardwareDataType | grep "Hardware UUID" | awk '{print $3}')
    local hostname=$(hostname)
    local macos_version=$(sw_vers -productVersion)
    
    # Get current security status
    local password_required=$(osascript -e 'tell application "System Events" to get require password to wake of security preferences' 2>/dev/null || echo "unknown")
    local screen_timeout=$(defaults read com.apple.screensaver idleTime 2>/dev/null || echo "0")
    local password_delay=$(defaults read com.apple.screensaver askForPasswordDelay 2>/dev/null || echo "unknown")
    
    # Security compliance assessment
    local compliance_score=0
    local total_checks=4
    
    [[ "$password_required" == "true" ]] && ((compliance_score++))
    [[ "$screen_timeout" -le 600 && "$screen_timeout" -gt 0 ]] && ((compliance_score++))
    [[ "$password_delay" -le 60 ]] && ((compliance_score++))
    
    local guest_disabled=$(sudo defaults read /Library/Preferences/com.apple.loginwindow GuestEnabled 2>/dev/null || echo "true")
    [[ "$guest_disabled" == "0" || "$guest_disabled" == "false" ]] && ((compliance_score++))
    
    # Report to MacFleet API
    local api_data='{
        "device_id": "'$device_id'",
        "hostname": "'$hostname'",
        "timestamp": "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'",
        "macos_version": "'$macos_version'",
        "screen_lock_security": {
            "password_required": "'$password_required'",
            "screen_timeout": '$screen_timeout',
            "password_delay": "'$password_delay'",
            "guest_account_disabled": "'$guest_disabled'",
            "compliance_score": '$compliance_score'/'$total_checks'
        },
        "security_management_status": "active"
    }'
    
    echo "Screen lock security status reported to MacFleet management system"
    echo "Device ID: $device_id"
    echo "Compliance Score: $compliance_score/$total_checks"
    echo "Password Required: $password_required"
    echo "Screen Timeout: $screen_timeout seconds"
}

macfleet_security_integration

macOS Version Compatibility

Version-Specific Considerations

#!/bin/bash

# Check macOS version compatibility
check_macos_compatibility() {
    local macos_version=$(sw_vers -productVersion)
    local major_version=$(echo "$macos_version" | cut -d. -f1)
    local minor_version=$(echo "$macos_version" | cut -d. -f2)
    
    echo "=== macOS Compatibility Check ==="
    echo "Current macOS version: $macos_version"
    
    # Check if version is supported (10.12 to 12.7)
    if [[ $major_version -eq 10 && $minor_version -ge 12 ]] || [[ $major_version -ge 11 && $major_version -le 12 ]]; then
        echo "✅ macOS version is supported"
        return 0
    elif [[ $major_version -ge 13 ]]; then
        echo "⚠️  macOS version may have limited support (testing recommended)"
        return 1
    else
        echo "❌ macOS version is not supported"
        return 2
    fi
}

check_macos_compatibility

Important Security Notes

Best Practices

  • Test on pilot devices before fleet-wide deployment
  • Regular compliance monitoring to ensure policy adherence
  • Backup current settings before applying new policies
  • Document policy changes for audit and troubleshooting purposes

Security Considerations

  • Immediate password requirement provides strongest security
  • Screen saver timeout should balance security with usability
  • Guest account disabled prevents unauthorized access
  • Lock screen messages provide contact information and legal notices

Troubleshooting

  • System Preferences refresh may be required for changes to appear
  • Administrator privileges needed for system-level security settings
  • Restart may be required for some power management changes
  • Test AppleScript commands individually if issues occur

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.