Automation guides, explanations and reader checklists on whilenetworking.com

Bash Challenge: Scripting an Automated Log Rotation Strategy for High-Volume Firewall Logs with Compression

Firewall logs are the digital exhaust of your network security posture. On high-volume systems, these logs can accumulate hundreds of gigabytes daily,…

Firewall logs are the digital exhaust of your network security posture. On high-volume systems, these logs can accumulate hundreds of gigabytes daily, filling disk space and degrading performance if not managed correctly. Manual rotation is impossible to sustain at scale; it requires an automated strategy that balances disk usage, readability, and retention policies. This guide outlines a robust Bash-based approach to automating log rotation with compression, suitable for Linux environments running firewalls like pfSense (Linux package), iptables setups, or custom appliances.

Understanding the Core Requirements

Before writing scripts, you must define your constraints. A typical high-volume firewall generates logs at a rate of 50MB to 200MB per hour. Without intervention, an /var/log partition might fill within days. Your rotation strategy needs three pillars:
1. Time-based Triggers: Rotate logs daily or hourly based on volume thresholds.
2. Compression: Use gzip or zstd to reduce storage footprint by 80-95%.
3. Retention Policies: Automatically delete old compressed files older than a specific period (e.g., 30 days) to comply with data governance while keeping recent data accessible.

The standard tool for this in Linux is logrotate, but understanding the underlying Bash logic allows you to customize behavior beyond default configurations, which often struggle with very large single files or specific retention windows.

Setting Up the Environment and Prerequisites

To implement this strategy safely, ensure your target system meets these prerequisites:
* Operating System: A stable Linux distribution (e.g., Ubuntu 22.04 LTS, RHEL 9, or Debian).
* Tools Installed: gzip (usually pre-installed), find, and cron. For modern high-compression needs, consider installing zstd (apt install zstd).
* Permissions: The script will run as root or via sudo, but the rotation logic should be isolated to avoid accidental deletion of active system logs.

Do not attempt this on a production firewall without first replicating the environment in a lab. High-volume log files are sensitive; rotating them while they are being written can cause brief I/O stalls or corruption if not handled with sync and proper locking.

Step 1: Analyzing Log Volume and Naming Conventions

The first step is identifying the target log file. Common firewall logs reside in /var/log/firewall.log or similar paths depending on the distro. You must verify the current size and growth rate.

Run the following command to inspect the active log:

ls -lh /var/log/firewall.log
du -sh /var/log/

Expected Result: The output will show the file size (e.g., 245M) and the total directory usage. If the file exceeds 1GB, immediate rotation is recommended.

Step 2: Creating the Custom Rotation Script

We will create a Bash script named /usr/local/bin/rotate-firewall-logs.sh. This script handles compression and cleanup in one pass.

Create the file using nano or vim:

sudo nano /usr/local/bin/rotate-firewall-logs.sh

Paste the following code, which implements a volume-based check followed by time-based rotation:

#!/bin/bash

# Configuration Variables
LOG_FILE="/var/log/firewall.log"
COMPRESSED_DIR="/var/log/archive"
MAX_SIZE_MB=100      # Rotate if file exceeds 100MB
RETENTION_DAYS=30    # Keep compressed logs for 30 days

# Ensure archive directory exists and is readable
mkdir -p "$COMPRESSED_DIR"
chmod 755 "$COMPRESSED_DIR"

# Check if log file exists
if [[ ! -f "$LOG_FILE" ]]; then
    echo "[INFO] Log file $LOG_FILE does not exist. Skipping rotation."
    exit 0
fi

# Get current timestamp for naming the new archive
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
ARCHIVE_NAME="firewall-${TIMESTAMP}.log.gz"

# Step A: Check Volume Threshold
CURRENT_SIZE=$(du -b "$LOG_FILE" | cut -f1)
MAX_BYTES=$((MAX_SIZE_MB * 1024 * 1024))

if [[ $CURRENT_SIZE -gt $MAX_BYTES ]]; then
    echo "[WARN] Log file exceeds ${MAX_SIZE_MB}MB. Initiating rotation."

    # Step B: Compress and Move
    # Using gzip with force to overwrite if a same-name archive exists (rare but safe)
    gzip -c "$LOG_FILE" > "$COMPRESSED_DIR/$ARCHIVE_NAME"

    # Clear the original log file to start fresh
    > "$LOG_FILE"
    sync

    echo "[SUCCESS] Rotated: $LOG_FILE -> $ARCHIVED_NAME"
else
    echo "[INFO] Log size is within limits. No rotation needed."
fi

# Step C: Cleanup Old Archives (Retention Policy)
echo "[INFO] Checking for files older than ${RETENTION_DAYS} days in $COMPRESSED_DIR..."
find "$COMPRESSED_DIR" -name "*.log.gz" -type f -mtime +$RETENTION_DAYS -delete

echo "[INFO] Rotation cycle complete."

Make the script executable:

sudo chmod +x /usr/local/bin/rotate-firewall-logs.sh

Step 3: Scheduling with Cron

Automation requires a scheduled job. We will use cron to run this script every hour, ensuring logs are captured frequently enough for analysis but not so often that disk I/O becomes an issue.

Edit the root crontab:

sudo crontab -e

Add the following line to run the script at minute 0 of every hour:

0 * * * * /usr/local/bin/rotate-firewall-logs.sh >> /var/log/cron-logrotate.log 2>&1

Note: Redirecting output to a separate log file (cron-logrotate.log) helps debug failures without cluttering the main system logs.

Verification and Common Errors

After scheduling, wait for the next hour or manually trigger the script with sudo /usr/local/bin/rotate-firewall-logs.sh.

Verification Steps:
1. Check the archive directory: ls -lh /var/log/archive/. You should see a new .gz file.
2. Check the original log: The file size should be near zero (or minimal if you are appending to it in real-time).
3. Review the error log: tail -n 50 /var/log/cron-logrotate.log.

Common Errors and Fixes:
* Permission Denied: If the script cannot write to /var/log/archive, ensure the directory owner is root or matches the user running cron (usually root). Fix with sudo chown root:root /var/log/archive.
* Missing gzip Command: If the compression step fails, gzip might be missing. Install it via your package manager (apt install gzip or yum install gzip).
* Race Condition: If the firewall application writes logs in a way that breaks atomicity during rotation, you may see corrupted files. Ensure the application flushes buffers before the script runs, or use logrotate‘s copytruncate mechanism instead of direct truncation for critical systems.

Student Practice Task and Industry Application

For Students: Set up a virtual machine (e.g., using VirtualBox with Ubuntu Server). Generate fake log data by running a loop that appends random text to /var/log/firewall.log every second. Then, deploy the script above and observe how it handles rapid growth. Experiment by changing MAX_SIZE_MB to see immediate vs. scheduled rotation effects.

For Industry Practitioners: This pattern integrates with Ansible playbooks for infrastructure-as-code management. You can include this logic in a playbook that deploys firewalls across multiple sites, ensuring consistent retention policies (e.g., 30 days for compliance) and compression standards are enforced automatically upon provisioning. Always verify local jurisdiction laws regarding data retention; some regions require logs to be kept longer than the standard 30-day window.

Conclusion

Automating log rotation is a critical hygiene task for network security operations. By combining volume checks, gzip compression, and cron scheduling, you create a resilient system that maintains disk health without manual intervention. This Bash-based solution offers flexibility beyond default logrotate configurations, allowing engineers to tailor retention and compression strategies to specific hardware constraints and compliance requirements.

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.