Back to Resources

Level Verified

Linux Monitor - SSH Keys Script

Created by

Level

Type

Script

Category

Security

Platforms
WindowsApple iOSLinux

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.

Description

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.

Script

1#!/bin/bash
2
3# This resource is provided as a convenience for Level users. We cannot 
4# guarantee it will work in all environments. Please test before deploying 
5# to your production environment. We welcome contributions to our community 
6# library
7
8# Level Library
9# https://level.io/library/script-linux-monitor-ssh-keys
10
11# Define the path to the authorized_keys files
12authorized_keys_paths=("/home/*/.ssh/authorized_keys" "/root/.ssh/authorized_keys")
13
14# Define the authorized users and keys
15declare -A authorized_users=(
16  ["SSH_KEY_HERE"]="admin"
17
18)
19# -----------------------------------------------------------------------------
20
21# Array to store the list of unauthorized keys and their locations
22unauthorized_keys=()
23
24# Iterate over the authorized_keys files for all users
25for path in "${authorized_keys_paths[@]}"; do
26  # Expand the glob pattern to find authorized_keys files
27  files=( $path )
28
29  for file in "${files[@]}"; do
30    # Extract the username from the file path
31    if [[ $file =~ /([^/]+)/\.ssh/authorized_keys$ ]]; then
32      username=${BASH_REMATCH[1]}
33
34      # Check if the authorized_keys file exists and is not empty
35      if [[ -e "$file" && -s "$file" ]]; then
36        # Read the contents of the authorized_keys file
37        while IFS= read -r line; do
38
39          # Check if the line is not a comment and contains an SSH key
40          if [[ $line != "#"* && $line != "" ]]; then
41            # Check if the key is authorized for the user
42            if [[ -n "${authorized_users[$line]}" ]]; then
43              continue
44            fi
45
46            unauthorized_keys+=("$line in $file")
47          fi
48        done < "$file"
49      fi
50    fi
51  done
52done
53
54# Check if any unauthorized keys were found
55if [[ ${#unauthorized_keys[@]} -gt 0 ]]; then
56  echo "ALERT: Unauthorized SSH key entries found in authorized_keys files for the following users:"
57  for key in "${unauthorized_keys[@]}"; do
58    echo "- $key"
59  done
60  exit 1
61else
62  echo "SUCCESS: No unauthorized SSH key entries found in authorized_keys files for any users."
63  exit 0
64fi

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

FAQ

  • 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.

Included with this Script:

Below is a list of what you can expect to find when importing this Script.

Script details:

The following data and settings will be imported with your script.

Script Name

Linux Monitor - SSH Keys

Description

This script checks for unauthorized SSH keys in the authorized_keys files of all users, comparing them against a predefined list of authorized keys, and alerts if any unauthorized entries are found to enhance system security.

Language

Bash

Timeout (In Seconds)

100

Run As

Local system

Import into Level

Related resources

Explore more automations, scripts, and policies to further enhance your IT operations.

View all resources