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.

Password Change Management on macOS

Securely manage password change operations across your MacFleet deployment with enterprise-grade security controls, policy enforcement, and comprehensive audit capabilities. This tutorial transforms the basic dscl command into a robust password management solution suitable for enterprise environments.

Understanding Enterprise Password Management

Enterprise password change operations require robust security measures beyond basic directory service commands:

  • Password policy enforcement to ensure security standards
  • Secure credential handling to prevent exposure
  • Comprehensive audit logging for compliance tracking
  • Multi-factor authentication integration for enhanced security
  • Privilege validation to ensure proper authorization
  • Keychain synchronization for seamless user experience

Core Password Change Operation

Basic Password Change Command

# Basic password change using dscl
sudo dscl . -passwd /Users/username currentpassword newpassword

This utilizes the directory service command-line utility (dscl) to modify user directory data, specifically the password field.

Enterprise Password Change Management System

#!/bin/bash

# MacFleet Enterprise Password Change Management System
# Secure password change operations with comprehensive enterprise controls

# Configuration
SCRIPT_NAME="MacFleet Password Change Manager"
VERSION="1.0.0"
LOG_FILE="/var/log/macfleet_password_operations.log"
AUDIT_LOG="/var/log/macfleet_password_audit.log"
POLICY_FILE="/etc/macfleet/password_policy.conf"
TEMP_DIR="/tmp/macfleet_password"
SECURE_LOG_RETENTION_DAYS=365
MAX_LOGIN_ATTEMPTS=3
PASSWORD_HISTORY_COUNT=12
LOCKOUT_DURATION=1800  # 30 minutes
MIN_PASSWORD_LENGTH=12
MAX_PASSWORD_LENGTH=128
COMPLEXITY_REQUIREMENTS=true
BUSINESS_HOURS_START=9
BUSINESS_HOURS_END=17
EMERGENCY_CONTACTS=("security@company.com" "admin@company.com")

# Password complexity requirements
REQUIRE_UPPERCASE=true
REQUIRE_LOWERCASE=true
REQUIRE_NUMBERS=true
REQUIRE_SPECIAL_CHARS=true
FORBIDDEN_PATTERNS=("password" "123456" "qwerty" "admin" "root")

# Create necessary directories
mkdir -p "$TEMP_DIR"
mkdir -p "$(dirname "$LOG_FILE")"
mkdir -p "$(dirname "$AUDIT_LOG")"
mkdir -p "$(dirname "$POLICY_FILE")"

# Set secure permissions
chmod 700 "$TEMP_DIR"
touch "$LOG_FILE" && chmod 640 "$LOG_FILE"
touch "$AUDIT_LOG" && chmod 600 "$AUDIT_LOG"

# Logging functions
log_operation() {
    local level="$1"
    local message="$2"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local username=$(whoami)
    echo "[$timestamp] [$level] [$username] $message" | tee -a "$LOG_FILE"
}

log_security_event() {
    local event_type="$1"
    local username="$2"
    local details="$3"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local source_ip=$(who am i | awk '{print $5}' | tr -d '()')
    local session_id=$(who am i | awk '{print $2}')
    
    {
        echo "SECURITY_EVENT|$timestamp|$event_type|$username|$source_ip|$session_id|$details"
    } >> "$AUDIT_LOG"
    
    log_operation "SECURITY" "$event_type for user $username: $details"
}

# Check if current time is within business hours
is_business_hours() {
    local current_hour=$(date +%H)
    if [[ $current_hour -ge $BUSINESS_HOURS_START && $current_hour -lt $BUSINESS_HOURS_END ]]; then
        return 0
    else
        return 1
    fi
}

# Check if user exists
user_exists() {
    local username="$1"
    dscl . -read "/Users/$username" &>/dev/null
    return $?
}

# Check if user is system account
is_system_account() {
    local username="$1"
    local uid=$(dscl . -read "/Users/$username" UniqueID 2>/dev/null | awk '{print $2}')
    
    # System accounts typically have UID < 500
    if [[ -n "$uid" && $uid -lt 500 ]]; then
        return 0
    fi
    
    # Check for common system accounts
    local system_accounts=("root" "daemon" "nobody" "_www" "_mysql" "_postgres")
    for sys_account in "${system_accounts[@]}"; do
        if [[ "$username" == "$sys_account" ]]; then
            return 0
        fi
    done
    
    return 1
}

# Validate current user has permission to change password
validate_permission() {
    local target_username="$1"
    local current_user=$(whoami)
    
    # Root can change any password
    if [[ "$current_user" == "root" ]]; then
        return 0
    fi
    
    # Users can change their own password
    if [[ "$current_user" == "$target_username" ]]; then
        return 0
    fi
    
    # Check if current user is admin
    if dseditgroup -o checkmember -m "$current_user" admin &>/dev/null; then
        return 0
    fi
    
    log_security_event "PERMISSION_DENIED" "$target_username" "User $current_user attempted unauthorized password change"
    return 1
}

# Generate secure random password
generate_secure_password() {
    local length="${1:-16}"
    local password=""
    local attempts=0
    local max_attempts=10
    
    while [[ $attempts -lt $max_attempts ]]; do
        # Generate password with mixed character set
        password=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-"$length")
        
        # Add special characters
        password="${password}$(openssl rand -base64 4 | tr -d "=+/" | tr 'A-Za-z0-9' '@#$%&*' | cut -c1-2)"
        
        # Validate password meets requirements
        if validate_password_complexity "$password"; then
            echo "$password"
            return 0
        fi
        
        ((attempts++))
    done
    
    log_operation "ERROR" "Failed to generate secure password after $max_attempts attempts"
    return 1
}

# Validate password complexity
validate_password_complexity() {
    local password="$1"
    local length=${#password}
    
    # Check length requirements
    if [[ $length -lt $MIN_PASSWORD_LENGTH ]]; then
        log_operation "WARNING" "Password too short: $length < $MIN_PASSWORD_LENGTH"
        return 1
    fi
    
    if [[ $length -gt $MAX_PASSWORD_LENGTH ]]; then
        log_operation "WARNING" "Password too long: $length > $MAX_PASSWORD_LENGTH"
        return 1
    fi
    
    if [[ "$COMPLEXITY_REQUIREMENTS" == "true" ]]; then
        # Check for uppercase letters
        if [[ "$REQUIRE_UPPERCASE" == "true" ]] && ! [[ "$password" =~ [A-Z] ]]; then
            log_operation "WARNING" "Password missing uppercase letters"
            return 1
        fi
        
        # Check for lowercase letters
        if [[ "$REQUIRE_LOWERCASE" == "true" ]] && ! [[ "$password" =~ [a-z] ]]; then
            log_operation "WARNING" "Password missing lowercase letters"
            return 1
        fi
        
        # Check for numbers
        if [[ "$REQUIRE_NUMBERS" == "true" ]] && ! [[ "$password" =~ [0-9] ]]; then
            log_operation "WARNING" "Password missing numbers"
            return 1
        fi
        
        # Check for special characters
        if [[ "$REQUIRE_SPECIAL_CHARS" == "true" ]] && ! [[ "$password" =~ [^a-zA-Z0-9] ]]; then
            log_operation "WARNING" "Password missing special characters"
            return 1
        fi
    fi
    
    # Check for forbidden patterns
    local password_lower=$(echo "$password" | tr '[:upper:]' '[:lower:]')
    for pattern in "${FORBIDDEN_PATTERNS[@]}"; do
        if [[ "$password_lower" == *"$pattern"* ]]; then
            log_operation "WARNING" "Password contains forbidden pattern: $pattern"
            return 1
        fi
    done
    
    return 0
}

# Check password history
check_password_history() {
    local username="$1"
    local new_password="$2"
    local history_file="/var/db/macfleet/password_history/$username"
    
    if [[ ! -f "$history_file" ]]; then
        return 0  # No history, password is acceptable
    fi
    
    # Hash new password for comparison
    local new_hash=$(echo -n "$new_password" | shasum -a 256 | cut -d' ' -f1)
    
    # Check against stored hashes
    if grep -q "$new_hash" "$history_file"; then
        log_operation "WARNING" "Password reuse detected for user $username"
        return 1
    fi
    
    return 0
}

# Store password in history
store_password_history() {
    local username="$1"
    local password="$2"
    local history_dir="/var/db/macfleet/password_history"
    local history_file="$history_dir/$username"
    
    # Create directory if it doesn't exist
    mkdir -p "$history_dir"
    chmod 700 "$history_dir"
    
    # Hash password
    local password_hash=$(echo -n "$password" | shasum -a 256 | cut -d' ' -f1)
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    # Add to history
    echo "$timestamp:$password_hash" >> "$history_file"
    chmod 600 "$history_file"
    
    # Maintain history count
    if [[ $(wc -l < "$history_file") -gt $PASSWORD_HISTORY_COUNT ]]; then
        tail -n "$PASSWORD_HISTORY_COUNT" "$history_file" > "$history_file.tmp"
        mv "$history_file.tmp" "$history_file"
    fi
}

# Verify current password
verify_current_password() {
    local username="$1"
    local current_password="$2"
    
    # Use dscl to verify password
    if dscl . -authonly "$username" "$current_password" &>/dev/null; then
        return 0
    else
        log_security_event "AUTH_FAILURE" "$username" "Current password verification failed"
        return 1
    fi
}

# Update keychain password
update_keychain_password() {
    local username="$1"
    local old_password="$2"
    local new_password="$3"
    
    log_operation "INFO" "Updating keychain password for user $username"
    
    # Get user's home directory
    local home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory | awk '{print $2}')
    local keychain_path="$home_dir/Library/Keychains/login.keychain-db"
    
    if [[ -f "$keychain_path" ]]; then
        # Update keychain password
        if su "$username" -c "security unlock-keychain -p '$old_password' '$keychain_path' && security set-keychain-password -o '$old_password' -p '$new_password' '$keychain_path'" &>/dev/null; then
            log_operation "SUCCESS" "Keychain password updated for user $username"
            return 0
        else
            log_operation "WARNING" "Failed to update keychain password for user $username"
            return 1
        fi
    else
        log_operation "INFO" "No keychain found for user $username"
        return 0
    fi
}

# Force password change on next login
force_password_change_on_login() {
    local username="$1"
    
    # Set password change required flag
    if dscl . -create "/Users/$username" accountPolicyData '<dict><key>isDisabled</key><false/><key>isAdminUser</key><false/><key>newPasswordRequired</key><true/></dict>'; then
        log_operation "SUCCESS" "Password change on next login set for user $username"
        return 0
    else
        log_operation "ERROR" "Failed to set password change requirement for user $username"
        return 1
    fi
}

# Send notification to security team
send_security_notification() {
    local event_type="$1"
    local username="$2"
    local details="$3"
    
    local subject="MacFleet Security Alert: $event_type"
    local message="Security Event Details:
Event: $event_type
User: $username
Time: $(date)
Host: $(hostname)
Details: $details

This is an automated security notification from MacFleet Password Management System."
    
    for email in "${EMERGENCY_CONTACTS[@]}"; do
        echo "$message" | mail -s "$subject" "$email" 2>/dev/null || true
    done
}

# Enterprise password change function
enterprise_change_password() {
    local username="$1"
    local current_password="$2"
    local new_password="$3"
    local force_change="${4:-false}"
    local bypass_history="${5:-false}"
    
    local operation_id=$(date +%s)
    log_operation "INFO" "Starting password change operation [$operation_id] for user: $username"
    
    # Validate user exists
    if ! user_exists "$username"; then
        log_operation "ERROR" "User does not exist: $username"
        log_security_event "USER_NOT_FOUND" "$username" "Password change attempted for non-existent user"
        return 1
    fi
    
    # Check if system account
    if is_system_account "$username"; then
        log_operation "ERROR" "Cannot change password for system account: $username"
        log_security_event "SYSTEM_ACCOUNT_ACCESS" "$username" "Attempted password change on system account"
        send_security_notification "SYSTEM_ACCOUNT_ACCESS" "$username" "Attempted password change on system account"
        return 1
    fi
    
    # Validate permissions
    if ! validate_permission "$username"; then
        log_operation "ERROR" "Permission denied for password change: $username"
        return 1
    fi
    
    # Verify current password (unless forced)
    if [[ "$force_change" != "true" ]]; then
        if ! verify_current_password "$username" "$current_password"; then
            log_operation "ERROR" "Current password verification failed for user: $username"
            return 1
        fi
    fi
    
    # Validate new password complexity
    if ! validate_password_complexity "$new_password"; then
        log_operation "ERROR" "New password does not meet complexity requirements for user: $username"
        return 1
    fi
    
    # Check password history (unless bypassed)
    if [[ "$bypass_history" != "true" ]]; then
        if ! check_password_history "$username" "$new_password"; then
            log_operation "ERROR" "Password reuse detected for user: $username"
            return 1
        fi
    fi
    
    # Create secure temporary files
    local temp_script="$TEMP_DIR/change_password_${operation_id}.sh"
    local temp_log="$TEMP_DIR/change_password_${operation_id}.log"
    
    # Change password using dscl
    log_operation "INFO" "Executing password change for user: $username"
    
    if [[ "$force_change" == "true" ]]; then
        # Force change without current password
        if dscl . -passwd "/Users/$username" "$new_password" 2>"$temp_log"; then
            local result=0
        else
            local result=1
        fi
    else
        # Normal change with current password verification
        if dscl . -passwd "/Users/$username" "$current_password" "$new_password" 2>"$temp_log"; then
            local result=0
        else
            local result=1
        fi
    fi
    
    # Check result
    if [[ $result -eq 0 ]]; then
        log_operation "SUCCESS" "Password changed successfully [$operation_id] for user: $username"
        log_security_event "PASSWORD_CHANGED" "$username" "Password changed successfully"
        
        # Store in password history
        store_password_history "$username" "$new_password"
        
        # Update keychain if not forced change
        if [[ "$force_change" != "true" ]]; then
            update_keychain_password "$username" "$current_password" "$new_password"
        fi
        
        # Clear temporary files securely
        shred -vfz -n 3 "$temp_script" "$temp_log" 2>/dev/null || {
            rm -f "$temp_script" "$temp_log"
        }
        
        return 0
    else
        log_operation "ERROR" "Password change failed [$operation_id] for user: $username"
        log_security_event "PASSWORD_CHANGE_FAILED" "$username" "Password change operation failed"
        
        # Log error details
        if [[ -f "$temp_log" ]]; then
            local error_msg=$(cat "$temp_log")
            log_operation "ERROR" "dscl error: $error_msg"
        fi
        
        # Clear temporary files securely
        shred -vfz -n 3 "$temp_script" "$temp_log" 2>/dev/null || {
            rm -f "$temp_script" "$temp_log"
        }
        
        return 1
    fi
}

# Bulk password change operation
bulk_password_change() {
    local users_file="$1"
    local password_source="${2:-generate}"  # "generate" or "file"
    local password_file="$3"
    
    if [[ ! -f "$users_file" ]]; then
        log_operation "ERROR" "Users file not found: $users_file"
        return 1
    fi
    
    local total_users=$(grep -v '^#\|^$' "$users_file" | wc -l)
    local current_user=0
    local success_count=0
    local failure_count=0
    
    log_operation "INFO" "Starting bulk password change operation - Total users: $total_users"
    
    while IFS='|' read -r username current_password force_change; do
        # Skip empty lines and comments
        [[ -z "$username" || "$username" =~ ^#.* ]] && continue
        
        ((current_user++))
        
        # Trim whitespace
        username=$(echo "$username" | xargs)
        current_password=$(echo "$current_password" | xargs)
        force_change=$(echo "$force_change" | xargs)
        
        echo "Processing [$current_user/$total_users]: $username"
        
        # Generate or get new password
        local new_password
        if [[ "$password_source" == "generate" ]]; then
            new_password=$(generate_secure_password)
            if [[ $? -ne 0 ]]; then
                log_operation "ERROR" "Failed to generate password for user: $username"
                ((failure_count++))
                continue
            fi
        elif [[ "$password_source" == "file" && -f "$password_file" ]]; then
            new_password=$(sed -n "${current_user}p" "$password_file")
            if [[ -z "$new_password" ]]; then
                log_operation "ERROR" "No password found in file for user: $username"
                ((failure_count++))
                continue
            fi
        else
            log_operation "ERROR" "Invalid password source or file not found"
            ((failure_count++))
            continue
        fi
        
        # Change password
        if enterprise_change_password "$username" "$current_password" "$new_password" "$force_change"; then
            ((success_count++))
            
            # Save generated password securely if needed
            if [[ "$password_source" == "generate" ]]; then
                local password_output="/tmp/macfleet_passwords_$(date +%s).txt"
                echo "$username:$new_password" >> "$password_output"
                chmod 600 "$password_output"
            fi
        else
            ((failure_count++))
        fi
        
        # Progress update
        local progress=$((current_user * 100 / total_users))
        echo "Progress: $progress% ($success_count successful, $failure_count failed)"
        
    done < "$users_file"
    
    log_operation "SUCCESS" "Bulk password change completed - Success: $success_count, Failed: $failure_count"
    
    if [[ "$password_source" == "generate" && -f "$password_output" ]]; then
        echo "Generated passwords saved to: $password_output"
        echo "WARNING: This file contains sensitive data. Handle appropriately and delete when no longer needed."
    fi
    
    return $failure_count
}

# Password expiration management
manage_password_expiration() {
    local username="$1"
    local expiration_days="${2:-90}"
    local action="${3:-set}"  # "set", "remove", "check"
    
    case "$action" in
        "set")
            local expiration_date=$(date -v+${expiration_days}d '+%Y-%m-%d %H:%M:%S')
            if dscl . -create "/Users/$username" accountPolicyData "<dict><key>passwordLastSetTime</key><date>$(date -u '+%Y-%m-%dT%H:%M:%SZ')</date><key>maxMinutesUntilChangePassword</key><integer>$((expiration_days * 24 * 60))</integer></dict>"; then
                log_operation "SUCCESS" "Password expiration set for user $username: $expiration_days days"
                return 0
            else
                log_operation "ERROR" "Failed to set password expiration for user $username"
                return 1
            fi
            ;;
        "remove")
            if dscl . -delete "/Users/$username" accountPolicyData; then
                log_operation "SUCCESS" "Password expiration removed for user $username"
                return 0
            else
                log_operation "ERROR" "Failed to remove password expiration for user $username"
                return 1
            fi
            ;;
        "check")
            local policy_data=$(dscl . -read "/Users/$username" accountPolicyData 2>/dev/null)
            if [[ -n "$policy_data" ]]; then
                echo "Password expiration policy exists for user $username"
                echo "$policy_data"
                return 0
            else
                echo "No password expiration policy for user $username"
                return 1
            fi
            ;;
    esac
}

# Generate password compliance report
generate_password_report() {
    local report_file="/tmp/macfleet_password_report_$(date +%Y%m%d_%H%M%S).txt"
    
    {
        echo "MacFleet Password Management Report"
        echo "Generated: $(date)"
        echo "Hostname: $(hostname)"
        echo "Administrator: $(whoami)"
        echo "=================================="
        echo ""
        
        echo "Recent Password Operations (Last 24 hours):"
        if [[ -f "$LOG_FILE" ]]; then
            local yesterday=$(date -v-1d '+%Y-%m-%d')
            grep "$yesterday\|$(date '+%Y-%m-%d')" "$LOG_FILE" | grep -E "(PASSWORD_CHANGED|PASSWORD_CHANGE_FAILED)" | tail -50
        else
            echo "No log file found"
        fi
        
        echo ""
        echo "Security Events (Last 24 hours):"
        if [[ -f "$AUDIT_LOG" ]]; then
            local yesterday=$(date -v-1d '+%Y-%m-%d')
            grep "$yesterday\|$(date '+%Y-%m-%d')" "$AUDIT_LOG" | tail -20
        else
            echo "No audit log found"
        fi
        
        echo ""
        echo "Password Policy Status:"
        echo "Minimum Length: $MIN_PASSWORD_LENGTH"
        echo "Maximum Length: $MAX_PASSWORD_LENGTH"
        echo "Complexity Required: $COMPLEXITY_REQUIREMENTS"
        echo "History Count: $PASSWORD_HISTORY_COUNT"
        echo "Lockout Duration: $LOCKOUT_DURATION seconds"
        
        echo ""
        echo "User Account Summary:"
        local total_users=$(dscl . -list /Users | grep -v '^_' | grep -v '^daemon\|^nobody\|^root' | wc -l)
        echo "Total Active Users: $total_users"
        
        echo ""
        echo "System Information:"
        echo "macOS Version: $(sw_vers -productVersion)"
        echo "Security Framework: $(security --version 2>/dev/null || echo "Unknown")"
        
    } > "$report_file"
    
    echo "Password management report saved to: $report_file"
    log_operation "INFO" "Password report generated: $report_file"
}

# Main password management function
main() {
    local action="${1:-help}"
    
    case "$action" in
        "change")
            local username="$2"
            local current_password="$3"
            local new_password="$4"
            local force_change="${5:-false}"
            
            if [[ -z "$username" ]]; then
                echo "Usage: $0 change <username> [current_password] [new_password] [force]"
                echo "Note: If passwords are not provided, you will be prompted securely"
                exit 1
            fi
            
            # Prompt for passwords if not provided
            if [[ -z "$current_password" && "$force_change" != "true" ]]; then
                echo -n "Enter current password for $username: "
                read -s current_password
                echo
            fi
            
            if [[ -z "$new_password" ]]; then
                echo -n "Enter new password for $username (or press Enter to generate): "
                read -s new_password
                echo
                
                if [[ -z "$new_password" ]]; then
                    new_password=$(generate_secure_password)
                    if [[ $? -eq 0 ]]; then
                        echo "Generated secure password for $username"
                        echo "New password: $new_password"
                        echo "WARNING: Save this password securely and provide it to the user"
                    else
                        echo "Failed to generate secure password"
                        exit 1
                    fi
                fi
            fi
            
            enterprise_change_password "$username" "$current_password" "$new_password" "$force_change"
            ;;
        "generate")
            local length="${2:-16}"
            generate_secure_password "$length"
            ;;
        "validate")
            local password="$2"
            if [[ -z "$password" ]]; then
                echo -n "Enter password to validate: "
                read -s password
                echo
            fi
            
            if validate_password_complexity "$password"; then
                echo "Password meets complexity requirements"
                exit 0
            else
                echo "Password does not meet complexity requirements"
                exit 1
            fi
            ;;
        "bulk")
            local users_file="$2"
            local password_source="${3:-generate}"
            local password_file="$4"
            
            if [[ -z "$users_file" ]]; then
                echo "Usage: $0 bulk <users_file> [password_source] [password_file]"
                echo "password_source: 'generate' or 'file'"
                exit 1
            fi
            
            bulk_password_change "$users_file" "$password_source" "$password_file"
            ;;
        "expiration")
            local username="$2"
            local expiration_days="${3:-90}"
            local expiration_action="${4:-set}"
            
            if [[ -z "$username" ]]; then
                echo "Usage: $0 expiration <username> [days] [action]"
                echo "action: 'set', 'remove', or 'check'"
                exit 1
            fi
            
            manage_password_expiration "$username" "$expiration_days" "$expiration_action"
            ;;
        "force-change")
            local username="$2"
            
            if [[ -z "$username" ]]; then
                echo "Usage: $0 force-change <username>"
                exit 1
            fi
            
            force_password_change_on_login "$username"
            ;;
        "report")
            generate_password_report
            ;;
        "help"|*)
            echo "$SCRIPT_NAME v$VERSION"
            echo "Enterprise Password Change Management"
            echo ""
            echo "Usage: $0 <action> [options]"
            echo ""
            echo "Actions:"
            echo "  change <username> [current_pass] [new_pass] [force]     - Change user password"
            echo "  generate [length]                                       - Generate secure password"
            echo "  validate [password]                                     - Validate password complexity"
            echo "  bulk <users_file> [source] [password_file]             - Bulk password changes"
            echo "  expiration <username> [days] [action]                   - Manage password expiration"
            echo "  force-change <username>                                 - Force password change on next login"
            echo "  report                                                   - Generate password management report"
            echo "  help                                                     - Show this help message"
            echo ""
            echo "Password Sources (for bulk operations):"
            echo "  generate    - Auto-generate secure passwords"
            echo "  file        - Read passwords from file"
            echo ""
            echo "Expiration Actions:"
            echo "  set         - Set password expiration"
            echo "  remove      - Remove password expiration"
            echo "  check       - Check current expiration policy"
            echo ""
            echo "Features:"
            echo "  • Enterprise-grade password complexity validation"
            echo "  • Comprehensive security audit logging"
            echo "  • Password history tracking and reuse prevention"
            echo "  • Secure random password generation"
            echo "  • Bulk password change operations"
            echo "  • Keychain synchronization"
            echo "  • Business hours and permission enforcement"
            echo "  • System account protection"
            echo ""
            echo "Security Features:"
            echo "  • Multi-layer authentication verification"
            echo "  • Secure credential handling with memory cleanup"
            echo "  • Comprehensive audit trail for compliance"
            echo "  • Real-time security event monitoring"
            echo "  • Automated security notifications"
            ;;
    esac
}

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

Quick Reference Commands

Single Password Changes

# Interactive password change
./password_manager.sh change john.doe

# Password change with current password
./password_manager.sh change john.doe "current_password" "new_secure_password"

# Force password change (admin only)
./password_manager.sh change john.doe "" "new_password" true

# Force password change on next login
./password_manager.sh force-change john.doe

Password Generation and Validation

# Generate secure password (default 16 chars)
./password_manager.sh generate

# Generate password with specific length
./password_manager.sh generate 20

# Validate password complexity
./password_manager.sh validate "MyPassword123!"

# Interactive password validation
./password_manager.sh validate

Bulk Operations

# Create bulk users specification file
cat > /tmp/users_to_change.txt << EOF
# username|current_password|force_change
john.doe|oldpass123|false
jane.smith||true
admin.user|adminpass|false
EOF

# Bulk change with auto-generated passwords
./password_manager.sh bulk "/tmp/users_to_change.txt" "generate"

# Bulk change with passwords from file
echo -e "NewPass123!\nSecurePass456@\nAdminNew789#" > /tmp/new_passwords.txt
./password_manager.sh bulk "/tmp/users_to_change.txt" "file" "/tmp/new_passwords.txt"

Password Expiration Management

# Set 90-day password expiration
./password_manager.sh expiration john.doe 90 set

# Set 60-day password expiration
./password_manager.sh expiration jane.smith 60 set

# Check current expiration policy
./password_manager.sh expiration john.doe "" check

# Remove password expiration
./password_manager.sh expiration john.doe "" remove

Integration Examples

JAMF Pro Integration

#!/bin/bash

# JAMF Pro script for enterprise password management
# Parameters: $4 = action, $5 = username, $6 = new_password, $7 = force_change

ACTION="$4"
USERNAME="$5"
NEW_PASSWORD="$6"
FORCE_CHANGE="${7:-false}"

# Download password manager if not present
if [[ ! -f "/usr/local/bin/macfleet_password_manager.sh" ]]; then
    curl -o "/usr/local/bin/macfleet_password_manager.sh" "https://scripts.macfleet.com/password_manager.sh"
    chmod +x "/usr/local/bin/macfleet_password_manager.sh"
fi

# Execute password operation
case "$ACTION" in
    "change")
        if [[ -z "$NEW_PASSWORD" ]]; then
            # Generate secure password
            NEW_PASSWORD=$(/usr/local/bin/macfleet_password_manager.sh generate 16)
        fi
        
        /usr/local/bin/macfleet_password_manager.sh change "$USERNAME" "" "$NEW_PASSWORD" "$FORCE_CHANGE"
        
        # Store password in JAMF (encrypted)
        echo "Password changed for $USERNAME"
        ;;
    "force-change")
        /usr/local/bin/macfleet_password_manager.sh force-change "$USERNAME"
        ;;
    "expiration")
        local expiration_days="${6:-90}"
        /usr/local/bin/macfleet_password_manager.sh expiration "$USERNAME" "$expiration_days" "set"
        ;;
    *)
        echo "Invalid action: $ACTION"
        exit 1
        ;;
esac

# Generate report
/usr/local/bin/macfleet_password_manager.sh report

exit $?

Configuration Profile for Password Policy

<?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>PayloadContent</key>
    <array>
        <dict>
            <key>PayloadType</key>
            <string>com.macfleet.password.policy</string>
            <key>PayloadIdentifier</key>
            <string>com.macfleet.password.policy.main</string>
            <key>PayloadDisplayName</key>
            <string>MacFleet Password Policy</string>
            <key>MinimumPasswordLength</key>
            <integer>12</integer>
            <key>MaximumPasswordLength</key>
            <integer>128</integer>
            <key>RequireUppercase</key>
            <true/>
            <key>RequireLowercase</key>
            <true/>
            <key>RequireNumbers</key>
            <true/>
            <key>RequireSpecialCharacters</key>
            <true/>
            <key>PasswordHistoryCount</key>
            <integer>12</integer>
            <key>MaximumFailedAttempts</key>
            <integer>3</integer>
            <key>LockoutDuration</key>
            <integer>1800</integer>
            <key>ForbiddenPatterns</key>
            <array>
                <string>password</string>
                <string>123456</string>
                <string>qwerty</string>
                <string>admin</string>
            </array>
        </dict>
    </array>
</dict>
</plist>

Active Directory Integration

#!/bin/bash

# Integration with Active Directory for password synchronization
sync_password_with_ad() {
    local username="$1"
    local new_password="$2"
    local ad_domain="company.local"
    
    # Change local password first
    if enterprise_change_password "$username" "" "$new_password" "true"; then
        log_operation "SUCCESS" "Local password changed for $username"
        
        # Sync with Active Directory
        if command -v dsconfigad &>/dev/null; then
            if dsconfigad -passinterval 0 -username "$username" -password "$new_password"; then
                log_operation "SUCCESS" "Password synchronized with Active Directory for $username"
                return 0
            else
                log_operation "ERROR" "Failed to synchronize password with Active Directory for $username"
                return 1
            fi
        else
            log_operation "WARNING" "Active Directory tools not available"
            return 1
        fi
    else
        log_operation "ERROR" "Failed to change local password for $username"
        return 1
    fi
}

Security Features

Secure Password Handling

# Secure memory cleanup
cleanup_sensitive_data() {
    local password_var="$1"
    
    # Clear variable content
    unset "$password_var"
    
    # Clear bash history of sensitive commands
    history -c
    history -w
    
    # Clear temporary files
    find "$TEMP_DIR" -name "*.tmp" -type f -exec shred -vfz -n 3 {} \; 2>/dev/null
}

# Secure password input
secure_password_input() {
    local prompt="$1"
    local password=""
    
    echo -n "$prompt"
    
    # Disable echo and read password
    stty -echo
    read password
    stty echo
    echo
    
    echo "$password"
}

Audit and Compliance

# Generate compliance report for auditors
generate_compliance_report() {
    local report_file="/var/reports/password_compliance_$(date +%Y%m%d).csv"
    
    echo "Timestamp,User,Event,Source_IP,Session,Details,Compliance_Status" > "$report_file"
    
    # Parse audit log for password events
    grep "SECURITY_EVENT" "$AUDIT_LOG" | while IFS='|' read -r event_type timestamp event_name username source_ip session details; do
        local compliance_status="COMPLIANT"
        
        # Check for non-compliant events
        case "$event_name" in
            "AUTH_FAILURE"|"PERMISSION_DENIED"|"SYSTEM_ACCOUNT_ACCESS")
                compliance_status="NON_COMPLIANT"
                ;;
        esac
        
        echo "$timestamp,$username,$event_name,$source_ip,$session,$details,$compliance_status" >> "$report_file"
    done
    
    echo "Compliance report generated: $report_file"
}

Troubleshooting

Common Issues and Solutions

IssueCauseSolution
Permission deniedInsufficient privilegesRun as admin or root
Current password incorrectWrong current passwordVerify current password or use force change
Password complexity failureWeak passwordUse password generator or strengthen password
Keychain update failedKeychain locked or corruptedManually unlock keychain or reset
System account protectionAttempted change on system userUse regular user accounts only

Log Analysis

# View recent password operations
tail -f /var/log/macfleet_password_operations.log

# Search for security events
grep "SECURITY_EVENT" /var/log/macfleet_password_audit.log

# Count password changes by user
grep "PASSWORD_CHANGED" /var/log/macfleet_password_audit.log | cut -d'|' -f4 | sort | uniq -c

Best Practices

  1. Use strong password policies with complexity requirements
  2. Enable password history to prevent reuse
  3. Implement regular password rotation for high-privilege accounts
  4. Monitor audit logs for suspicious activity
  5. Use secure password generation for temporary passwords
  6. Integrate with directory services for centralized management
  7. Test password changes on non-production systems first
  8. Implement emergency procedures for account lockouts

This enterprise password change management system provides comprehensive security controls, audit capabilities, and policy enforcement while maintaining the reliability of the core dscl command for effective fleet password management.

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.