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.

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

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.