In modern cybersecurity operations, log management is not just about storage; it is about balancing compliance archiving with immediate threat detection. A common challenge for system administrators and junior engineers is handling high-volume firewall logs from devices like pfSense, iptables, or cloud gateways. These logs fill disk space rapidly while critical security events—such as port scans, brute-force attempts, or data exfiltration patterns—need instant attention. This guide walks you through building a robust Bash script that automates the archiving of historical logs to Amazon S3 (or compatible object storage) while simultaneously parsing for critical alerts and triggering notifications to security teams via email or Slack.
This lab scenario assumes a Linux environment where firewall logs are stored in /var/log/firewall/. The goal is to create a scheduled job that processes these logs, moves files older than 24 hours to an S3 bucket, and analyzes the most recent entries for specific threat signatures.
Prerequisites and Environment Setup
Before writing the script, you must ensure your environment meets specific requirements. This lab uses standard Linux tools available on Ubuntu, Debian, or RHEL distributions.
Required Tools:
* Bash Shell: Version 4.x or higher is recommended for associative arrays and advanced string manipulation.
* AWS CLI v2: Installed and configured with valid credentials (aws configure).
* Python3: Required for the boto3 library to interact with S3 securely.
* Sed/Grep/Awk: Standard utilities included in most Linux distros for log parsing.
* Notification Tool: We will use curl to send a payload to a webhook (e.g., Slack, Discord, or a custom SMTP server).
Safety First: Always test automation scripts on a non-production machine first. Ensure your AWS credentials have the minimal required permissions: s3:PutObject, s3:GetObject, and sns:Publish. Never commit actual access keys to version control systems like Git.
Step 1: Define Threat Signatures and Archive Policies
The logic of the script relies on two distinct policies: retention for compliance and detection for security. We must define what constitutes “old” data and what constitutes a “critical alert.”
Archive Policy:
* Threshold: Files modified more than 24 hours ago.
* Destination: An S3 bucket named company-firewall-archive-prod.
* Naming Convention: Append the original filename with a timestamp (e.g., firewall.log.2023-10-27T12-00-00Z).
Critical Alert Definitions:
We will look for three common attack patterns in the latest 1,000 lines of the active log file:
1. Port Scans: Strings matching INVALID USER or repeated connection rejections.
2. Brute Force: Strings containing failed password or authentication failure.
3. Exfiltration: Large outbound transfers (e.g., sent bytes > 100M).
Step 2: Constructing the Bash Script Architecture
We will create a script named /usr/local/bin/log_manager.sh. This script uses a function-based approach to keep code modular and readable.
#!/bin/bash
# log_manager.sh - Firewall Log Archiver and Alert Generator
# Author: IT Automation Team
# Date: 2023-10-27
set -euo pipefail # Exit on error, undefined vars, or failed pipe
# Configuration Variables
LOG_DIR="/var/log/firewall"
ACTIVE_LOG="${LOG_DIR}/firewall.log"
ARCHIVE_BUCKET="company-firewall-archive-prod"
AWS_REGION="us-east-1"
ALERT_WEBHOOK_URL="https://hooks.slack.com/services/YOUR/WEBHOOK/URL" # Replace with real URL or SMTP config
# Function: Check prerequisites
check_prereqs() {
if ! command -v aws &> /dev/null; then
echo "ERROR: AWS CLI is not installed." >&2
exit 1
fi
if [[ ! -f "$ACTIVE_LOG" ]]; then
echo "WARNING: Active log file not found at $ACTIVE_LOG. Skipping analysis." >&2
# Proceed to archive check if active log is missing but bucket exists
fi
}
# Function: Archive old logs to S3
archive_old_logs() {
local cutoff_time=$(date -d "24 hours ago" +%s)
for file in "$LOG_DIR"/*.log.*; do
[[ -f "$file" ]] || continue
# Get modification time in seconds since epoch
local mtime=$(stat -c %Y "$file")
if (( mtime < cutoff_time )); then
echo "Archiving: $(basename $file)"
# Upload to S3 with metadata tagging
aws s3 cp "$file" "s3://${ARCHIVE_BUCKET}/$(date +%Y%m%d)/$(basename $file)" \
--metadata "source=firewall-automation,type=archive" \
--region "$AWS_REGION"
# Optional: Remove local file after successful upload
# rm "$file"
fi
done
}
# Function: Analyze recent logs for threats
analyze_threats() {
if [[ ! -f "$ACTIVE_LOG" ]]; then
return
fi
# Read the last 1000 lines to avoid OOM on massive logs
tail -n 1000 "$ACTIVE_LOG" | grep -iE "(INVALID USER|failed password|authentication failure|sent bytes > 100)" > /tmp/threat_hits.log || true
if [[ -s /tmp/threat_hits.log ]]; then
local alert_count=$(wc -l < /tmp/threat_hits.log)
# Construct the alert message
local alert_msg="🚨 **CRITICAL SECURITY ALERT** 🚨\n\n"
alert_msg+="Detected $alert_count potential threat events in recent firewall logs.\n\n"
alert_msg+="**Details:**\n$(cat /tmp/threat_hits.log)\n\n"
alert_msg+="**Action Required:** Security team to review immediate traffic patterns."
# Send notification (Simulated curl command for demo)
echo "$alert_msg" | curl -s -X POST "$ALERT_WEBHOOK_URL" \
-H 'Content-Type: application/json' \
--data-urlencode "payload={\"text\":\"$alert_msg\"}"
echo "Alert sent successfully."
else
echo "No critical threats detected in the recent log window."
fi
rm -f /tmp/threat_hits.log
}
# Main Execution Flow
check_prereqs
archive_old_logs
analyze_threats
echo "Log management cycle completed at $(date)."
Explanation of Key Sections
set -euo pipefail: This ensures the script stops immediately if a command fails, preventing partial executions that could corrupt data.check_prereqs: Validates that necessary tools exist before running heavy operations.archive_old_logs: Usesstatto check file modification times against a calculated cutoff. It then uses the AWS CLIs3 cpcommand with metadata tagging for better inventory management later.analyze_threats: Utilizestailto focus only on recent activity, which is crucial for performance. It pipes output throughgrep -iEusing an Extended Regular Expression to catch multiple threat types in one pass.
Step 3: Expected Results and Verification
When you run the script (sudo /usr/local/bin/log_manager.sh), you should observe specific behaviors depending on the state of your logs.
Illustrative Output (Success Scenario):
Archiving: firewall.log.2023-10-26T12-00-00Z
Alert sent successfully.
Log management cycle completed at Thu Oct 27 14:30:00 UTC 2023.
Illustrative Output (No Threats Scenario):
No critical threats detected in the recent log window.
Archiving: firewall.log.2023-10-25T12-00-00Z
Log management cycle completed at Thu Oct 27 14:30:00 UTC 2023.
Verification Steps:
1. Check S3 Console: Navigate to the AWS S3 console, locate the bucket, and verify that the archived file exists in the YYYYMMDD folder structure. Check the metadata tab to ensure tags were applied correctly.
2. Review Notification History: If using Slack or Discord, check the channel history for the embedded alert message. Ensure the payload JSON was formatted correctly.
3. Inspect Log Rotation: Verify that the local log file has not been deleted (unless explicitly commented out in the script) to ensure audit trails remain intact until manual rotation policies are applied.
Common Errors and Fixes
- Error:
aws s3 cpreturns “Access Denied”- Cause: Invalid AWS credentials or missing S3 permissions.
- Fix: Re-run
aws configureor check IAM role attached to the EC2 instance if running in a cloud environment. Ensure the bucket policy allows uploads from your specific IP or VPC endpoint.
- Error:
grep: invalid option -- 'i'- Cause: Running on an older macOS terminal (BSD grep) or a restricted container without GNU grep.
- Fix: Update
grepto the GNU version (sudo apt install grepon Debian/Ubuntu) or modify the script to usesedfor filtering if compatibility is an issue.
- Error: Permission Denied
- Cause: The script attempts to read
/var/log/firewall. - Fix: Always run the script with
sudoor change the file permissions of the log directory (chmod 750 /var/log/firewall) and add the user running the script to the appropriate group.
- Cause: The script attempts to read
Student Practice Task and Industry Application
Student Practice Task:
Modify the provided script to add a new alert condition: flag any line containing the word root combined with login failure. Update the alert_msg variable to include a link to your organization’s Incident Response Plan (IRP). Submit the modified code snippet.
Industry Application:
In a production environment, this script would be integrated into a CI/CD pipeline or a configuration management tool like Ansible. You could use cron to schedule the script to run every hour:
0 * * * * /usr/local/bin/log_manager.sh >> /var/log/log_manager.log 2>&1
For enterprise deployments, consider replacing the simple curl webhook with a dedicated SIEM ingestion agent (like Splunk HEC or ELK Stack) to ensure alerts are indexed for long-term forensic analysis rather than just displayed in a chat channel.
By automating the separation of “hot” data (real-time security monitoring) and “cold” data (compliance archiving), organizations can reduce storage costs, improve disk I/O performance, and ensure that security teams are never overwhelmed by noise while critical threats are instantly highlighted.
Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.

