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.

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

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.