Course contentsShow
← Linux
Lesson 1053 of 1,8199. Security Hardening and Mandatory Access ControlFree lesson

Automated Cleanup of Stale Policies

Implement scripts to identify and remove unused policies to keep the system clean.

In this lesson, you will learn how to implement automated cleanup routines to safely identify and prune stale or unused security policies, ensuring your Mandatory Access Control (MAC) layer remains lean and performant.

The Problem of Policy Bloat

As systems evolve, services are decommissioned, and applications are updated, security policies often remain on the disk long after they have served their purpose. In systems using frameworks like SELinux or AppArmor, this "policy drift" doesn't just clutter your /etc/ directories; it increases the complexity of policy audits and can inadvertently expand your attack surface by leaving permissive rules active for software that is no longer present.

Implementing Automated Cleanup

To clean up stale policies, we must correlate active system processes or installed packages with the loaded security profiles. A common approach involves identifying "orphan" policy files—those that do not correspond to any currently installed software or active system service.

Consider a simple cleanup script logic that identifies policy files that haven't been referenced by a service recently. You can leverage the audit logs or systemd metadata to track usage:

#!/bin/bash
# Identify and list stale policy profiles
POLICY_DIR="/etc/apparmor.d"

for profile in "$POLICY_DIR"/*; do
    profile_name=$(basename "$profile")
    # Check if the service associated with the profile is running
    if ! systemctl is-active --quiet "$profile_name"; then
        echo "Potential stale policy found: $profile_name"
        # Move to a quarantine directory for verification
        mv "$profile" /var/lib/security_quarantine/
    fi
done

Safety First: The Quarantine Workflow

Never delete stale policies immediately. Instead, move them to a "quarantine" or "archive" directory. This allows you to verify if the system or a specific user-space application actually relies on the policy during unusual events (like a maintenance script or a rare administrative task). By observing the system for a retention period (e.g., 30 days) after moving the file to quarantine, you can confidently delete files that have not caused any "Permission Denied" errors in your MAC audit logs.

Automating this cleanup ensures that your security posture remains tight and that your policy engine isn't wasting resources parsing rules for defunct software.

Key Takeaway: Automated cleanup of stale policies improves system security and auditability by moving unused rules into a quarantine zone for verification before permanent deletion.