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.

User Privilege Management and Security Compliance on macOS

Implement comprehensive user privilege management and security compliance across your MacFleet devices. This tutorial covers administrator access verification, privilege escalation monitoring, role-based access control (RBAC), security policy enforcement, and automated compliance frameworks for enterprise environments.

Understanding macOS User Privilege System

macOS uses a layered privilege system for security and access control:

  • Standard Users - Basic system access with limited administrative capabilities
  • Administrator Users - Full system access and ability to modify system settings
  • Root User - Superuser with unrestricted system access (typically disabled)
  • Service Accounts - System accounts for running services and daemons
  • Group Memberships - Additional privileges through group assignments

Basic Administrator Verification

Check Individual User Admin Status

#!/bin/bash

# Check if specific user has administrator privileges
check_user_admin_status() {
    local username="$1"
    
    if [[ -z "$username" ]]; then
        echo "❌ Username required"
        return 1
    fi
    
    echo "=== Checking Admin Status for User: $username ==="
    
    # Verify user exists
    if ! dscl . -read "/Users/$username" &>/dev/null; then
        echo "❌ User '$username' does not exist"
        return 1
    fi
    
    # Check admin group membership
    if groups "$username" | grep -q -w admin; then
        echo "✅ User '$username' IS an administrator"
        return 0
    else
        echo "ℹ️  User '$username' is NOT an administrator"
        return 1
    fi
}

# Usage example
# check_user_admin_status "testuser"

List All Administrator Users

#!/bin/bash

# Get list of all administrator users
list_admin_users() {
    echo "=== Administrator Users List ==="
    
    # Get admin group members
    local admin_users
    admin_users=$(dscl . -read /Groups/admin GroupMembership 2>/dev/null | cut -d: -f2)
    
    if [[ -z "$admin_users" ]]; then
        echo "⚠️  No administrator users found"
        return 1
    fi
    
    echo "Administrator users:"
    for user in $admin_users; do
        # Verify user still exists and get additional info
        if dscl . -read "/Users/$user" &>/dev/null; then
            local real_name
            real_name=$(dscl . -read "/Users/$user" RealName 2>/dev/null | cut -d: -f2 | xargs)
            local uid
            uid=$(dscl . -read "/Users/$user" UniqueID 2>/dev/null | cut -d: -f2 | xargs)
            
            echo "  👤 $user (UID: $uid) - $real_name"
        else
            echo "  ⚠️  $user (User account not found)"
        fi
    done
    
    return 0
}

# Execute function
list_admin_users

Enterprise User Privilege Management System

#!/bin/bash

# MacFleet Enterprise User Privilege Management System
# Comprehensive access control, security compliance, and privilege monitoring

# Configuration
LOG_FILE="/var/log/macfleet_user_privileges.log"
CONFIG_DIR="/etc/macfleet/user_management"
POLICIES_DIR="$CONFIG_DIR/policies"
REPORTS_DIR="$CONFIG_DIR/reports"
COMPLIANCE_DIR="$CONFIG_DIR/compliance"
AUDIT_DIR="$CONFIG_DIR/audit"

# Security compliance frameworks
declare -A COMPLIANCE_FRAMEWORKS=(
    ["nist"]="least_privilege,separation_duties,access_review,audit_trails"
    ["iso27001"]="access_control,privilege_management,monitoring,documentation"
    ["cis"]="admin_minimization,privilege_escalation_monitoring,account_lifecycle"
    ["sox"]="financial_access_control,privilege_separation,audit_requirements"
    ["hipaa"]="minimum_necessary,access_controls,audit_logs,sanctions"
    ["pci_dss"]="unique_ids,access_control,privilege_limitation,monitoring"
)

# User role definitions
declare -A USER_ROLES=(
    ["standard"]="basic_access,file_management,application_usage"
    ["power_user"]="advanced_settings,software_installation,system_preferences"
    ["developer"]="development_tools,system_debugging,certificate_management"
    ["administrator"]="full_system_access,user_management,security_settings"
    ["security_admin"]="security_policies,audit_access,compliance_management"
    ["service_account"]="automated_processes,background_services,api_access"
)

# Privilege escalation patterns
declare -A ESCALATION_PATTERNS=(
    ["sudo_abuse"]="excessive_sudo_usage,sudo_without_password,sudo_all_commands"
    ["group_manipulation"]="unauthorized_group_addition,privilege_group_access"
    ["file_permissions"]="setuid_modifications,sensitive_file_access,system_file_changes"
    ["service_abuse"]="service_account_usage,daemon_manipulation,system_service_access"
)

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

# Setup directories
setup_directories() {
    for dir in "$CONFIG_DIR" "$POLICIES_DIR" "$REPORTS_DIR" "$COMPLIANCE_DIR" "$AUDIT_DIR"; do
        if [[ ! -d "$dir" ]]; then
            mkdir -p "$dir"
            log_action "Created directory: $dir"
        fi
    done
}

# Get comprehensive user information
get_user_details() {
    local username="$1"
    
    if [[ -z "$username" ]]; then
        return 1
    fi
    
    # Check if user exists
    if ! dscl . -read "/Users/$username" &>/dev/null; then
        return 1
    fi
    
    local user_info="{}"
    
    # Basic user information
    local uid
    uid=$(dscl . -read "/Users/$username" UniqueID 2>/dev/null | awk '{print $2}')
    local gid
    gid=$(dscl . -read "/Users/$username" PrimaryGroupID 2>/dev/null | awk '{print $2}')
    local real_name
    real_name=$(dscl . -read "/Users/$username" RealName 2>/dev/null | cut -d: -f2- | xargs)
    local home_dir
    home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory 2>/dev/null | awk '{print $2}')
    local shell
    shell=$(dscl . -read "/Users/$username" UserShell 2>/dev/null | awk '{print $2}')
    
    # Group memberships
    local groups_list
    groups_list=$(groups "$username" 2>/dev/null | cut -d: -f2)
    
    # Check admin status
    local is_admin="false"
    if groups "$username" | grep -q -w admin; then
        is_admin="true"
    fi
    
    # Last login information
    local last_login
    last_login=$(last -1 "$username" 2>/dev/null | head -1 | awk '{print $4, $5, $6, $7}' || echo "Never")
    
    # Home directory permissions
    local home_permissions=""
    if [[ -d "$home_dir" ]]; then
        home_permissions=$(ls -ld "$home_dir" | awk '{print $1}')
    fi
    
    # SSH key information
    local ssh_keys_count=0
    if [[ -d "$home_dir/.ssh" ]]; then
        ssh_keys_count=$(find "$home_dir/.ssh" -name "*.pub" 2>/dev/null | wc -l | xargs)
    fi
    
    user_info=$(cat << EOF
{
    "username": "$username",
    "uid": $uid,
    "gid": $gid,
    "real_name": "$real_name",
    "home_directory": "$home_dir",
    "shell": "$shell",
    "is_administrator": $is_admin,
    "groups": "$(echo $groups_list | sed 's/ /,/g')",
    "last_login": "$last_login",
    "home_permissions": "$home_permissions",
    "ssh_keys_count": $ssh_keys_count
}
EOF
)
    
    echo "$user_info"
}

# Comprehensive privilege audit
audit_user_privileges() {
    log_action "Starting comprehensive user privilege audit"
    
    local audit_report="$REPORTS_DIR/privilege_audit_$(date '+%Y%m%d_%H%M%S').json"
    
    cat > "$audit_report" << EOF
{
    "audit_metadata": {
        "timestamp": "$(date -Iseconds)",
        "hostname": "$(hostname)",
        "os_version": "$(sw_vers -productVersion)",
        "generator": "MacFleet User Privilege Manager"
    },
    "system_users": [
EOF

    local first=true
    local total_users=0
    local admin_users=0
    local standard_users=0
    local service_accounts=0
    
    # Get all users with UID >= 500 (regular users) and system accounts
    while IFS= read -r user; do
        local uid
        uid=$(dscl . -read "/Users/$user" UniqueID 2>/dev/null | awk '{print $2}')
        
        if [[ -n "$uid" ]]; then
            total_users=$((total_users + 1))
            
            if [[ "$first" == true ]]; then
                first=false
            else
                echo "," >> "$audit_report"
            fi
            
            local user_details
            user_details=$(get_user_details "$user")
            
            # Categorize user type
            if [[ $uid -lt 500 ]]; then
                service_accounts=$((service_accounts + 1))
            elif echo "$user_details" | jq -r '.is_administrator' | grep -q "true"; then
                admin_users=$((admin_users + 1))
            else
                standard_users=$((standard_users + 1))
            fi
            
            # Add privilege risk assessment
            local risk_score
            risk_score=$(assess_privilege_risk "$user")
            
            # Add security compliance status
            local compliance_status
            compliance_status=$(assess_user_compliance "$user")
            
            local enhanced_details
            enhanced_details=$(echo "$user_details" | jq ". + {\"privilege_risk_score\": $risk_score, \"compliance_status\": $compliance_status}")
            
            echo "        $enhanced_details" >> "$audit_report"
            
            log_action "Audited user: $user (UID: $uid)"
        fi
    done < <(dscl . list /Users | grep -v "^_")
    
    cat >> "$audit_report" << EOF
    ],
    "summary": {
        "total_users": $total_users,
        "administrator_users": $admin_users,
        "standard_users": $standard_users,
        "service_accounts": $service_accounts,
        "admin_percentage": $(awk "BEGIN {printf \"%.1f\", ($admin_users/$total_users)*100}")
    },
    "security_recommendations": $(generate_security_recommendations)
}
EOF

    log_action "✅ User privilege audit completed: $audit_report"
    echo "$audit_report"
}

# Assess privilege risk for a user
assess_privilege_risk() {
    local username="$1"
    local risk_score=0
    
    # Check if user is admin (high risk)
    if groups "$username" | grep -q -w admin; then
        risk_score=$((risk_score + 5))
    fi
    
    # Check for excessive group memberships
    local group_count
    group_count=$(groups "$username" | tr ' ' '\n' | wc -l)
    if [[ $group_count -gt 5 ]]; then
        risk_score=$((risk_score + 2))
    fi
    
    # Check for sudo usage patterns
    local sudo_entries
    sudo_entries=$(grep "sudo.*$username" /var/log/auth.log 2>/dev/null | wc -l || echo 0)
    if [[ $sudo_entries -gt 50 ]]; then
        risk_score=$((risk_score + 3))
    elif [[ $sudo_entries -gt 10 ]]; then
        risk_score=$((risk_score + 1))
    fi
    
    # Check for SSH keys (potential lateral movement)
    local home_dir
    home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory 2>/dev/null | awk '{print $2}')
    if [[ -d "$home_dir/.ssh" ]]; then
        local key_count
        key_count=$(find "$home_dir/.ssh" -name "*.pub" 2>/dev/null | wc -l)
        if [[ $key_count -gt 3 ]]; then
            risk_score=$((risk_score + 2))
        fi
    fi
    
    # Check for service account patterns
    if [[ "$username" =~ ^(service|daemon|app).*$ ]]; then
        risk_score=$((risk_score + 1))
    fi
    
    # Cap at 10
    if [[ $risk_score -gt 10 ]]; then
        risk_score=10
    fi
    
    echo "$risk_score"
}

# Assess user compliance with security frameworks
assess_user_compliance() {
    local username="$1"
    
    local compliance_issues=0
    local total_checks=4
    
    # Check 1: Least privilege principle
    if groups "$username" | grep -q -w admin; then
        # Admin users need justification
        if [[ ! -f "$POLICIES_DIR/admin_justification_$username.conf" ]]; then
            compliance_issues=$((compliance_issues + 1))
        fi
    fi
    
    # Check 2: Account activity
    local last_login
    last_login=$(last -1 "$username" | head -1 | awk '{print $4}' | grep -v "^$")
    if [[ -z "$last_login" || "$last_login" == "Never" ]]; then
        compliance_issues=$((compliance_issues + 1))
    fi
    
    # Check 3: Home directory permissions
    local home_dir
    home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory 2>/dev/null | awk '{print $2}')
    if [[ -d "$home_dir" ]]; then
        local perms
        perms=$(ls -ld "$home_dir" | cut -c1-10)
        if [[ "$perms" =~ ^d.......w.$ ]] || [[ "$perms" =~ ^d........w$ ]]; then
            compliance_issues=$((compliance_issues + 1))
        fi
    fi
    
    # Check 4: Password policy compliance
    local password_policy_compliant="true"
    # This would typically integrate with password policy checking
    # For demo purposes, we'll assume compliance
    
    local compliance_score
    compliance_score=$(awk "BEGIN {printf \"%.0f\", (($total_checks - $compliance_issues)/$total_checks)*100}")
    
    local status="compliant"
    if [[ $compliance_score -lt 80 ]]; then
        status="non_compliant"
    elif [[ $compliance_score -lt 90 ]]; then
        status="needs_attention"
    fi
    
    echo "{\"score\": $compliance_score, \"status\": \"$status\", \"issues\": $compliance_issues}"
}

# Monitor privilege escalation attempts
monitor_privilege_escalation() {
    log_action "Starting privilege escalation monitoring"
    
    local monitoring_report="$AUDIT_DIR/privilege_escalation_$(date '+%Y%m%d_%H%M%S').json"
    
    cat > "$monitoring_report" << EOF
{
    "monitoring_metadata": {
        "timestamp": "$(date -Iseconds)",
        "hostname": "$(hostname)",
        "monitoring_period": "last_24_hours"
    },
    "escalation_events": [
EOF

    local first=true
    local event_count=0
    
    # Monitor sudo usage
    if [[ -f "/var/log/auth.log" ]]; then
        local sudo_events
        sudo_events=$(grep "sudo" /var/log/auth.log | tail -50)
        
        while IFS= read -r line; do
            if [[ -n "$line" ]]; then
                if [[ "$first" == true ]]; then
                    first=false
                else
                    echo "," >> "$monitoring_report"
                fi
                
                local timestamp
                timestamp=$(echo "$line" | awk '{print $1, $2, $3}')
                local user
                user=$(echo "$line" | grep -o "USER=[^ ]*" | cut -d= -f2)
                local command
                command=$(echo "$line" | grep -o "COMMAND=.*" | cut -d= -f2-)
                
                cat >> "$monitoring_report" << EOF
        {
            "type": "sudo_usage",
            "timestamp": "$timestamp",
            "user": "$user",
            "command": "$command",
            "risk_level": "$(assess_command_risk "$command")"
        }
EOF
                event_count=$((event_count + 1))
            fi
        done <<< "$sudo_events"
    fi
    
    # Monitor group membership changes
    local group_changes
    group_changes=$(grep "group" /var/log/system.log 2>/dev/null | grep -E "(add|remove)" | tail -10)
    
    while IFS= read -r line; do
        if [[ -n "$line" ]]; then
            if [[ "$first" == true ]]; then
                first=false
            else
                echo "," >> "$monitoring_report"
            fi
            
            cat >> "$monitoring_report" << EOF
        {
            "type": "group_change",
            "event": "$line",
            "risk_level": "medium"
        }
EOF
            event_count=$((event_count + 1))
        fi
    done <<< "$group_changes"
    
    cat >> "$monitoring_report" << EOF
    ],
    "summary": {
        "total_events": $event_count,
        "high_risk_events": $(grep -c '"risk_level": "high"' "$monitoring_report" 2>/dev/null || echo 0),
        "medium_risk_events": $(grep -c '"risk_level": "medium"' "$monitoring_report" 2>/dev/null || echo 0)
    }
}
EOF

    log_action "✅ Privilege escalation monitoring completed: $monitoring_report"
    echo "$monitoring_report"
}

# Assess command risk level
assess_command_risk() {
    local command="$1"
    
    # High-risk commands
    if echo "$command" | grep -qE "(rm -rf|chmod 777|chown root|passwd|visudo|su -|sudo su)"; then
        echo "high"
    # Medium-risk commands
    elif echo "$command" | grep -qE "(install|update|systemctl|launchctl|diskutil)"; then
        echo "medium"
    # Low-risk commands
    else
        echo "low"
    fi
}

# Apply security policies
apply_security_policy() {
    local policy_name="$1"
    local target_users="$2"
    
    log_action "Applying security policy: $policy_name"
    
    # Get target users
    local users=()
    if [[ -n "$target_users" ]]; then
        IFS=',' read -ra users <<< "$target_users"
    else
        # Apply to all non-system users
        while IFS= read -r user; do
            local uid
            uid=$(dscl . -read "/Users/$user" UniqueID 2>/dev/null | awk '{print $2}')
            if [[ $uid -ge 500 ]]; then
                users+=("$user")
            fi
        done < <(dscl . list /Users | grep -v "^_")
    fi
    
    for user in "${users[@]}"; do
        case "$policy_name" in
            "least_privilege")
                enforce_least_privilege "$user"
                ;;
            "admin_review")
                review_admin_privileges "$user"
                ;;
            "password_policy")
                enforce_password_policy "$user"
                ;;
            "session_limits")
                configure_session_limits "$user"
                ;;
            *)
                log_action "⚠️  Unknown policy: $policy_name"
                ;;
        esac
    done
    
    log_action "✅ Security policy '$policy_name' applied"
}

# Enforce least privilege principle
enforce_least_privilege() {
    local username="$1"
    
    log_action "Enforcing least privilege for user: $username"
    
    # Check if user really needs admin privileges
    if groups "$username" | grep -q -w admin; then
        local justification_file="$POLICIES_DIR/admin_justification_$username.conf"
        
        if [[ ! -f "$justification_file" ]]; then
            log_action "⚠️  Admin user '$username' lacks justification documentation"
            
            # Create justification template
            cat > "$justification_file" << EOF
# Admin Justification for User: $username
# Created: $(date)
# Status: PENDING_REVIEW

BUSINESS_JUSTIFICATION=""
APPROVED_BY=""
APPROVAL_DATE=""
REVIEW_DATE=""
REVOCATION_DATE=""

# Risk Assessment
PRIVILEGE_LEVEL="admin"
JUSTIFICATION_SCORE=0
REVIEW_REQUIRED=true

# Notes
COMMENTS=""
EOF
            
            log_action "📝 Created justification template: $justification_file"
        fi
    fi
}

# Generate security recommendations
generate_security_recommendations() {
    local recommendations='['
    local first=true
    
    # Get admin user count
    local admin_count
    admin_count=$(dscl . -read /Groups/admin GroupMembership 2>/dev/null | wc -w)
    
    if [[ $admin_count -gt 5 ]]; then
        if [[ "$first" == true ]]; then
            first=false
        else
            recommendations+=','
        fi
        recommendations+='"Consider reducing number of administrator accounts for better security"'
    fi
    
    # Check for unused accounts
    local unused_accounts=0
    while IFS= read -r user; do
        local last_login
        last_login=$(last -1 "$user" | head -1 | awk '{print $4}')
        if [[ -z "$last_login" || "$last_login" == "Never" ]]; then
            unused_accounts=$((unused_accounts + 1))
        fi
    done < <(dscl . list /Users | grep -v "^_")
    
    if [[ $unused_accounts -gt 0 ]]; then
        if [[ "$first" == true ]]; then
            first=false
        else
            recommendations+=','
        fi
        recommendations+="\"Consider disabling or removing $unused_accounts unused user accounts\""
    fi
    
    # Add default recommendations
    if [[ "$first" == true ]]; then
        first=false
    else
        recommendations+=','
    fi
    recommendations+='"Implement regular privilege review cycles"'
    
    recommendations+=','
    recommendations+='"Enable comprehensive audit logging"'
    
    recommendations+=','
    recommendations+='"Configure automated privilege escalation monitoring"'
    
    recommendations+=']'
    echo "$recommendations"
}

# Generate compliance report
generate_compliance_report() {
    local framework="$1"
    
    log_action "Generating compliance report for framework: $framework"
    
    local compliance_report="$COMPLIANCE_DIR/compliance_${framework}_$(date '+%Y%m%d_%H%M%S').json"
    
    cat > "$compliance_report" << EOF
{
    "compliance_metadata": {
        "timestamp": "$(date -Iseconds)",
        "framework": "$framework",
        "hostname": "$(hostname)",
        "generator": "MacFleet User Privilege Compliance Manager"
    },
    "framework_requirements": $(get_framework_requirements "$framework"),
    "compliance_assessment": {
        "overall_score": $(calculate_overall_compliance "$framework"),
        "user_compliance": $(assess_all_users_compliance "$framework"),
        "policy_compliance": $(assess_policy_compliance "$framework"),
        "recommendations": $(generate_compliance_recommendations "$framework")
    }
}
EOF

    log_action "✅ Compliance report generated: $compliance_report"
    echo "$compliance_report"
}

# Get framework requirements
get_framework_requirements() {
    local framework="$1"
    
    case "$framework" in
        "nist")
            echo '{"least_privilege": true, "separation_of_duties": true, "access_review": true, "audit_trails": true}'
            ;;
        "iso27001")
            echo '{"access_control": true, "privilege_management": true, "monitoring": true, "documentation": true}'
            ;;
        "cis")
            echo '{"admin_minimization": true, "privilege_escalation_monitoring": true, "account_lifecycle": true}'
            ;;
        *)
            echo '{"basic_access_control": true, "user_management": true}'
            ;;
    esac
}

# Calculate overall compliance score
calculate_overall_compliance() {
    local framework="$1"
    
    local total_score=0
    local check_count=0
    
    # Basic compliance checks
    check_count=$((check_count + 1))
    local admin_count
    admin_count=$(dscl . -read /Groups/admin GroupMembership 2>/dev/null | wc -w)
    if [[ $admin_count -le 5 ]]; then
        total_score=$((total_score + 20))
    fi
    
    check_count=$((check_count + 1))
    if [[ -f "$LOG_FILE" ]]; then
        total_score=$((total_score + 20))
    fi
    
    check_count=$((check_count + 1))
    if [[ -d "$POLICIES_DIR" ]]; then
        total_score=$((total_score + 20))
    fi
    
    # Framework-specific checks
    case "$framework" in
        "nist")
            check_count=$((check_count + 2))
            # Check for privilege documentation
            if find "$POLICIES_DIR" -name "admin_justification_*.conf" | grep -q .; then
                total_score=$((total_score + 20))
            fi
            # Check for audit capabilities
            if [[ -d "$AUDIT_DIR" ]]; then
                total_score=$((total_score + 20))
            fi
            ;;
    esac
    
    local final_score
    final_score=$(awk "BEGIN {printf \"%.0f\", ($total_score/$check_count)}")
    
    echo "$final_score"
}

# Main execution function
main() {
    local action="${1:-audit}"
    local parameter="$2"
    local additional_param="$3"
    
    log_action "=== MacFleet User Privilege Management Started ==="
    log_action "Action: $action"
    log_action "Parameter: ${parameter:-N/A}"
    
    setup_directories
    
    case "$action" in
        "check")
            if [[ -z "$parameter" ]]; then
                echo "Usage: $0 check <username>"
                exit 1
            fi
            check_user_admin_status "$parameter"
            ;;
        "list")
            list_admin_users
            ;;
        "audit")
            audit_user_privileges
            ;;
        "monitor")
            monitor_privilege_escalation
            ;;
        "policy")
            if [[ -z "$parameter" ]]; then
                echo "Available security policies:"
                echo "  - least_privilege"
                echo "  - admin_review"
                echo "  - password_policy"
                echo "  - session_limits"
                echo ""
                echo "Usage: $0 policy <policy_name> [target_users]"
                exit 1
            fi
            apply_security_policy "$parameter" "$additional_param"
            ;;
        "compliance")
            if [[ -z "$parameter" ]]; then
                echo "Available compliance frameworks:"
                for framework in "${!COMPLIANCE_FRAMEWORKS[@]}"; do
                    echo "  - $framework: ${COMPLIANCE_FRAMEWORKS[$framework]}"
                done
                echo ""
                echo "Usage: $0 compliance <framework>"
                exit 1
            fi
            generate_compliance_report "$parameter"
            ;;
        "details")
            if [[ -z "$parameter" ]]; then
                echo "Usage: $0 details <username>"
                exit 1
            fi
            get_user_details "$parameter" | jq .
            ;;
        *)
            echo "Usage: $0 {check|list|audit|monitor|policy|compliance|details}"
            echo "  check       - Check if specific user is administrator"
            echo "  list        - List all administrator users"
            echo "  audit       - Generate comprehensive privilege audit"
            echo "  monitor     - Monitor privilege escalation attempts"
            echo "  policy      - Apply security policy to users"
            echo "  compliance  - Generate compliance report"
            echo "  details     - Get detailed user information"
            exit 1
            ;;
    esac
    
    log_action "=== User privilege management completed ==="
}

# Execute main function
main "$@"

Advanced User Management Features

Role-Based Access Control (RBAC)

#!/bin/bash

# Implement role-based access control system
implement_rbac() {
    echo "=== Role-Based Access Control Implementation ==="
    
    local rbac_config="$CONFIG_DIR/rbac_configuration.json"
    
    cat > "$rbac_config" << EOF
{
    "rbac_configuration": {
        "roles": {
            "standard_user": {
                "permissions": ["read_files", "run_applications", "modify_user_preferences"],
                "groups": ["users"],
                "restrictions": ["no_system_modifications", "no_user_creation"]
            },
            "power_user": {
                "permissions": ["install_software", "modify_system_preferences", "access_dev_tools"],
                "groups": ["users", "developer"],
                "restrictions": ["no_user_management", "no_security_settings"]
            },
            "administrator": {
                "permissions": ["full_system_access", "user_management", "security_configuration"],
                "groups": ["admin", "users"],
                "restrictions": ["audit_required", "justification_needed"]
            },
            "security_admin": {
                "permissions": ["security_policies", "audit_access", "compliance_management"],
                "groups": ["admin", "security"],
                "restrictions": ["dual_approval_required"]
            }
        },
        "assignment_rules": {
            "auto_assignment": false,
            "approval_required": true,
            "review_period": "90_days"
        }
    }
}
EOF

    echo "📋 RBAC configuration created: $rbac_config"
}

# Assign role to user
assign_user_role() {
    local username="$1"
    local role="$2"
    
    if [[ -z "$username" || -z "$role" ]]; then
        echo "Usage: assign_user_role <username> <role>"
        return 1
    fi
    
    echo "👤 Assigning role '$role' to user '$username'"
    
    # Create role assignment record
    local role_file="$POLICIES_DIR/role_assignment_$username.conf"
    
    cat > "$role_file" << EOF
# Role Assignment for User: $username
# Assigned: $(date)

ASSIGNED_ROLE="$role"
ASSIGNED_BY="$(whoami)"
ASSIGNMENT_DATE="$(date -Iseconds)"
REVIEW_DATE="$(date -d '+90 days' -Iseconds)"
JUSTIFICATION=""

# Role Permissions
$(grep -A 10 "\"$role\":" "$CONFIG_DIR/rbac_configuration.json" 2>/dev/null || echo "# Role definition not found")

# Approval Status
APPROVAL_STATUS="pending"
APPROVED_BY=""
APPROVAL_DATE=""
EOF

    log_action "Role '$role' assigned to user '$username'"
}

Automated Compliance Monitoring

#!/bin/bash

# Continuous compliance monitoring
continuous_compliance_monitoring() {
    echo "=== Continuous Compliance Monitoring ==="
    
    local monitoring_config="$CONFIG_DIR/compliance_monitoring.conf"
    
    cat > "$monitoring_config" << EOF
# MacFleet Compliance Monitoring Configuration

# Monitoring Intervals
PRIVILEGE_CHECK_INTERVAL=3600    # 1 hour
AUDIT_INTERVAL=86400            # 24 hours
COMPLIANCE_REPORT_INTERVAL=604800  # 1 week

# Alert Thresholds
MAX_ADMIN_USERS=5
MAX_PRIVILEGE_RISK_SCORE=7
MAX_INACTIVE_DAYS=30

# Compliance Frameworks
ENABLED_FRAMEWORKS="nist,iso27001,cis"

# Notification Settings
ALERT_EMAIL="security@company.com"
SLACK_WEBHOOK_URL=""

# Remediation Settings
AUTO_REMEDIATION=false
REQUIRE_APPROVAL=true
EOF

    # Create monitoring daemon
    local daemon_script="/usr/local/bin/macfleet-compliance-monitor"
    
    cat > "$daemon_script" << 'EOF'
#!/bin/bash

# MacFleet Compliance Monitoring Daemon
source /etc/macfleet/user_management/compliance_monitoring.conf

while true; do
    # Run privilege checks
    /usr/local/bin/macfleet-user-management audit
    
    # Check for compliance violations
    /usr/local/bin/macfleet-user-management monitor
    
    # Sleep until next check
    sleep $PRIVILEGE_CHECK_INTERVAL
done
EOF

    chmod +x "$daemon_script"
    
    echo "🔄 Compliance monitoring configured"
}

Security Best Practices

🔐 Privilege Management

  • Least privilege principle with regular access reviews and justification requirements
  • Role-based access control with predefined permission sets and approval workflows
  • Privilege escalation monitoring with real-time detection and alerting
  • Administrative account minimization with documented justifications for admin access

📊 Compliance and Auditing

  • Multi-framework support (NIST, ISO 27001, CIS, SOX, HIPAA, PCI DSS)
  • Continuous compliance monitoring with automated assessment and reporting
  • Comprehensive audit trails with detailed logging and forensic capabilities
  • Regular compliance reporting with risk scoring and remediation recommendations

🛡️ Security Controls

  • Access control enforcement with group membership validation and permission monitoring
  • Session management with timeout controls and concurrent session limits
  • Security policy automation with fleet-wide deployment and compliance tracking
  • Incident response with automated detection and notification capabilities

🔧 Enterprise Operations

  • Fleet-wide user management with centralized policy deployment and monitoring
  • Automated onboarding/offboarding with role assignment and access provisioning
  • Integration capabilities with existing identity management and security systems
  • Scalable architecture supporting thousands of devices and users

Important Notes

  • Administrative privileges should be granted sparingly and with proper justification
  • Regular access reviews are essential for maintaining security compliance
  • Monitoring configurations should be tailored to organizational security requirements
  • Compliance frameworks may require specific documentation and audit procedures
  • Emergency access procedures should be established for critical system access
  • User training on privilege management and security policies improves overall 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.