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.

Chrome Extension Management and Security on macOS

Manage and secure Google Chrome extensions across your MacFleet devices with comprehensive discovery, analysis, and policy enforcement tools. This tutorial covers extension enumeration, security assessment, and enterprise browser management.

Understanding Chrome Extension Management

Chrome extensions enhance browser functionality but can introduce security risks. Enterprise management includes:

  • Extension Discovery - Identify all installed extensions across devices
  • Security Analysis - Assess extension permissions and risks
  • Policy Enforcement - Control which extensions are allowed
  • Compliance Monitoring - Ensure adherence to security policies

Extension Security Concerns

Browser extensions can pose enterprise security risks:

  • Data Access - Extensions can read browsing data and personal information
  • Network Requests - Some extensions communicate with external servers
  • Malicious Extensions - Unauthorized or compromised extensions
  • Productivity Impact - Non-business extensions affecting work efficiency
  • Compliance Violations - Extensions that conflict with regulatory requirements

Basic Chrome Extension Discovery

List All Installed Extensions

#!/bin/bash

# Basic Chrome extension listing
currentUser=$(ls -l /dev/console | awk '{print $3}')
ext_dir="/Users/$currentUser/Library/Application Support/Google/Chrome/Default/Extensions/"

echo "Chrome extensions for user: $currentUser"
echo "======================================="

for i in $(find "$ext_dir" -name 'manifest.json'); do
    extension_id=$(basename "$(dirname "$(dirname "$i")")")
    echo "$extension_id"
done

Enhanced Extension Discovery with Details

#!/bin/bash

# Enhanced Chrome extension discovery with metadata
discover_chrome_extensions() {
    local user_name="${1:-$(ls -l /dev/console | awk '{print $3}')}"
    local detailed="${2:-false}"
    
    local chrome_dir="/Users/$user_name/Library/Application Support/Google/Chrome"
    local extensions_dir="$chrome_dir/Default/Extensions"
    
    if [[ ! -d "$extensions_dir" ]]; then
        echo "Chrome extensions directory not found for user: $user_name"
        return 1
    fi
    
    echo "=== Chrome Extension Discovery ==="
    echo "User: $user_name"
    echo "Extensions Directory: $extensions_dir"
    echo "Discovery Date: $(date)"
    echo ""
    
    local extension_count=0
    local extensions_found=()
    
    # Find all manifest.json files
    while IFS= read -r -d '' manifest_path; do
        ((extension_count++))
        
        local extension_id=$(basename "$(dirname "$(dirname "$manifest_path")")")
        local version_dir=$(dirname "$manifest_path")
        local version=$(basename "$version_dir")
        
        extensions_found+=("$extension_id:$version:$manifest_path")
        
        if [[ "$detailed" == "true" ]]; then
            echo "--- Extension $extension_count ---"
            echo "ID: $extension_id"
            echo "Version: $version"
            echo "Manifest: $manifest_path"
            
            # Extract extension name and description from manifest
            if [[ -f "$manifest_path" ]]; then
                local name=$(python3 -c "import json, sys; data=json.load(open('$manifest_path')); print(data.get('name', 'Unknown'))" 2>/dev/null || echo "Unknown")
                local description=$(python3 -c "import json, sys; data=json.load(open('$manifest_path')); print(data.get('description', 'No description'))" 2>/dev/null || echo "No description")
                
                echo "Name: $name"
                echo "Description: $description"
            fi
            echo ""
        else
            echo "$extension_id"
        fi
        
    done < <(find "$extensions_dir" -name 'manifest.json' -print0 2>/dev/null)
    
    echo ""
    echo "Total extensions found: $extension_count"
    
    return 0
}

# Usage examples
discover_chrome_extensions "$(whoami)" "true"
discover_chrome_extensions "$(whoami)" "false"

Check Specific Extension Installation

#!/bin/bash

# Check if specific extension is installed
check_extension_installed() {
    local extension_id="$1"
    local user_name="${2:-$(ls -l /dev/console | cut -d " " -f 4)}"
    
    if [[ -z "$extension_id" ]]; then
        echo "Usage: check_extension_installed <extension_id> [username]"
        echo "Example: check_extension_installed nmmhkkegccagdldgiimedpiccmgmieda"
        return 1
    fi
    
    local extension_path="/Users/$user_name/Library/Application Support/Google/Chrome/Default/Extensions/$extension_id"
    
    if [[ -d "$extension_path" ]]; then
        echo "<result>The extension $extension_id is installed.</result>"
        
        # Get extension details if manifest exists
        local manifest_files=("$extension_path"/*/manifest.json)
        if [[ -f "${manifest_files[0]}" ]]; then
            local manifest_path="${manifest_files[0]}"
            local version=$(basename "$(dirname "$manifest_path")")
            
            echo "Extension Details:"
            echo "- ID: $extension_id"
            echo "- Version: $version"
            echo "- Path: $extension_path"
            
            # Extract name from manifest
            local name=$(python3 -c "import json; data=json.load(open('$manifest_path')); print(data.get('name', 'Unknown'))" 2>/dev/null || echo "Unknown")
            echo "- Name: $name"
        fi
        
        return 0
    else
        echo "<result>Extension $extension_id is not installed.</result>"
        return 1
    fi
}

# Example usage
check_extension_installed "nmmhkkegccagdldgiimedpiccmgmieda"
check_extension_installed "cjpalhdlnbpafiamejdnhcphjbkeiagm"

Advanced Extension Analysis

Comprehensive Extension Security Analysis

#!/bin/bash

# Comprehensive Chrome extension security analysis
analyze_extension_security() {
    local extension_id="$1"
    local user_name="${2:-$(ls -l /dev/console | awk '{print $3}')}"
    
    if [[ -z "$extension_id" ]]; then
        echo "Usage: analyze_extension_security <extension_id> [username]"
        return 1
    fi
    
    local extension_path="/Users/$user_name/Library/Application Support/Google/Chrome/Default/Extensions/$extension_id"
    
    if [[ ! -d "$extension_path" ]]; then
        echo "Extension $extension_id not found for user $user_name"
        return 1
    fi
    
    echo "=== Extension Security Analysis ==="
    echo "Extension ID: $extension_id"
    echo "User: $user_name"
    echo "Analysis Date: $(date)"
    echo ""
    
    # Find the manifest file
    local manifest_files=("$extension_path"/*/manifest.json)
    if [[ ! -f "${manifest_files[0]}" ]]; then
        echo "Manifest file not found for extension $extension_id"
        return 1
    fi
    
    local manifest_path="${manifest_files[0]}"
    local version_dir=$(dirname "$manifest_path")
    local version=$(basename "$version_dir")
    
    echo "--- Basic Information ---"
    echo "Version: $version"
    echo "Install Path: $extension_path"
    echo "Manifest: $manifest_path"
    
    # Parse manifest for security analysis
    if command -v python3 >/dev/null 2>&1; then
        echo ""
        echo "--- Extension Metadata ---"
        
        # Extract basic information
        local name=$(python3 -c "import json; data=json.load(open('$manifest_path')); print(data.get('name', 'Unknown'))" 2>/dev/null || echo "Unknown")
        local description=$(python3 -c "import json; data=json.load(open('$manifest_path')); print(data.get('description', 'No description'))" 2>/dev/null || echo "No description")
        local manifest_version=$(python3 -c "import json; data=json.load(open('$manifest_path')); print(data.get('manifest_version', 'Unknown'))" 2>/dev/null || echo "Unknown")
        
        echo "Name: $name"
        echo "Description: $description"
        echo "Manifest Version: $manifest_version"
        
        # Security analysis
        echo ""
        echo "--- Security Analysis ---"
        
        # Check permissions
        local permissions=$(python3 -c "
import json
try:
    data = json.load(open('$manifest_path'))
    perms = data.get('permissions', [])
    for perm in perms:
        print(f'  - {perm}')
except:
    print('  - Error reading permissions')
" 2>/dev/null)
        
        if [[ -n "$permissions" ]]; then
            echo "Permissions:"
            echo "$permissions"
        else
            echo "Permissions: None declared"
        fi
        
        # Check host permissions
        local host_permissions=$(python3 -c "
import json
try:
    data = json.load(open('$manifest_path'))
    hosts = data.get('host_permissions', [])
    if not hosts:
        hosts = data.get('permissions', [])
        hosts = [h for h in hosts if h.startswith('http') or '*' in h]
    for host in hosts:
        print(f'  - {host}')
except:
    print('  - Error reading host permissions')
" 2>/dev/null)
        
        if [[ -n "$host_permissions" ]]; then
            echo "Host Permissions:"
            echo "$host_permissions"
        else
            echo "Host Permissions: None declared"
        fi
        
        # Check content scripts
        local content_scripts=$(python3 -c "
import json
try:
    data = json.load(open('$manifest_path'))
    scripts = data.get('content_scripts', [])
    if scripts:
        print('Content scripts detected:')
        for i, script in enumerate(scripts):
            matches = script.get('matches', [])
            print(f'  Script {i+1}: {matches}')
    else:
        print('No content scripts')
except:
    print('Error reading content scripts')
" 2>/dev/null)
        
        echo "Content Scripts: $content_scripts"
        
        # Risk assessment
        echo ""
        echo "--- Risk Assessment ---"
        assess_extension_risk "$manifest_path"
        
    else
        echo "Python3 not available - limited analysis"
    fi
    
    # File analysis
    echo ""
    echo "--- File Analysis ---"
    local file_count=$(find "$version_dir" -type f | wc -l)
    local total_size=$(du -sh "$version_dir" | cut -f1)
    
    echo "Total Files: $file_count"
    echo "Total Size: $total_size"
    
    # Check for suspicious files
    local js_files=$(find "$version_dir" -name "*.js" | wc -l)
    local html_files=$(find "$version_dir" -name "*.html" | wc -l)
    local json_files=$(find "$version_dir" -name "*.json" | wc -l)
    
    echo "JavaScript Files: $js_files"
    echo "HTML Files: $html_files"
    echo "JSON Files: $json_files"
    
    echo ""
    echo "=== Analysis Complete ==="
}

# Risk assessment function
assess_extension_risk() {
    local manifest_path="$1"
    local risk_score=0
    local risk_factors=()
    
    # Check for high-risk permissions
    local high_risk_perms=$(python3 -c "
import json
high_risk = ['activeTab', 'tabs', 'storage', 'cookies', 'history', 'bookmarks', 'downloads', 'management', 'nativeMessaging', 'proxy', 'webRequest', 'webRequestBlocking']
try:
    data = json.load(open('$manifest_path'))
    perms = data.get('permissions', [])
    host_perms = data.get('host_permissions', [])
    all_perms = perms + host_perms
    
    found_high_risk = []
    for perm in all_perms:
        if perm in high_risk:
            found_high_risk.append(perm)
        elif perm == '<all_urls>' or perm == '*://*/*':
            found_high_risk.append('all_urls')
    
    print(','.join(found_high_risk))
except:
    pass
" 2>/dev/null)
    
    if [[ -n "$high_risk_perms" ]]; then
        IFS=',' read -ra PERMS <<< "$high_risk_perms"
        for perm in "${PERMS[@]}"; do
            case "$perm" in
                "all_urls"|"*://*/*")
                    risk_score=$((risk_score + 30))
                    risk_factors+=("Access to all websites")
                    ;;
                "tabs"|"activeTab")
                    risk_score=$((risk_score + 20))
                    risk_factors+=("Can access browser tabs")
                    ;;
                "storage"|"cookies")
                    risk_score=$((risk_score + 15))
                    risk_factors+=("Can access stored data")
                    ;;
                "webRequest"|"webRequestBlocking")
                    risk_score=$((risk_score + 25))
                    risk_factors+=("Can intercept web requests")
                    ;;
                "nativeMessaging")
                    risk_score=$((risk_score + 20))
                    risk_factors+=("Can communicate with native applications")
                    ;;
                *)
                    risk_score=$((risk_score + 10))
                    risk_factors+=("Has $perm permission")
                    ;;
            esac
        done
    fi
    
    # Determine risk level
    local risk_level
    if [[ $risk_score -ge 50 ]]; then
        risk_level="HIGH"
    elif [[ $risk_score -ge 25 ]]; then
        risk_level="MEDIUM"
    elif [[ $risk_score -ge 10 ]]; then
        risk_level="LOW"
    else
        risk_level="MINIMAL"
    fi
    
    echo "Risk Level: $risk_level (Score: $risk_score)"
    
    if [[ ${#risk_factors[@]} -gt 0 ]]; then
        echo "Risk Factors:"
        for factor in "${risk_factors[@]}"; do
            echo "  ⚠️ $factor"
        done
    else
        echo "✓ No significant risk factors identified"
    fi
}

# Usage
analyze_extension_security "nmmhkkegccagdldgiimedpiccmgmieda"

Enterprise Chrome Extension Management System

#!/bin/bash

# MacFleet Chrome Extension Management Tool
# Comprehensive browser extension discovery, analysis, and policy enforcement

# Configuration
SCRIPT_VERSION="1.0.0"
LOG_FILE="/var/log/macfleet_chrome_extensions.log"
REPORT_DIR="/etc/macfleet/reports/chrome_extensions"
CONFIG_DIR="/etc/macfleet/chrome_extensions"
POLICY_DIR="/etc/macfleet/policies/chrome_extensions"
ALLOWLIST_FILE="$CONFIG_DIR/allowed_extensions.json"
BLOCKLIST_FILE="$CONFIG_DIR/blocked_extensions.json"

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

# Extension policy templates
declare -A EXTENSION_POLICIES=(
    ["enterprise_strict"]="allowlist_only,no_developer_mode,approved_store_only,security_review_required"
    ["healthcare"]="hipaa_compliant_only,no_data_access,approved_medical_only,audit_required"
    ["financial"]="sox_compliant,no_financial_data_access,bank_approved_only,strict_monitoring"
    ["education"]="educational_approved,student_safe,no_social_media,content_filtered"
    ["development"]="dev_tools_allowed,github_integration,productivity_focus,moderate_restrictions"
    ["general_business"]="productivity_focus,no_games,security_validated,business_approved"
    ["kiosk_lockdown"]="no_extensions,system_locked,maximum_security,zero_customization"
    ["government"]="security_cleared,no_external_communication,audit_trail,maximum_security"
    ["retail"]="pos_safe,no_personal_use,business_hours_only,transaction_secure"
    ["manufacturing"]="industrial_approved,no_social_access,production_safe,minimal_permissions"
)

# Known security risk extensions
declare -A RISKY_EXTENSIONS=(
    ["adware"]="AdBlock variants with suspicious permissions,Free VPN extensions,Coupon extensions"
    ["privacy_risk"]="Extensions requesting all_urls,Password managers from unknown developers,Extensions with native messaging"
    ["productivity_risk"]="Social media extensions,Gaming extensions,Streaming video extensions"
    ["security_risk"]="Extensions from unknown developers,Extensions with webRequest permissions,Proxy extensions"
)

# Trusted extension developers
declare -A TRUSTED_DEVELOPERS=(
    ["google"]="Google LLC,Chrome Web Store official"
    ["microsoft"]="Microsoft Corporation"
    ["adobe"]="Adobe Inc."
    ["1password"]="AgileBits Inc."
    ["lastpass"]="LogMeIn, Inc."
    ["ublock"]="Raymond Hill (gorhill)"
    ["grammarly"]="Grammarly Inc."
    ["zoom"]="Zoom Video Communications, Inc."
)

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

# Discover all Chrome extensions across all users
discover_fleet_extensions() {
    local scan_all_users="${1:-false}"
    local output_format="${2:-detailed}"
    local security_analysis="${3:-true}"
    
    log_action "Starting fleet-wide Chrome extension discovery"
    
    echo "=== MacFleet Chrome Extension Discovery ==="
    echo "Scan All Users: $scan_all_users"
    echo "Output Format: $output_format"
    echo "Security Analysis: $security_analysis"
    echo ""
    
    local total_extensions=0
    local total_users=0
    local high_risk_extensions=0
    local unknown_extensions=0
    local fleet_data=()
    
    # Determine users to scan
    local users_to_scan=()
    if [[ "$scan_all_users" == "true" ]]; then
        # Get all users with home directories
        while IFS= read -r user_dir; do
            local username=$(basename "$user_dir")
            users_to_scan+=("$username")
        done < <(find /Users -maxdepth 1 -type d -not -name "Shared" -not -name "." -not -name ".." | grep -v "/Users$")
    else
        # Current console user only
        local current_user=$(ls -l /dev/console | awk '{print $3}')
        users_to_scan=("$current_user")
    fi
    
    # Scan each user
    for username in "${users_to_scan[@]}"; do
        local chrome_dir="/Users/$username/Library/Application Support/Google/Chrome"
        local extensions_dir="$chrome_dir/Default/Extensions"
        
        if [[ ! -d "$extensions_dir" ]]; then
            continue
        fi
        
        ((total_users++))
        echo "--- User: $username ---"
        
        local user_extension_count=0
        
        # Find all extensions for this user
        while IFS= read -r -d '' manifest_path; do
            ((total_extensions++))
            ((user_extension_count++))
            
            local extension_id=$(basename "$(dirname "$(dirname "$manifest_path")")")
            local version_dir=$(dirname "$manifest_path")
            local version=$(basename "$version_dir")
            
            # Basic extension info
            local name="Unknown"
            local description="No description"
            local risk_level="UNKNOWN"
            
            if command -v python3 >/dev/null 2>&1; then
                name=$(python3 -c "import json; data=json.load(open('$manifest_path')); print(data.get('name', 'Unknown'))" 2>/dev/null || echo "Unknown")
                description=$(python3 -c "import json; data=json.load(open('$manifest_path')); print(data.get('description', 'No description'))" 2>/dev/null || echo "No description")
                
                if [[ "$security_analysis" == "true" ]]; then
                    risk_level=$(assess_extension_risk_level "$manifest_path")
                    if [[ "$risk_level" == "HIGH" ]]; then
                        ((high_risk_extensions++))
                    fi
                fi
            fi
            
            # Check if extension is known/trusted
            local trust_status="UNKNOWN"
            check_extension_trust "$extension_id" "$name" trust_status
            
            if [[ "$trust_status" == "UNKNOWN" ]]; then
                ((unknown_extensions++))
            fi
            
            # Store data for reporting
            fleet_data+=("$username|$extension_id|$name|$version|$risk_level|$trust_status|$description")
            
            # Output based on format
            case "$output_format" in
                "detailed")
                    echo "  Extension: $name"
                    echo "    ID: $extension_id"
                    echo "    Version: $version"
                    echo "    Risk: $risk_level"
                    echo "    Trust: $trust_status"
                    echo ""
                    ;;
                "summary")
                    echo "  $extension_id ($name) - Risk: $risk_level"
                    ;;
                "ids_only")
                    echo "  $extension_id"
                    ;;
            esac
            
        done < <(find "$extensions_dir" -name 'manifest.json' -print0 2>/dev/null)
        
        echo "  User Extensions: $user_extension_count"
        echo ""
    done
    
    # Generate summary
    echo "=== Fleet Discovery Summary ==="
    echo "Total Users Scanned: $total_users"
    echo "Total Extensions Found: $total_extensions"
    echo "High Risk Extensions: $high_risk_extensions"
    echo "Unknown Extensions: $unknown_extensions"
    echo ""
    
    # Generate reports
    if [[ "$output_format" == "json" ]]; then
        generate_json_fleet_report fleet_data
    elif [[ "$output_format" == "csv" ]]; then
        generate_csv_fleet_report fleet_data
    fi
    
    log_action "Fleet extension discovery completed: $total_extensions extensions found across $total_users users"
}

# Assess extension risk level
assess_extension_risk_level() {
    local manifest_path="$1"
    local risk_score=0
    
    # Use Python to analyze manifest
    risk_score=$(python3 -c "
import json
try:
    data = json.load(open('$manifest_path'))
    score = 0
    
    # Check permissions
    perms = data.get('permissions', []) + data.get('host_permissions', [])
    
    for perm in perms:
        if perm in ['<all_urls>', '*://*/*']:
            score += 30
        elif perm in ['tabs', 'activeTab']:
            score += 20
        elif perm in ['webRequest', 'webRequestBlocking']:
            score += 25
        elif perm in ['storage', 'cookies', 'history']:
            score += 15
        elif perm in ['nativeMessaging']:
            score += 20
        elif perm.startswith('http'):
            score += 5
    
    print(score)
except:
    print(0)
" 2>/dev/null || echo "0")
    
    if [[ $risk_score -ge 50 ]]; then
        echo "HIGH"
    elif [[ $risk_score -ge 25 ]]; then
        echo "MEDIUM"
    elif [[ $risk_score -ge 10 ]]; then
        echo "LOW"
    else
        echo "MINIMAL"
    fi
}

# Check extension trust status
check_extension_trust() {
    local extension_id="$1"
    local extension_name="$2"
    local -n trust_ref=$3
    
    # Check against allowlist
    if [[ -f "$ALLOWLIST_FILE" ]]; then
        if grep -q "$extension_id" "$ALLOWLIST_FILE" 2>/dev/null; then
            trust_ref="APPROVED"
            return
        fi
    fi
    
    # Check against blocklist
    if [[ -f "$BLOCKLIST_FILE" ]]; then
        if grep -q "$extension_id" "$BLOCKLIST_FILE" 2>/dev/null; then
            trust_ref="BLOCKED"
            return
        fi
    fi
    
    # Check against known good extensions (simplified)
    case "$extension_id" in
        "cjpalhdlnbpafiamejdnhcphjbkeiagm") # uBlock Origin
            trust_ref="TRUSTED"
            ;;
        "nmmhkkegccagdldgiimedpiccmgmieda") # Google Translate
            trust_ref="TRUSTED"
            ;;
        "gighmmpiobklfepjocnamgkkbiglidom") # AdBlock
            trust_ref="TRUSTED"
            ;;
        *)
            trust_ref="UNKNOWN"
            ;;
    esac
}

# Generate JSON fleet report
generate_json_fleet_report() {
    local -n data_ref=$1
    local report_file="$REPORT_DIR/fleet_extensions_$(date +%Y%m%d_%H%M%S).json"
    
    cat > "$report_file" << EOF
{
    "chrome_extension_fleet_report": {
        "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
        "hostname": "$(hostname)",
        "script_version": "$SCRIPT_VERSION",
        "extensions": [
EOF
    
    local first=true
    for data_line in "${data_ref[@]}"; do
        IFS='|' read -r username extension_id name version risk_level trust_status description <<< "$data_line"
        
        if [[ "$first" == "true" ]]; then
            first=false
        else
            echo "," >> "$report_file"
        fi
        
        cat >> "$report_file" << EOF
            {
                "user": "$username",
                "extension_id": "$extension_id",
                "name": "$name",
                "version": "$version",
                "risk_level": "$risk_level",
                "trust_status": "$trust_status",
                "description": "$description"
            }
EOF
    done
    
    cat >> "$report_file" << EOF

        ]
    }
}
EOF
    
    echo "JSON report generated: $report_file"
}

# Enforce extension policies
enforce_extension_policy() {
    local policy_name="$1"
    local action="${2:-report}"
    local target_user="${3:-all}"
    
    echo "=== Enforcing Extension Policy: $policy_name ==="
    echo "Action: $action"
    echo "Target User: $target_user"
    echo ""
    
    if [[ -z "${EXTENSION_POLICIES[$policy_name]}" ]]; then
        echo "Error: Unknown policy '$policy_name'"
        echo "Available policies: ${!EXTENSION_POLICIES[*]}"
        return 1
    fi
    
    local policy_rules="${EXTENSION_POLICIES[$policy_name]}"
    echo "Policy Rules: $policy_rules"
    echo ""
    
    local violations=()
    local compliant_extensions=()
    
    # Implement policy enforcement logic based on policy type
    case "$policy_name" in
        "enterprise_strict")
            enforce_strict_policy violations compliant_extensions "$target_user"
            ;;
        "healthcare")
            enforce_healthcare_policy violations compliant_extensions "$target_user"
            ;;
        "kiosk_lockdown")
            enforce_kiosk_policy violations compliant_extensions "$target_user"
            ;;
        *)
            enforce_general_policy "$policy_name" violations compliant_extensions "$target_user"
            ;;
    esac
    
    # Report results
    echo "Policy Enforcement Results:"
    echo "Compliant Extensions: ${#compliant_extensions[@]}"
    echo "Policy Violations: ${#violations[@]}"
    
    if [[ ${#violations[@]} -gt 0 ]]; then
        echo ""
        echo "Violations Found:"
        for violation in "${violations[@]}"; do
            echo "  ⚠️ $violation"
        done
    fi
    
    # Take action
    case "$action" in
        "report")
            echo ""
            echo "Action: Report Only - No changes made"
            ;;
        "disable")
            echo ""
            echo "Action: Disable violating extensions"
            disable_violating_extensions violations
            ;;
        "remove")
            echo ""
            echo "Action: Remove violating extensions"
            remove_violating_extensions violations
            ;;
    esac
    
    log_action "Extension policy enforcement completed: $policy_name"
}

# Main execution function
main() {
    local action="${1:-help}"
    local param1="${2:-}"
    local param2="${3:-}"
    local param3="${4:-}"
    local param4="${5:-}"
    
    log_action "=== MacFleet Chrome Extension Management Started ==="
    log_action "Action: $action"
    
    case "$action" in
        "discover")
            discover_chrome_extensions "${param1:-$(whoami)}" "${param2:-true}"
            ;;
        "check")
            if [[ -z "$param1" ]]; then
                echo "Usage: $0 check <extension_id> [username]"
                exit 1
            fi
            check_extension_installed "$param1" "$param2"
            ;;
        "analyze")
            if [[ -z "$param1" ]]; then
                echo "Usage: $0 analyze <extension_id> [username]"
                exit 1
            fi
            analyze_extension_security "$param1" "$param2"
            ;;
        "fleet")
            discover_fleet_extensions "${param1:-false}" "${param2:-detailed}" "${param3:-true}"
            ;;
        "policy")
            if [[ -z "$param1" ]]; then
                echo "Available policies: ${!EXTENSION_POLICIES[*]}"
                exit 1
            fi
            enforce_extension_policy "$param1" "${param2:-report}" "${param3:-all}"
            ;;
        "help")
            echo "Usage: $0 [action] [options...]"
            echo "Actions:"
            echo "  discover [username] [detailed] - Discover extensions for user"
            echo "  check <extension_id> [username] - Check if extension is installed"
            echo "  analyze <extension_id> [username] - Analyze extension security"
            echo "  fleet [all_users] [format] [security] - Fleet-wide discovery"
            echo "  policy <policy_name> [action] [user] - Enforce extension policy"
            echo "  help - Show this help"
            echo ""
            echo "Policies: ${!EXTENSION_POLICIES[*]}"
            ;;
        *)
            log_action "ERROR: Unknown action: $action"
            echo "Use '$0 help' for usage information"
            exit 1
            ;;
    esac
    
    log_action "=== Chrome extension management completed ==="
}

# Execute main function
main "$@"

Important Notes

  • Extension IDs are 32-character strings uniquely identifying each extension
  • Manifest files contain extension metadata and permission requirements
  • Security analysis should focus on permissions and data access
  • Enterprise policies should balance functionality with security requirements
  • Regular monitoring helps detect unauthorized or risky extensions
  • User training is essential for extension security awareness

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.