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.

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

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.