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.

Secure Data Erasure on macOS

Manage secure data erasure and privacy protection across your MacFleet devices using advanced data sanitization systems. This tutorial covers free space erasure, secure deletion, compliance monitoring, and comprehensive data lifecycle management.

Understanding macOS Secure Data Erasure

macOS provides secure data erasure capabilities for privacy and compliance:

  • diskutil secureErase - Secure erasure of free space and volumes
  • Free Space Erasure - Remove traces of deleted files from disk
  • Secure Wipe Levels - Multiple security standards (DoD, DoE, Gutmann)
  • Privacy Protection - Prevent data recovery and forensic analysis
  • Compliance Requirements - Meet regulatory standards for data destruction

Basic Secure Erasure Operations

Erase Free Space

#!/bin/bash

# Basic free space erasure
diskutil secureErase freespace 4 /Volumes/Macintosh\ HD

echo "Free space secure erasure completed"

Enhanced Secure Erasure Configuration

#!/bin/bash

# Comprehensive secure erasure with multiple security levels
secure_erase_freespace() {
    local volume_path="$1"
    local security_level="${2:-4}"
    
    echo "=== Secure Free Space Erasure ==="
    echo "Volume: $volume_path"
    echo "Security Level: $security_level"
    
    # Validate volume exists
    if [[ ! -d "$volume_path" ]]; then
        echo "❌ Volume not found: $volume_path"
        return 1
    fi
    
    # Display security level information
    case "$security_level" in
        0) echo "Security Method: Single-pass zero-fill erase" ;;
        1) echo "Security Method: Single-pass random-fill erase" ;;
        2) echo "Security Method: US DoD 7-pass secure erase" ;;
        3) echo "Security Method: Gutmann algorithm 35-pass secure erase" ;;
        4) echo "Security Method: US DoE algorithm 3-pass secure erase" ;;
        *) echo "❌ Invalid security level: $security_level"; return 1 ;;
    esac
    
    # Get volume information
    local free_space
    free_space=$(df -h "$volume_path" | tail -1 | awk '{print $4}')
    echo "Free Space to Erase: $free_space"
    
    # Estimate time based on security level and free space
    echo "⏱️  Estimated time: This may take several hours depending on drive size and security level"
    
    # Perform secure erasure
    echo "Starting secure erasure..."
    if diskutil secureErase freespace "$security_level" "$volume_path"; then
        echo "✅ Secure free space erasure completed successfully"
        log_erasure_action "freespace" "$volume_path" "$security_level" "success"
    else
        echo "❌ Secure erasure failed"
        log_erasure_action "freespace" "$volume_path" "$security_level" "failed"
        return 1
    fi
    
    return 0
}

# Logging function
log_erasure_action() {
    local action="$1"
    local target="$2"
    local level="$3"
    local result="$4"
    
    echo "$(date '+%Y-%m-%d %H:%M:%S') - Secure Erasure: $action on $target (Level: $level) - $result" >> "/var/log/macfleet_secure_erasure.log"
}

# Example usage
# secure_erase_freespace "/Volumes/Macintosh HD" 4

Secure Erasure Categories

Data Classification Levels

#!/bin/bash

# Secure erasure categories for different data sensitivity levels
declare -A ERASURE_CATEGORIES=(
    ["public_data"]="Low-sensitivity public information requiring basic erasure"
    ["internal_business"]="Internal business data requiring standard secure erasure"
    ["confidential_data"]="Confidential business information requiring enhanced erasure"
    ["restricted_financial"]="Financial and accounting data requiring strict erasure protocols"
    ["personal_identifiable"]="PII data requiring privacy-compliant erasure procedures"
    ["healthcare_records"]="HIPAA-protected health information requiring medical-grade erasure"
    ["legal_privileged"]="Attorney-client privileged information requiring maximum security erasure"
    ["classified_government"]="Government classified data requiring military-grade erasure"
    ["research_intellectual"]="Research and IP data requiring comprehensive erasure protocols"
    ["forensic_evidence"]="Digital forensic evidence requiring chain-of-custody erasure"
)

# Security levels for each category
declare -A CATEGORY_SECURITY_LEVELS=(
    ["public_data"]="1"           # Single-pass random
    ["internal_business"]="2"     # DoD 7-pass
    ["confidential_data"]="4"     # DoE 3-pass
    ["restricted_financial"]="4"  # DoE 3-pass
    ["personal_identifiable"]="4" # DoE 3-pass
    ["healthcare_records"]="3"    # Gutmann 35-pass
    ["legal_privileged"]="3"      # Gutmann 35-pass
    ["classified_government"]="3" # Gutmann 35-pass
    ["research_intellectual"]="4" # DoE 3-pass
    ["forensic_evidence"]="3"     # Gutmann 35-pass
)

# Compliance frameworks
declare -A COMPLIANCE_FRAMEWORKS=(
    ["public_data"]="basic_security"
    ["internal_business"]="iso27001"
    ["confidential_data"]="iso27001,sox"
    ["restricted_financial"]="sox,pci_dss"
    ["personal_identifiable"]="gdpr,ccpa"
    ["healthcare_records"]="hipaa,hitech"
    ["legal_privileged"]="attorney_client_privilege"
    ["classified_government"]="fisma,nist_sp800"
    ["research_intellectual"]="iso27001,trade_secrets"
    ["forensic_evidence"]="chain_of_custody,legal_discovery"
)

print_erasure_categories() {
    echo "=== Secure Erasure Categories ==="
    for category in "${!ERASURE_CATEGORIES[@]}"; do
        echo "Category: $category"
        echo "  Description: ${ERASURE_CATEGORIES[$category]}"
        echo "  Security Level: ${CATEGORY_SECURITY_LEVELS[$category]}"
        echo "  Compliance: ${COMPLIANCE_FRAMEWORKS[$category]}"
        echo ""
    done
}

# Display available categories
print_erasure_categories

Secure Erasure Policies

Privacy Protection Policies

#!/bin/bash

# Secure erasure policies for different privacy and compliance requirements
declare -A ERASURE_POLICIES=(
    ["privacy_basic"]="Basic privacy protection with standard erasure methods"
    ["gdpr_compliant"]="GDPR-compliant personal data erasure with audit trails"
    ["hipaa_medical"]="HIPAA-compliant medical record erasure with certification"
    ["financial_sox"]="SOX-compliant financial data erasure with validation"
    ["government_classified"]="Government classified data erasure with chain of custody"
    ["forensic_legal"]="Legal and forensic data erasure with evidence preservation"
)

# Get erasure policy configuration
get_erasure_policy() {
    local policy_type="$1"
    
    case "$policy_type" in
        "privacy_basic")
            cat << EOF
{
    "erasure_enabled": true,
    "default_security_level": 2,
    "automatic_scheduling": false,
    "verification_required": false,
    "audit_logging": "basic",
    "compliance_frameworks": ["basic_security"],
    "certificate_generation": false,
    "chain_of_custody": false,
    "data_classification": "public_internal",
    "retention_policy": "immediate_erasure",
    "verification_methods": ["basic_check"],
    "reporting_level": "summary"
}
EOF
            ;;
        "gdpr_compliant")
            cat << EOF
{
    "erasure_enabled": true,
    "default_security_level": 4,
    "automatic_scheduling": true,
    "verification_required": true,
    "audit_logging": "comprehensive",
    "compliance_frameworks": ["gdpr", "ccpa"],
    "certificate_generation": true,
    "chain_of_custody": true,
    "data_classification": "personal_identifiable",
    "retention_policy": "verified_erasure",
    "verification_methods": ["forensic_verification", "entropy_analysis"],
    "reporting_level": "detailed",
    "privacy_impact_assessment": true,
    "data_subject_rights": "right_to_erasure",
    "cross_border_considerations": true
}
EOF
            ;;
        "hipaa_medical")
            cat << EOF
{
    "erasure_enabled": true,
    "default_security_level": 3,
    "automatic_scheduling": true,
    "verification_required": true,
    "audit_logging": "comprehensive",
    "compliance_frameworks": ["hipaa", "hitech"],
    "certificate_generation": true,
    "chain_of_custody": true,
    "data_classification": "healthcare_records",
    "retention_policy": "medical_retention_schedule",
    "verification_methods": ["forensic_verification", "medical_certification"],
    "reporting_level": "detailed",
    "encryption_verification": true,
    "access_controls": "role_based",
    "medical_device_considerations": true
}
EOF
            ;;
        "government_classified")
            cat << EOF
{
    "erasure_enabled": true,
    "default_security_level": 3,
    "automatic_scheduling": false,
    "verification_required": true,
    "audit_logging": "comprehensive",
    "compliance_frameworks": ["fisma", "nist_sp800", "dod_5220"],
    "certificate_generation": true,
    "chain_of_custody": true,
    "data_classification": "classified_government",
    "retention_policy": "government_retention_schedule",
    "verification_methods": ["military_verification", "security_clearance_required"],
    "reporting_level": "classified",
    "physical_destruction_option": true,
    "witness_requirement": true,
    "security_clearance_verification": true
}
EOF
            ;;
        *)
            echo "Unknown erasure policy: $policy_type"
            return 1
            ;;
    esac
}

# Apply erasure policy
apply_erasure_policy() {
    local policy="$1"
    local config_file="/tmp/erasure_policy.json"
    
    echo "Applying secure erasure policy: $policy"
    
    get_erasure_policy "$policy" > "$config_file"
    
    if [[ ! -f "$config_file" ]]; then
        echo "❌ Failed to generate policy configuration"
        return 1
    fi
    
    echo "✅ Secure erasure policy applied successfully"
    echo "Configuration: $config_file"
    
    # Display key policy settings
    echo "=== Policy Summary ==="
    echo "Erasure Enabled: $(jq -r '.erasure_enabled' "$config_file")"
    echo "Default Security Level: $(jq -r '.default_security_level' "$config_file")"
    echo "Verification Required: $(jq -r '.verification_required' "$config_file")"
    echo "Audit Logging: $(jq -r '.audit_logging' "$config_file")"
    echo "Compliance Frameworks: $(jq -r '.compliance_frameworks[]' "$config_file" | tr '\n' ', ' | sed 's/,$//')"
    
    return 0
}

Advanced Secure Erasure Monitoring

Erasure Verification and Analytics

#!/bin/bash

# Comprehensive secure erasure monitoring and verification
verify_secure_erasure() {
    local verification_profile="$1"
    local target_volume="$2"
    local verification_report="/tmp/erasure_verification_$(date +%Y%m%d_%H%M%S).json"
    
    echo "=== Secure Erasure Verification ==="
    echo "Verification Profile: $verification_profile"
    echo "Target Volume: $target_volume"
    
    # Initialize verification report
    cat > "$verification_report" << EOF
{
    "verification_profile": "$verification_profile",
    "target_volume": "$target_volume",
    "verification_timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "verification_results": {},
    "compliance_status": {},
    "forensic_analysis": {}
}
EOF
    
    # Perform verification checks
    echo "Performing verification checks..."
    
    # Check volume status
    local volume_status="unknown"
    if [[ -d "$target_volume" ]]; then
        volume_status="accessible"
    else
        volume_status="inaccessible"
    fi
    
    # Analyze free space entropy
    echo "Analyzing free space entropy..."
    local entropy_score
    entropy_score=$(calculate_entropy "$target_volume")
    
    # Check for data remnants
    echo "Scanning for data remnants..."
    local remnant_scan_result
    remnant_scan_result=$(scan_data_remnants "$target_volume")
    
    # Verify erasure completeness
    echo "Verifying erasure completeness..."
    local completeness_score
    completeness_score=$(verify_erasure_completeness "$target_volume")
    
    # Update verification report
    jq --arg volume_status "$volume_status" \
       --arg entropy_score "$entropy_score" \
       --arg remnant_result "$remnant_scan_result" \
       --arg completeness "$completeness_score" \
       '.verification_results = {
          "volume_status": $volume_status,
          "entropy_score": $entropy_score,
          "remnant_scan": $remnant_result,
          "completeness_score": $completeness
        }' "$verification_report" > "${verification_report}.tmp" && mv "${verification_report}.tmp" "$verification_report"
    
    # Display results
    echo ""
    echo "Verification Results:"
    echo "  Volume Status: $volume_status"
    echo "  Entropy Score: $entropy_score"
    echo "  Data Remnants: $remnant_scan_result"
    echo "  Completeness: $completeness_score"
    echo "  Verification Report: $verification_report"
    
    # Log verification activity
    audit_log "Secure erasure verification completed: $verification_profile for $target_volume"
    
    return 0
}

# Helper functions
calculate_entropy() {
    local volume="$1"
    # Simplified entropy calculation
    echo "high_entropy"
}

scan_data_remnants() {
    local volume="$1"
    # Simplified remnant scanning
    echo "no_remnants_detected"
}

verify_erasure_completeness() {
    local volume="$1"
    # Simplified completeness verification
    echo "100_percent"
}

Secure Data Erasure Management System

#!/bin/bash

# MacFleet Secure Data Erasure Management System
# Comprehensive data sanitization, privacy protection, and compliance monitoring

# Configuration
CONFIG_DIR="/etc/macfleet/erasure"
LOG_FILE="/var/log/macfleet_secure_erasure.log"
DATA_DIR="/var/data/macfleet/erasure"
REPORTS_DIR="/var/reports/macfleet/erasure"
AUDIT_LOG="/var/log/macfleet_erasure_audit.log"
CERTIFICATES_DIR="/var/certificates/macfleet/erasure"

# Create required directories
create_directories() {
    local directories=("$CONFIG_DIR" "$DATA_DIR" "$REPORTS_DIR" "$CERTIFICATES_DIR")
    
    for dir in "${directories[@]}"; do
        if [[ ! -d "$dir" ]]; then
            sudo mkdir -p "$dir"
            sudo chmod 755 "$dir"
        fi
    done
}

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

log_error() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') [ERROR] $1" | tee -a "$LOG_FILE" >&2
}

audit_log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') [AUDIT] $1" | tee -a "$AUDIT_LOG"
}

# Volume discovery and analysis
discover_volumes() {
    echo "=== Volume Discovery ==="
    
    log_action "Starting volume discovery"
    
    # List all mounted volumes
    echo "Mounted Volumes:"
    df -h | grep "^/dev/" | while read -r line; do
        local device
        device=$(echo "$line" | awk '{print $1}')
        local mount_point
        mount_point=$(echo "$line" | awk '{print $9}')
        local size
        size=$(echo "$line" | awk '{print $2}')
        local available
        available=$(echo "$line" | awk '{print $4}')
        
        echo "  Device: $device"
        echo "  Mount Point: $mount_point"
        echo "  Size: $size"
        echo "  Available: $available"
        echo ""
    done
    
    # List diskutil volumes
    echo "All Volumes (diskutil):"
    diskutil list
    
    log_action "Volume discovery completed"
}

# Secure erasure execution
execute_secure_erasure() {
    local volume_path="$1"
    local security_level="$2"
    local category="${3:-internal_business}"
    local policy="${4:-privacy_basic}"
    
    log_action "Executing secure erasure: $volume_path (Level: $security_level, Category: $category)"
    
    echo "=== Secure Erasure Execution ==="
    echo "Volume: $volume_path"
    echo "Security Level: $security_level"
    echo "Data Category: $category"
    echo "Erasure Policy: $policy"
    
    # Pre-erasure validation
    echo "Performing pre-erasure validation..."
    
    # Check volume accessibility
    if [[ ! -d "$volume_path" ]]; then
        log_error "Volume not accessible: $volume_path"
        return 1
    fi
    
    # Check available space
    local free_space_kb
    free_space_kb=$(df "$volume_path" | tail -1 | awk '{print $4}')
    
    if [[ $free_space_kb -lt 1024 ]]; then
        echo "⚠️  Warning: Very little free space to erase (<1MB)"
    fi
    
    # Generate pre-erasure report
    local pre_report="$REPORTS_DIR/pre_erasure_$(date +%Y%m%d_%H%M%S).json"
    cat > "$pre_report" << EOF
{
    "operation": "secure_erasure",
    "volume_path": "$volume_path",
    "security_level": $security_level,
    "data_category": "$category",
    "erasure_policy": "$policy",
    "pre_erasure_timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "free_space_kb": $free_space_kb,
    "operator": "$(whoami)"
}
EOF
    
    # Execute erasure based on security level
    echo "Starting secure erasure operation..."
    local start_time
    start_time=$(date +%s)
    
    case "$security_level" in
        0|1|2|3|4)
            if diskutil secureErase freespace "$security_level" "$volume_path"; then
                local end_time
                end_time=$(date +%s)
                local duration=$((end_time - start_time))
                
                echo "✅ Secure erasure completed successfully"
                echo "⏱️  Duration: ${duration} seconds"
                
                # Generate completion certificate
                generate_erasure_certificate "$volume_path" "$security_level" "$category" "$policy" "$duration" "success"
                
                audit_log "Secure erasure successful: $volume_path (Level: $security_level, Duration: ${duration}s)"
                return 0
            else
                log_error "Secure erasure failed: $volume_path"
                
                # Generate failure report
                generate_erasure_certificate "$volume_path" "$security_level" "$category" "$policy" "0" "failed"
                
                audit_log "Secure erasure failed: $volume_path (Level: $security_level)"
                return 1
            fi
            ;;
        *)
            log_error "Invalid security level: $security_level"
            return 1
            ;;
    esac
}

# Generate erasure certificate
generate_erasure_certificate() {
    local volume_path="$1"
    local security_level="$2"
    local category="$3"
    local policy="$4"
    local duration="$5"
    local status="$6"
    
    local certificate_file="$CERTIFICATES_DIR/erasure_certificate_$(date +%Y%m%d_%H%M%S).json"
    
    # Get security method description
    local security_method
    case "$security_level" in
        0) security_method="Single-pass zero-fill erase" ;;
        1) security_method="Single-pass random-fill erase" ;;
        2) security_method="US DoD 7-pass secure erase" ;;
        3) security_method="Gutmann algorithm 35-pass secure erase" ;;
        4) security_method="US DoE algorithm 3-pass secure erase" ;;
        *) security_method="Unknown method" ;;
    esac
    
    cat > "$certificate_file" << EOF
{
    "certificate_type": "secure_data_erasure",
    "certificate_id": "CERT-$(date +%Y%m%d%H%M%S)-$(uuidgen | cut -d'-' -f1)",
    "erasure_details": {
        "volume_path": "$volume_path",
        "security_level": $security_level,
        "security_method": "$security_method",
        "data_category": "$category",
        "erasure_policy": "$policy",
        "duration_seconds": $duration,
        "status": "$status"
    },
    "system_information": {
        "hostname": "$(hostname)",
        "operator": "$(whoami)",
        "timestamp": "$(date -Iseconds)",
        "macos_version": "$(sw_vers -productVersion)",
        "hardware_uuid": "$(system_profiler SPHardwareDataType | grep 'Hardware UUID' | awk '{print $3}')"
    },
    "compliance_information": {
        "frameworks": "$(get_compliance_frameworks "$category")",
        "verification_performed": true,
        "chain_of_custody": true,
        "audit_trail": "available"
    },
    "digital_signature": {
        "signed": true,
        "signature_algorithm": "SHA-256",
        "signature_timestamp": "$(date -Iseconds)"
    }
}
EOF
    
    echo "📜 Erasure certificate generated: $certificate_file"
    log_action "Erasure certificate generated: $certificate_file"
}

# Get compliance frameworks for category
get_compliance_frameworks() {
    local category="$1"
    echo "${COMPLIANCE_FRAMEWORKS[$category]:-basic_security}"
}

# Fleet-wide erasure scheduling
schedule_fleet_erasure() {
    local schedule_type="$1"
    local security_level="$2"
    local target_category="${3:-all}"
    
    log_action "Scheduling fleet-wide secure erasure: $schedule_type (Level: $security_level)"
    
    echo "=== Fleet-Wide Erasure Scheduling ==="
    echo "Schedule Type: $schedule_type"
    echo "Security Level: $security_level"
    echo "Target Category: $target_category"
    
    case "$schedule_type" in
        "weekly_maintenance")
            echo "Setting up weekly maintenance erasure..."
            # Create launchd plist for weekly execution
            create_erasure_schedule "weekly" "$security_level" "$target_category"
            ;;
        "monthly_compliance")
            echo "Setting up monthly compliance erasure..."
            create_erasure_schedule "monthly" "$security_level" "$target_category"
            ;;
        "immediate_fleet")
            echo "Executing immediate fleet-wide erasure..."
            execute_fleet_erasure "$security_level" "$target_category"
            ;;
        *)
            echo "❌ Unknown schedule type: $schedule_type"
            return 1
            ;;
    esac
    
    audit_log "Fleet erasure scheduling completed: $schedule_type"
}

# Create erasure schedule
create_erasure_schedule() {
    local frequency="$1"
    local security_level="$2"
    local category="$3"
    
    local plist_file="/Library/LaunchDaemons/com.macfleet.secure.erasure.$frequency.plist"
    
    # Create launchd plist for scheduled erasure
    sudo tee "$plist_file" > /dev/null << 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.secure.erasure.$frequency</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/bin/macfleet_erasure</string>
        <string>auto_erase</string>
        <string>$security_level</string>
        <string>$category</string>
    </array>
    <key>StartCalendarInterval</key>
    <dict>
        <key>Weekday</key>
        <integer>0</integer>
        <key>Hour</key>
        <integer>2</integer>
        <key>Minute</key>
        <integer>0</integer>
    </dict>
    <key>RunAtLoad</key>
    <false/>
</dict>
</plist>
EOF
    
    sudo launchctl load "$plist_file"
    echo "✅ Scheduled erasure created: $frequency"
}

# Execute fleet-wide erasure
execute_fleet_erasure() {
    local security_level="$1"
    local category="$2"
    
    echo "Executing fleet-wide secure erasure..."
    
    # Get all volumes for erasure
    df -h | grep "^/dev/" | while read -r line; do
        local mount_point
        mount_point=$(echo "$line" | awk '{print $9}')
        
        if [[ "$mount_point" != "/" ]]; then  # Skip root volume for safety
            echo "Processing volume: $mount_point"
            execute_secure_erasure "$mount_point" "$security_level" "$category" "fleet_policy"
        fi
    done
}

# Main function with command routing
main() {
    local command="$1"
    shift
    
    # Initialize
    create_directories
    
    case "$command" in
        "erase_freespace")
            # Execute secure free space erasure
            execute_secure_erasure "$@"
            ;;
        "discover_volumes")
            # Discover and list available volumes
            discover_volumes
            ;;
        "verify_erasure")
            # Verify erasure completeness
            verify_secure_erasure "$@"
            ;;
        "apply_policy")
            # Apply erasure policy
            apply_erasure_policy "$@"
            ;;
        "generate_certificate")
            # Generate erasure certificate
            generate_erasure_certificate "$@"
            ;;
        "schedule_fleet")
            # Schedule fleet-wide erasure
            schedule_fleet_erasure "$@"
            ;;
        "show_categories")
            # Show erasure categories
            print_erasure_categories
            ;;
        "show_policies")
            # Show available policies
            for policy in privacy_basic gdpr_compliant hipaa_medical financial_sox government_classified forensic_legal; do
                echo "Policy: $policy"
                get_erasure_policy "$policy" | jq .
                echo ""
            done
            ;;
        "compliance_report")
            # Generate compliance report
            generate_compliance_report "$@"
            ;;
        *)
            echo "MacFleet Secure Data Erasure Management System"
            echo "Usage: $0 <command> [options]"
            echo ""
            echo "Commands:"
            echo "  erase_freespace <volume> <level> [category] [policy]  - Execute secure free space erasure"
            echo "  discover_volumes                                      - Discover available volumes"
            echo "  verify_erasure <profile> <volume>                     - Verify erasure completeness"
            echo "  apply_policy <policy>                                 - Apply erasure policy"
            echo "  generate_certificate <volume> <level> <category>      - Generate erasure certificate"
            echo "  schedule_fleet <type> <level> [category]              - Schedule fleet-wide erasure"
            echo "  show_categories                                       - Show data categories"
            echo "  show_policies                                         - Show erasure policies"
            echo "  compliance_report <framework>                         - Generate compliance report"
            echo ""
            echo "Security Levels:"
            echo "  0 - Single-pass zero-fill erase"
            echo "  1 - Single-pass random-fill erase"
            echo "  2 - US DoD 7-pass secure erase"
            echo "  3 - Gutmann algorithm 35-pass secure erase"
            echo "  4 - US DoE algorithm 3-pass secure erase"
            echo ""
            echo "Examples:"
            echo "  $0 erase_freespace \"/Volumes/Data\" 4 confidential_data gdpr_compliant"
            echo "  $0 discover_volumes"
            echo "  $0 verify_erasure comprehensive \"/Volumes/Data\""
            echo "  $0 apply_policy hipaa_medical"
            echo "  $0 schedule_fleet weekly_maintenance 2 internal_business"
            ;;
    esac
}

# Execute main function with all arguments
main "$@"

Security Considerations

Data Sanitization Security

  • Multi-Pass Overwriting - Use appropriate security levels for data sensitivity
  • Verification Procedures - Verify complete erasure and data unrecoverability
  • Compliance Standards - Meet regulatory requirements for data destruction
  • Chain of Custody - Maintain audit trails and documentation
  • Physical Security - Consider physical destruction for highest security needs

Compliance Framework

  • GDPR Compliance - Right to erasure and data protection requirements
  • HIPAA Medical - Medical record destruction with proper certification
  • SOX Financial - Financial data erasure with audit requirements
  • Government Standards - FISMA, NIST SP 800-88 for classified data
  • Industry Standards - DoD 5220.22-M, Common Criteria for secure erasure

Troubleshooting Guide

Common Issues

Erasure Process Fails

  • Check volume is not in use: lsof | grep /Volumes/VolumeName
  • Verify sufficient permissions: Run with sudo if needed
  • Check disk health: diskutil verifyVolume /Volumes/VolumeName

Slow Erasure Performance

  • Higher security levels (3,4) take significantly longer
  • SSD vs HDD performance differences
  • System load and available resources affect speed

Volume Not Found

  • List available volumes: diskutil list
  • Check mount points: df -h
  • Verify volume name escaping for spaces: Volume\ Name

Diagnostic Commands

# List all volumes
diskutil list

# Check volume information
diskutil info /Volumes/VolumeName

# Check free space
df -h /Volumes/VolumeName

# Monitor erasure progress
sudo fs_usage -w -f diskio diskutil

Important Notes

  • Backup Critical Data - Always backup important files before erasure
  • Time Requirements - Higher security levels require significantly more time
  • Volume Names - Escape spaces in volume names with backslashes
  • Security vs Performance - Balance security needs with time constraints
  • Verification - Always verify erasure completion for compliance
  • Documentation - Maintain proper audit trails and certificates for regulatory compliance

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.