Tutorial

Neue Updates und Verbesserungen zu Macfleet.

Wichtiger Hinweis

Die in diesen Tutorials bereitgestellten Codebeispiele und Skripte dienen nur zu Bildungszwecken. Macfleet ist nicht verantwortlich für Probleme, Schäden oder Sicherheitslücken, die durch die Verwendung, Änderung oder Implementierung dieser Beispiele entstehen können. Überprüfen und testen Sie Code immer in einer sicheren Umgebung, bevor Sie ihn in Produktionssystemen verwenden.

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

Neue Updates und Verbesserungen zu Macfleet.

Konfiguration eines GitHub Actions Runners auf einem Mac Mini (Apple Silicon)

GitHub Actions Runner

GitHub Actions ist eine leistungsstarke CI/CD-Plattform, die es Ihnen ermöglicht, Ihre Software-Entwicklungsworkflows zu automatisieren. Während GitHub gehostete Runner anbietet, bieten selbst-gehostete Runner erhöhte Kontrolle und Anpassung für Ihr CI/CD-Setup. Dieses Tutorial führt Sie durch die Einrichtung, Konfiguration und Verbindung eines selbst-gehosteten Runners auf einem Mac mini zur Ausführung von macOS-Pipelines.

Voraussetzungen

Bevor Sie beginnen, stellen Sie sicher, dass Sie haben:

  • Einen Mac mini (registrieren Sie sich bei Macfleet)
  • Ein GitHub-Repository mit Administratorrechten
  • Einen installierten Paketmanager (vorzugsweise Homebrew)
  • Git auf Ihrem System installiert

Schritt 1: Ein dediziertes Benutzerkonto erstellen

Erstellen Sie zunächst ein dediziertes Benutzerkonto für den GitHub Actions Runner:

# Das 'gh-runner' Benutzerkonto erstellen
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

# Das Passwort für den Benutzer setzen
sudo dscl . -passwd /Users/gh-runner ihr_passwort

# 'gh-runner' zur 'admin'-Gruppe hinzufügen
sudo dscl . -append /Groups/admin GroupMembership gh-runner

Wechseln Sie zum neuen Benutzerkonto:

su gh-runner

Schritt 2: Erforderliche Software installieren

Installieren Sie Git und Rosetta 2 (wenn Sie Apple Silicon verwenden):

# Git installieren, falls noch nicht installiert
brew install git

# Rosetta 2 für Apple Silicon Macs installieren
softwareupdate --install-rosetta

Schritt 3: Den GitHub Actions Runner konfigurieren

  1. Gehen Sie zu Ihrem GitHub-Repository
  2. Navigieren Sie zu Einstellungen > Actions > Runners

GitHub Actions Runner

  1. Klicken Sie auf "New self-hosted runner" (https://github.com/<username>/<repository>/settings/actions/runners/new)
  2. Wählen Sie macOS als Runner-Image und ARM64 als Architektur
  3. Folgen Sie den bereitgestellten Befehlen, um den Runner herunterzuladen und zu konfigurieren

GitHub Actions Runner

Erstellen Sie eine .env-Datei im _work-Verzeichnis des Runners:

# _work/.env Datei
ImageOS=macos15
XCODE_15_DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
  1. Führen Sie das run.sh-Skript in Ihrem Runner-Verzeichnis aus, um die Einrichtung abzuschließen.
  2. Überprüfen Sie, dass der Runner aktiv ist und auf Jobs im Terminal wartet, und überprüfen Sie die GitHub-Repository-Einstellungen für die Runner-Zuordnung und den Idle-Status.

GitHub Actions Runner

Schritt 4: Sudoers konfigurieren (Optional)

Wenn Ihre Actions Root-Privilegien benötigen, konfigurieren Sie die sudoers-Datei:

sudo visudo

Fügen Sie die folgende Zeile hinzu:

gh-runner ALL=(ALL) NOPASSWD: ALL

Schritt 5: Den Runner in Workflows verwenden

Konfigurieren Sie Ihren GitHub Actions Workflow, um den selbst-gehosteten Runner zu verwenden:

name: Beispiel-Workflow

on:
  workflow_dispatch:

jobs:
  build:
    runs-on: [self-hosted, macOS, ARM64]
    steps:
      - name: NodeJS installieren
        run: brew install node

Der Runner ist bei Ihrem Repository authentifiziert und mit self-hosted, macOS und ARM64 markiert. Verwenden Sie ihn in Ihren Workflows, indem Sie diese Labels im runs-on-Feld angeben:

runs-on: [self-hosted, macOS, ARM64]

Best Practices

  • Halten Sie Ihre Runner-Software auf dem neuesten Stand
  • Überwachen Sie regelmäßig Runner-Logs auf Probleme
  • Verwenden Sie spezifische Labels für verschiedene Runner-Typen
  • Implementieren Sie angemessene Sicherheitsmaßnahmen
  • Erwägen Sie die Verwendung mehrerer Runner für Lastverteilung

Fehlerbehebung

Häufige Probleme und Lösungen:

  1. Runner verbindet sich nicht:

    • Überprüfen Sie die Netzwerkverbindung
    • Überprüfen Sie die Gültigkeit des GitHub-Tokens
    • Stellen Sie angemessene Berechtigungen sicher
  2. Build-Fehler:

    • Überprüfen Sie die Xcode-Installation
    • Überprüfen Sie erforderliche Abhängigkeiten
    • Überprüfen Sie Workflow-Logs
  3. Berechtigungsprobleme:

    • Überprüfen Sie Benutzerberechtigungen
    • Überprüfen Sie sudoers-Konfiguration
    • Überprüfen Sie Dateisystem-Berechtigungen

Fazit

Sie haben jetzt einen selbst-gehosteten GitHub Actions Runner auf Ihrem Mac mini konfiguriert. Diese Einrichtung bietet Ihnen mehr Kontrolle über Ihre CI/CD-Umgebung und ermöglicht es Ihnen, macOS-spezifische Workflows effizient auszuführen.

Denken Sie daran, Ihren Runner regelmäßig zu warten und ihn mit den neuesten Sicherheitspatches und Software-Versionen auf dem neuesten Stand zu halten.

Native App

Macfleet native App

Macfleet Installationsanleitung

Macfleet ist eine leistungsstarke Flottenmanagement-Lösung, die speziell für Cloud-gehostete Mac Mini-Umgebungen entwickelt wurde. Als Mac Mini Cloud-Hosting-Anbieter können Sie Macfleet verwenden, um Ihre gesamte Flotte virtualisierter Mac-Instanzen zu überwachen, zu verwalten und zu optimieren.

Diese Installationsanleitung führt Sie durch die Einrichtung der Macfleet-Überwachung auf macOS-, Windows- und Linux-Systemen, um eine umfassende Übersicht über Ihre Cloud-Infrastruktur zu gewährleisten.

🍎 macOS

  • Laden Sie die .dmg-Datei für Mac hier herunter
  • Doppelklicken Sie auf die heruntergeladene .dmg-Datei
  • Ziehen Sie die Macfleet-App in den Anwendungsordner
  • Werfen Sie die .dmg-Datei aus
  • Öffnen Sie Systemeinstellungen > Sicherheit & Datenschutz
    • Datenschutz-Tab > Bedienungshilfen
    • Aktivieren Sie Macfleet, um Überwachung zu erlauben
  • Starten Sie Macfleet aus den Anwendungen
  • Die Verfolgung startet automatisch

🪟 Windows

  • Laden Sie die .exe-Datei für Windows hier herunter
  • Rechtsklick auf die .exe-Datei > "Als Administrator ausführen"
  • Folgen Sie dem Installationsassistenten
  • Akzeptieren Sie die Allgemeinen Geschäftsbedingungen
  • Erlauben Sie in Windows Defender, wenn aufgefordert
  • Gewähren Sie Anwendungsüberwachungsberechtigungen
  • Starten Sie Macfleet aus dem Startmenü
  • Die Anwendung beginnt automatisch mit der Verfolgung

🐧 Linux

  • Laden Sie das .deb-Paket (Ubuntu/Debian) oder .rpm (CentOS/RHEL) hier herunter
  • Installieren Sie mit Ihrem Paketmanager
    • Ubuntu/Debian: sudo dpkg -i Macfleet-linux.deb
    • CentOS/RHEL: sudo rpm -ivh Macfleet-linux.rpm
  • Erlauben Sie X11-Zugriffsberechtigungen, wenn aufgefordert
  • Fügen Sie den Benutzer zu entsprechenden Gruppen hinzu, falls erforderlich
  • Starten Sie Macfleet aus dem Anwendungsmenü
  • Die Anwendung beginnt automatisch mit der Verfolgung

Hinweis: Nach der Installation auf allen Systemen melden Sie sich mit Ihren Macfleet-Anmeldedaten an, um Daten mit Ihrem Dashboard zu synchronisieren.