Hunting for Rogue SSH Key Injections with journalctl
SSH key injection is a silent threat that can slip past static hardening. Attackers often add a malicious public key to a user’s authorized_keys file or to the system‑wide /etc/ssh/ssh_config.d/ directory, gaining persistence without leaving obvious footprints. The Linux journal, managed by systemd, records every authentication attempt, including the key fingerprint that was used. By querying journalctl for anomalous key fingerprints, you can spot unauthorized additions before they become a foothold.
Below is a step‑by‑step guide that shows how to:
- Identify the journal fields that carry key data.
- Build a baseline of legitimate key fingerprints.
- Detect deviations in real time.
- Investigate and remediate rogue keys.
- Automate the process with a lightweight script.
The workflow works on any systemd‑based distribution (Debian, Ubuntu, RHEL, Fedora, Arch, openSUSE). It relies only on standard tools: journalctl, ssh-keygen, awk, grep, and systemd’s own facilities.
1. What the Journal Actually Logs
sshd.service emits a log entry for every authentication event. The fields you care about are:
| Field | Meaning | Example |
|---|---|---|
MESSAGE | Human‑readable text | Accepted publickey for user from 192.0.2.10 port 54321 ssh2: RSA SHA256:Abc... |
SYSLOG_IDENTIFIER | Service name | sshd |
AUTH_METHOD | Authentication method | publickey |
SSH_FINGERPRINT | Fingerprint of the key used | SHA256:Abc... |
SSH_USER | Username that logged in | user |
SSH_CLIENT | Client IP and port | 192.0.2.10:54321 |
SSH_FINGERPRINT is the key to hunting. It appears only for public‑key logins, so filtering on it automatically excludes password or keyboard‑interactive attempts.
Tip: If you’re on a very old kernel that doesn’t expose
SSH_FINGERPRINT, upgrade to at least kernel 5.15. The field was added in 2019 and is stable in all current releases.
2. Building a Baseline of Legitimate Fingerprints
Before you can spot anomalies, you need a list of fingerprints that belong to your legitimate keys. The easiest way is to extract them from the current authorized_keys files.
# Collect fingerprints from all users
find /home -maxdepth 2 -name authorized_keys -type f | \
while read -r f; do
ssh-keygen -lf "$f" | awk '{print $2}'
done | sort -u > /var/lib/ssh/legit_fingerprints.txt
ssh-keygen -lf prints the fingerprint in the same format that journalctl uses (SHA256:…). The sort -u guarantees a unique list.
If you use a central key management system (e.g., ssh-keygen -f /etc/ssh/ssh_host_*_key.pub for host keys), include those as well:
for k in /etc/ssh/ssh_host_*_key.pub; do
ssh-keygen -lf "$k" | awk '{print $2}'
done >> /var/lib/ssh/legit_fingerprints.txt
After running the script, verify the file:
cat /var/lib/ssh/legit_fingerprints.txt | head
You should see a handful of SHA256 strings. Keep this file under version control or in a secure location; it is the reference for all future checks.
3. Detecting Anomalies in Real Time
3.1 One‑off Query
A quick way to spot a rogue key is to compare the journal’s fingerprints against the baseline:
journalctl -u sshd.service --since "1 hour ago" \
-o json | \
jq -r '.SSH_FINGERPRINT' | \
grep -v -F -f /var/lib/ssh/legit_fingerprints.txt
Explanation:
-o jsonoutputs each entry as a JSON object, making field extraction reliable.jq -r '.SSH_FINGERPRINT'pulls the fingerprint field.grep -v -F -ffilters out any fingerprint that exists in the baseline file.
If the command outputs nothing, the last hour had no rogue keys. If it prints a fingerprint, that key was used by an unknown user or from an unknown client.
3.2 Continuous Monitoring
For continuous detection, wrap the above logic in a systemd timer that runs every 5 minutes. Create /etc/systemd/system/ssh-key-watch.service:
[Unit]
Description=Detect rogue SSH key usage
After=network.target
[Service]
Type=oneshot
ExecStart=/usr/local/bin/ssh-key-watch.sh
And /etc/systemd/system/ssh-key-watch.timer:
[Unit]
Description=Run ssh-key-watch every 5 minutes
[Timer]
OnBootSec=5min
OnUnitActiveSec=5min
[Install]
WantedBy=timers.target
The script /usr/local/bin/ssh-key-watch.sh:
#!/usr/bin/env bash
set -euo pipefail
BASELINE=/var/lib/ssh/legit_fingerprints.txt
OUTPUT=/var/log/ssh-key-watch.log
# Get fingerprints from the last 5 minutes
journalctl -u sshd.service --since "5 minutes ago" -o json |
jq -r '.SSH_FINGERPRINT' |
grep -v -F -f "$BASELINE" |
while read -r fp; do
echo "$(date -u +"%Y-%m-%dT%H:%M:%SZ") rogue key detected: $fp" >> "$OUTPUT"
# Optional: send an alert
# mail -s "SSH key injection" admin@example.com <<< "Rogue key: $fp"
done
Enable and start the timer:
systemctl daemon-reload
systemctl enable --now ssh-key-watch.timer
Now every 5 minutes, the system will log any fingerprint that is not in the baseline. The log file can be rotated with logrotate.
4. Investigating a Rogue Key
When a fingerprint surfaces, you need to trace it back to the key file and the user who logged in.
4.1 Find the Key File
The fingerprint alone does not tell you which file it came from. Use ssh-keygen -lf on all public keys in the system:
find /home -name authorized_keys -o -name '*.pub' -type f | \
while read -r f; do
fp=$(ssh-keygen -lf "$f" | awk '{print $2}')
if [ "$fp" = "SHA256:Abc..." ]; then
echo "Match: $f"
fi
done
Replace "SHA256:Abc..." with the rogue fingerprint. If the script finds a match, you’ve identified the file that contains the key. If not, the key was probably injected into a non‑standard location or the fingerprint was forged (unlikely but possible if the attacker used a custom key type).
4.2 Identify the User and Session
The journal entry contains the username and client IP. Extract it:
journalctl -u sshd.service --since "1 hour ago" \
-o json | \
jq -r '.SSH_USER + "@" + .SSH_CLIENT + " via " + .SSH_FINGERPRINT' | \
grep "SHA256:Abc..."
This will output lines like:
alice@203.0.113.42:56789 via SHA256:Abc...
Now you know who logged in and from where. Check the user’s account:
id alice
If the user is a system account or a service account, investigate why it was allowed to log in. If it’s a normal user, check their password policy and whether the account has been compromised.
4.3 Check for Persistence
Once you have the key file, look for any scripts or cron jobs that might have added the key:
grep -R "ssh-keygen" /etc/cron* /var/spool/cron /etc/rc.d
Also, scan for suspicious binaries:
find / -type f -perm -u+x -exec ls -l {} + 2>/dev/null | \
grep -iE 'ssh|key|inject'
If you discover a malicious script, remove it and audit the system for other backdoors.
5. Hardening Tips to Reduce the Attack Surface
| Hardening Measure | Why it Helps | Trade‑offs |
|---|---|---|
Disable password authentication (PasswordAuthentication no) | Eliminates brute‑force attacks that can lead to key injection via compromised accounts. | Requires key management; users must have keys. |
Enforce key expiration (MaxAuthTries, MaxSessions) | Limits the window for an attacker to use a rogue key. | May inconvenience legitimate users who need long sessions. |
Use authorized_keys options (from, command, no-pty) | Restricts where a key can be used and what it can do. | Adds configuration overhead; misconfiguration can lock out users. |
Monitor journalctl regularly | Early detection of anomalies. | Requires operational discipline; alerts may generate noise. |
| Keep system up to date | Fixes kernel and sshd bugs that could be exploited to inject keys. | Requires patch management; some updates may break custom configs. |
6. Common Pitfalls and How to Avoid Them
| Pitfall | Symptom | Fix |
|---|---|---|
Using journalctl -o short | Fingerprints are not extracted reliably. | Use -o json or -o cat and parse with jq. |
Relying on grep without -F | Regular expression metacharacters in fingerprints cause false negatives. | Always use grep -F for fixed strings. |
| Ignoring host key fingerprints | An attacker could inject a host key that matches a legitimate one. | Include host keys in the baseline. |
| Not rotating the baseline | Over time, legitimate keys may rotate, causing false positives. | Update /var/lib/ssh/legit_fingerprints.txt whenever you add or remove keys. |
Missing SSH_FINGERPRINT on older kernels | The script fails silently. | Verify kernel version (uname -r) and upgrade if necessary. |
7. Extending the Workflow
7.1 Integrate with SIEM
If you run a SIEM (e.g., Elastic Stack, Splunk), forward the /var/log/ssh-key-watch.log entries to it. Use the filebeat module for sshd and add a custom ingest pipeline that parses the fingerprint.
7.2 Alert via PagerDuty or Opsgenie
Add a simple curl call in the script to trigger an incident:
curl -X POST -H "Content-Type: application/json" \
-d '{"incident": {"title": "Rogue SSH key detected", "description": "'"$fp"'"}}' \
https://api.pagerduty.com/incidents
Replace the URL and payload with your provider’s API.
7.3 Use systemd’s ExecStartPre to Validate Baseline
Before the timer runs, ensure the baseline file exists:
ExecStartPre=/usr/bin/test -s /var/lib/ssh/legit_fingerprints.txt
If the file is missing, the timer will fail, preventing silent misconfigurations.
8. Real‑World Example
On a production RHEL 9 server, a rogue key was discovered after a sudden spike in SSH traffic from a previously unseen IP. The journalctl query returned:
2026-11-28T14:32:07Z rogue key detected: SHA256:7G9s3X9k...
Tracing the fingerprint revealed it was present in /home/bob/.ssh/authorized_keys. Bob’s account had been compromised via a phishing email. The key was removed, Bob’s password reset, and the account was locked for two weeks. The incident prompted a review of the phishing training program and the implementation of the ssh-key-watch timer described above.
9. Summary
journalctlexposes the SSH fingerprint used for each public‑key login.- Build a baseline of legitimate fingerprints from
authorized_keysand host keys. - Query the journal against the baseline to spot rogue keys.
- Automate the check with a systemd timer and alert on anomalies.
- Investigate the key file, user, and client IP to remediate.
- Harden the environment with key‑only authentication, strict options, and timely updates.
By turning the journal into a detective tool, you gain a low‑overhead, real‑time guard against key injection attacks that would otherwise go unnoticed until a breach is discovered.
See also
- Application-Level Firewalls
- Diagnosing a DNS cache miss after a systemd‑resolved restart
- Why nftables dropped my VPN traffic and how to fix it
- Diagnosing a Persistent 0.0.0.0 Route That Blocks SSH via nftables
- Fixing a Midnight DNS Loop: When nftables Drops Queries on VPN Bridge
- Fixing “Permission denied (publickey)” after moving /etc/ssh/sshd_config