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.

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

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.