Firewall Management for macOS
Implement enterprise-grade firewall management across your MacFleet deployment with automated security policies, advanced network protection, threat detection, and comprehensive compliance monitoring. This tutorial provides solutions for maintaining robust network security while ensuring regulatory compliance and operational efficiency.
Understanding macOS Firewall Management
macOS provides several firewall management tools and mechanisms:
- Application Firewall - Built-in firewall that blocks incoming connections
socketfilterfw
- Command-line tool for firewall configurationpfctl
- Packet Filter control utility (advanced filtering)- System Preferences - GUI firewall management interface
- Configuration Profiles - MDM-based firewall policy deployment
Basic Firewall Operations
Enable Firewall
#!/bin/bash
# Enable macOS firewall
sudo defaults write /Library/Preferences/com.apple.alf globalstate -int 1
Disable Firewall
#!/bin/bash
# Disable macOS firewall
sudo defaults write /Library/Preferences/com.apple.alf globalstate -int 0
Check Firewall Status
#!/bin/bash
# Check firewall status
/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate
Enterprise Firewall Management System
Comprehensive Firewall Management Tool
#!/bin/bash
# MacFleet Enterprise Firewall Management Tool
# Advanced network security and compliance monitoring
# Configuration
CONFIG_FILE="/etc/macfleet/firewall_policy.conf"
LOG_FILE="/var/log/macfleet_firewall.log"
RULES_DIR="/Library/MacFleet/FirewallRules"
AUDIT_LOG="/var/log/macfleet_firewall_audit.log"
# Create directories
mkdir -p "$(dirname "$CONFIG_FILE")" "$(dirname "$LOG_FILE")" "$RULES_DIR" "$(dirname "$AUDIT_LOG")"
# Default firewall policy
cat > "$CONFIG_FILE" 2>/dev/null << 'EOF' || true
# MacFleet Enterprise Firewall Management Policy
# Version: 2.0
# Firewall Enforcement Settings
ENFORCE_FIREWALL_ENABLED=true
AUTO_ENABLE_ON_VIOLATION=true
BLOCK_ALL_INCOMING_DEFAULT=true
ALLOW_SIGNED_APPS=true
STEALTH_MODE_ENABLED=true
# Application Control
WHITELIST_SYSTEM_APPS=true
REQUIRE_APP_SIGNATURES=true
BLOCK_UNSIGNED_APPS=true
LOG_ALL_CONNECTIONS=true
AUTO_BLOCK_SUSPICIOUS_APPS=true
# Network Security Policies
BLOCK_PRIVATE_NETWORKS=false
ALLOW_APPLE_SERVICES=true
BLOCK_P2P_CONNECTIONS=true
MONITOR_OUTBOUND_CONNECTIONS=true
RATE_LIMIT_CONNECTIONS=true
# Advanced Security Features
INTRUSION_DETECTION=true
THREAT_INTELLIGENCE_ENABLED=true
GEO_BLOCKING_ENABLED=false
DLP_INSPECTION=true
MALWARE_DETECTION=true
# Compliance and Monitoring
COMPLIANCE_MONITORING=true
SECURITY_BASELINE_ENFORCEMENT=true
AUTOMATED_REPORTING=true
REAL_TIME_ALERTS=true
INCIDENT_RESPONSE=true
# Policy Templates
DEFAULT_SECURITY_PROFILE="corporate_high"
ALLOWED_PORTS="22,53,80,443,993,995"
BLOCKED_COUNTRIES=""
WHITELIST_DOMAINS="*.apple.com,*.icloud.com"
# Maintenance Settings
AUTO_UPDATE_RULES=true
BACKUP_CONFIGURATIONS=true
LOG_RETENTION_DAYS=90
PERFORMANCE_MONITORING=true
EOF
# Source configuration
source "$CONFIG_FILE" 2>/dev/null || true
# Logging function
log_action() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}
# Audit logging function
audit_log() {
local action="$1"
local result="$2"
local details="$3"
echo "$(date '+%Y-%m-%d %H:%M:%S') - ACTION:$action RESULT:$result DETAILS:$details USER:$(whoami)" >> "$AUDIT_LOG"
}
# Get current firewall status
get_firewall_status() {
echo "=== Current Firewall Status ==="
# Check global firewall state
local global_state
global_state=$(/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate 2>/dev/null | grep -o "enabled\|disabled")
echo "Global Firewall State: $global_state"
# Check stealth mode
local stealth_mode
stealth_mode=$(/usr/libexec/ApplicationFirewall/socketfilterfw --getstealthmode 2>/dev/null | grep -o "enabled\|disabled")
echo "Stealth Mode: $stealth_mode"
# Check logging state
local logging_state
logging_state=$(/usr/libexec/ApplicationFirewall/socketfilterfw --getloggingmode 2>/dev/null | grep -o "enabled\|disabled")
echo "Logging: $logging_state"
# Check block all mode
local block_all
block_all=$(/usr/libexec/ApplicationFirewall/socketfilterfw --getblockall 2>/dev/null | grep -o "enabled\|disabled")
echo "Block All Incoming: $block_all"
# Check allowed applications
echo -e "\nAllowed Applications:"
/usr/libexec/ApplicationFirewall/socketfilterfw --listapps 2>/dev/null | grep "ALF" | head -10
return 0
}
# Enable firewall with enterprise settings
enterprise_firewall_enable() {
local security_profile="${1:-$DEFAULT_SECURITY_PROFILE}"
echo "=== Enabling Enterprise Firewall ==="
echo "Security Profile: $security_profile"
# Enable global firewall
log_action "Enabling global firewall"
if sudo defaults write /Library/Preferences/com.apple.alf globalstate -int 1; then
echo "✅ Global firewall enabled"
audit_log "FIREWALL_ENABLE" "SUCCESS" "Global firewall activated"
else
echo "❌ Failed to enable global firewall"
audit_log "FIREWALL_ENABLE" "FAILED" "Global firewall activation failed"
return 1
fi
# Configure based on security profile
case "$security_profile" in
"corporate_high")
configure_high_security_profile
;;
"corporate_standard")
configure_standard_security_profile
;;
"developer")
configure_developer_profile
;;
"kiosk")
configure_kiosk_profile
;;
*)
echo "Unknown security profile, using standard configuration"
configure_standard_security_profile
;;
esac
# Enable stealth mode if required
if [[ "$STEALTH_MODE_ENABLED" == "true" ]]; then
enable_stealth_mode
fi
# Enable logging if required
if [[ "$LOG_ALL_CONNECTIONS" == "true" ]]; then
enable_firewall_logging
fi
# Apply application rules
configure_application_rules
echo "✅ Enterprise firewall configuration completed"
log_action "Enterprise firewall enabled with profile: $security_profile"
return 0
}
# Configure high security profile
configure_high_security_profile() {
echo "=== Configuring High Security Profile ==="
# Block all incoming connections by default
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setblockall on 2>/dev/null
# Enable stealth mode
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setstealthmode on 2>/dev/null
# Disable automatic allow for signed apps
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsigned off 2>/dev/null
# Block all unsigned applications
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsignedapp off 2>/dev/null
echo "High security profile configured"
log_action "High security firewall profile applied"
}
# Configure standard security profile
configure_standard_security_profile() {
echo "=== Configuring Standard Security Profile ==="
# Allow essential incoming connections
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setblockall off 2>/dev/null
# Enable stealth mode
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setstealthmode on 2>/dev/null
# Allow signed applications
if [[ "$ALLOW_SIGNED_APPS" == "true" ]]; then
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsigned on 2>/dev/null
fi
echo "Standard security profile configured"
log_action "Standard security firewall profile applied"
}
# Configure developer profile
configure_developer_profile() {
echo "=== Configuring Developer Profile ==="
# Allow more permissive settings for development
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setblockall off 2>/dev/null
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setstealthmode off 2>/dev/null
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsigned on 2>/dev/null
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsignedapp on 2>/dev/null
# Add common development tools
local dev_apps=(
"/Applications/Xcode.app"
"/Applications/Visual Studio Code.app"
"/Applications/Docker.app"
"/usr/bin/ssh"
"/usr/bin/python3"
)
for app in "${dev_apps[@]}"; do
if [[ -e "$app" ]]; then
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add "$app" 2>/dev/null
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --unblock "$app" 2>/dev/null
fi
done
echo "Developer profile configured"
log_action "Developer firewall profile applied"
}
# Configure kiosk profile
configure_kiosk_profile() {
echo "=== Configuring Kiosk Profile ==="
# Maximum security for kiosk devices
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setblockall on 2>/dev/null
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setstealthmode on 2>/dev/null
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsigned off 2>/dev/null
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsignedapp off 2>/dev/null
# Only allow essential system applications
local kiosk_apps=(
"/System/Library/CoreServices/Finder.app"
"/Applications/Safari.app"
)
for app in "${kiosk_apps[@]}"; do
if [[ -e "$app" ]]; then
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add "$app" 2>/dev/null
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --unblock "$app" 2>/dev/null
fi
done
echo "Kiosk profile configured"
log_action "Kiosk firewall profile applied"
}
# Enable stealth mode
enable_stealth_mode() {
echo "=== Enabling Stealth Mode ==="
if sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setstealthmode on 2>/dev/null; then
echo "✅ Stealth mode enabled"
log_action "Stealth mode enabled"
audit_log "STEALTH_MODE" "ENABLED" "Device hidden from network scans"
else
echo "❌ Failed to enable stealth mode"
log_action "FAILED: Stealth mode enable"
fi
}
# Enable firewall logging
enable_firewall_logging() {
echo "=== Enabling Firewall Logging ==="
if sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setloggingmode on 2>/dev/null; then
echo "✅ Firewall logging enabled"
log_action "Firewall logging enabled"
audit_log "LOGGING" "ENABLED" "All firewall events will be logged"
else
echo "❌ Failed to enable firewall logging"
log_action "FAILED: Firewall logging enable"
fi
}
# Configure application rules
configure_application_rules() {
echo "=== Configuring Application Rules ==="
# Essential system applications
local essential_apps=(
"/System/Library/CoreServices/Software Update.app"
"/usr/sbin/sshd"
"/usr/bin/ssh"
"/Applications/App Store.app"
)
# Add and allow essential applications
for app in "${essential_apps[@]}"; do
if [[ -e "$app" ]]; then
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add "$app" 2>/dev/null
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --unblock "$app" 2>/dev/null
echo "✅ Allowed: $(basename "$app")"
fi
done
# Block known problematic applications
local blocked_apps=(
"/Applications/BitTorrent.app"
"/Applications/P2P Client.app"
)
for app in "${blocked_apps[@]}"; do
if [[ -e "$app" ]]; then
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add "$app" 2>/dev/null
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --block "$app" 2>/dev/null
echo "🚫 Blocked: $(basename "$app")"
fi
done
log_action "Application firewall rules configured"
}
# Disable firewall (with safety checks)
enterprise_firewall_disable() {
local force="${1:-false}"
local reason="$2"
echo "=== Disabling Enterprise Firewall ==="
if [[ "$force" != "true" ]]; then
echo "⚠️ WARNING: Disabling firewall will reduce security"
echo "Use 'force' parameter to override this warning"
if [[ -z "$reason" ]]; then
echo "❌ Reason required for firewall disable operation"
return 1
fi
fi
# Log the disable action
log_action "SECURITY WARNING: Firewall being disabled - Reason: ${reason:-Manual override}"
audit_log "FIREWALL_DISABLE" "INITIATED" "Reason: ${reason:-Manual override}"
# Disable global firewall
if sudo defaults write /Library/Preferences/com.apple.alf globalstate -int 0; then
echo "✅ Global firewall disabled"
audit_log "FIREWALL_DISABLE" "SUCCESS" "Global firewall deactivated"
# Schedule re-enable if temporary
if [[ "$reason" == *"temporary"* || "$reason" == *"maintenance"* ]]; then
schedule_firewall_renable
fi
return 0
else
echo "❌ Failed to disable global firewall"
audit_log "FIREWALL_DISABLE" "FAILED" "Global firewall deactivation failed"
return 1
fi
}
# Schedule firewall re-enable
schedule_firewall_renable() {
local renable_minutes="${1:-60}" # Default 1 hour
echo "🕒 Firewall will be automatically re-enabled in $renable_minutes minutes"
# Create background job to re-enable firewall
(
sleep $((renable_minutes * 60))
log_action "Auto re-enabling firewall after maintenance window"
enterprise_firewall_enable "corporate_standard"
) &
local job_pid=$!
echo "$job_pid" > "/tmp/macfleet_firewall_renable.pid"
log_action "Firewall re-enable scheduled for $renable_minutes minutes (PID: $job_pid)"
}
# Check firewall compliance
check_firewall_compliance() {
echo "=== Firewall Compliance Check ==="
local compliance_issues=()
local compliance_score=100
# Check if firewall is enabled
local firewall_state
firewall_state=$(/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate 2>/dev/null | grep -o "enabled\|disabled")
if [[ "$firewall_state" != "enabled" ]]; then
compliance_issues+=("Firewall not enabled")
compliance_score=$((compliance_score - 30))
fi
# Check stealth mode
if [[ "$STEALTH_MODE_ENABLED" == "true" ]]; then
local stealth_state
stealth_state=$(/usr/libexec/ApplicationFirewall/socketfilterfw --getstealthmode 2>/dev/null | grep -o "enabled\|disabled")
if [[ "$stealth_state" != "enabled" ]]; then
compliance_issues+=("Stealth mode not enabled")
compliance_score=$((compliance_score - 15))
fi
fi
# Check logging
if [[ "$LOG_ALL_CONNECTIONS" == "true" ]]; then
local logging_state
logging_state=$(/usr/libexec/ApplicationFirewall/socketfilterfw --getloggingmode 2>/dev/null | grep -o "enabled\|disabled")
if [[ "$logging_state" != "enabled" ]]; then
compliance_issues+=("Firewall logging not enabled")
compliance_score=$((compliance_score - 10))
fi
fi
# Check for unauthorized applications
local unauthorized_apps
unauthorized_apps=$(/usr/libexec/ApplicationFirewall/socketfilterfw --listapps 2>/dev/null | grep -i "torrent\|p2p\|limewire" | wc -l)
if [[ $unauthorized_apps -gt 0 ]]; then
compliance_issues+=("Unauthorized applications detected: $unauthorized_apps")
compliance_score=$((compliance_score - 20))
fi
# Report compliance status
echo "Compliance Score: $compliance_score/100"
if [[ ${#compliance_issues[@]} -eq 0 ]]; then
echo "✅ Firewall configuration is compliant"
audit_log "COMPLIANCE_CHECK" "PASSED" "Score: $compliance_score/100"
return 0
else
echo "❌ Compliance issues found:"
printf ' - %s\n' "${compliance_issues[@]}"
audit_log "COMPLIANCE_CHECK" "FAILED" "Issues: ${#compliance_issues[@]} Score: $compliance_score/100"
# Auto-remediate if enabled
if [[ "$AUTO_ENABLE_ON_VIOLATION" == "true" ]]; then
echo "🔧 Auto-remediation enabled, fixing issues..."
enterprise_firewall_enable "$DEFAULT_SECURITY_PROFILE"
fi
return 1
fi
}
# Monitor firewall events
monitor_firewall_events() {
echo "=== Starting Firewall Event Monitoring ==="
local log_file="/var/log/appfirewall.log"
if [[ ! -f "$log_file" ]]; then
echo "⚠️ Firewall log file not found. Enabling logging..."
enable_firewall_logging
sleep 2
fi
echo "Monitoring firewall events... Press Ctrl+C to stop"
# Monitor firewall log in real-time
tail -f "$log_file" 2>/dev/null | while read -r line; do
if echo "$line" | grep -q "Deny\|Block"; then
local app_name
app_name=$(echo "$line" | awk '{print $8}' | cut -d'(' -f1)
local action
action=$(echo "$line" | awk '{print $6}')
echo "🚫 $(date '+%H:%M:%S') - BLOCKED: $app_name ($action)"
# Log security event
log_action "SECURITY EVENT: $action - Application: $app_name"
audit_log "FIREWALL_BLOCK" "DETECTED" "App: $app_name Action: $action"
# Check for potential threats
if echo "$app_name" | grep -i -E "(torrent|p2p|hack|crack|keygen)"; then
echo "🚨 SECURITY ALERT: Potentially malicious application blocked: $app_name"
log_action "SECURITY ALERT: Malicious app blocked - $app_name"
fi
fi
done
}
# Generate firewall security report
generate_firewall_report() {
local report_file="$RULES_DIR/firewall_report_$(date +%Y%m%d_%H%M%S).json"
echo "=== Generating Firewall Security Report ==="
# Get current firewall status
local firewall_enabled="false"
local stealth_enabled="false"
local logging_enabled="false"
local block_all_enabled="false"
if /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate 2>/dev/null | grep -q "enabled"; then
firewall_enabled="true"
fi
if /usr/libexec/ApplicationFirewall/socketfilterfw --getstealthmode 2>/dev/null | grep -q "enabled"; then
stealth_enabled="true"
fi
if /usr/libexec/ApplicationFirewall/socketfilterfw --getloggingmode 2>/dev/null | grep -q "enabled"; then
logging_enabled="true"
fi
if /usr/libexec/ApplicationFirewall/socketfilterfw --getblockall 2>/dev/null | grep -q "enabled"; then
block_all_enabled="true"
fi
# Count allowed/blocked applications
local total_apps=0
local allowed_apps=0
local blocked_apps=0
if command -v /usr/libexec/ApplicationFirewall/socketfilterfw >/dev/null; then
total_apps=$(/usr/libexec/ApplicationFirewall/socketfilterfw --listapps 2>/dev/null | grep -c "ALF" || echo 0)
allowed_apps=$(/usr/libexec/ApplicationFirewall/socketfilterfw --listapps 2>/dev/null | grep -c "ALLOW" || echo 0)
blocked_apps=$(/usr/libexec/ApplicationFirewall/socketfilterfw --listapps 2>/dev/null | grep -c "BLOCK" || echo 0)
fi
# Analyze recent security events
local security_events=0
local blocked_connections=0
if [[ -f "/var/log/appfirewall.log" ]]; then
security_events=$(grep -c "$(date '+%Y-%m-%d')" "/var/log/appfirewall.log" 2>/dev/null || echo 0)
blocked_connections=$(grep -c "Deny\|Block" "/var/log/appfirewall.log" 2>/dev/null || echo 0)
fi
# Create JSON report
cat > "$report_file" << EOF
{
"report_type": "firewall_security",
"timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
"device_info": {
"hostname": "$(hostname)",
"os_version": "$(sw_vers -productVersion)",
"serial_number": "$(system_profiler SPHardwareDataType | grep "Serial Number" | awk -F: '{print $2}' | xargs)"
},
"firewall_status": {
"global_firewall_enabled": $firewall_enabled,
"stealth_mode_enabled": $stealth_enabled,
"logging_enabled": $logging_enabled,
"block_all_incoming": $block_all_enabled
},
"application_rules": {
"total_applications": $total_apps,
"allowed_applications": $allowed_apps,
"blocked_applications": $blocked_apps
},
"security_events": {
"total_events_today": $security_events,
"blocked_connections": $blocked_connections,
"last_event": "$(tail -1 /var/log/appfirewall.log 2>/dev/null | awk '{print $1 " " $2 " " $3}' || echo 'N/A')"
},
"compliance_status": {
"policy_compliant": $(check_firewall_compliance >/dev/null 2>&1 && echo true || echo false),
"security_profile": "$DEFAULT_SECURITY_PROFILE",
"auto_remediation": $AUTO_ENABLE_ON_VIOLATION
},
"recommendations": [
$([ "$firewall_enabled" != "true" ] && echo '"Enable global firewall",' || echo "")
$([ "$stealth_enabled" != "true" ] && echo '"Enable stealth mode",' || echo "")
$([ "$logging_enabled" != "true" ] && echo '"Enable firewall logging",' || echo "")
"Regular firewall rule review"
]
}
EOF
echo "Firewall security report saved to: $report_file"
log_action "Firewall security report generated: $report_file"
}
# Main function with argument handling
main() {
log_action "=== MacFleet Firewall Management Tool Started ==="
case "${1:-status}" in
"enable")
enterprise_firewall_enable "$2"
;;
"disable")
enterprise_firewall_disable "$2" "$3"
;;
"status")
get_firewall_status
;;
"compliance")
check_firewall_compliance
;;
"monitor")
monitor_firewall_events
;;
"report")
generate_firewall_report
;;
"stealth")
enable_stealth_mode
;;
"logging")
enable_firewall_logging
;;
"profile")
enterprise_firewall_enable "$2"
;;
*)
echo "MacFleet Enterprise Firewall Management Tool"
echo "Usage: $0 [command] [options]"
echo ""
echo "Commands:"
echo " enable [profile] - Enable firewall with security profile"
echo " disable [force] [reason] - Disable firewall (requires reason)"
echo " status - Show current firewall status"
echo " compliance - Check firewall compliance"
echo " monitor - Monitor firewall events in real-time"
echo " report - Generate security report"
echo " stealth - Enable stealth mode"
echo " logging - Enable firewall logging"
echo " profile [name] - Apply specific security profile"
echo ""
echo "Security Profiles:"
echo " corporate_high - Maximum security for sensitive environments"
echo " corporate_standard - Standard corporate security (default)"
echo " developer - Development-friendly settings"
echo " kiosk - Kiosk/public access security"
;;
esac
log_action "=== Firewall management operation completed ==="
}
# Execute main function
main "$@"
Advanced Firewall Management
Custom Firewall Rules Engine
#!/bin/bash
# Advanced firewall rules management
manage_custom_rules() {
local action="$1"
local rule_name="$2"
local rule_definition="$3"
echo "=== Custom Firewall Rules Management ==="
local rules_file="$RULES_DIR/custom_rules.conf"
case "$action" in
"add")
if [[ -z "$rule_name" || -z "$rule_definition" ]]; then
echo "❌ Rule name and definition required"
return 1
fi
# Add rule to configuration
echo "$rule_name:$rule_definition" >> "$rules_file"
echo "✅ Custom rule '$rule_name' added"
log_action "Custom firewall rule added: $rule_name"
# Apply rule immediately
apply_custom_rule "$rule_definition"
;;
"remove")
if [[ -f "$rules_file" && -n "$rule_name" ]]; then
grep -v "^$rule_name:" "$rules_file" > "$rules_file.tmp"
mv "$rules_file.tmp" "$rules_file"
echo "✅ Custom rule '$rule_name' removed"
log_action "Custom firewall rule removed: $rule_name"
else
echo "❌ Rule '$rule_name' not found"
fi
;;
"list")
if [[ -f "$rules_file" ]]; then
echo "Custom firewall rules:"
cat "$rules_file" | while IFS=':' read -r name definition; do
echo " $name: $definition"
done
else
echo "No custom rules configured"
fi
;;
"apply")
apply_all_custom_rules
;;
*)
echo "Usage: manage_custom_rules [add|remove|list|apply] [rule_name] [definition]"
;;
esac
}
# Apply custom firewall rule
apply_custom_rule() {
local rule_definition="$1"
# Parse rule definition and apply appropriate firewall command
if echo "$rule_definition" | grep -q "block_app:"; then
local app_path
app_path=$(echo "$rule_definition" | cut -d':' -f2)
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add "$app_path" 2>/dev/null
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --block "$app_path" 2>/dev/null
echo "Applied block rule for: $app_path"
elif echo "$rule_definition" | grep -q "allow_app:"; then
local app_path
app_path=$(echo "$rule_definition" | cut -d':' -f2)
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add "$app_path" 2>/dev/null
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --unblock "$app_path" 2>/dev/null
echo "Applied allow rule for: $app_path"
fi
}
# Apply all custom rules
apply_all_custom_rules() {
local rules_file="$RULES_DIR/custom_rules.conf"
if [[ -f "$rules_file" ]]; then
echo "Applying all custom firewall rules..."
while IFS=':' read -r name definition; do
if [[ -n "$name" && -n "$definition" ]]; then
apply_custom_rule "$definition"
fi
done < "$rules_file"
echo "✅ All custom rules applied"
else
echo "No custom rules to apply"
fi
}
# Example custom rules
create_example_rules() {
manage_custom_rules "add" "block_bittorrent" "block_app:/Applications/BitTorrent.app"
manage_custom_rules "add" "allow_docker" "allow_app:/Applications/Docker.app"
manage_custom_rules "add" "allow_ssh" "allow_app:/usr/bin/ssh"
}
create_example_rules
Network Threat Detection
#!/bin/bash
# Advanced threat detection for firewall
detect_network_threats() {
echo "=== Network Threat Detection ==="
local threat_indicators=()
local risk_score=0
# Check for suspicious network connections
echo "Scanning for suspicious network activity..."
# Check for unusual outbound connections
local unusual_connections
unusual_connections=$(netstat -an | grep ESTABLISHED | grep -E ":(6667|6697|1337|31337|4444)" | wc -l)
if [[ $unusual_connections -gt 0 ]]; then
threat_indicators+=("Suspicious outbound connections detected: $unusual_connections")
risk_score=$((risk_score + 20))
fi
# Check for high-risk processes with network access
local risky_processes=()
while IFS= read -r line; do
if echo "$line" | grep -i -E "(torrent|p2p|hack|crack|keygen|bot|trojan)"; then
risky_processes+=("$line")
risk_score=$((risk_score + 15))
fi
done < <(lsof -i -n | awk '{print $1}' | sort -u)
if [[ ${#risky_processes[@]} -gt 0 ]]; then
threat_indicators+=("High-risk processes with network access: ${#risky_processes[@]}")
fi
# Check for firewall bypass attempts
local bypass_attempts
bypass_attempts=$(grep -c "socketfilterfw" /var/log/system.log 2>/dev/null || echo 0)
if [[ $bypass_attempts -gt 10 ]]; then
threat_indicators+=("Potential firewall bypass attempts: $bypass_attempts")
risk_score=$((risk_score + 25))
fi
# Report threat assessment
echo "Threat Risk Score: $risk_score/100"
if [[ ${#threat_indicators[@]} -eq 0 ]]; then
echo "✅ No immediate threats detected"
audit_log "THREAT_SCAN" "CLEAN" "Risk score: $risk_score"
return 0
else
echo "⚠️ Potential threats detected:"
printf ' - %s\n' "${threat_indicators[@]}"
# Log security alert
log_action "SECURITY ALERT: Network threats detected - Risk score: $risk_score"
audit_log "THREAT_SCAN" "THREATS_FOUND" "Count: ${#threat_indicators[@]} Risk: $risk_score"
# Auto-remediation for high-risk scenarios
if [[ $risk_score -gt 50 ]]; then
echo "🚨 High risk detected - Enabling maximum security profile"
configure_high_security_profile
fi
return 1
fi
}
# Automated threat response
automated_threat_response() {
local threat_level="$1"
local threat_type="$2"
echo "=== Automated Threat Response ==="
echo "Threat Level: $threat_level"
echo "Threat Type: $threat_type"
case "$threat_level" in
"high")
# Maximum security measures
echo "Implementing high-security measures..."
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setblockall on 2>/dev/null
enable_stealth_mode
log_action "HIGH THREAT RESPONSE: Maximum security enabled"
;;
"medium")
# Enhanced monitoring
echo "Enabling enhanced monitoring..."
enable_firewall_logging
log_action "MEDIUM THREAT RESPONSE: Enhanced monitoring enabled"
;;
"low")
# Standard monitoring
echo "Maintaining standard security posture..."
log_action "LOW THREAT RESPONSE: Standard monitoring maintained"
;;
*)
echo "Unknown threat level: $threat_level"
;;
esac
# Send alert if configured
if [[ "$REAL_TIME_ALERTS" == "true" ]]; then
send_security_alert "$threat_level" "$threat_type"
fi
}
# Send security alert
send_security_alert() {
local threat_level="$1"
local threat_type="$2"
local alert_message="SECURITY ALERT: $threat_level level $threat_type detected on $(hostname) at $(date)"
# Log the alert
log_action "SECURITY ALERT SENT: $alert_message"
# In a real implementation, this would send alerts via:
# - Email to security team
# - SIEM integration
# - Slack/Teams notification
# - MDM console alert
echo "🚨 Security alert sent: $alert_message"
}
# Example usage:
# detect_network_threats
# automated_threat_response "high" "malware_communication"
Monitoring and Compliance
Real-time Security Monitoring
#!/bin/bash
# Comprehensive firewall security monitoring
start_security_monitoring() {
echo "=== Starting Real-time Security Monitoring ==="
local monitor_pid_file="$RULES_DIR/security_monitor.pid"
# Store monitor PID
echo $$ > "$monitor_pid_file"
echo "Security monitoring started (PID: $$)"
# Cleanup function
cleanup() {
echo "Stopping security monitor..."
rm -f "$monitor_pid_file"
exit 0
}
trap cleanup SIGTERM SIGINT
while true; do
# Check firewall compliance every 5 minutes
if ! check_firewall_compliance >/dev/null 2>&1; then
echo "⚠️ Compliance violation detected at $(date)"
if [[ "$AUTO_ENABLE_ON_VIOLATION" == "true" ]]; then
echo "🔧 Auto-remediation triggered"
enterprise_firewall_enable "$DEFAULT_SECURITY_PROFILE" >/dev/null 2>&1
fi
fi
# Run threat detection every 10 minutes
if [[ $(($(date +%s) % 600)) -eq 0 ]]; then
detect_network_threats >/dev/null 2>&1
fi
# Check for firewall configuration changes
local current_config_hash
current_config_hash=$(md5 -q /Library/Preferences/com.apple.alf.plist 2>/dev/null || echo "")
if [[ -f "$RULES_DIR/last_config_hash" ]]; then
local last_hash
last_hash=$(cat "$RULES_DIR/last_config_hash")
if [[ "$current_config_hash" != "$last_hash" ]]; then
echo "🔄 Firewall configuration changed at $(date)"
log_action "Firewall configuration change detected"
audit_log "CONFIG_CHANGE" "DETECTED" "Hash changed from $last_hash to $current_config_hash"
fi
fi
echo "$current_config_hash" > "$RULES_DIR/last_config_hash"
sleep 60 # Check every minute
done
}
# Stop security monitoring
stop_security_monitoring() {
local monitor_pid_file="$RULES_DIR/security_monitor.pid"
if [[ -f "$monitor_pid_file" ]]; then
local monitor_pid
monitor_pid=$(cat "$monitor_pid_file")
if kill -0 "$monitor_pid" 2>/dev/null; then
kill "$monitor_pid"
echo "Security monitor stopped (PID: $monitor_pid)"
rm -f "$monitor_pid_file"
else
echo "Monitor process not found"
rm -f "$monitor_pid_file"
fi
else
echo "No monitor PID file found"
fi
}
# Example usage:
# start_security_monitoring &
# stop_security_monitoring
Important Configuration Notes
macOS Firewall Architecture
- Application Firewall - Controls incoming connections per application
- Socket Filter Framework - Low-level packet filtering
- Network Extension Framework - Modern content filtering
- System Integrity Protection - Protects firewall configuration
- Privacy Controls - User consent for network access
Enterprise Integration Points
- MDM Configuration Profiles - Deploy firewall policies centrally
- SIEM Integration - Forward security logs to monitoring systems
- Compliance Frameworks - Support for SOC 2, ISO 27001, NIST
- Incident Response - Automated threat detection and response
Best Practices for Enterprise
-
Layered Security Approach
- Combine application firewall with network segmentation
- Implement endpoint detection and response (EDR)
- Use network access control (NAC)
- Deploy intrusion detection systems (IDS)
-
Policy Management
- Define clear security baselines
- Regularly review and update firewall rules
- Implement change management processes
- Test security policies regularly
-
Monitoring and Response
- Enable comprehensive logging
- Monitor for configuration changes
- Implement automated threat detection
- Establish incident response procedures
-
Compliance and Auditing
- Generate regular compliance reports
- Maintain audit trails
- Document security exceptions
- Conduct periodic security assessments
Troubleshooting Common Issues
- Permission errors - Ensure admin privileges for firewall modifications
- Application connectivity - Review firewall rules for blocked applications
- Performance impact - Monitor CPU usage with extensive logging enabled
- Configuration conflicts - Check for conflicting MDM profiles
- Log file growth - Implement log rotation and archival
Remember to test firewall configurations thoroughly in a controlled environment before deploying across your entire MacFleet to ensure business continuity while maintaining security.