Linux: Regenerate sshd host keys


to generate sshd host keys, for example in case of cloning a virtual linux instance, do the following steps:

Checkout the key file names

root@debdevt:~# grep HostKey /etc/ssh/sshd_config
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key

and generate new keys without a passphrase and a 4096Bit key

root@debdevt:~# ssh-keygen -b 4096 -f /etc/ssh/ssh_host_rsa_key -t rsa -N ""
root@debdevt:~# ssh-keygen -b 4096 -f /etc/ssh/ssh_host_dsa_key -t dsa -N ""
root@debdevt:~# ssh-keygen -b 4096 -f /etc/ssh/ssh_host_ecdsa_key -t ecdsa -N ""
root@debdevt:~# ssh-keygen -b 4096 -f /etc/ssh/ssh_host_ed25519_key -t ed25519 -N ""

Last step. Ensure that only root have access to the key files

root@debdevt:~# chmod 600 /etc/ssh/ssh_host_*_key


Advertisment to support

5 thoughts on “Linux: Regenerate sshd host keys”

  1. Since Ed25519 keys have a fixed length, the “-b 4096” is rather misleading in this use case. The 4096 bit is also too large for ECDSA keys, see “man ssh-keygen” at “-b”:

    […] For ECDSA keys, the -b flag determines the key length by selecting from one of three elliptic curve sizes: 256, 384 or 521 bits. Attempting to use bit lengths other than these three values for ECDSA keys will fail. […]

    I understand this blog post is 7 years, so maybe the parameter processing has been changed.

    Anyway, this post provided the information i was looking for. Thank you!

  2. Sheldon’s right. Additionally the `-a` option might be interesting as an alternative, because it enables you to set the number of rounds for the key derivation function, which helps with brute forcing (like a higher number of bits would for RSA)

    1. Fynn, I agree for the -a option in regards to personal encrypted ssh-keys, but not for host keys as they usually are not encrypted. The -a option is only relevant for keys encrypted with a passphrase.

  3. Once you removed the old keys, you may as well run “ssh-keygen -A”. Its purpose is to create the missing host keys.
    If you are on RedHat or CentOS, after deleting old keys, you may run “systemctl start sshd-keygen.service”.
    If you are on Debian or derivatives, after removing the old keys, just restart sshd service: it will create the host keys automatically.

  4. Hi, Im experiencing the opposite behavior, RedHat does include a script to rebuild the keys if they are missing during init, Ubuntu does not.

    For the later, you can run dpkg-reconfigure openssh-server or the ssh-keygen tool.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.