Goal

Master cron scheduling for security automation, build security maintenance scripts, and create a complete automated security workflow suite.

Prerequisites: Week 10a (Bash Scripting & GPG Automation)

This is Part 2 of 2 - Covers scheduling and complete automation workflows.


1. Cron Jobs for Automation

Understanding Cron Syntax

# ┌───────────── minute (0-59)
# │ ┌─────────── hour (0-23)
# │ │ ┌───────── day of month (1-31)
# │ │ │ ┌─────── month (1-12)
# │ │ │ │ ┌───── day of week (0-7, Sunday = 0 or 7)
# │ │ │ │ │
# * * * * * command to execute

Examples:

# Every day at 2 AM
0 2 * * * /home/user/scripts/backup.sh

# Every Monday at 9 AM
0 9 * * 1 /home/user/scripts/weekly-report.sh

# Every hour
0 * * * * /home/user/scripts/hourly-check.sh

# Every 15 minutes
*/15 * * * * /home/user/scripts/frequent-task.sh

Setting Up Cron Jobs

# Edit crontab
crontab -e

# Add your jobs
0 2 * * * /home/user/scripts/encrypted-backup.sh
0 3 * * * /home/user/scripts/cleanup-logs.sh
0 4 * * 0 /home/user/scripts/weekly-key-rotation.sh

# List current cron jobs
crontab -l

# Remove all cron jobs (careful!)
crontab -r

Cron Best Practices for Security Scripts

1. Use absolute paths:

# Bad
cd ~/scripts && ./backup.sh  # Might not work

# Good
/home/user/scripts/backup.sh  # Always works

2. Set PATH in crontab:

PATH=/usr/local/bin:/usr/bin:/bin
0 2 * * * encrypted-backup.sh

3. Redirect output to log:

0 2 * * * /home/user/scripts/backup.sh >> /var/log/backup.log 2>&1

4. Email failures:

MAILTO=[email protected]
0 2 * * * /home/user/scripts/backup.sh

2. Security Maintenance Scripts

System Update Automation

#!/bin/bash
# auto-update.sh - Automated security updates with logging

LOG="/var/log/auto-update.log"

echo "[$(date)] Starting security updates" >> "$LOG"

# Update package lists
apt-get update >> "$LOG" 2>&1

# Upgrade security packages only
apt-get upgrade -y --only-upgrade -o Dpkg::Options::="--force-confdef" >> "$LOG" 2>&1

# Auto-remove unnecessary packages
apt-get autoremove -y >> "$LOG" 2>&1

echo "[$(date)] Updates complete" >> "$LOG"

# Check if reboot needed
if [ -f /var/run/reboot-required ]; then
    echo "[$(date)] REBOOT REQUIRED" >> "$LOG"
    # Optionally send email alert
fi

Failed Login Monitor

#!/bin/bash
# monitor-failed-logins.sh - Alert on suspicious login attempts

THRESHOLD=5
LOG_FILE="/var/log/auth.log"
ALERT_EMAIL="[email protected]"

# Count failed login attempts in last hour
FAILED_LOGINS=$(grep "Failed password" "$LOG_FILE" | \
    grep "$(date +%b\ %d\ %H)" | wc -l)

if [ $FAILED_LOGINS -gt $THRESHOLD ]; then
    echo "WARNING: $FAILED_LOGINS failed login attempts in the last hour" | \
        mail -s "Security Alert: Failed Logins" "$ALERT_EMAIL"

    # Log to encrypted audit trail
    ./log-encrypted.sh "ALERT: $FAILED_LOGINS failed logins detected"
fi

Disk Encryption Health Check

#!/bin/bash
# check-encryption.sh - Verify LUKS encryption status

# Check all encrypted volumes
lsblk -f | grep crypto | while read line; do
    DEVICE=$(echo "$line" | awk '{print $1}')

    # Verify encryption is active
    cryptsetup status "$DEVICE" > /dev/null 2>&1

    if [ $? -eq 0 ]; then
        echo "✓ $DEVICE is encrypted and active"
    else
        echo "✗ WARNING: $DEVICE encryption issue!"
    fi
done

# Check gocryptfs mounts
mount | grep gocryptfs | while read line; do
    echo "✓ gocryptfs mount detected: $line"
done

3. Complete Automation Workflow

Daily Security Routine (Cron)

# Daily at 2 AM: Encrypted backup
0 2 * * * /home/user/scripts/encrypted-backup.sh

# Daily at 3 AM: Log rotation
0 3 * * * /home/user/scripts/rotate-logs.sh

# Daily at 4 AM: System updates
0 4 * * * /home/user/scripts/auto-update.sh

# Every 6 hours: Failed login check
0 */6 * * * /home/user/scripts/monitor-failed-logins.sh

# Weekly on Sunday at 5 AM: Full system report
0 5 * * 0 /home/user/scripts/weekly-security-report.sh

Weekly Security Report Script

#!/bin/bash
# weekly-security-report.sh - Comprehensive security status

REPORT="/tmp/security-report-$(date +%Y-%m-%d).txt"

echo "Weekly Security Report - $(date)" > "$REPORT"
echo "======================================" >> "$REPORT"

# Disk usage
echo -e "\nDisk Usage:" >> "$REPORT"
df -h >> "$REPORT"

# Backup status
echo -e "\nRecent Backups:" >> "$REPORT"
ls -lh /mnt/backup/ | tail -5 >> "$REPORT"

# Failed logins
echo -e "\nFailed Login Attempts (Last 7 Days):" >> "$REPORT"
grep "Failed password" /var/log/auth.log | tail -10 >> "$REPORT"

# Key expiration check
echo -e "\nGPG Key Status:" >> "$REPORT"
gpg --list-keys >> "$REPORT"

# Encrypt and email report
gpg --encrypt --recipient "[email protected]" \
    --output "${REPORT}.gpg" "$REPORT"

mail -s "Weekly Security Report" \
    -a "${REPORT}.gpg" \
    [email protected] < /dev/null

# Clean up
shred -u "$REPORT"
rm "${REPORT}.gpg"

4. Hands-On Labs

Lab 1: Create Encrypted Backup System

Goal: Build automated daily encrypted backups

Steps:

  1. Write encrypted-backup.sh script
  2. Test script manually
  3. Add to crontab for daily 2 AM execution
  4. Verify backup created and encrypted
  5. Test restore procedure

Deliverable: Working automated backup system


Lab 2: Build Security Monitoring System

Goal: Automate security checks

Steps:

  1. Create failed-login-monitor.sh
  2. Create disk-encryption-check.sh
  3. Create weekly-security-report.sh
  4. Schedule all with cron
  5. Test alert notifications

Deliverable: Automated security monitoring


Lab 3: Encrypted Logging System

Goal: Implement encrypted audit trail

Steps:

  1. Create log-encrypted.sh function
  2. Create rotate-logs.sh for log rotation
  3. Integrate logging into other scripts
  4. Schedule monthly log rotation
  5. Test decrypting and reading logs

Deliverable: Encrypted logging infrastructure


Lab 4: Personal Security Automation Suite

Goal: Design complete automation workflow

Steps:

  1. List all manual security tasks you do
  2. Write scripts to automate each task
  3. Create master cron schedule
  4. Document your automation system
  5. Test for one week

Deliverable: Personal security automation documentation


5. Security Considerations

Secure Script Storage

Store scripts in encrypted directory:

# Create encrypted script directory
mkdir ~/scripts-encrypted
gocryptfs -init ~/scripts-encrypted
gocryptfs ~/scripts-encrypted ~/scripts

# Store scripts in ~/scripts (actually encrypted)

Passphrase Management for Scripts

Options:

1. gpg-agent (recommended):

  • Caches passphrase securely
  • Works for GPG operations
  • Timeout configurable

2. Keyfile approach:

# Encrypt with keyfile instead of passphrase
gpg --symmetric --cipher-algo AES256 \
    --passphrase-file /secure/path/keyfile \
    input.txt

3. Hardware tokens:

  • YubiKey for GPG operations
  • No passphrase needed, requires physical key

6. Journal & Git Commit

echo "Week 10: Built complete security automation suite - encrypted backups, log rotation, failed login monitoring, weekly reports. All scheduled with cron. Key insight: automation prevents security fatigue." >> notes/week10_journal.md

git add .
git commit -S -m "Week 10 - Security automation, cron scheduling, encrypted workflows"

Week 10 Checklist

Bash Scripting:

  • Understand error handling (set -euo pipefail)
  • Write functions for reusable code
  • Use variables and arrays effectively
  • Implement logging in scripts

GPG in Scripts:

  • Configure gpg-agent for automation
  • Encrypt/decrypt files programmatically
  • Pipe data through GPG
  • Handle errors gracefully

Backup Automation:

  • Create encrypted backup scripts
  • Implement rotation/cleanup logic
  • Test restore procedures
  • Schedule with cron

Security Automation:

  • Monitor failed logins
  • Check encryption status
  • Rotate logs securely
  • Generate security reports

Cron Mastery:

  • Understand cron syntax
  • Schedule tasks appropriately
  • Handle output and errors
  • Test cron jobs thoroughly

Additional Resources

Bash Scripting

GPG Automation

Cron


Key Takeaways

  • Cron syntax is minute/hour/day/month/weekday - Learn the pattern
  • Always use absolute paths in cron - Relative paths fail silently
  • Redirect cron output to logs - Debug failures easily
  • Security monitoring should be automated - Failed logins, encryption status
  • Weekly reports provide overview - Catch issues before they become problems
  • Test manually before scheduling - Cron failures are silent without logging