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.

Login History Management on macOS

Monitor and analyze user login activity across your MacFleet devices using advanced command-line tools. This tutorial covers login history tracking, user session analysis, security auditing, and enterprise-grade compliance monitoring with comprehensive reporting capabilities.

Understanding macOS Login History Management

macOS provides several powerful tools for tracking user login activity:

  • who - Shows currently logged-in users and brief login history
  • last - Displays detailed login history with session information
  • dscl - Directory Services command line utility for user management
  • w - Extended user activity information with system load
  • finger - User information and login details (if available)

These tools access system logs and user databases to provide comprehensive login tracking capabilities.

Basic Login History Commands

Brief Login History with who

#!/bin/bash

# Display brief login history
get_brief_login_history() {
    echo "=== Brief Login History ==="
    who
    echo ""
    
    # Alternative with timestamps
    echo "=== Current User Sessions ==="
    who -u
}

# Execute basic login check
get_brief_login_history

Detailed Login History with last

#!/bin/bash

# Display detailed login history
get_detailed_login_history() {
    echo "=== Detailed Login History ==="
    last
    echo ""
    
    # Show last 10 login entries
    echo "=== Recent 10 Login Sessions ==="
    last -10
    echo ""
    
    # Show login history for today
    echo "=== Today's Login Sessions ==="
    last -t "$(date '+%Y%m%d%H%M%S')"
}

# Execute detailed login check
get_detailed_login_history

Check Specific User Login History

#!/bin/bash

# Get last login time for specific user
check_user_login() {
    local username="$1"
    
    if [[ -z "$username" ]]; then
        echo "Usage: check_user_login <username>"
        return 1
    fi
    
    echo "=== Last Login for User: $username ==="
    last -1 "$username"
    echo ""
    
    # Additional user information
    echo "=== User Account Information ==="
    dscl . -read "/Users/$username" RealName 2>/dev/null || echo "User not found"
    dscl . -read "/Users/$username" UniqueID 2>/dev/null || echo "UID not available"
}

# Example usage
# check_user_login "john.doe"

Advanced Login History Analysis

Comprehensive User Session Analysis

#!/bin/bash

# Advanced login history analysis with security insights
analyze_login_patterns() {
    echo "=== Comprehensive Login Analysis ==="
    echo "Generated: $(date)"
    echo "Hostname: $(hostname)"
    echo "=================================="
    echo ""
    
    # Current active sessions
    echo "1. ACTIVE USER SESSIONS:"
    echo "------------------------"
    who -u | while IFS= read -r line; do
        echo "  $line"
    done
    echo ""
    
    # Recent login activity (last 24 hours)
    echo "2. RECENT LOGIN ACTIVITY (24 hours):"
    echo "------------------------------------"
    local yesterday
    yesterday=$(date -v-1d '+%Y%m%d%H%M%S' 2>/dev/null || date -d 'yesterday' '+%Y%m%d%H%M%S' 2>/dev/null)
    
    if [[ -n "$yesterday" ]]; then
        last -t "$yesterday" | head -20
    else
        last -20
    fi
    echo ""
    
    # Failed login attempts (if available in logs)
    echo "3. FAILED LOGIN ATTEMPTS:"
    echo "-------------------------"
    grep "authentication failure" /var/log/system.log 2>/dev/null | tail -10 || echo "No recent failures found"
    echo ""
    
    # Login frequency analysis
    echo "4. LOGIN FREQUENCY BY USER:"
    echo "---------------------------"
    last | grep -v "wtmp begins" | awk '{print $1}' | sort | uniq -c | sort -nr | head -10
    echo ""
    
    # Remote vs local logins
    echo "5. LOGIN SOURCE ANALYSIS:"
    echo "-------------------------"
    echo "Console logins:"
    last | grep -c "console" || echo "0"
    echo "Remote logins:"
    last | grep -v "console" | grep -v "wtmp begins" | wc -l | tr -d ' '
}

# Execute comprehensive analysis
analyze_login_patterns

User Account Discovery

#!/bin/bash

# List all users and their login status
discover_users() {
    echo "=== User Account Discovery ==="
    echo ""
    
    # All users from directory services
    echo "1. ALL SYSTEM USERS:"
    echo "-------------------"
    dscl . list /Users | grep -v "^_" | grep -v "^root" | grep -v "^daemon" | grep -v "^nobody"
    echo ""
    
    # Users with UID >= 500 (typically regular users)
    echo "2. REGULAR USER ACCOUNTS:"
    echo "------------------------"
    dscl . list /Users UniqueID | awk '$2 >= 500 {print $1, "(UID: " $2 ")"}'
    echo ""
    
    # Users with recent login activity
    echo "3. USERS WITH RECENT LOGIN ACTIVITY:"
    echo "------------------------------------"
    last | awk '{print $1}' | sort | uniq | grep -v "wtmp" | grep -v "^$" | head -10
    echo ""
    
    # Home directories
    echo "4. USER HOME DIRECTORIES:"
    echo "------------------------"
    ls -la /Users/ | grep -v "^total" | grep -v "Shared" | awk '{print $9, $3, $4}' | grep -v "^$"
}

# Execute user discovery
discover_users

Enterprise Login History Management System

#!/bin/bash

# MacFleet Enterprise Login History Management System
# Comprehensive user activity monitoring and security auditing

# Configuration
LOG_FILE="/var/log/macfleet_login_history.log"
REPORT_DIR="/var/reports/macfleet/login_history"
CONFIG_FILE="/etc/macfleet/login_monitoring.conf"
ALERT_THRESHOLD_FAILED_LOGINS=5
ALERT_THRESHOLD_UNUSUAL_HOURS=22  # Alert for logins after 10 PM

# Create directory structure
setup_directories() {
    mkdir -p "$(dirname "$LOG_FILE")" "$REPORT_DIR" "$(dirname "$CONFIG_FILE")"
    touch "$LOG_FILE"
}

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

# Generate comprehensive login report
generate_login_report() {
    local report_file="$REPORT_DIR/login_report_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Generating comprehensive login history report: $report_file"
    
    {
        echo "{"
        echo "  \"report_type\": \"login_history\","
        echo "  \"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\","
        echo "  \"hostname\": \"$(hostname)\","
        echo "  \"system_info\": {"
        echo "    \"macos_version\": \"$(sw_vers -productVersion)\","
        echo "    \"uptime\": \"$(uptime | awk -F'up ' '{print $2}' | awk -F', ' '{print $1}')\","
        echo "    \"current_users\": $(who | wc -l | tr -d ' ')"
        echo "  },"
        
        # Active sessions
        echo "  \"active_sessions\": ["
        local first_session=true
        who -u | while IFS= read -r line; do
            if [[ "$first_session" == "false" ]]; then
                echo ","
            fi
            first_session=false
            
            local user terminal login_time pid
            user=$(echo "$line" | awk '{print $1}')
            terminal=$(echo "$line" | awk '{print $2}')
            login_time=$(echo "$line" | awk '{print $3, $4}')
            pid=$(echo "$line" | awk '{print $6}')
            
            echo "    {"
            echo "      \"user\": \"$user\","
            echo "      \"terminal\": \"$terminal\","
            echo "      \"login_time\": \"$login_time\","
            echo "      \"pid\": \"$pid\""
            echo -n "    }"
        done
        echo ""
        echo "  ],"
        
        # Recent login history
        echo "  \"recent_logins\": ["
        local first_login=true
        last -20 | grep -v "wtmp begins" | while IFS= read -r line; do
            if [[ -n "$line" ]]; then
                if [[ "$first_login" == "false" ]]; then
                    echo ","
                fi
                first_login=false
                
                local user terminal source login_date login_time logout_info
                user=$(echo "$line" | awk '{print $1}')
                terminal=$(echo "$line" | awk '{print $2}')
                source=$(echo "$line" | awk '{print $3}')
                login_date=$(echo "$line" | awk '{print $4, $5, $6}')
                login_time=$(echo "$line" | awk '{print $7}')
                logout_info=$(echo "$line" | awk '{print $9, $10}')
                
                echo "    {"
                echo "      \"user\": \"$user\","
                echo "      \"terminal\": \"$terminal\","
                echo "      \"source\": \"$source\","
                echo "      \"login_date\": \"$login_date\","
                echo "      \"login_time\": \"$login_time\","
                echo "      \"logout_info\": \"$logout_info\""
                echo -n "    }"
            fi
        done
        echo ""
        echo "  ],"
        
        # User statistics
        echo "  \"user_statistics\": {"
        local total_users
        total_users=$(dscl . list /Users | grep -v "^_" | wc -l | tr -d ' ')
        echo "    \"total_system_users\": $total_users,"
        
        local regular_users
        regular_users=$(dscl . list /Users UniqueID | awk '$2 >= 500' | wc -l | tr -d ' ')
        echo "    \"regular_users\": $regular_users,"
        
        local active_login_users
        active_login_users=$(last | awk '{print $1}' | sort | uniq | grep -v "wtmp" | grep -v "^$" | wc -l | tr -d ' ')
        echo "    \"users_with_login_history\": $active_login_users"
        echo "  }"
        echo "}"
    } > "$report_file"
    
    log_action "Login history report generated successfully"
    echo "$report_file"
}

# Monitor for suspicious login activity
monitor_suspicious_activity() {
    log_action "Starting suspicious login activity monitoring..."
    
    local alerts=()
    
    # Check for unusual login times (configurable)
    local current_hour
    current_hour=$(date +%H)
    
    if [[ "$current_hour" -ge "$ALERT_THRESHOLD_UNUSUAL_HOURS" ]]; then
        local late_logins
        late_logins=$(who | wc -l | tr -d ' ')
        
        if [[ "$late_logins" -gt 0 ]]; then
            alerts+=("Late night login activity detected: $late_logins active sessions after $ALERT_THRESHOLD_UNUSUAL_HOURS:00")
        fi
    fi
    
    # Check for multiple failed login attempts
    local failed_logins
    failed_logins=$(grep "authentication failure" /var/log/system.log 2>/dev/null | grep "$(date '+%b %d')" | wc -l | tr -d ' ')
    
    if [[ "$failed_logins" -ge "$ALERT_THRESHOLD_FAILED_LOGINS" ]]; then
        alerts+=("High number of failed login attempts today: $failed_logins failures")
    fi
    
    # Check for root logins
    local root_logins
    root_logins=$(last | grep "^root " | head -5 | wc -l | tr -d ' ')
    
    if [[ "$root_logins" -gt 0 ]]; then
        alerts+=("Recent root login activity detected: $root_logins sessions")
    fi
    
    # Check for simultaneous logins from same user
    local duplicate_users
    duplicate_users=$(who | awk '{print $1}' | sort | uniq -d)
    
    if [[ -n "$duplicate_users" ]]; then
        alerts+=("Multiple simultaneous sessions detected for users: $duplicate_users")
    fi
    
    # Report alerts
    if [[ ${#alerts[@]} -eq 0 ]]; then
        log_action "✅ No suspicious login activity detected"
        return 0
    else
        log_action "⚠️  Suspicious login activity alerts:"
        for alert in "${alerts[@]}"; do
            log_action "  - $alert"
        done
        return 1
    fi
}

# Analyze login patterns for security insights
analyze_security_patterns() {
    log_action "Analyzing login patterns for security insights..."
    
    echo "=== Security Pattern Analysis ==="
    echo ""
    
    # Login frequency by day of week
    echo "1. LOGIN FREQUENCY BY DAY:"
    echo "--------------------------"
    last | grep -v "wtmp begins" | awk '{print $4}' | sort | uniq -c | sort -nr
    echo ""
    
    # Most active users
    echo "2. MOST ACTIVE USERS:"
    echo "--------------------"
    last | grep -v "wtmp begins" | awk '{print $1}' | sort | uniq -c | sort -nr | head -10
    echo ""
    
    # Login sources analysis
    echo "3. LOGIN SOURCES:"
    echo "----------------"
    echo "Console logins: $(last | grep -c "console")"
    echo "Remote logins: $(last | grep -v "console" | grep -v "wtmp begins" | wc -l | tr -d ' ')"
    echo ""
    
    # Session duration analysis
    echo "4. SESSION PATTERNS:"
    echo "-------------------"
    local avg_sessions
    avg_sessions=$(last | grep -v "wtmp begins" | grep -v "still logged in" | wc -l | tr -d ' ')
    echo "Total completed sessions: $avg_sessions"
    
    local active_sessions
    active_sessions=$(who | wc -l | tr -d ' ')
    echo "Currently active sessions: $active_sessions"
    echo ""
    
    # Time-based analysis
    echo "5. LOGIN TIME PATTERNS:"
    echo "----------------------"
    echo "Business hours (9-17): $(last | awk '{print $7}' | grep -E '^(09|1[0-7]):' | wc -l | tr -d ' ')"
    echo "After hours (18-08): $(last | awk '{print $7}' | grep -E '^(1[8-9]|2[0-3]|0[0-8]):' | wc -l | tr -d ' ')"
}

# User access audit
perform_user_audit() {
    local audit_file="$REPORT_DIR/user_audit_$(date +%Y%m%d_%H%M%S).txt"
    
    log_action "Performing comprehensive user access audit: $audit_file"
    
    {
        echo "MacFleet User Access Audit Report"
        echo "Generated: $(date)"
        echo "Hostname: $(hostname)"
        echo "=================================="
        echo ""
        
        echo "SYSTEM OVERVIEW:"
        echo "----------------"
        echo "macOS Version: $(sw_vers -productVersion)"
        echo "Build: $(sw_vers -buildVersion)"
        echo "System Uptime: $(uptime | awk -F'up ' '{print $2}' | awk -F', ' '{print $1}')"
        echo "Current Date/Time: $(date)"
        echo ""
        
        echo "USER ACCOUNT SUMMARY:"
        echo "---------------------"
        echo "Total system users: $(dscl . list /Users | wc -l | tr -d ' ')"
        echo "Regular users (UID >= 500): $(dscl . list /Users UniqueID | awk '$2 >= 500' | wc -l | tr -d ' ')"
        echo "Currently logged in: $(who | wc -l | tr -d ' ')"
        echo ""
        
        echo "DETAILED USER INFORMATION:"
        echo "--------------------------"
        dscl . list /Users UniqueID | awk '$2 >= 500' | while read -r username uid; do
            echo "User: $username (UID: $uid)"
            
            # Real name
            local real_name
            real_name=$(dscl . -read "/Users/$username" RealName 2>/dev/null | grep "RealName:" | cut -d' ' -f2-)
            echo "  Real Name: ${real_name:-"Not set"}"
            
            # Home directory
            local home_dir
            home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory 2>/dev/null | grep "NFSHomeDirectory:" | cut -d' ' -f2)
            echo "  Home Directory: ${home_dir:-"Not set"}"
            
            # Last login
            local last_login
            last_login=$(last -1 "$username" 2>/dev/null | head -1 | awk '{print $4, $5, $6, $7}')
            echo "  Last Login: ${last_login:-"Never"}"
            
            # Account status
            local account_disabled
            account_disabled=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep -c "DisabledUser" || echo "0")
            if [[ "$account_disabled" -gt 0 ]]; then
                echo "  Status: DISABLED"
            else
                echo "  Status: Active"
            fi
            
            echo ""
        done
        
        echo "RECENT LOGIN ACTIVITY:"
        echo "----------------------"
        last -50
        
        echo ""
        echo "SECURITY RECOMMENDATIONS:"
        echo "-------------------------"
        
        # Check for users without recent login activity
        local inactive_users
        inactive_users=$(dscl . list /Users UniqueID | awk '$2 >= 500 {print $1}' | while read -r user; do
            if ! last "$user" | grep -q "$(date '+%b')" 2>/dev/null; then
                echo "$user"
            fi
        done)
        
        if [[ -n "$inactive_users" ]]; then
            echo "• Consider reviewing inactive user accounts:"
            echo "$inactive_users" | while read -r user; do
                echo "  - $user"
            done
        else
            echo "• All users have recent login activity"
        fi
        
        # Check for admin users
        local admin_users
        admin_users=$(dscl . -read /Groups/admin GroupMembership 2>/dev/null | cut -d' ' -f2-)
        if [[ -n "$admin_users" ]]; then
            echo "• Review admin user access regularly:"
            for admin in $admin_users; do
                echo "  - $admin"
            done
        fi
        
    } > "$audit_file"
    
    log_action "User access audit completed successfully"
    echo "$audit_file"
}

# Export login data for external analysis
export_login_data() {
    local export_format="${1:-json}"  # json, csv, xml
    local export_file="$REPORT_DIR/login_export_$(date +%Y%m%d_%H%M%S).$export_format"
    
    log_action "Exporting login data in $export_format format: $export_file"
    
    case "$export_format" in
        "csv")
            {
                echo "User,Terminal,Source,LoginDate,LoginTime,LogoutInfo,Duration"
                last -100 | grep -v "wtmp begins" | while IFS= read -r line; do
                    if [[ -n "$line" ]]; then
                        echo "$line" | awk -F' ' '{
                            user=$1; terminal=$2; source=$3; 
                            login_date=$4" "$5" "$6; login_time=$7; 
                            logout_info=$9" "$10; duration=$8;
                            print user","terminal","source","login_date","login_time","logout_info","duration
                        }'
                    fi
                done
            } > "$export_file"
            ;;
        "json")
            generate_login_report > /dev/null
            cp "$REPORT_DIR"/login_report_*.json "$export_file" 2>/dev/null || echo "{\"error\": \"No recent report found\"}" > "$export_file"
            ;;
        "xml")
            {
                echo '<?xml version="1.0" encoding="UTF-8"?>'
                echo '<login_history>'
                echo "  <generated>$(date -u +%Y-%m-%dT%H:%M:%SZ)</generated>"
                echo "  <hostname>$(hostname)</hostname>"
                echo "  <sessions>"
                
                last -50 | grep -v "wtmp begins" | while IFS= read -r line; do
                    if [[ -n "$line" ]]; then
                        local user terminal source login_date login_time
                        user=$(echo "$line" | awk '{print $1}')
                        terminal=$(echo "$line" | awk '{print $2}')
                        source=$(echo "$line" | awk '{print $3}')
                        login_date=$(echo "$line" | awk '{print $4, $5, $6}')
                        login_time=$(echo "$line" | awk '{print $7}')
                        
                        echo "    <session>"
                        echo "      <user>$user</user>"
                        echo "      <terminal>$terminal</terminal>"
                        echo "      <source>$source</source>"
                        echo "      <login_date>$login_date</login_date>"
                        echo "      <login_time>$login_time</login_time>"
                        echo "    </session>"
                    fi
                done
                
                echo "  </sessions>"
                echo '</login_history>'
            } > "$export_file"
            ;;
        *)
            log_action "ERROR: Unsupported export format: $export_format"
            return 1
            ;;
    esac
    
    log_action "Login data exported successfully"
    echo "$export_file"
}

# Main management function
main() {
    local action="${1:-report}"
    local parameter="$2"
    
    setup_directories
    log_action "MacFleet Login History Management started with action: $action"
    
    case "$action" in
        "brief")
            who
            ;;
        "detailed")
            last
            ;;
        "user")
            if [[ -n "$parameter" ]]; then
                last -1 "$parameter"
            else
                echo "Usage: $0 user <username>"
                exit 1
            fi
            ;;
        "users")
            dscl . list /Users | grep -v "^_"
            ;;
        "analyze")
            analyze_security_patterns
            ;;
        "monitor")
            monitor_suspicious_activity
            ;;
        "audit")
            perform_user_audit
            ;;
        "export")
            export_login_data "$parameter"
            ;;
        "report"|*)
            generate_login_report
            ;;
    esac
    
    log_action "MacFleet Login History Management completed with action: $action"
}

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

Quick Management Functions

Simple Login Status Check

#!/bin/bash

# Quick login status with enhanced output
quick_login_status() {
    echo "📊 MacFleet Login Status - $(date)"
    echo "=================================="
    
    # Current users
    local current_users
    current_users=$(who | wc -l | tr -d ' ')
    echo "👥 Currently logged in: $current_users users"
    
    if [[ "$current_users" -gt 0 ]]; then
        echo ""
        echo "Active Sessions:"
        who | while IFS= read -r line; do
            echo "  🔹 $line"
        done
    fi
    
    echo ""
    echo "📈 Recent Activity:"
    echo "  - Last 24 hours: $(last -t "$(date -v-1d '+%Y%m%d%H%M%S' 2>/dev/null || date -d 'yesterday' '+%Y%m%d%H%M%S')" | wc -l | tr -d ' ') logins"
    echo "  - This week: $(last | grep "$(date '+%b')" | wc -l | tr -d ' ') logins"
    
    # System uptime
    echo "  - System uptime: $(uptime | awk -F'up ' '{print $2}' | awk -F', ' '{print $1}')"
}

quick_login_status

User Login Summary

#!/bin/bash

# Generate user login summary
user_login_summary() {
    echo "🔍 User Login Summary"
    echo "===================="
    echo ""
    
    echo "Top 10 Most Active Users:"
    echo "------------------------"
    last | grep -v "wtmp begins" | awk '{print $1}' | sort | uniq -c | sort -nr | head -10 | while read -r count user; do
        echo "  $user: $count logins"
    done
    
    echo ""
    echo "Recent User Activity:"
    echo "--------------------"
    dscl . list /Users UniqueID | awk '$2 >= 500 {print $1}' | head -10 | while read -r username; do
        local last_login
        last_login=$(last -1 "$username" 2>/dev/null | head -1 | awk '{print $4, $5, $7}' | tr -s ' ')
        echo "  $username: ${last_login:-"No recent activity"}"
    done
}

user_login_summary

Security Monitoring Functions

Failed Login Detection

#!/bin/bash

# Monitor and report failed login attempts
monitor_failed_logins() {
    echo "🔒 Failed Login Monitoring"
    echo "=========================="
    echo ""
    
    # Check system log for authentication failures
    echo "Recent Failed Login Attempts:"
    echo "-----------------------------"
    
    # Last 24 hours of failed attempts
    grep "authentication failure" /var/log/system.log 2>/dev/null | grep "$(date '+%b %d')" | while IFS= read -r line; do
        echo "  ⚠️  $line"
    done || echo "  ✅ No failed login attempts found today"
    
    echo ""
    echo "Failed Login Summary:"
    echo "--------------------"
    
    # Count failures by user (if available)
    local failure_count
    failure_count=$(grep "authentication failure" /var/log/system.log 2>/dev/null | grep "$(date '+%b %d')" | wc -l | tr -d ' ')
    echo "  Total failures today: $failure_count"
    
    # Recommendations
    if [[ "$failure_count" -gt 5 ]]; then
        echo ""
        echo "🚨 Security Alert: High number of failed logins detected!"
        echo "  - Review user accounts for potential brute force attacks"
        echo "  - Consider implementing account lockout policies"
        echo "  - Check for suspicious IP addresses in logs"
    fi
}

monitor_failed_logins

Session Duration Analysis

#!/bin/bash

# Analyze user session durations
analyze_session_duration() {
    echo "⏱️  Session Duration Analysis"
    echo "============================="
    echo ""
    
    echo "Session Statistics:"
    echo "-------------------"
    
    # Active sessions
    local active_count
    active_count=$(who | wc -l | tr -d ' ')
    echo "  Active sessions: $active_count"
    
    # Completed sessions analysis
    echo "  Recent completed sessions:"
    last | grep -v "still logged in" | grep -v "wtmp begins" | head -10 | while IFS= read -r line; do
        local duration
        duration=$(echo "$line" | awk '{print $10}' | tr -d '()')
        if [[ -n "$duration" ]]; then
            echo "    Duration: $duration"
        fi
    done
    
    echo ""
    echo "Long-running Sessions (Active):"
    echo "-------------------------------"
    who -u | while IFS= read -r line; do
        local login_time pid idle
        login_time=$(echo "$line" | awk '{print $3, $4}')
        pid=$(echo "$line" | awk '{print $6}')
        idle=$(echo "$line" | awk '{print $5}')
        
        if [[ "$idle" != "." ]]; then
            echo "  Session started: $login_time (Idle: $idle)"
        else
            echo "  Session started: $login_time (Active)"
        fi
    done
}

analyze_session_duration

Configuration and Compliance

Login Policy Configuration

# /etc/macfleet/login_monitoring.conf
# MacFleet Login History Monitoring Configuration

# Alert thresholds
ALERT_THRESHOLD_FAILED_LOGINS=5
ALERT_THRESHOLD_UNUSUAL_HOURS=22
ALERT_THRESHOLD_SIMULTANEOUS_SESSIONS=3

# Monitoring settings
MONITOR_INTERVAL_MINUTES=15
LOG_RETENTION_DAYS=90
REPORT_GENERATION_SCHEDULE="daily"

# Security policies
REQUIRE_LOGIN_AUDIT_TRAIL=true
ALERT_ON_ROOT_LOGIN=true
ALERT_ON_AFTER_HOURS_LOGIN=true
MONITOR_REMOTE_LOGINS=true

# Compliance settings
GDPR_COMPLIANCE=true
SOX_COMPLIANCE=false
HIPAA_COMPLIANCE=false
EXPORT_FORMAT="json"  # json, csv, xml

Compliance Reporting

#!/bin/bash

# Generate compliance-ready login reports
generate_compliance_report() {
    local compliance_type="${1:-general}"
    local report_file="$REPORT_DIR/compliance_${compliance_type}_$(date +%Y%m%d).txt"
    
    echo "📋 Generating $compliance_type compliance report..."
    
    {
        echo "LOGIN HISTORY COMPLIANCE REPORT"
        echo "==============================="
        echo "Report Type: $compliance_type"
        echo "Generated: $(date)"
        echo "Period: $(date -v-30d '+%Y-%m-%d') to $(date '+%Y-%m-%d')"
        echo "System: $(hostname)"
        echo ""
        
        case "$compliance_type" in
            "gdpr")
                echo "GDPR DATA PROCESSING RECORD:"
                echo "----------------------------"
                echo "• Login data collected for security monitoring"
                echo "• Data retention: 90 days (configurable)"
                echo "• Access controls: Admin users only"
                echo "• Data subjects: All system users"
                echo ""
                ;;
            "sox")
                echo "SOX ACCESS CONTROL COMPLIANCE:"
                echo "------------------------------"
                echo "• User access monitoring: Enabled"
                echo "• Privileged access tracking: Enabled"
                echo "• Failed login monitoring: Enabled"
                echo "• Audit trail completeness: Verified"
                echo ""
                ;;
            "hipaa")
                echo "HIPAA ACCESS AUDIT REQUIREMENTS:"
                echo "--------------------------------"
                echo "• User authentication logging: Active"
                echo "• Access attempt monitoring: Enabled"
                echo "• Minimum necessary access: Under review"
                echo "• Audit log integrity: Maintained"
                echo ""
                ;;
        esac
        
        echo "DETAILED LOGIN ACTIVITY:"
        echo "------------------------"
        last -30
        
        echo ""
        echo "USER ACCESS SUMMARY:"
        echo "-------------------"
        dscl . list /Users UniqueID | awk '$2 >= 500' | while read -r username uid; do
            local login_count
            login_count=$(last "$username" | grep -v "wtmp begins" | wc -l | tr -d ' ')
            echo "$username (UID: $uid): $login_count login sessions"
        done
        
    } > "$report_file"
    
    echo "✅ Compliance report generated: $report_file"
}

# Generate different compliance reports
# generate_compliance_report "gdpr"
# generate_compliance_report "sox"
# generate_compliance_report "hipaa"

Important Technical Notes

Command Details

  • who: Shows current logged-in users with login times
  • last: Displays login history from /var/log/wtmp
  • dscl: Directory Services command line for user information
  • w: Extended version of who with system load information

Log File Locations

  • /var/log/wtmp: Binary login history database
  • /var/log/system.log: System log including authentication events
  • /var/log/secure.log: Security-related log entries (if enabled)

Security Considerations

  1. Privacy Compliance: Login monitoring must comply with local privacy laws
  2. Data Retention: Implement appropriate retention policies for audit logs
  3. Access Control: Restrict access to login history data to authorized personnel
  4. Real-time Monitoring: Consider implementing real-time alerts for suspicious activity

Best Practices

  1. Regular Auditing: Review login patterns regularly for anomalies
  2. Automated Monitoring: Set up automated alerts for suspicious activity
  3. Data Retention: Maintain appropriate log retention for compliance requirements
  4. User Privacy: Balance security monitoring with user privacy expectations
  5. Documentation: Maintain clear documentation of monitoring procedures
  6. Integration: Consider integrating with SIEM systems for centralized monitoring
  7. Performance Impact: Monitor system performance impact of logging activities
  8. Backup Strategy: Implement backup procedures for critical audit logs

Remember to validate all scripts on test devices before deploying across your MacFleet environment, and ensure compliance with your organization's privacy and security policies when implementing login history monitoring.

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.