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.

Find My Mac Security Management and Compliance

Ensure enterprise security compliance by monitoring and managing Find My Mac status across your MacFleet devices. This tutorial covers security auditing, Apple ID verification, automated compliance reporting, and enterprise security policy enforcement.

Understanding Find My Mac Security

Find My Mac is Apple's built-in device location and security service that provides:

  • Device Location Tracking - Real-time location services for lost or stolen devices
  • Remote Lock and Wipe - Secure device data remotely
  • Activation Lock - Prevents unauthorized device reactivation
  • Security Integration - Works with Apple ID and iCloud services

Basic Find My Mac Status Check

Simple Status Verification

#!/bin/bash

# Basic Find My Mac status check
fmmToken=$(/usr/sbin/nvram -x -p | /usr/bin/grep fmm-mobileme-token-FMM)

if [ -z "$fmmToken" ]; then
    echo "Find My Mac is disabled"
else
    echo "Find My Mac is enabled"
fi

Enhanced Status Check with Details

#!/bin/bash

# Enhanced Find My Mac verification
check_find_my_mac_basic() {
    echo "=== Find My Mac Status Check ==="
    
    # Check for Find My Mac token
    local fmm_token
    fmm_token=$(/usr/sbin/nvram -x -p | /usr/bin/grep fmm-mobileme-token-FMM 2>/dev/null)
    
    if [ -z "$fmm_token" ]; then
        echo "❌ Find My Mac: DISABLED"
        return 1
    else
        echo "✅ Find My Mac: ENABLED"
        
        # Extract additional details if available
        echo "Token found in NVRAM"
        return 0
    fi
}

# Execute the check
check_find_my_mac_basic

Enterprise Security Management Script

#!/bin/bash

# MacFleet Find My Mac Security Management
# Comprehensive security auditing and compliance monitoring

# Configuration
LOG_FILE="/var/log/macfleet_security.log"
REPORT_DIR="/var/reports/security"
COMPLIANCE_DIR="/var/compliance"
TEMP_DIR="/tmp/macfleet_security"

# Security policies configuration
REQUIRE_FIND_MY_MAC=true
REQUIRE_APPLE_ID=true
REQUIRE_ACTIVATION_LOCK=true
MAX_OFFLINE_DAYS=30

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

# Create necessary directories
setup_directories() {
    for dir in "$REPORT_DIR" "$COMPLIANCE_DIR" "$TEMP_DIR"; do
        if [[ ! -d "$dir" ]]; then
            mkdir -p "$dir"
            log_action "Created directory: $dir"
        fi
    done
}

# Check Find My Mac status with detailed analysis
check_find_my_mac_status() {
    log_action "Checking Find My Mac status"
    
    local status_report="$TEMP_DIR/fmm_status.json"
    
    # Initialize status object
    cat > "$status_report" << EOF
{
    "timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "find_my_mac": {
        "enabled": false,
        "token_present": false,
        "activation_lock": false,
        "apple_id_signed_in": false
    },
    "compliance": {
        "status": "non_compliant",
        "issues": []
    }
}
EOF

    # Check for Find My Mac token in NVRAM
    local fmm_token
    fmm_token=$(/usr/sbin/nvram -x -p | /usr/bin/grep fmm-mobileme-token-FMM 2>/dev/null)
    
    if [[ -n "$fmm_token" ]]; then
        log_action "✅ Find My Mac token found in NVRAM"
        
        # Update JSON status
        /usr/bin/python3 -c "
import json
with open('$status_report', 'r') as f:
    data = json.load(f)
data['find_my_mac']['enabled'] = True
data['find_my_mac']['token_present'] = True
with open('$status_report', 'w') as f:
    json.dump(data, f, indent=2)
"
        echo "enabled"
    else
        log_action "❌ Find My Mac not enabled - no token found"
        
        # Add compliance issue
        /usr/bin/python3 -c "
import json
with open('$status_report', 'r') as f:
    data = json.load(f)
data['compliance']['issues'].append('Find My Mac not enabled')
with open('$status_report', 'w') as f:
    json.dump(data, f, indent=2)
"
        echo "disabled"
    fi
}

# Check Apple ID sign-in status
check_apple_id_status() {
    log_action "Checking Apple ID sign-in status"
    
    # Check if user is signed into iCloud
    local icloud_account
    icloud_account=$(defaults read MobileMeAccounts Accounts 2>/dev/null | grep -c AccountID || echo "0")
    
    if [[ "$icloud_account" -gt 0 ]]; then
        log_action "✅ Apple ID signed in to iCloud"
        
        # Get Apple ID details (masked for privacy)
        local apple_id_info
        apple_id_info=$(defaults read MobileMeAccounts Accounts 2>/dev/null | grep AccountID | head -1 | sed 's/.*= "\(.*\)";/\1/' | sed 's/\(.*@\)\(.*\)/\1***/g')
        log_action "Apple ID: $apple_id_info"
        
        return 0
    else
        log_action "❌ No Apple ID signed in"
        return 1
    fi
}

# Check system integrity and security settings
check_system_security() {
    log_action "Performing system security audit"
    
    local security_report="$TEMP_DIR/security_audit.json"
    
    cat > "$security_report" << EOF
{
    "timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "security_audit": {
        "sip_status": "unknown",
        "gatekeeper_status": "unknown",
        "filevault_status": "unknown",
        "firewall_status": "unknown",
        "secure_boot": "unknown"
    }
}
EOF

    # Check System Integrity Protection (SIP)
    local sip_status
    sip_status=$(csrutil status 2>/dev/null | grep -i enabled && echo "enabled" || echo "disabled")
    log_action "SIP Status: $sip_status"
    
    # Check Gatekeeper
    local gatekeeper_status
    gatekeeper_status=$(spctl --status 2>/dev/null | grep -i enabled && echo "enabled" || echo "disabled")
    log_action "Gatekeeper Status: $gatekeeper_status"
    
    # Check FileVault
    local filevault_status
    filevault_status=$(fdesetup status 2>/dev/null | grep -i "on" && echo "enabled" || echo "disabled")
    log_action "FileVault Status: $filevault_status"
    
    # Check Firewall
    local firewall_status
    firewall_status=$(/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate 2>/dev/null | grep -i enabled && echo "enabled" || echo "disabled")
    log_action "Firewall Status: $firewall_status"
    
    # Update security report
    /usr/bin/python3 -c "
import json
with open('$security_report', 'r') as f:
    data = json.load(f)
data['security_audit']['sip_status'] = '$sip_status'
data['security_audit']['gatekeeper_status'] = '$gatekeeper_status'
data['security_audit']['filevault_status'] = '$filevault_status'
data['security_audit']['firewall_status'] = '$firewall_status'
with open('$security_report', 'w') as f:
    json.dump(data, f, indent=2)
"

    echo "$security_report"
}

# Check activation lock status
check_activation_lock() {
    log_action "Checking Activation Lock status"
    
    # Check if device has activation lock enabled
    # This requires checking with Apple's servers or MDM enrollment
    local activation_lock_status="unknown"
    
    # For enterprise devices, check MDM enrollment
    if profiles -P 2>/dev/null | grep -q "com.apple.mdm"; then
        log_action "✅ Device is MDM enrolled"
        activation_lock_status="mdm_managed"
    else
        log_action "⚠️  Device not MDM enrolled"
        activation_lock_status="not_managed"
    fi
    
    # Check for DEP/ABM enrollment
    if profiles -e 2>/dev/null | grep -q "DEP"; then
        log_action "✅ Device is DEP/ABM enrolled"
        activation_lock_status="dep_enrolled"
    fi
    
    echo "$activation_lock_status"
}

# Generate comprehensive security report
generate_security_report() {
    local report_timestamp
    report_timestamp=$(date '+%Y%m%d_%H%M%S')
    local report_file="$REPORT_DIR/security_report_$report_timestamp.json"
    
    log_action "Generating comprehensive security report: $report_file"
    
    # Get system information
    local os_version
    local serial_number
    local hardware_uuid
    os_version=$(sw_vers -productVersion)
    serial_number=$(system_profiler SPHardwareDataType | grep "Serial Number" | awk '{print $4}')
    hardware_uuid=$(system_profiler SPHardwareDataType | grep "Hardware UUID" | awk '{print $3}')
    
    # Compile comprehensive report
    cat > "$report_file" << EOF
{
    "report_metadata": {
        "timestamp": "$(date -Iseconds)",
        "report_version": "1.0",
        "generator": "MacFleet Security Audit"
    },
    "device_info": {
        "hostname": "$(hostname)",
        "serial_number": "$serial_number",
        "hardware_uuid": "$hardware_uuid",
        "os_version": "$os_version",
        "model": "$(system_profiler SPHardwareDataType | grep "Model Name" | awk -F': ' '{print $2}')"
    },
    "security_status": {
        "find_my_mac": {
            "enabled": $(check_find_my_mac_status >/dev/null && echo "true" || echo "false"),
            "compliance": $([ "$REQUIRE_FIND_MY_MAC" = true ] && check_find_my_mac_status >/dev/null && echo "true" || echo "false")
        },
        "apple_id": {
            "signed_in": $(check_apple_id_status >/dev/null && echo "true" || echo "false"),
            "compliance": $([ "$REQUIRE_APPLE_ID" = true ] && check_apple_id_status >/dev/null && echo "true" || echo "false")
        },
        "activation_lock": {
            "status": "$(check_activation_lock)",
            "compliance": $([ "$REQUIRE_ACTIVATION_LOCK" = true ] && echo "true" || echo "false")
        }
    },
    "compliance_summary": {
        "overall_status": "$(calculate_compliance_status)",
        "required_actions": $(generate_required_actions),
        "risk_level": "$(calculate_risk_level)"
    }
}
EOF

    log_action "Security report generated: $report_file"
    echo "$report_file"
}

# Calculate overall compliance status
calculate_compliance_status() {
    local fmm_status
    local apple_id_status
    local issues=0
    
    fmm_status=$(check_find_my_mac_status)
    if [[ "$REQUIRE_FIND_MY_MAC" = true && "$fmm_status" != "enabled" ]]; then
        ((issues++))
    fi
    
    if ! check_apple_id_status >/dev/null 2>&1; then
        if [[ "$REQUIRE_APPLE_ID" = true ]]; then
            ((issues++))
        fi
    fi
    
    if [[ $issues -eq 0 ]]; then
        echo "compliant"
    elif [[ $issues -le 2 ]]; then
        echo "partially_compliant"
    else
        echo "non_compliant"
    fi
}

# Generate required actions for compliance
generate_required_actions() {
    local actions=()
    
    if [[ "$REQUIRE_FIND_MY_MAC" = true ]] && [[ "$(check_find_my_mac_status)" != "enabled" ]]; then
        actions+=("\"Enable Find My Mac in System Preferences\"")
    fi
    
    if [[ "$REQUIRE_APPLE_ID" = true ]] && ! check_apple_id_status >/dev/null 2>&1; then
        actions+=("\"Sign in with Apple ID in System Preferences\"")
    fi
    
    if [[ ${#actions[@]} -eq 0 ]]; then
        echo "[]"
    else
        printf "[%s]" "$(IFS=,; echo "${actions[*]}")"
    fi
}

# Calculate risk level based on security status
calculate_risk_level() {
    local risk_score=0
    
    # Find My Mac disabled adds risk
    if [[ "$(check_find_my_mac_status)" != "enabled" ]]; then
        ((risk_score += 3))
    fi
    
    # No Apple ID adds risk
    if ! check_apple_id_status >/dev/null 2>&1; then
        ((risk_score += 2))
    fi
    
    # System security issues add risk
    if [[ "$(csrutil status 2>/dev/null | grep -i disabled)" ]]; then
        ((risk_score += 2))
    fi
    
    if [[ $risk_score -le 1 ]]; then
        echo "low"
    elif [[ $risk_score -le 4 ]]; then
        echo "medium"
    else
        echo "high"
    fi
}

# Remediation actions for common issues
remediate_security_issues() {
    log_action "Starting automated remediation process"
    
    local remediation_report="$TEMP_DIR/remediation_$(date '+%Y%m%d_%H%M%S').json"
    
    cat > "$remediation_report" << EOF
{
    "timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "remediation_actions": []
}
EOF

    # Check if Find My Mac can be enabled programmatically
    if [[ "$(check_find_my_mac_status)" != "enabled" ]]; then
        log_action "⚠️  Find My Mac is disabled - manual intervention required"
        log_action "   User must enable Find My Mac in System Preferences > Apple ID > Find My"
        
        # Add to remediation report
        /usr/bin/python3 -c "
import json
with open('$remediation_report', 'r') as f:
    data = json.load(f)
data['remediation_actions'].append({
    'issue': 'Find My Mac disabled',
    'action': 'manual_intervention_required',
    'instructions': 'Enable Find My Mac in System Preferences > Apple ID > Find My'
})
with open('$remediation_report', 'w') as f:
    json.dump(data, f, indent=2)
"
    fi
    
    # Generate user notification if needed
    if [[ "$(calculate_compliance_status)" != "compliant" ]]; then
        create_user_notification
    fi
    
    echo "$remediation_report"
}

# Create user notification for security compliance
create_user_notification() {
    log_action "Creating user notification for security compliance"
    
    local notification_title="MacFleet Security Compliance"
    local notification_message="Your device requires security configuration updates. Please contact IT support."
    
    # Use AppleScript to show notification
    osascript -e "display notification \"$notification_message\" with title \"$notification_title\""
    
    # Create persistent reminder file
    cat > "/tmp/macfleet_security_reminder.txt" << EOF
MacFleet Security Compliance Required

Your device needs the following security features enabled:
- Find My Mac
- Apple ID sign-in
- Activation Lock

Please contact IT support for assistance.
Generated: $(date)
EOF
}

# Monitor Find My Mac status over time
monitor_security_status() {
    log_action "Starting continuous security monitoring"
    
    local monitoring_interval=3600  # 1 hour
    local monitoring_log="$LOG_FILE.monitoring"
    
    while true; do
        {
            echo "=== Security Status Check - $(date) ==="
            echo "Find My Mac: $(check_find_my_mac_status)"
            echo "Apple ID: $(check_apple_id_status >/dev/null && echo "signed_in" || echo "not_signed_in")"
            echo "Compliance: $(calculate_compliance_status)"
            echo "Risk Level: $(calculate_risk_level)"
            echo "----------------------------------------"
        } >> "$monitoring_log"
        
        sleep "$monitoring_interval"
    done
}

# Fleet-wide security assessment
fleet_security_assessment() {
    log_action "Performing fleet-wide security assessment"
    
    local fleet_report="$REPORT_DIR/fleet_security_$(date '+%Y%m%d_%H%M%S').json"
    
    # This would typically integrate with MDM or configuration management
    # For demonstration, we'll show the current device assessment
    
    cat > "$fleet_report" << EOF
{
    "assessment_timestamp": "$(date -Iseconds)",
    "fleet_summary": {
        "total_devices": 1,
        "compliant_devices": $([ "$(calculate_compliance_status)" = "compliant" ] && echo "1" || echo "0"),
        "non_compliant_devices": $([ "$(calculate_compliance_status)" != "compliant" ] && echo "1" || echo "0")
    },
    "devices": [
        $(generate_security_report | tail -n +2 | head -n -1)
    ],
    "recommendations": [
        "Implement automated Find My Mac enablement via MDM",
        "Enforce Apple ID sign-in through device enrollment",
        "Regular security compliance auditing",
        "User education on security features"
    ]
}
EOF

    log_action "Fleet security assessment completed: $fleet_report"
    echo "$fleet_report"
}

# Main execution function
main() {
    local action="${1:-check}"
    
    log_action "=== MacFleet Security Management Started ==="
    log_action "Action: $action"
    log_action "Hostname: $(hostname)"
    log_action "User: $(whoami)"
    
    # Setup
    setup_directories
    
    case "$action" in
        "check")
            echo "=== Find My Mac Security Check ==="
            echo "Find My Mac Status: $(check_find_my_mac_status)"
            echo "Apple ID Status: $(check_apple_id_status >/dev/null && echo "signed_in" || echo "not_signed_in")"
            echo "Activation Lock: $(check_activation_lock)"
            echo "Compliance Status: $(calculate_compliance_status)"
            echo "Risk Level: $(calculate_risk_level)"
            ;;
        "audit")
            echo "Performing comprehensive security audit..."
            security_report=$(generate_security_report)
            echo "Security audit completed: $security_report"
            ;;
        "remediate")
            echo "Starting remediation process..."
            remediation_report=$(remediate_security_issues)
            echo "Remediation completed: $remediation_report"
            ;;
        "monitor")
            echo "Starting continuous monitoring..."
            monitor_security_status
            ;;
        "fleet")
            echo "Performing fleet-wide assessment..."
            fleet_report=$(fleet_security_assessment)
            echo "Fleet assessment completed: $fleet_report"
            ;;
        *)
            echo "Usage: $0 {check|audit|remediate|monitor|fleet}"
            echo "  check     - Quick security status check"
            echo "  audit     - Comprehensive security audit"
            echo "  remediate - Automated remediation actions"
            echo "  monitor   - Continuous security monitoring"
            echo "  fleet     - Fleet-wide security assessment"
            exit 1
            ;;
    esac
    
    # Cleanup
    rm -rf "$TEMP_DIR"
    
    log_action "=== Security management completed ==="
}

# Execute main function
main "$@"

Apple ID and iCloud Integration

Check Apple ID Sign-in Status

#!/bin/bash

# Comprehensive Apple ID verification
check_apple_id_comprehensive() {
    echo "=== Apple ID Status Check ==="
    
    # Check iCloud accounts
    local icloud_accounts
    icloud_accounts=$(defaults read MobileMeAccounts Accounts 2>/dev/null | grep -c AccountID || echo "0")
    
    if [[ "$icloud_accounts" -gt 0 ]]; then
        echo "✅ Apple ID signed in ($icloud_accounts account(s))"
        
        # Get account details (privacy-safe)
        defaults read MobileMeAccounts Accounts 2>/dev/null | grep AccountID | while read -r line; do
            local account_id
            account_id=$(echo "$line" | sed 's/.*= "\(.*\)";/\1/' | sed 's/\(.*@\)\(.*\)/\1***/g')
            echo "   Account: $account_id"
        done
        
        # Check iCloud services
        echo "iCloud Services:"
        defaults read MobileMeAccounts Accounts 2>/dev/null | grep -E "(BookmarksSyncEnabled|ContactsSyncEnabled|MailSyncEnabled)" | while read -r service; do
            echo "   $service"
        done
        
        return 0
    else
        echo "❌ No Apple ID signed in"
        return 1
    fi
}

Verify iCloud Services Status

#!/bin/bash

# Check specific iCloud services
check_icloud_services() {
    echo "=== iCloud Services Status ==="
    
    # Check Find My Mac specifically
    local fmf_token
    fmf_token=$(defaults read MobileMeAccounts Accounts 2>/dev/null | grep -i findmyfriends || echo "")
    
    if [[ -n "$fmf_token" ]]; then
        echo "✅ Find My Friends/Family service active"
    else
        echo "⚠️  Find My Friends/Family service not configured"
    fi
    
    # Check other critical services
    local services=(
        "BookmarksSyncEnabled:Safari Bookmarks"
        "ContactsSyncEnabled:Contacts"
        "CalendarSyncEnabled:Calendar"
        "KeychainSyncEnabled:Keychain"
    )
    
    for service in "${services[@]}"; do
        local key="${service%%:*}"
        local name="${service##*:}"
        local status
        status=$(defaults read MobileMeAccounts Accounts 2>/dev/null | grep "$key" | head -1 | grep -o "[01]" || echo "0")
        
        if [[ "$status" = "1" ]]; then
            echo "✅ $name sync enabled"
        else
            echo "❌ $name sync disabled"
        fi
    done
}

Enterprise Security Policies

Define Security Requirements

#!/bin/bash

# Enterprise security policy configuration
apply_security_policies() {
    echo "=== Applying Enterprise Security Policies ==="
    
    local policy_file="/etc/macfleet/security_policies.json"
    
    # Create security policy configuration
    mkdir -p "$(dirname "$policy_file")"
    cat > "$policy_file" << 'EOF'
{
    "security_policies": {
        "find_my_mac": {
            "required": true,
            "enforcement": "advisory",
            "grace_period_days": 7
        },
        "apple_id": {
            "required": true,
            "corporate_domain_only": false,
            "enforcement": "mandatory"
        },
        "activation_lock": {
            "required": true,
            "mdm_managed": true
        },
        "system_security": {
            "sip_required": true,
            "gatekeeper_required": true,
            "filevault_required": true,
            "firewall_required": true
        }
    },
    "compliance_reporting": {
        "frequency": "daily",
        "recipients": ["security@company.com"],
        "escalation_threshold": "medium"
    }
}
EOF

    echo "Security policies configured: $policy_file"
}

Compliance Monitoring

#!/bin/bash

# Automated compliance monitoring
setup_compliance_monitoring() {
    local monitoring_script="/usr/local/bin/macfleet_compliance_monitor.sh"
    local launchd_plist="/Library/LaunchDaemons/com.macfleet.security.compliance.plist"
    
    # Create monitoring script
    cat > "$monitoring_script" << 'EOF'
#!/bin/bash
LOG_FILE="/var/log/macfleet_compliance.log"
exec > >(tee -a "$LOG_FILE") 2>&1

echo "$(date): Starting security compliance check"

# Run security audit
/usr/local/bin/macfleet_security_manager.sh audit

# Check for non-compliance
COMPLIANCE_STATUS=$(calculate_compliance_status)
if [[ "$COMPLIANCE_STATUS" != "compliant" ]]; then
    echo "$(date): Non-compliance detected - $COMPLIANCE_STATUS"
    
    # Send alert (implement according to your notification system)
    echo "Device $(hostname) is non-compliant" | mail -s "Security Compliance Alert" security@company.com
fi

echo "$(date): Compliance check completed"
EOF

    chmod +x "$monitoring_script"
    
    # Create LaunchDaemon for scheduled compliance checks
    cat > "$launchd_plist" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.macfleet.security.compliance</string>
    <key>ProgramArguments</key>
    <array>
        <string>$monitoring_script</string>
    </array>
    <key>StartCalendarInterval</key>
    <array>
        <dict>
            <key>Hour</key>
            <integer>9</integer>
            <key>Minute</key>
            <integer>0</integer>
        </dict>
        <dict>
            <key>Hour</key>
            <integer>17</integer>
            <key>Minute</key>
            <integer>0</integer>
        </dict>
    </array>
    <key>RunAtLoad</key>
    <false/>
</dict>
</plist>
EOF

    # Load the LaunchDaemon
    sudo launchctl load "$launchd_plist"
    
    echo "Compliance monitoring configured"
    echo "Script: $monitoring_script"
    echo "Schedule: Daily at 9:00 AM and 5:00 PM"
}

Security Status Indicators

Understanding NVRAM Tokens

The Find My Mac status is stored in NVRAM (Non-Volatile Random Access Memory) tokens:

TokenDescriptionIndicates
fmm-mobileme-token-FMMPrimary Find My Mac tokenService is active and configured
fmm-computer-nameDevice name for Find MyDevice identification in Find My network
fmm-mobileme-token-FMFFind My Friends tokenLocation sharing services

Interpreting Security States

StateFind My MacApple IDComplianceAction Required
Fully Compliant✅ Enabled✅ Signed In✅ CompliantNone
Partially Compliant✅ Enabled❌ Not Signed In⚠️ PartialSign in to Apple ID
Non-Compliant❌ Disabled❌ Not Signed In❌ Non-CompliantEnable Find My Mac and sign in
Unknown State❓ Cannot Detect❓ Cannot Detect❓ UnknownManual verification required

Troubleshooting Common Issues

Find My Mac Not Enabling

#!/bin/bash

# Troubleshoot Find My Mac issues
troubleshoot_find_my_mac() {
    echo "=== Find My Mac Troubleshooting ==="
    
    # Check prerequisites
    echo "Checking prerequisites..."
    
    # 1. Check internet connectivity
    if ping -c 1 apple.com >/dev/null 2>&1; then
        echo "✅ Internet connectivity: OK"
    else
        echo "❌ Internet connectivity: FAILED"
        echo "   - Check network connection"
        echo "   - Verify DNS settings"
    fi
    
    # 2. Check Apple ID sign-in
    if check_apple_id_status >/dev/null 2>&1; then
        echo "✅ Apple ID sign-in: OK"
    else
        echo "❌ Apple ID sign-in: REQUIRED"
        echo "   - Sign in to Apple ID in System Preferences"
        echo "   - Enable iCloud services"
    fi
    
    # 3. Check iCloud services
    local icloud_enabled
    icloud_enabled=$(defaults read MobileMeAccounts Accounts 2>/dev/null | grep -c "Enabled.*1" || echo "0")
    
    if [[ "$icloud_enabled" -gt 0 ]]; then
        echo "✅ iCloud services: ENABLED"
    else
        echo "❌ iCloud services: DISABLED"
        echo "   - Enable iCloud in System Preferences"
        echo "   - Ensure Find My Mac is checked"
    fi
    
    # 4. Check system requirements
    local os_version
    os_version=$(sw_vers -productVersion)
    
    if [[ "$(echo "$os_version" | cut -d. -f1)" -ge 10 ]] && [[ "$(echo "$os_version" | cut -d. -f2)" -ge 11 ]]; then
        echo "✅ macOS version: SUPPORTED ($os_version)"
    else
        echo "❌ macOS version: UNSUPPORTED ($os_version)"
        echo "   - Find My Mac requires macOS 10.11 or later"
    fi
}

Manual Remediation Steps

#!/bin/bash

# Generate manual remediation guide
generate_remediation_guide() {
    local guide_file="/tmp/macfleet_remediation_guide.txt"
    
    cat > "$guide_file" << EOF
MacFleet Security Remediation Guide
==================================

Device: $(hostname)
Date: $(date)

Required Actions:
EOF

    if [[ "$(check_find_my_mac_status)" != "enabled" ]]; then
        cat >> "$guide_file" << EOF

1. Enable Find My Mac:
   - Open System Preferences
   - Click on Apple ID (or iCloud on older systems)
   - Sign in with your Apple ID if not already signed in
   - Click on "Find My" in the sidebar
   - Check "Find My Mac"
   - Check "Enable offline finding" (if available)
   - Click "Allow" when prompted for location access

EOF
    fi
    
    if ! check_apple_id_status >/dev/null 2>&1; then
        cat >> "$guide_file" << EOF

2. Sign in to Apple ID:
   - Open System Preferences
   - Click on Apple ID at the top
   - Enter your Apple ID and password
   - Complete two-factor authentication if prompted
   - Enable iCloud services as needed

EOF
    fi
    
    cat >> "$guide_file" << EOF

For assistance, contact IT Support:
- Email: support@company.com
- Phone: +1-555-0123
- Ticket System: https://support.company.com

EOF

    echo "Remediation guide created: $guide_file"
    open "$guide_file"
}

Best Practices

🔐 Security Guidelines

  • Enable Find My Mac on all enterprise devices
  • Require Apple ID sign-in for device accountability
  • Monitor compliance status regularly
  • Implement automated alerting for non-compliance

📋 Management Recommendations

  • Use MDM enrollment for enterprise activation lock
  • Regular security audits across device fleet
  • User education on security feature importance
  • Automated compliance monitoring and reporting

🔍 Monitoring Strategy

  • Daily compliance checks during business hours
  • Immediate alerts for security violations
  • Trend analysis of compliance metrics
  • Regular policy review and updates

Important Notes

  • Find My Mac requires macOS 10.11 or later for full functionality
  • Apple ID sign-in is mandatory for Find My Mac operation
  • Network connectivity required for initial setup and ongoing operation
  • Privacy considerations should be documented for enterprise use
  • Test remediation procedures before enterprise deployment

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.