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.

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

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.