Level Verified

Linux Monitor - SSH Keys Script

Scans authorized_keys files on Linux systems to detect any SSH keys not defined as authorized. Ideal for script-based monitoring and automated remediation with Level.

Import into Level

Problem overview

Unapproved SSH keys pose a major security risk, allowing potential unauthorized access to critical servers and data. Manually reviewing authorized_keys files is tedious and error-prone, leaving organizations vulnerable if a key is overlooked or maliciously inserted.

Bash 100s timeout Runs as Local system Linux
#!/bin/bash

# This resource is provided as a convenience for Level users. We cannot 
# guarantee it will work in all environments. Please test before deploying 
# to your production environment. We welcome contributions to our community 
# library

# Level Library
# https://level.io/library/script-linux-monitor-ssh-keys

# Define the path to the authorized_keys files
authorized_keys_paths=("/home/*/.ssh/authorized_keys" "/root/.ssh/authorized_keys")

# Define the authorized users and keys
declare -A authorized_users=(
  ["SSH_KEY_HERE"]="admin"

)
# -----------------------------------------------------------------------------

# Array to store the list of unauthorized keys and their locations
unauthorized_keys=()

# Iterate over the authorized_keys files for all users
for path in "${authorized_keys_paths[@]}"; do
  # Expand the glob pattern to find authorized_keys files
  files=( $path )

  for file in "${files[@]}"; do
    # Extract the username from the file path
    if [[ $file =~ /([^/]+)/\.ssh/authorized_keys$ ]]; then
      username=${BASH_REMATCH[1]}

      # Check if the authorized_keys file exists and is not empty
      if [[ -e "$file" && -s "$file" ]]; then
        # Read the contents of the authorized_keys file
        while IFS= read -r line; do

          # Check if the line is not a comment and contains an SSH key
          if [[ $line != "#"* && $line != "" ]]; then
            # Check if the key is authorized for the user
            if [[ -n "${authorized_users[$line]}" ]]; then
              continue
            fi

            unauthorized_keys+=("$line in $file")
          fi
        done < "$file"
      fi
    fi
  done
done

# Check if any unauthorized keys were found
if [[ ${#unauthorized_keys[@]} -gt 0 ]]; then
  echo "ALERT: Unauthorized SSH key entries found in authorized_keys files for the following users:"
  for key in "${unauthorized_keys[@]}"; do
    echo "- $key"
  done
  exit 1
else
  echo "SUCCESS: No unauthorized SSH key entries found in authorized_keys files for any users."
  exit 0
fi

This script examines authorized_keys files across user accounts and compares each key to an internal list of sanctioned keys. If it detects an entry that isn’t recognized, it alerts you by returning an error, providing a clear indication of an unauthorized or rogue key. You can seamlessly integrate it with a script-based monitor in Level to trigger on-demand scans whenever suspicious activity is detected.

You can also schedule recurring checks through a Level Automation to continuously verify that only approved keys remain. With System or Root-level permissions, the script ensures full visibility into all authorized_keys files, delivering a comprehensive security measure for your Linux environment.

Use cases

  • Verifying trusted SSH keys for administrators
  • Detecting newly added SSH keys in multi-user setups
  • Maintaining compliance with internal security policies
  • Proactively uncovering suspicious access credentials

Recommendations

  • Test the script in a safe environment before deploying
  • Use a script-based monitor in Level to catch unauthorized keys in real time
  • Schedule regular scans via a Level Automation for ongoing protection
  • Customize the authorized users and keys array to match your environment
  • Investigate and remove unauthorized keys immediately

Frequently asked questions.

How can I add multiple authorized keys?

Update the authorized_users array in the script, adding one entry per valid key–user pairing.

What if a key is flagged as unauthorized?

The script returns an alert. Review the flagged key and, if genuinely unauthorized, remove it from the authorized_keys file.

How does this script access user directories?

It runs with System or Root privileges under Level, allowing it to traverse and read any authorized_keys files.

Can I ignore certain users or directories?

Customize the authorized_keys_paths array to target or exclude specific locations.

Is this script compatible with all Linux distributions?

It works on most modern Linux systems with standard filesystem layouts and the Bash shell. Testing is recommended before production use.

Ready when you are.

No credit card. No sales call. Just sign up and start managing.