CH-J Toolsserver management over SSH
Menu
All guides and articles →

How to securely replace SSH keys on a production server

Replace user SSH key with a temporary overlap, verify new identity, and targeted removal of old access. Consider automation and leaked keys.

First, distinguish between user key and server key

The user SSH key proves to the server that a specific client is allowed to log in. The host key, on the other hand, proves to the client the identity of the server and its fingerprint is stored in known_hosts. This guide covers changing the user key. Therefore, when changing the login key normally, do not delete the host entries and do not generate new keys in /etc/ssh without reason.

Rotation can be planned, for example when replacing a laptop or transferring responsibility. Suspicion of a private key leak requires a different procedure. For a planned change, a short overlap of two keys is practical. In the event of an incident, it may be necessary to revoke the old access immediately from the trusted console and at the same time verify that the attacker has not added additional access.

The basic sequence is simple: determine the scope, create a new key, add its public part, verify the new login, and then remove the original authorization. But the details are important. A single key can be used by multiple accounts, multiple servers, a bastion, or a backup script. Success on a single machine is not proof of a complete migration.

Inventory and rescue path before change

Write down where the original public key is authorized and who uses it. Record its SHA-256 fingerprint, purpose, associated account, and restrictions. The comment after the key is a useful description, but is not a cryptographic identity. Two keys with the same comment may be different, and one key may have a different comment in different places.

# Na klientovi pro veřejnou část původního klíče:
ssh-keygen -lf ~/.ssh/id_ed25519.pub

# Na serveru pod příslušným účtem:
ssh-keygen -lf ~/.ssh/authorized_keys

The authorized_keys path is a common default example. The server may use an AuthorizedKeysFile in another location, AuthorizedKeysCommand, central administration, or SSH certificates. Find out the true source of authorization, otherwise you will change an unused file and the old access will remain active. Do not perform a blanket search in other people's home directories unless you have the appropriate permissions to do so.

Prepare a spare console and leave the current administrator session open. Save the authorization backup privately with the correct permissions. The backup itself represents access information; it must not end up in the regular webroot or in the public repository. When rolling back, only revert your change and respect the new authorizations of other administrators.

Creating a new key without overwriting the original one

Generate a new private key on a trusted client or supported hardware device. If you are changing the key for a compromised laptop, do not create a replacement on the same unauthenticated system. Use a separate file name so that the generator cannot accidentally replace the key needed for rollback.

ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_rotace \
  -C "sprava-notebook-2026"
ssh-keygen -lf ~/.ssh/id_ed25519_rotace.pub

Example Ed25519 needs to be evaluated based on client, server, and security policy support. For environments with different requirements, use an approved type. The type selection does not address storage security: protect the private part with a passphrase, appropriate permissions, and a suitable backup. Do not enter the passphrase on the command line, which can be recorded by history or process auditing tools.

The public part with the .pub extension may be given to the server administrator; the private part without this extension remains with the client. Before installation, compare the fingerprint of the expected new public part. This will reveal, for example, an old file selected by mistake or a confusion between the working and personal keys. The file description alone is not enough for this.

Add a public part and keep the necessary restrictions

Add the new key to the actual authorization source, leaving the old one for now. If your environment uses configuration management, make the change there; manually adding it to the server may remove it in the next automatic run. For regular authorized_keys, the new entry has one full line and the correct public key format.

For the old entry, check for options such as from, command, restrict, no-agent-forwarding, or no-port-forwarding. Replacing the restricted backup key with an unrestricted new key may fix the login, but it will also expand the permissions. The new authorization must maintain the intended purpose and restrictions. Also, verify the owner and permissions of the entire directory access chain.

# Kontrolní příkazy pod příslušným serverovým účtem:
ls -ld ~ ~/.ssh ~/.ssh/authorized_keys
ssh-keygen -lf ~/.ssh/authorized_keys

There is no need to restart the entire SSH server when changing the contents of the regular authorized_keys; a new authentication attempt reloads the authorization. A restart would add additional operational risk without addressing the bad key or permissions. If you are changing other server policies, treat them as a separate change with a syntax check and a new test.

Prove your new login with the new key

Open a new connection and force a new identity. The test must not fail with a password or other key from the agent by mistake. The verbose statement must match the fingerprint of the new public part. For the regular administrator, also verify the correct account, host, and necessary sudo. For the purpose-built key, test its allowed operation directly, not the shell, which it may not have intentionally.

ssh -vvv -o IdentitiesOnly=yes -i ~/.ssh/id_ed25519_rotace \
  -o PreferredAuthentications=publickey \
  -o PasswordAuthentication=no -o KbdInteractiveAuthentication=no \
  spravce@server.example

# U běžného správce po přihlášení:
whoami
hostname
sudo -v

If you use certificates or multi-factor authentication, adapt the test to the actual login policy: the above disabling of additional methods applies to single key login. Do not use it as a reason to disable the second factor on the server. The goal is to prove the use of the new identity in an existing policy, not to simplify the policy for the sake of testing.

In CH-J Tools, create or edit the corresponding profile and test the new key in a separate connection. Leave the original return path temporarily available. Changing the key name in the profile itself will not overwrite the server authorization and importing into the application will not remove the old key from other clients.

Convert the automation and only then remove the old authorization

Backups, scheduled tasks, and integration scripts often run in a different user environment than the administrator. They may not have the same SSH agent, passphrase, or file paths. Verify the new key from the real service environment and perform a limited verification operation. It is not a good idea to copy the administrator's personal unrestricted key to all automations just for a quick migration.

Once all necessary paths are verified, remove exactly the original authorization identified by its fingerprint. Edit the file with concurrent changes in mind; don't write back a copy that is several hours old and remove other people's new keys. If the old key is centrally authorized, removing it from just one local copy is not enough.

  • Check all accounts and servers from the inventory.
  • Remove the old key from bastions, purpose-built wrappers, and central sources where it was actually enabled.
  • Remove it from the loaded agent and client profiles only when they are not needed for an approved return.
  • Record the new fingerprint, owner, purpose, and completed tests without attaching the private part.

When a key leaks, its normal rotation is not enough

Removing public authorization prevents new logins in this way, but it does not close existing sessions or remove changes made by the attacker. If a compromise is suspected, verify active sessions, timestamps, authorization changes, and scope of permissions. Proceed from a trusted environment and preserve available evidence.

Changing the passphrase of a private file changes its protection in a given copy, not the cryptographic identity of the key. An already stolen usable copy does not disappear. To actually remove access, a change of authorization and, depending on the situation, a completely new key is required. For SSH certificates, also consider the trusted CA, validity, and revocation mechanism, not just the authorized_keys line.

If the compromised account had broad sudo, it may be necessary to assess the trustworthiness of the entire machine. It is not fair to call such an incident resolved just because the old key no longer works. The scope of next steps must be based on actual findings and the organization's operating policies.

Final verification: new key works, old one doesn't anymore

After removing the old authorization, perform a new positive test of the new identity. Then, depending on the authorization and considering the protection against repeated attempts, perform one targeted negative test of the old key. Keep the fallback to password or another identity disabled, otherwise a successful login would not prove what you think. Do not use dozens of attempts for a negative test, which can block the correct new path.

Assess the failure of the old key by phase: network timeout does not prove the removal of authorization. You need the corresponding authentication rejection on the correct server. Also check the real run of the automation after the change. The task that starts once a week did not verify itself with today's successful manual login.

The planned replacement is complete when you have verified the new identity, revoked the original access in all intended locations, and updated the inventory. Private keys and their passphrases do not belong in this record. The next administrator is supposed to learn the purpose and procedure from the documentation, not to extract the access secret from it.

Frequently asked questions

Is changing the passphrase the same as changing the key?

No. It protects a specific private file with a different phrase, but it does not change its public identity and does not invalidate a usable stolen copy.

Do I need to restart sshd after editing authorized_keys?

No, for regular file authorization. New authentication loads current content. Consider changes to other server policies separately.

Will deleting a key remove running sessions?

Not automatically. Removing authorization is handled by a new login; existing sessions and any incident require their own assessment.

Can I add the new key next to the old one first?

A short controlled run is practical for planned rotation. If a leak is suspected, immediate removal of the old approach may be necessary.

Detailed documentation

OpenSSH: key generation and fingerprinting →

OpenSSH: authorized_keys format and its limitations →

OpenSSH: authorization and authentication sources →

OpenSSH: choosing client identity →

Biometric unlock and security →

All tutorials by category →