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.

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

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.