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.

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

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.