LinkedIn Sourceforge

Vincent's Blog

Pleasure in the job puts perfection in the work (Aristote)

Goodbye id_rsa, Hello id_ed25519: Rotating Your SSH Keys Without Locking Yourself Out

Posted on 2026-12-05 11:14:00 from Vincent in OpenBSD FreeBSD Security

Give a shoutout to  FlyD on unsplash.com Somewhere in your home directory there is a file you created years ago, probably on a laptop you no longer own, by typing ssh-keygen and pressing Enter three times. It is called id_rsa. Since then it has quietly opened doors for you on dozens of servers: the production box, the backup NAS, the Raspberry Pi in the cupboard, that VPS you forgot you were still paying for. It has never complained. It has never failed you.

And that is exactly the problem.

That key was born in another era of cryptography. Today there is a smaller, faster, simpler and more robust alternative sitting one command away. The hard part is not generating the new key. The hard part is replacing the old one on every machine that trusts it, without breaking the from= and command= restrictions you carefully added years ago, and without locking yourself out of a server at 11 p.m. on a Friday.

This post explains why you should move from id_rsa to id_ed25519, then walks through a small POSIX shell script that does the migration safely, one host at a time, and finally shows how to know when the old key can really be retired.


Part 1 — id_rsa vs id_ed25519

Two families of mathematics

An SSH key pair is just a private key you keep secret and a public key you hand out. What differs between id_rsa and id_ed25519 is the mathematics underneath.

RSA (Rivest–Shamir–Adleman, 1977) bases its security on the difficulty of factoring a very large number into its two prime factors. It is the venerable workhorse of public-key cryptography, it is understood very well, and it is supported everywhere. Its weakness is that factoring algorithms keep improving, so RSA has to keep growing its key size to stay ahead: 1024 bits is considered too weak today, 2048 bits is the minimum, and 3072 bits (the current ssh-keygen default for RSA) is needed to reach roughly 128 bits of security.

Ed25519 is an implementation of the EdDSA signature scheme on Curve25519, an elliptic curve designed by Daniel J. Bernstein and colleagues. Its security rests on the elliptic-curve discrete logarithm problem, for which no shortcut comparable to the improvements in factoring is known. A 256-bit Ed25519 key gives about the same 128-bit security level as a 3072-bit RSA key.

Why Ed25519 wins in practice

The difference is more than a matter of size:

  • Compact keys. An Ed25519 public key fits on a single short line, around 80 characters. A 3072-bit RSA public key is more than 500 characters of base64. Your authorized_keys files become readable again.
  • Speed. Signing and verifying with Ed25519 is very fast, and generating a key is almost instantaneous. Generating a large RSA key can take noticeable time.
  • Fewer ways to get it wrong. RSA comes with choices: key size, padding scheme, hash algorithm. Each choice has been a source of vulnerabilities over the years. Ed25519 has essentially one way to do things, and the designers made it the safe way.
  • Deterministic signatures. Ed25519 signatures do not depend on a random number generated at signing time. Several famous key leaks in other schemes came from a weak or reused random number during signing. With Ed25519 that whole class of failure disappears.
  • Designed against side channels. The reference implementations avoid branches and memory accesses that depend on secret data, which makes timing attacks much harder.

The "ssh-rsa" deprecation that confused everyone

In 2021, OpenSSH 8.8 disabled the ssh-rsa signature algorithm by default (see PubkeyAcceptedAlgorithms in sshd_config(5) and ssh_config(5)), and many people concluded that their RSA keys were dead. That is not quite right. What was disabled is the combination of RSA with SHA-1, which is no longer collision resistant. The same RSA key still works with the rsa-sha2-256 and rsa-sha2-512 algorithms on any modern server.

The signal was clear, though: RSA in SSH survives by constant patching. And with OpenSSH 9.5 (2023), ssh-keygen with no arguments now generates an Ed25519 key. The ecosystem has made its choice.

What about old systems and quantum computers?

Ed25519 has been supported since OpenSSH 6.5 (2014). If one of your machines cannot accept it, that machine has bigger problems than its key type. Some old network appliances and embedded systems remain the exception, which is a good reason to keep the old key available on your side until you have checked every host.

On the quantum question: neither RSA nor Ed25519 resists a large quantum computer. Recent OpenSSH versions already protect the key exchange with hybrid post-quantum algorithms (see KexAlgorithms in ssh_config(5)), which protects your recorded sessions today. Post-quantum authentication keys are not yet standard in OpenSSH. Until they are, Ed25519 is the best choice you have.

Creating the new key

ssh-keygen -t ed25519 -C "you@yourlaptop-2026"

Choose a good passphrase; all options are documented in ssh-keygen(1). You now have ~/.ssh/id_ed25519 and ~/.ssh/id_ed25519.pub. Now comes the part that most tutorials skip: putting it everywhere the old key lives.


Part 2 — The script: ssh-rotate-key.sh

Why not just append the new key?

ssh-copy-id and cat ~/.ssh/id_ed25519.pub | ssh target "cat >> ~/.ssh/authorized_keys" only add a key. They do not remove the old one, they do not know that the old key was restricted with from="10.0.0.0/8" or command="/usr/local/bin/backup", and they happily install your new key with no restrictions at all on a server where the old key was carefully limited. In other words, a naive migration can silently widen your access.

ssh-rotate-key.sh takes a different approach: it replaces the old key with the new one, line by line, and keeps everything around it.

Usage

ssh-rotate-key.sh [-n] [-N new.pub] [-O old.pub] host
  • -n runs a dry run: it shows the diff that would be applied and changes nothing.
  • -N sets the new public key (default: ~/.ssh/id_ed25519.pub).
  • -O sets the old public key (default: ~/.ssh/id_rsa.pub).
  • host is anything ssh(1) accepts: a hostname, user@host, or an alias from ~/.ssh/config (see ssh_config(5)).

A typical session looks like this:

ssh-rotate-key.sh -n backup-nas      # look first
ssh-rotate-key.sh backup-nas         # then do it
ssh -o IdentitiesOnly=yes -i ~/.ssh/id_ed25519 backup-nas  # then check that the new key works

The rules it follows

The rules are short, and each one exists to avoid a specific accident:

  1. Every active line containing the old key is rewritten (the line format is described in the AUTHORIZED_KEYS FILE FORMAT section of sshd(8)). The key type and the base64 blob are swapped for the new ones, all options in front of the key (from=, command=, no-pty, …) are kept exactly as they were, and the comment becomes the comment of the new key.
  2. Commented-out lines (# ...) that contain the old key are removed. A disabled copy of a retired key is just clutter.
  3. If the old key is not active on the host, nothing happens. The new key is not installed, the file is not touched, no backup is made. The script only rotates existing access; it never grants new access.
  4. Identical duplicate lines with the new key are removed. If you already added the new key by hand, you don't end up with it twice.
  5. A timestamped backup is created before any change: authorized_keys.bak.YYYYmmddHHMMSS.

Rule 3 deserves attention. It is what makes the script safe to run in a loop over your whole inventory: hosts where you never had access through the old key are left completely alone.

How it works

Validating the keys locally

Before touching the network, the script checks both public key files. ssh-keygen -l -f must accept them as valid keys. Then a small awk function, key_field, extracts the type (ssh-ed25519, ssh-rsa, …), the base64 blob, and the comment from the first non-empty, non-comment line. The type and blob are checked against strict character sets, and the script refuses to continue if the old and new keys are identical. Anything strange stops the script before it reaches a server.

One connection, one remote script

The most interesting design decision is how the work is done on the remote side. The script does not copy files back and forth and does not open several connections. It generates a shell script and pipes it into a single session:

remote_script | ssh -T "$host" sh -s

sh -s reads the commands from standard input, and -T tells ssh(1) not to allocate a terminal. Two consequences follow: if the server asks for a password, you type it only once, and the remote host needs nothing beyond standard Unix tools (sh, awk, cmp, diff, mktemp, cp, mv). No Python, no Bash-specific features, no agent to install. It works on Linux, the BSDs, macOS and most embedded systems.

The key values are written at the top of the generated script as shell variables. Even though they were validated already, they go through a shquote function that wraps them in single quotes and escapes any embedded quote. The key comment, which is free text, is the reason this matters: a comment containing ' or $(...) must never turn into code on the server. The values are then passed to awk through the environment (ENVIRON[...]) instead of awk -v, which would interpret backslashes.

Finding the key, precisely

Inside the remote script, awk reads authorized_keys line by line. The core is a function called keypos, which finds a key as whole fields: the blob must be followed by a blank or the end of the line, preceded by at least one blank, and preceded in turn by the exact key type as a complete token.

This care is not paranoia. An authorized_keys line can start with options that contain quoted strings and spaces, such as command="echo hi",from="1.2.3.4" ssh-rsa AAAA... me@host, so a naive "split on spaces and take field 1" does not work. And a simple substring search could match one key inside a longer one, or confuse a key with an option value. keypos returns the position where the key type starts, so the script can keep everything before it (the options) untouched and replace everything after it with type blob comment of the new key.

Windows line endings (\r) are removed along the way, because someone, somewhere, edited that file in Notepad.

Doing nothing, loudly

If no active line held the old key, awk exits with code 3. The shell catches this specific code and exits cleanly, leaving the file exactly as it was, with a message that also tells you whether the new key is already present. Any other non-zero code is a real failure and aborts with an error. Because the script runs with set -eu, the awk call is written as awk ... || rc=$?, so that the shell does not stop before it can inspect the code.

If the result is byte-for-byte identical to the original (checked with cmp -s), the script reports "nothing to change" and stops there.

Dry run, backup, atomic swap

In dry-run mode the new content goes into a temporary file, diff -u shows exactly what would change, and the script stops. This is the mode to use the first time on every important host.

In normal mode, three steps keep the operation safe:

  1. A backup is created with cp -p, which preserves permissions and timestamps.
  2. The new content is written to a temporary file created by mktemp in the same ~/.ssh directory, under umask 077, then set to mode 600 with chmod.
  3. The temporary file is moved over authorized_keys with mv -f.

Creating the temporary file in the same directory is important: on the same filesystem, mv is an atomic rename(2). At no moment does authorized_keys exist half written, so a login arriving during the update sees either the old file or the new one, never a broken one. A trap removes the temporary file if anything goes wrong.

A warning you should read

After the rewrite, the script counts how many different lines now hold the new key. If there are several (for example, one line with from= restrictions and another one without), it prints a warning. sshd uses the first matching line it finds, so the restrictions you think apply may not be the ones that actually do. The script cannot decide for you which line is the right one, but it makes sure you know.

Rolling it out

Since the script works on one host and does nothing where the old key is absent, a whole inventory is a simple loop:

for h in web1 web2 db1 backup-nas pi-cupboard; do
    ssh-rotate-key.sh -n "$h"
done

Read the diffs, remove -n, and run it again. Your hosts now trust the new key instead of the old one. One question remains: when can id_rsa itself go?

Retiring id_rsa: when, and how

This is the real goal of the whole exercise, and also the step where people get hurt: delete the private key one day too early, and the one server you forgot is out of reach. The answer is simple to state: you can retire id_rsa when no system accepts it anymore and nothing you run still uses it. Getting there takes four steps.

1. Prove it on every host

On each host you rotated, the new key must work and the old key must be refused. A plain ssh -i ~/.ssh/id_ed25519 host is not a valid test: if id_rsa is loaded in your agent or sits at its default location, ssh silently tries it too, and the login succeeds for the wrong reason. IdentitiesOnly=yes forces ssh to use only the key given with -i:

check() { ssh -n -o BatchMode=yes -o IdentitiesOnly=yes -i "$2" "$1" true 2>/dev/null; }

for h in web1 web2 db1 backup-nas pi-cupboard; do
    check "$h" ~/.ssh/id_ed25519 && new=ok || new=FAIL
    check "$h" ~/.ssh/id_rsa     && old=ACCEPTED || old=refused
    echo "$h: new key $new, old key $old"
done

BatchMode=yes prevents any password prompt, so load both keys into your agent with ssh-add before running it if they have a passphrase. The only acceptable result, on every line, is new key ok, old key refused. A FAIL means you would lose access to that host; an ACCEPTED means the old key is still trusted somewhere, often in a place the script does not touch.

2. Hunt for the places the script cannot see

ssh-rotate-key.sh only edits ~/.ssh/authorized_keys of the account you log in with, on the hosts you give it. The old public key can live elsewhere:

  • other accounts on the same host, typically root or a dedicated backup or deploy user: run the script once more with user@host for each of them;
  • non-default key files, when the server sets AuthorizedKeysFile to something like /etc/ssh/authorized_keys/%u;
  • web services: the SSH keys of your account on GitHub, GitLab, Codeberg or your own forge, where you add the new key and delete the old one by hand;
  • automation: CI/CD secrets, deploy keys, backup jobs, cron entries that call ssh -i ~/.ssh/id_rsa;
  • your own configuration: IdentityFile ~/.ssh/id_rsa lines in ~/.ssh/config, and scripts that name the key explicitly. A grep -r id_rsa ~/.ssh/config ~/bin finds most of them.

3. Put the key aside, not in the bin

When every host shows old key refused and the hunt finds nothing, retire the key reversibly first. Remove it from the agent with ssh-add -d ~/.ssh/id_rsa, then move it out of ~/.ssh, where ssh would otherwise keep trying it by default:

mkdir -m 700 ~/ssh-retired
mv ~/.ssh/id_rsa ~/.ssh/id_rsa.pub ~/ssh-retired/

Then live with that for a few weeks. If something breaks, the error message tells you exactly which host or service you forgot, and the key is one mv away. The authorized_keys.bak.* files on the servers are your second safety net during this period.

4. Destroy it

If nothing has complained by the end of the grace period, delete ~/ssh-retired and remove the authorized_keys.bak.* files on the servers, since they still contain the old public key and only add confusion. Remember that the private key may also live in your backups. If they are encrypted, that is acceptable, but it is one more reason why the server side should stop trusting RSA altogether, which is the subject of the next section.

Closing the door behind you: sshd_config

Rotating your own key does not change what the server accepts: as long as sshd accepts RSA, any forgotten id_rsa line, yours or a colleague's, still opens the door. Once every account on a host has moved to Ed25519, you can tell the server to stop accepting anything else. A few lines in /etc/ssh/sshd_config (see sshd_config(5)) are enough:

# Accept only Ed25519 user keys (the sk- variant is for FIDO/U2F hardware keys)
PubkeyAcceptedAlgorithms ssh-ed25519,sk-ssh-ed25519@openssh.com

# Offer only the Ed25519 host key
HostKey /etc/ssh/ssh_host_ed25519_key
#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key

# Keys only: no passwords
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin prohibit-password

PubkeyAcceptedAlgorithms is the line that really retires RSA: after it, an ssh-rsa line in authorized_keys is simply ignored. Keep in mind that it applies to all users of the server, so check their authorized_keys files first. If you use OpenSSH certificates, add the -cert-v01@openssh.com variants to the list. The HostKey lines do the same for the server's own identity. Clients that only know the old RSA host key will see a host key warning; recent OpenSSH clients usually learn the new key automatically thanks to UpdateHostKeys, as long as you connect once before removing the RSA host key. PasswordAuthentication no completes the picture: if keys are your only way in, there is no password left to guess. And if you never log in as root directly, set PermitRootLogin to no instead of prohibit-password.

Now the golden rule of editing sshd_config: never close the session you are working in. Check the syntax with sshd -t, look at the effective values with sshd -T | grep -i pubkeyaccepted, then reload the daemon, with rcctl reload sshd on OpenBSD or service sshd reload on FreeBSD. Existing connections survive a reload. Open a second terminal and log in with the new key; only when that works should you close the first one. If it fails, you still have a shell to put things right.

The complete script

You can download the whole script here. Save it as ssh-rotate-key.sh, make it executable with chmod +x ssh-rotate-key.sh, read it before you run it, and always start with -n.


Conclusion

Your id_rsa did its job. It was never broken; it simply belongs to a generation of cryptography that needs larger keys, more parameters and regular patching to stay safe. Ed25519 is smaller, faster, harder to misuse, and it is now the default choice of OpenSSH itself.

The real obstacle to migrating was never the cryptography. It was the fear of the last step: editing authorized_keys on dozens of servers, by hand, hoping not to break a carefully restricted line or to lock yourself out. ssh-rotate-key.sh turns that step into something boring: one connection per host, a dry run you can read, options preserved, a backup before every change, an atomic swap, and no change at all where the old key was not trusted in the first place. And retiring id_rsa stops being a leap of faith: when every host answers "new key ok, old key refused" and a few quiet weeks have passed with the key set aside, you can delete it knowing that nothing still depends on it.

So open a terminal, generate your new key, and run the dry run on the first server on your list. The old key has earned its retirement. Let's give it a clean one.



👍 0, 👎 0
displayed: 1206



What is the first vowel of the word Moon?