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.

AirDrop Management on macOS

Control AirDrop functionality on your MacFleet devices to enhance security and prevent unauthorized file transfers. This tutorial covers enabling, disabling, monitoring, and managing AirDrop settings for corporate compliance and data protection.

Understanding AirDrop on macOS

AirDrop is Apple's wireless file sharing technology that allows users to transfer files between nearby Apple devices including:

  • Mac computers running macOS Lion (10.7) or later
  • iOS devices (iPhone, iPad, iPod touch) with iOS 7 or later
  • Apple Watch for supported content types

Security Considerations

In enterprise environments, AirDrop can pose security risks:

  • Data leakage through unauthorized file transfers
  • Malware distribution via infected files
  • Corporate policy violations through uncontrolled sharing
  • Network security bypassing traditional file transfer controls

Basic AirDrop Control Commands

Disable AirDrop Functionality

#!/bin/sh

# Disable AirDrop by shutting down AWDL interface
sudo ifconfig awdl0 down

echo "AirDrop functionality disabled"

Enable AirDrop Functionality

#!/bin/sh

# Enable AirDrop by bringing up AWDL interface
sudo ifconfig awdl0 up

echo "AirDrop functionality enabled"

Check AirDrop Status

#!/bin/bash

# Check current AirDrop/AWDL interface status
check_airdrop_status() {
    local awdl_status
    awdl_status=$(ifconfig awdl0 2>/dev/null | grep "status:" | awk '{print $2}')
    
    if [[ "$awdl_status" == "active" ]]; then
        echo "AirDrop: ENABLED"
        return 0
    elif [[ "$awdl_status" == "inactive" ]]; then
        echo "AirDrop: DISABLED"
        return 1
    else
        echo "AirDrop: STATUS UNKNOWN"
        return 2
    fi
}

check_airdrop_status

Advanced AirDrop Management

Comprehensive AirDrop Control Script

#!/bin/bash

# Advanced AirDrop management with validation and logging
manage_airdrop() {
    local action="$1"
    local force="${2:-false}"
    
    # Validate admin privileges
    if [[ $EUID -ne 0 ]]; then
        echo "Error: This script requires administrator privileges"
        echo "Please run with sudo: sudo $0"
        exit 1
    fi
    
    case "$action" in
        "disable")
            echo "Disabling AirDrop functionality..."
            
            # Check current status
            local current_status
            current_status=$(ifconfig awdl0 2>/dev/null | grep "status:" | awk '{print $2}')
            
            if [[ "$current_status" == "inactive" ]]; then
                echo "AirDrop is already disabled"
                return 0
            fi
            
            # Disable AWDL interface
            if ifconfig awdl0 down 2>/dev/null; then
                echo "✓ AirDrop disabled successfully"
                
                # Verify the change
                sleep 2
                local new_status
                new_status=$(ifconfig awdl0 2>/dev/null | grep "status:" | awk '{print $2}')
                
                if [[ "$new_status" == "inactive" ]]; then
                    echo "✓ AirDrop status verified: DISABLED"
                    return 0
                else
                    echo "⚠ Warning: AirDrop status verification failed"
                    return 1
                fi
            else
                echo "✗ Failed to disable AirDrop"
                return 1
            fi
            ;;
        "enable")
            echo "Enabling AirDrop functionality..."
            
            # Check current status
            local current_status
            current_status=$(ifconfig awdl0 2>/dev/null | grep "status:" | awk '{print $2}')
            
            if [[ "$current_status" == "active" ]]; then
                echo "AirDrop is already enabled"
                return 0
            fi
            
            # Enable AWDL interface
            if ifconfig awdl0 up 2>/dev/null; then
                echo "✓ AirDrop enabled successfully"
                
                # Verify the change
                sleep 2
                local new_status
                new_status=$(ifconfig awdl0 2>/dev/null | grep "status:" | awk '{print $2}')
                
                if [[ "$new_status" == "active" ]]; then
                    echo "✓ AirDrop status verified: ENABLED"
                    return 0
                else
                    echo "⚠ Warning: AirDrop status verification failed"
                    return 1
                fi
            else
                echo "✗ Failed to enable AirDrop"
                return 1
            fi
            ;;
        "status")
            echo "Checking AirDrop status..."
            
            # Get detailed interface information
            if ifconfig awdl0 &>/dev/null; then
                local status_line
                status_line=$(ifconfig awdl0 | grep "status:")
                echo "AWDL Interface: $status_line"
                
                local flags_line
                flags_line=$(ifconfig awdl0 | head -1 | cut -d'<' -f2 | cut -d'>' -f1)
                echo "Interface Flags: $flags_line"
                
                # Check if interface is up and running
                if echo "$flags_line" | grep -q "UP"; then
                    echo "AirDrop Status: ENABLED"
                else
                    echo "AirDrop Status: DISABLED"
                fi
            else
                echo "AWDL Interface: NOT AVAILABLE"
                echo "AirDrop Status: NOT SUPPORTED"
            fi
            ;;
        *)
            echo "Usage: manage_airdrop [disable|enable|status]"
            echo "  disable - Disable AirDrop functionality"
            echo "  enable  - Enable AirDrop functionality"
            echo "  status  - Check current AirDrop status"
            return 1
            ;;
    esac
}

# Execute function with provided arguments
manage_airdrop "$@"

User-Level AirDrop Settings Management

#!/bin/bash

# Manage user-level AirDrop discovery settings
manage_airdrop_discovery() {
    local username="$1"
    local setting="$2"
    
    # Validate inputs
    if [[ -z "$username" || -z "$setting" ]]; then
        echo "Usage: manage_airdrop_discovery <username> <off|contacts|everyone>"
        return 1
    fi
    
    # Check if user exists
    if ! id "$username" &>/dev/null; then
        echo "Error: User '$username' does not exist"
        return 1
    fi
    
    # Map setting to numeric value
    local discovery_value
    case "$setting" in
        "off")
            discovery_value="0"
            ;;
        "contacts")
            discovery_value="1"
            ;;
        "everyone")
            discovery_value="2"
            ;;
        *)
            echo "Error: Invalid setting '$setting'"
            echo "Valid options: off, contacts, everyone"
            return 1
            ;;
    esac
    
    echo "Setting AirDrop discovery to '$setting' for user: $username"
    
    # Set the preference for the user
    if sudo -u "$username" defaults write com.apple.sharingd DiscoverableMode -int "$discovery_value"; then
        echo "✓ AirDrop discovery setting updated"
        
        # Restart sharing daemon to apply changes
        sudo -u "$username" killall sharingd 2>/dev/null
        
        echo "✓ Settings applied successfully"
        return 0
    else
        echo "✗ Failed to update AirDrop discovery setting"
        return 1
    fi
}

# Usage examples
manage_airdrop_discovery "$(whoami)" "contacts"

Enterprise AirDrop Policy Management

#!/bin/bash

# Enterprise AirDrop policy enforcement
apply_airdrop_policy() {
    local policy_type="$1"
    local apply_to_all_users="${2:-false}"
    
    echo "=== Applying AirDrop Policy: $policy_type ==="
    
    case "$policy_type" in
        "corporate_lockdown")
            echo "Applying corporate lockdown policy..."
            
            # Disable AirDrop system-wide
            sudo ifconfig awdl0 down
            
            # Disable for all users
            if [[ "$apply_to_all_users" == "true" ]]; then
                local users
                users=$(dscl . -list /Users | grep -v "^_" | grep -v "daemon\|nobody\|root")
                
                for user in $users; do
                    echo "Disabling AirDrop for user: $user"
                    sudo -u "$user" defaults write com.apple.sharingd DiscoverableMode -int 0
                done
            fi
            
            echo "✓ Corporate lockdown policy applied"
            ;;
        "contacts_only")
            echo "Applying contacts-only policy..."
            
            # Enable AirDrop but restrict to contacts
            sudo ifconfig awdl0 up
            
            if [[ "$apply_to_all_users" == "true" ]]; then
                local users
                users=$(dscl . -list /Users | grep -v "^_" | grep -v "daemon\|nobody\|root")
                
                for user in $users; do
                    echo "Setting contacts-only for user: $user"
                    sudo -u "$user" defaults write com.apple.sharingd DiscoverableMode -int 1
                done
            fi
            
            echo "✓ Contacts-only policy applied"
            ;;
        "unrestricted")
            echo "Applying unrestricted policy..."
            
            # Enable AirDrop with full discovery
            sudo ifconfig awdl0 up
            
            if [[ "$apply_to_all_users" == "true" ]]; then
                local users
                users=$(dscl . -list /Users | grep -v "^_" | grep -v "daemon\|nobody\|root")
                
                for user in $users; do
                    echo "Setting unrestricted for user: $user"
                    sudo -u "$user" defaults write com.apple.sharingd DiscoverableMode -int 2
                done
            fi
            
            echo "✓ Unrestricted policy applied"
            ;;
        *)
            echo "Error: Unknown policy type '$policy_type'"
            echo "Available policies: corporate_lockdown, contacts_only, unrestricted"
            return 1
            ;;
    esac
}

# Usage
apply_airdrop_policy "corporate_lockdown" "true"

Enterprise AirDrop Management System

#!/bin/bash

# MacFleet AirDrop Management Tool
# Comprehensive AirDrop control and monitoring for fleet devices

# Configuration
SCRIPT_VERSION="1.0.0"
LOG_FILE="/var/log/macfleet_airdrop.log"
REPORT_DIR="/etc/macfleet/reports/airdrop"
CONFIG_DIR="/etc/macfleet/airdrop"
POLICY_DIR="/etc/macfleet/policies/airdrop"

# Create directories if they don't exist
mkdir -p "$REPORT_DIR" "$CONFIG_DIR" "$POLICY_DIR"

# AirDrop policy templates
declare -A AIRDROP_POLICIES=(
    ["high_security"]="disabled,no_discovery,monitoring_enabled,audit_logging"
    ["medium_security"]="enabled,contacts_only,monitoring_enabled,audit_logging"
    ["low_security"]="enabled,everyone,monitoring_disabled,basic_logging"
    ["development"]="enabled,everyone,monitoring_enabled,debug_logging"
    ["kiosk_mode"]="disabled,no_discovery,monitoring_disabled,no_logging"
    ["guest_network"]="enabled,contacts_only,monitoring_enabled,audit_logging"
    ["executive"]="enabled,contacts_only,monitoring_enabled,executive_reporting"
    ["classroom"]="disabled,no_discovery,monitoring_enabled,educational_logging"
    ["healthcare"]="disabled,no_discovery,monitoring_enabled,hipaa_compliance"
    ["financial"]="disabled,no_discovery,monitoring_enabled,sox_compliance"
)

# Security compliance frameworks
declare -A COMPLIANCE_SETTINGS=(
    ["hipaa"]="airdrop_disabled,audit_all_attempts,data_loss_prevention"
    ["sox"]="airdrop_disabled,financial_data_protection,executive_monitoring"
    ["gdpr"]="privacy_controls,user_consent_required,data_transfer_logging"
    ["pci_dss"]="payment_data_protection,cardholder_isolation,secure_networks"
    ["iso27001"]="information_security,access_controls,incident_management"
)

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

# Advanced AirDrop status monitoring
monitor_airdrop_status() {
    local detailed="${1:-false}"
    
    log_action "Monitoring AirDrop status (detailed: $detailed)"
    
    echo "=== AirDrop Status Monitor ==="
    
    # Check AWDL interface status
    local awdl_status="unknown"
    local awdl_flags=""
    local awdl_ip=""
    
    if ifconfig awdl0 &>/dev/null; then
        awdl_status=$(ifconfig awdl0 | grep "status:" | awk '{print $2}' || echo "unknown")
        awdl_flags=$(ifconfig awdl0 | head -1 | grep -o '<.*>' | tr -d '<>')
        awdl_ip=$(ifconfig awdl0 | grep "inet " | awk '{print $2}' || echo "none")
    fi
    
    echo "AWDL Interface Status: $awdl_status"
    echo "Interface Flags: $awdl_flags"
    echo "AWDL IP Address: $awdl_ip"
    
    # Check system-wide AirDrop enablement
    local system_airdrop_enabled="false"
    if [[ "$awdl_status" == "active" ]] && echo "$awdl_flags" | grep -q "UP"; then
        system_airdrop_enabled="true"
    fi
    
    echo "System AirDrop Status: $([ "$system_airdrop_enabled" == "true" ] && echo "ENABLED" || echo "DISABLED")"
    
    if [[ "$detailed" == "true" ]]; then
        echo ""
        echo "=== Detailed Analysis ==="
        
        # Check user-level settings
        local users
        users=$(dscl . -list /Users | grep -v "^_" | grep -v "daemon\|nobody\|root")
        
        echo "User-Level AirDrop Settings:"
        for user in $users; do
            local user_setting
            user_setting=$(sudo -u "$user" defaults read com.apple.sharingd DiscoverableMode 2>/dev/null || echo "not_set")
            
            local setting_text
            case "$user_setting" in
                "0") setting_text="OFF" ;;
                "1") setting_text="CONTACTS ONLY" ;;
                "2") setting_text="EVERYONE" ;;
                *) setting_text="NOT SET" ;;
            esac
            
            echo "  $user: $setting_text"
        done
        
        # Check network connectivity
        echo ""
        echo "Network Interface Information:"
        echo "Wi-Fi Status: $(networksetup -getairportpower en0 | awk '{print $4}')"
        echo "Bluetooth Status: $(system_profiler SPBluetoothDataType | grep "State:" | awk '{print $2}' | head -1)"
        
        # Check running processes
        echo ""
        echo "Related Processes:"
        ps aux | grep -E "(sharingd|airportd)" | grep -v grep | awk '{print $11}'
    fi
}

# Comprehensive AirDrop policy enforcement
enforce_airdrop_policy() {
    local policy_name="$1"
    local target_users="$2"
    local dry_run="${3:-false}"
    
    log_action "Enforcing AirDrop policy: $policy_name (dry_run: $dry_run)"
    
    if [[ -z "${AIRDROP_POLICIES[$policy_name]}" ]]; then
        log_action "ERROR: Unknown policy '$policy_name'"
        echo "Available policies: ${!AIRDROP_POLICIES[*]}"
        return 1
    fi
    
    # Parse policy configuration
    IFS=',' read -ra POLICY_PARTS <<< "${AIRDROP_POLICIES[$policy_name]}"
    local airdrop_state="${POLICY_PARTS[0]}"
    local discovery_setting="${POLICY_PARTS[1]}"
    local monitoring_level="${POLICY_PARTS[2]}"
    local logging_level="${POLICY_PARTS[3]}"
    
    echo "=== Enforcing Policy: $policy_name ==="
    echo "AirDrop State: $airdrop_state"
    echo "Discovery Setting: $discovery_setting"
    echo "Monitoring Level: $monitoring_level"
    echo "Logging Level: $logging_level"
    
    if [[ "$dry_run" == "true" ]]; then
        echo "DRY RUN MODE - No changes will be applied"
        return 0
    fi
    
    # Apply system-level settings
    case "$airdrop_state" in
        "enabled")
            echo "Enabling AirDrop system-wide..."
            sudo ifconfig awdl0 up
            ;;
        "disabled")
            echo "Disabling AirDrop system-wide..."
            sudo ifconfig awdl0 down
            ;;
    esac
    
    # Apply user-level settings
    if [[ "$target_users" == "all" ]]; then
        local users
        users=$(dscl . -list /Users | grep -v "^_" | grep -v "daemon\|nobody\|root")
    else
        IFS=',' read -ra users <<< "$target_users"
    fi
    
    local discovery_value
    case "$discovery_setting" in
        "no_discovery") discovery_value="0" ;;
        "contacts_only") discovery_value="1" ;;
        "everyone") discovery_value="2" ;;
    esac
    
    for user in "${users[@]}"; do
        if id "$user" &>/dev/null; then
            echo "Applying settings for user: $user"
            sudo -u "$user" defaults write com.apple.sharingd DiscoverableMode -int "$discovery_value"
            
            # Restart sharing daemon
            sudo -u "$user" killall sharingd 2>/dev/null
        fi
    done
    
    # Configure monitoring
    configure_airdrop_monitoring "$monitoring_level" "$logging_level"
    
    # Generate policy compliance report
    local report_file="$REPORT_DIR/policy_enforcement_${policy_name}_$(date +%Y%m%d_%H%M%S).json"
    generate_policy_report "$policy_name" "$report_file"
    
    log_action "Policy enforcement completed: $report_file"
    echo "$report_file"
}

# Configure AirDrop monitoring and logging
configure_airdrop_monitoring() {
    local monitoring_level="$1"
    local logging_level="$2"
    
    echo "Configuring monitoring (level: $monitoring_level, logging: $logging_level)"
    
    case "$monitoring_level" in
        "monitoring_enabled")
            # Create monitoring script
            cat > "/usr/local/bin/macfleet_airdrop_monitor.sh" << 'EOF'
#!/bin/bash
# AirDrop activity monitor
while true; do
    # Monitor AWDL interface changes
    ifconfig awdl0 | grep "status:" >> /var/log/macfleet_airdrop_activity.log
    sleep 30
done
EOF
            chmod +x "/usr/local/bin/macfleet_airdrop_monitor.sh"
            
            # Create LaunchDaemon for monitoring
            cat > "/Library/LaunchDaemons/com.macfleet.airdrop.monitor.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.airdrop.monitor</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/bin/macfleet_airdrop_monitor.sh</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
</dict>
</plist>
EOF
            launchctl load "/Library/LaunchDaemons/com.macfleet.airdrop.monitor.plist"
            ;;
        "monitoring_disabled")
            # Remove monitoring components
            launchctl unload "/Library/LaunchDaemons/com.macfleet.airdrop.monitor.plist" 2>/dev/null
            rm -f "/Library/LaunchDaemons/com.macfleet.airdrop.monitor.plist"
            rm -f "/usr/local/bin/macfleet_airdrop_monitor.sh"
            ;;
    esac
}

# Generate comprehensive policy compliance report
generate_policy_report() {
    local policy_name="$1"
    local report_file="$2"
    
    # Get current system state
    local awdl_status=$(ifconfig awdl0 2>/dev/null | grep "status:" | awk '{print $2}' || echo "unknown")
    local system_enabled="false"
    [[ "$awdl_status" == "active" ]] && system_enabled="true"
    
    # Get user settings
    local users
    users=$(dscl . -list /Users | grep -v "^_" | grep -v "daemon\|nobody\|root")
    
    cat > "$report_file" << EOF
{
    "policy_report": {
        "policy_name": "$policy_name",
        "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
        "hostname": "$(hostname)",
        "script_version": "$SCRIPT_VERSION",
        "system_status": {
            "awdl_interface": "$awdl_status",
            "system_airdrop_enabled": $system_enabled
        },
        "user_settings": [],
        "compliance_status": "compliant",
        "recommendations": []
    }
}
EOF
    
    # Add user-specific settings
    for user in $users; do
        local user_setting
        user_setting=$(sudo -u "$user" defaults read com.apple.sharingd DiscoverableMode 2>/dev/null || echo "-1")
        
        jq --arg user "$user" \
           --argjson setting "$user_setting" \
           '.policy_report.user_settings += [{
               "username": $user,
               "discovery_mode": $setting,
               "discovery_text": (if $setting == 0 then "OFF" elif $setting == 1 then "CONTACTS_ONLY" elif $setting == 2 then "EVERYONE" else "NOT_SET" end)
           }]' "$report_file" > "${report_file}.tmp" && mv "${report_file}.tmp" "$report_file"
    done
    
    log_action "Policy report generated: $report_file"
}

# Fleet-wide AirDrop audit
audit_fleet_airdrop() {
    local scope="${1:-all}"
    
    echo "=== Fleet AirDrop Audit ==="
    log_action "Starting fleet AirDrop audit (scope: $scope)"
    
    local audit_report="$REPORT_DIR/fleet_airdrop_audit_$(date +%Y%m%d_%H%M%S).json"
    
    cat > "$audit_report" << EOF
{
    "audit_info": {
        "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
        "hostname": "$(hostname)",
        "scope": "$scope",
        "audit_type": "airdrop_security"
    },
    "system_analysis": {},
    "user_analysis": [],
    "security_findings": [],
    "recommendations": []
}
EOF
    
    # System-level analysis
    local awdl_status=$(ifconfig awdl0 2>/dev/null | grep "status:" | awk '{print $2}' || echo "unknown")
    local wifi_status=$(networksetup -getairportpower en0 | awk '{print $4}')
    local bluetooth_status=$(system_profiler SPBluetoothDataType | grep "State:" | awk '{print $2}' | head -1)
    
    jq --arg awdl "$awdl_status" \
       --arg wifi "$wifi_status" \
       --arg bluetooth "$bluetooth_status" \
       '.audit_info.system_analysis = {
           "awdl_interface": $awdl,
           "wifi_enabled": ($wifi == "On"),
           "bluetooth_enabled": ($bluetooth == "On"),
           "airdrop_capable": (($wifi == "On") and ($bluetooth == "On"))
       }' "$audit_report" > "${audit_report}.tmp" && mv "${audit_report}.tmp" "$audit_report"
    
    # User-level analysis
    local users
    users=$(dscl . -list /Users | grep -v "^_" | grep -v "daemon\|nobody\|root")
    
    local security_issues=0
    
    for user in $users; do
        local discovery_mode
        discovery_mode=$(sudo -u "$user" defaults read com.apple.sharingd DiscoverableMode 2>/dev/null || echo "-1")
        
        local home_dir
        home_dir=$(dscl . -read "/Users/$user" NFSHomeDirectory 2>/dev/null | cut -d: -f2 | xargs)
        
        local is_admin="false"
        if dseditgroup -o checkmember -m "$user" admin &>/dev/null; then
            is_admin="true"
        fi
        
        # Check for security concerns
        local security_concern="none"
        if [[ "$discovery_mode" == "2" ]] && [[ "$is_admin" == "true" ]]; then
            security_concern="admin_user_unrestricted_airdrop"
            ((security_issues++))
        elif [[ "$discovery_mode" == "2" ]]; then
            security_concern="unrestricted_airdrop_enabled"
        fi
        
        jq --arg user "$user" \
           --argjson discovery "$discovery_mode" \
           --arg home "$home_dir" \
           --arg admin "$is_admin" \
           --arg concern "$security_concern" \
           '.audit_info.user_analysis += [{
               "username": $user,
               "discovery_mode": $discovery,
               "home_directory": $home,
               "is_admin": ($admin == "true"),
               "security_concern": $concern
           }]' "$audit_report" > "${audit_report}.tmp" && mv "${audit_report}.tmp" "$audit_report"
    done
    
    # Generate security summary
    jq --argjson issues "$security_issues" \
       '.audit_info.security_findings = [
           {
               "total_security_issues": $issues,
               "severity": (if $issues == 0 then "low" elif $issues < 3 then "medium" else "high" end),
               "compliance_status": (if $issues == 0 then "compliant" else "non_compliant" end)
           }
       ]' "$audit_report" > "${audit_report}.tmp" && mv "${audit_report}.tmp" "$audit_report"
    
    echo "Audit completed. Found $security_issues security issues."
    log_action "Fleet audit completed: $audit_report"
    echo "$audit_report"
}

# Main execution function
main() {
    local action="${1:-status}"
    local param1="${2:-}"
    local param2="${3:-}"
    local param3="${4:-}"
    
    log_action "=== MacFleet AirDrop Management Started ==="
    log_action "Action: $action"
    
    # Ensure required privileges for most operations
    if [[ "$action" != "status" && "$action" != "help" && $EUID -ne 0 ]]; then
        echo "Error: This action requires administrator privileges"
        echo "Please run with sudo: sudo $0 $*"
        exit 1
    fi
    
    case "$action" in
        "disable")
            echo "Disabling AirDrop..."
            sudo ifconfig awdl0 down && echo "✓ AirDrop disabled" || echo "✗ Failed to disable AirDrop"
            ;;
        "enable")
            echo "Enabling AirDrop..."
            sudo ifconfig awdl0 up && echo "✓ AirDrop enabled" || echo "✗ Failed to enable AirDrop"
            ;;
        "status")
            monitor_airdrop_status "$param1"
            ;;
        "policy")
            if [[ -z "$param1" ]]; then
                echo "Available policies: ${!AIRDROP_POLICIES[*]}"
                exit 1
            fi
            enforce_airdrop_policy "$param1" "${param2:-all}" "$param3"
            ;;
        "audit")
            audit_fleet_airdrop "$param1"
            ;;
        "user")
            if [[ -z "$param1" || -z "$param2" ]]; then
                echo "Usage: $0 user <username> <off|contacts|everyone>"
                exit 1
            fi
            manage_airdrop_discovery "$param1" "$param2"
            ;;
        "help")
            echo "Usage: $0 [action] [options...]"
            echo "Actions:"
            echo "  disable - Disable AirDrop system-wide"
            echo "  enable - Enable AirDrop system-wide"
            echo "  status [detailed] - Check AirDrop status"
            echo "  policy <policy_name> [users] [dry_run] - Apply policy"
            echo "  user <username> <setting> - Set user AirDrop setting"
            echo "  audit [scope] - Audit AirDrop security"
            echo "  help - Show this help"
            echo ""
            echo "Policies: ${!AIRDROP_POLICIES[*]}"
            ;;
        *)
            log_action "ERROR: Unknown action: $action"
            echo "Use '$0 help' for usage information"
            exit 1
            ;;
    esac
    
    log_action "=== AirDrop management completed ==="
}

# Execute main function
main "$@"

AirDrop Security Best Practices

Corporate Security Policies

#!/bin/bash

# Implement corporate AirDrop security policies
implement_corporate_security() {
    echo "=== Implementing Corporate AirDrop Security ==="
    
    # 1. Disable AirDrop on shared/public computers
    echo "Disabling AirDrop on shared workstations..."
    sudo ifconfig awdl0 down
    
    # 2. Set restrictive user defaults
    echo "Setting restrictive AirDrop defaults..."
    local users
    users=$(dscl . -list /Users | grep -v "^_" | grep -v "daemon\|nobody\|root")
    
    for user in $users; do
        sudo -u "$user" defaults write com.apple.sharingd DiscoverableMode -int 0
    done
    
    # 3. Create system-wide policy enforcement
    cat > "/Library/Preferences/com.apple.sharingd.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>DiscoverableMode</key>
    <integer>0</integer>
    <key>AirDropEnabled</key>
    <false/>
</dict>
</plist>
EOF
    
    # 4. Set proper permissions
    chmod 644 "/Library/Preferences/com.apple.sharingd.plist"
    chown root:wheel "/Library/Preferences/com.apple.sharingd.plist"
    
    echo "✓ Corporate security policies implemented"
}

implement_corporate_security

Compliance Monitoring

#!/bin/bash

# Monitor AirDrop compliance with security policies
monitor_compliance() {
    local compliance_standard="$1"
    
    echo "=== AirDrop Compliance Monitoring: $compliance_standard ==="
    
    case "$compliance_standard" in
        "hipaa")
            # Healthcare compliance - AirDrop must be disabled
            if ifconfig awdl0 | grep -q "status: active"; then
                echo "⚠ HIPAA VIOLATION: AirDrop is enabled"
                echo "Recommendation: Disable AirDrop to prevent PHI leakage"
                return 1
            else
                echo "✓ HIPAA COMPLIANT: AirDrop is disabled"
            fi
            ;;
        "pci_dss")
            # Payment card industry compliance
            if ifconfig awdl0 | grep -q "status: active"; then
                echo "⚠ PCI DSS VIOLATION: AirDrop creates uncontrolled network path"
                echo "Recommendation: Disable AirDrop in cardholder data environment"
                return 1
            else
                echo "✓ PCI DSS COMPLIANT: AirDrop is disabled"
            fi
            ;;
        "sox")
            # Sarbanes-Oxley compliance for financial data
            echo "Checking SOX compliance for financial data protection..."
            # Implementation specific to financial data handling
            ;;
        *)
            echo "Unknown compliance standard: $compliance_standard"
            return 1
            ;;
    esac
}

# Usage
monitor_compliance "hipaa"

Troubleshooting AirDrop Issues

Network Diagnostics

#!/bin/bash

# Comprehensive AirDrop troubleshooting
troubleshoot_airdrop() {
    echo "=== AirDrop Troubleshooting Diagnostics ==="
    
    echo "1. Checking AWDL Interface..."
    if ifconfig awdl0 &>/dev/null; then
        ifconfig awdl0 | head -10
    else
        echo "AWDL interface not available"
    fi
    
    echo -e "\n2. Checking Wi-Fi Status..."
    networksetup -getairportpower en0
    
    echo -e "\n3. Checking Bluetooth Status..."
    system_profiler SPBluetoothDataType | grep -A 5 "State:"
    
    echo -e "\n4. Checking Firewall Settings..."
    /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate
    
    echo -e "\n5. Checking Sharing Preferences..."
    local users
    users=$(dscl . -list /Users | grep -v "^_" | grep -v "daemon\|nobody\|root")
    
    for user in $users; do
        local setting
        setting=$(sudo -u "$user" defaults read com.apple.sharingd DiscoverableMode 2>/dev/null || echo "not set")
        echo "User $user: $setting"
    done
    
    echo -e "\n6. Checking Related Processes..."
    ps aux | grep -E "(sharingd|airportd|bluetoothd)" | grep -v grep
    
    echo -e "\n7. Network Interface Summary..."
    networksetup -listallhardwareports | grep -A 1 "Wi-Fi\|Bluetooth"
}

troubleshoot_airdrop

Reset AirDrop Configuration

#!/bin/bash

# Reset AirDrop to default configuration
reset_airdrop_config() {
    echo "=== Resetting AirDrop Configuration ==="
    
    # Stop sharing daemon
    echo "Stopping sharing daemon..."
    sudo killall sharingd 2>/dev/null
    
    # Reset AWDL interface
    echo "Resetting AWDL interface..."
    sudo ifconfig awdl0 down
    sleep 2
    sudo ifconfig awdl0 up
    
    # Clear user preferences
    echo "Clearing user AirDrop preferences..."
    local users
    users=$(dscl . -list /Users | grep -v "^_" | grep -v "daemon\|nobody\|root")
    
    for user in $users; do
        echo "Resetting preferences for user: $user"
        sudo -u "$user" defaults delete com.apple.sharingd DiscoverableMode 2>/dev/null || true
    done
    
    # Remove system-wide policies
    echo "Removing system-wide AirDrop policies..."
    sudo rm -f "/Library/Preferences/com.apple.sharingd.plist"
    
    # Restart sharing daemon
    echo "Restarting sharing daemon..."
    sudo launchctl kickstart -k system/com.apple.sharingd
    
    echo "✓ AirDrop configuration reset to defaults"
}

reset_airdrop_config

Important Notes

  • AWDL Interface - Apple Wireless Direct Link is the underlying technology for AirDrop
  • Administrative privileges required for system-wide AirDrop control
  • User-level settings can override system policies unless enforced
  • Network dependencies - Requires both Wi-Fi and Bluetooth to be enabled
  • Security implications - Consider corporate policies before enabling
  • Compliance requirements - Some industries require AirDrop to be disabled
  • Test thoroughly - Validate changes on test devices before fleet 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.