Разбираемся, как создать шифрованный протокол для связи с сервером и входить в систему без пароля учетной записи.
Введение
Использование SSH-ключей — простой и надежный способ обеспечения безопасности соединения с сервером. В отличие от пароля, взломать SSH-ключ практически невозможно. Сгенерировать SSH-ключ очень просто.
SSH-ключ для Linux/MacOS
Откройте терминал и выполните команду:
$ ssh-keygen -t rsa
На консоль будет выведен следующий диалог:
Enter file in which to save the key (/home/user/.ssh/id_rsa):
Нажмите на клавишу Enter. Далее система предложит ввести кодовую фразу для дополнительной защиты SSH-подключения:
Enter passphrase (empty for no passphrase):
Этот шаг можно пропустить. При ответе на этот и следующий вопрос просто нажмите клавишу Enter.
После этого ключ будет создан, а на консоль будет выведено следующее сообщение:
Your identification has been saved in /home/user/.ssh/id_rsa.
Your public key has been saved in /home/user/.ssh/id_rsa.pub.
The key fingerprint is:
476:b2:a8:7f:08:b4:c0:af:81:25:7e:21:48:01:0e:98 user@localhostThe key's randomart image is:
+--[ RSA 2048]----+
|+.o. |
|ooE |
|oo |
|o.+.. |
|.+.+.. S . |
|....+ o + |
| .o .... |
| . .. . |
| .... |
+-----------------+
Далее выполните в терминале команду:
$ cat ~/.ssh/id_rsa.pub
На консоль будет выведен ключ. Скопируйте его и вставьте в соответствующее поле:
Нажмите на кнопку «Добавить».
Добавив ключ, выполните в терминале команду:
$ ssh root@[IP-адрес сервера]
После этого соединение с сервером будет установлено. Вводить пароль при этом не потребуется.
SSH-ключ для Windows
В OC Windows подключение к удаленным серверам по SSH возможно, например, с помощью клиента Putty. Скачать его можно здесь (ссылка взята с официального сайта). Putty не требует установки — чтобы начать с ним работать, достаточно просто распаковать скачанный архив.
По завершении распаковки запустите файл puttygen.exe.
Выберите тип ключа SSH-2 RSA и длину 2048 бит, а затем нажмите на кнопку Generate:
Во время генерации водите курсором в пустой области окна (это нужно для создания псевдослучайности):
Сохраните сгенерированную пару ключей на локальной машине (кнопки Save public key и Save private key).
Скопируйте сгененированный ключ и вставьте его в соответствующее поле.
Заключение
В этой инструкции мы рассмотрели, как создать шифрованный протокол для связи с сервером: сгенерировали SSH-ключ для Linux/MacOS и Windows. Теперь вы можете входить в систему без пароля учетной записи.
1. Overview
SSH, the secure shell, is often used to access remote Linux systems. But its authentication mechanism, where a private local key is paired with a public remote key, is used to secure all kinds of online services, from GitHub and Launchpad to Linux running on Microsoft’s Azure cloud.
Generating these keys from Linux is easy, and thanks to Ubuntu on WSL, you can follow the same process from Windows 10. But even without Ubuntu, SSH keys can also be generated with the free and open source OpenSSH client built into Windows 10 or with PuTTY for Windows 8.1 and earlier.
Over the following few steps, we’ll guide you through the process of generating SSH keys using Ubuntu on WSL, OpenSSH, and PuTTY.
Requirements
All you need is a PC running Windows and one of the following installed:
- Ubuntu on WSL for Windows 10
- The OpenSSH client built into Windows 10
- The
puttygen.exe
executable from PuTTY for Windows 7 or 8.1
If you don’t already have Ubuntu on WSL, take a look at our Install Ubuntu on WSL tutorial.
Originally authored by Graham Morrison.
2. Passphrase considerations
When creating the SSH key pair, as shown in the following steps, you can choose to either lock your private key with a passphrase or use no passphrase at all.
Adding a passphrase requires the same passphrase to be entered whenever the key pair is used. Not adding a passphrase removes this requirement. For this reason, creating a key pair without a passphrase is more convenient and potentially essential for certain scripts and automation tasks. But it’s also less secure.
If a third-party gains access to a private key without a passphrase they will be able to access all connections and services using the public key.
A good compromise between convenience and security is to generate a separate key pair for each service or connection you want to use, adding a passphrase only for critical services. If you suspect a key has been compromised, simply generate a new pair for that service and remove the less secure key.
3. Key generation with Ubuntu on WSL
Launch Ubuntu on WSL from the start menu and make sure SSH is installed by entering following command at the command prompt:
sudo apt install openssh-client
The key generation process is identical to the process on a native Linux or Ubuntu installation. With SSH installed, run the SSH key generator by typing the following:
ssh-keygen -t rsa
You will be asked two questions. The first asks where to save the key, and you can press return to accept the default value. The second question asks for the passphrase. As discussed, entering a passphrase will require you to use the same passphrase whenever the key is accessed.
However, the passphrase isn’t a requirement, and pressing return (twice) will generate a key pair without one. Consequently, you won’t be asked for a passphrase when using your key.
When the process has finished, the private key and the public key can be found in the ~/.ssh
directory accessible from the Ubuntu terminal, or the following folder from Windows file manager:
\\wsl$\\Ubuntu\home\<username>\.ssh\
4. Key generation with OpenSSH
Recent versions of Windows 10 include the OpenSSH client by default, but if yours does not or you’re unsure, follow these steps:
Open Settings and then navigate to Apps > Apps and Features > Optional Features:
Scan this list to see if OpenSSH client is already installed. If not, at the top of the page select Add a feature, then, to install the OpenSSH client, locate OpenSSH Client and click Install
Once the installation completes, return to Apps > Apps and Features > Optional Features and you should see the OpenSSH component(s) listed:
You can optionally install the OpenSSH client using PowerShell, first launch ‘Windows PowerShell’ as an Administrator. To check the status of the OpenSSH client type the command:
Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Client*'
This should return:
Name : OpenSSH.Client~~~~0.0.1.0
State : Installed
If OpenSSH client is listed as “NotPresent” you can install by typing:
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
The command should return:
Path :
Online : True
RestartNeeded : False
Finally, to generate your keys, launch ‘Windows PowerShell’ as an Administrator, and type:
ssh-keygen
5. Key generation with Putty
To generate a key pair with the PuTTY key generator, simply run puttygen.exe
and click the Generate button in the window that appears.
You will be asked to move the mouse and press keys to improve the random number generation at the heart of SSH security. After this, the raw contents of the public key will be displayed alongside its fingerprint and a timestamp comment.
Two important fields, Key passphrase and Confirm passphrase, allow you to enter a passphrase to protect the private key.
Finally, you will need to export both the private and public keys separately:
- to export the private key, select Export OpenSSH key from the Conversions menu
- to export the public key, click Save public key from the main window
Public keys typically use the .pub
suffix. By convention, the private key is usually called id_rsa
and the public key id_rsa.pub
, but this isn’t a requirement. It’s common to have many keys with more descriptive filenames, for instance.
6. Getting help
Congratulations! You have just generated a SSH key pair from Windows 10. You can now add the public key to those services you wish to authenticate.
If you need more details on using SSH keys, take a look at the Ubuntu community documentation, and if you get stuck, help is always at hand:
- Ask Ubuntu
- Ubuntu Forums
- IRC-based support
Was this tutorial useful?
Thank you for your feedback.
В этой статье мы настроим SSH аутентификацию в Windows по RSA или EdDSA ключам для безопасного доступа к удаленным компьютерам/серверам. Рассмотрим, как сгенерировать открытый и закрытый ключи (сертификаты) в Windows и настроить сервер OpenSSH в Windows 10/11 и Windows Server 2019/2022 для аутентификации по ключам (без паролей).
Аутентификация по SSH ключам широко используется в мире Linux, а в Windows этот функционал появился относительно недавно. Идея заключается в том, что на SSH сервере добавляется открытый ключ клиента и при подключении сервер проверяет наличие соответствующего закрытого ключа у клиента. Таким образом удаленный пользователь может аутентифицироваться в Windows без ввода пароля.
Содержание:
- Генерация SSH ключей на клиенте Windows
- Настройка OpenSSH в Windows для авторизации по ключам
- Вход по SSH ключу для локальных администраторов Windows
Генерация SSH ключей на клиенте Windows
На клиентском, компьютере, с которого вы будет подключаетесь к удалённому серверу Windows с OpenSSH, вам нужно сгенерировать пару ключей (открытый и закрытый). Закрытый ключ хранится на клиенте (не отдавайте его никому!), а открытый ключ нужно скопировать в файл authorized_keys на SSH сервере. Чтобы сгенерировать SSH ключи на клиенте Windows, вы должны установить клиент OpenSSH.
В Windows 10/11 и Windows Server 2019/2022 клиент OpenSSH устанавливается как отдельный встроенный компонент с помощью PowerShell:
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
Запустите обычную (непривилегированную сессию PowerShell) и сгенерируйте пару ED25519 ключей:
ssh-keygen -t ed25519
По умолчанию утилита ssh-keygen генерирует ключи RSA 2048. В настоящий момент вместо RSA ключей рекомендуется использовать именно ED25519.
Утилита попросит вас указать пароль для защиты закрытого ключа. Если вы укажете пароль, то каждый раз при использовании этого ключа для SSH авторизации, вы должны будете вводить этот пароль. Я не стал указывать пароль для ключа (не рекомендуется).
Generating public/private ed25519 key pair. Enter file in which to save the key (C:\Users\myuser/.ssh/id_ed25519): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in C:\Users\myuser/.ssh/id_ed25519. Your public key has been saved in C:\Users\myuser/.ssh/id_ed25519.pub. The key fingerprint is: SHA256:C2wXeCQSUcJyq0 myuser@computername The key's randomart image is: +--[ED25519 256]--+ | ..*O=..o. | +----[SHA256]-----+
Утилита ssh-keygen создаст каталог .ssh в профиле текущего пользователя Windows (%USERPROFILE%\.ssh) и сгенерирует 2 файла:
-
id_ed25519
– закрытый ключ (если вы сгенерировали ключ типа RSA, файл будет называться
id_rsa
) -
id_ed25519.pub
– публичный ключ (аналогичный RSA ключ называется
id_rsa.pub
)
После того, как ключи созданы, вы можете добавить закрытый ключ в службу SSH Agent, которая позволяет удобно управлять закрытыми ключами и использовать их для аутентификации.
SSH Agent может хранить закрытые ключи и предоставлять их в контексте безопасности текущего пользователя. Запустите службу ssh-agent и настройте автоматический запуск с помощью PowerShell команд управления службами:
Set-service ssh-agent StartupType ‘Automatic’
Start-Service ssh-agent
Добавьте ваш закрытый ключ в базу ssh-agent:
ssh-add "C:\Users\user\.ssh\id_ed25519"
Identity added: C:\Users\kbuldogov\.ssh\id_ed25519 (kbuldogov@computername)
Или так:
ssh-add.exe $ENV:UserProfile\.ssh\id_ed25519
Настройка OpenSSH в Windows для авторизации по ключам
SSH сервер (в этом примере это удаленный компьютер с Windows 11 и настроенной службой OpenSSH).
Скопируйте файл id_ed25519.pub в каталог .ssh профиля пользователя, под которым вы будете подключаться к SSH серверу. Например, у меня в Windows 11 создан пользователь user1, значит я должен скопировать ключ в файл C:\Users\user1\.ssh\authorized_keys.
В данном примере подразумевается, что user1 это обычная учетная запись пользователя без прав локального администратора на компьютере с сервером SSH.
Если каталог .ssh в профиле отсутствует, его нужно создать вручную.
Можно скопировать ключ на SSH сервер с клиента с помощью SCP:
scp C:\Users\youruser\.ssh\id_rsa.pub [email protected]:c:\users\user1\.ssh\authorized_keys
В один файл authorized_keys можно добавить несколько открытых ключей.
По умолчанию в OpenSSH сервере в Windows отключена аутентификация по ключам. Вы можете проверить это в конфигурационном файле sshd_config. Проще всего получить список разрешенных способов аутентификации в OpenSSH с помощью такой PowerShell команды (Select-String используется как аналог grep в PowerShell):
cat "C:\ProgramData\ssh\sshd_config"| Select-String "Authentication"
#PubkeyAuthentication yes #HostbasedAuthentication no # HostbasedAuthentication PasswordAuthentication yes #GSSAPIAuthentication no
В этом примере строка PubkeyAuthentication закомментирована, значит этот способ аутентификации отключен.
Откройте файл sshd_config с помощью блокнота, раскоментируйте строку:
Notepad C:\ProgramData\ssh\sshd_config
PubkeyAuthentication yes
Также в конфигурационном файле sshd_config придется отключить режим StrictModes. По умолчанию этот режим включен и запрещает аутентификацию по ключам, если закрытый и открытый ключ недостаточно защищены. Раскомментируйте строку
#StrictModes yes
, измените на
StrictModes no
.
Сохраните файл и перезапустите службу sshd:
Restart-Service sshd
Теперь вы можете подключиться к SSH серверу без ввода пароля пользователя. А если вы не задали пароль (passphrase) для закрытого ключа, вы сразу автоматически подключитесь к вашему удаленному серверу Windows.
Для подключения через SSH к удаленному хосту используется следующая команда:
ssh (username)@(имя или IP адрес SSH сервера)
Например,
ssh [email protected]
Это означает, что вы хотите подключиться к удаленному SSH серверу с адресом 192.168.1.90 под учетной записью admin. Служба SSH Agent автоматически попытается использовать для авторизации сохраненный ранее закрытый ключ.
- Если вы не хотите использовать ssh-agent для управления ключами, вы можете указать путь к закрытому ключу, который нужно использовать для SSH аутентификации:
ssh [email protected] -i "C:\Users\user\.ssh\id_ed25519"
- Для подключения с помощью учетной записи пользователя из домена Active Directory используется формат:
ssh kbu[email protected]@168.1.90 -i <private_key_absolute_path>
При первом подключении нужно добавить отпечаток ключа SSH сервера в доверенные. Наберите yes -> Enter.
The authenticity of host '192.168.1.90 (192.168.1.90)' can't be established. ECDSA key fingerprint is SHA256:LNMJTbTS0EmrsGYTHB3Aa3Tisp+7fvHwZHbTA900ofw. Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Информацию по аутентификации в Windows с помощью SSH ключей можно найти в журнале события. В современных версиях OpenSSH логи пишутся не в текстовые файлы, а в отдельный журнал Event Viewer (Application and services logs -> OpenSSH -> Operational).
При успешном подключении с помощью ключа в журнале появится событие:
EventID 4 sshd: Accepted publickey for locadm from 192.168.14.1 port 55772 ssh2: ED25519 SHA256:FEHDWM/J74FbIzCCoJNbh14phS67kQgh7k8UrKPSvCM
Если вы не смогли подключиться к вашему SSH серверу по RSA ключу, и у вас все равно запрашивается пароль, скорее всего пользователь, под которым вы подключаетесь, входит в группу локальных администраторов сервера (SID группы S-1-5-32-544). Об этом далее.
Вход по SSH ключу для локальных администраторов Windows
В OpenSSH используются особые настройки доступа по ключам для пользователей с правами локального администратора Windows.
В первую очередь, вместо ключа authorized_keys в профиле пользователя нужно использовать файл с ключами C:\ProgramData\ssh\administrators_authorized_keys. Вам нужно добавить ваш ключ в этот текстовый файл (в целях безопасности права на этот файл должны быть только у группы Administrators и SYSTEM).
Вы можете изменить NTFS права на файл с помощью:
- утилиты icacls:
icacls.exe "C:\ProgramData\ssh\administrators_authorized_keys" /inheritance:r /grant "Administrators:F" /grant "SYSTEM:F
- или с помощью PowerShell командлетов get-acl и set-acl:
get-acl "$env:programdata\ssh\ssh_host_rsa_key" | set-acl "$env:programdata\ssh\administrators_authorized_keys"
После этого SSH аутентификация по ключам работает даже при отключенном режиме StrictModes
alert]Чтобы использовать ключ authorized_keys из профиля пользователя, и не переносить данные открытого ключа в файл administrators_authorized_keys, вы можете закомментировать строку в файле конфигурации OpenSSH (C:\ProgramData\ssh\sshd_config).
Закомментируйте строки:
#Match Group administrators # AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys
Дополнительно в файле sshd_config вы можете запретить SSH подключение по паролю по паролю:
PasswordAuthentication no
После сохранения изменений в файле sshd_config не забудьте перезапустить службу sshd.
restart-service sshd
Если вы установили PasswordAuthentication no, и некорректно настроите аутентификацию по ключам, то при подключении по ssh будет появляться ошибка:
[email protected]: Permission denied (publickey,keyboard-interactive).
В OpenSSH на Linux доступна опция PermitRootLogin, позволяющая ограничить доступ к SSH серверу под аккаунтом root. В Windows OpenSSH эта директива не доступна и для ограничения доступа администраторов нужно использовать параметр DenyGroups.
Итак, вы настроили SSH аутентификацию в Windows по открытому RSA-ключу (сертификату). Теперь вы можете использовать такой способ аутентификации для безопасного доступа к удаленным северам, автоматического поднятия проброса портов в SSH туннеле, запуска скриптов и других задачах автоматизации.
Logging into remote systems with SSH implementations is secure by default — but those connections are secured only in that they use the TLS protocol to encrypt network protocol exchanges. SSH can be made even more secure by using it to authenticate communicating hosts through the exchange of public keys — keys that are created using the ssh-keygen command.
This tutorial shows how to use the ssh-keygen command to create a new public key and how to use that key to do the following:
- upload the public key to a remote server to enable automated and authenticated logins;
- use the same public key on multiple remote servers; and
- use multiple public keys for different functions on the same server.
GUI versions of SSH usually include the same functionality as the command-line versions. For example, the PuTTYgen program is a GUI version of ssh-keygen for use with PuTTY, a GUI implementation of SSH for Windows. However, modern OSes, including Windows 10 and later, Linux and macOS, include command-line versions of the OpenSSH implementation of SSH.
This tutorial uses examples from OpenSSH in Windows PowerShell and in Linux Bash (Bourne Again Shell) command-line interfaces (CLIs), but they also should apply to the macOS version of OpenSSH. The advantage of using a CLI version of SSH is that commands are consistent across OSes, unlike with GUI versions that may implement commands using a variety of GUI techniques.
Why generate SSH keys?
SSH can be used without a prior exchange of public key pairs, and those uses can be reasonably secure. The best approach for securely authenticating SSH sessions, however, is to create a public key pair for the local computer and copy the public key file to the remote SSH server. Only a user with authenticated permission should be able to copy files to the server. If local users do not have sufficient permission, they can request that a system administrator of the remote host copy the files for them.
Putting a public key file on an SSH server enables the user associated with the public key to securely log in to the SSH server. This is done by having users authenticate their ownership of the public key by demonstrating they control the private key of the public key pair.
This tutorial addresses three use cases:
- Configuring an SSH server to recognize the SSH client by copying the public key file from the user’s local computer to the remote server.
- Copying a single user’s public key file to multiple remote servers. This enables the user to remotely access multiple systems via SSH using the same login ID and is particularly useful for system administrators doing remote system maintenance, for example.
- Copying multiple public keys associated with different user accounts, each with varying levels of permission to a remote server. In this case, the user employs one public key to authenticate when logging in to terminal emulation sessions with the remote server and another public key with higher permissions for doing system administration.
The procedures outlined in this tutorial are best applied to individual clients and servers and to demonstrate how SSH keys can be generated and used. Centralized key management systems are preferred for more general use in large organizations where many different users need to be accredited for access to many different servers. Those key management systems are able to automate the processes explained here, however.
How SSH works
SSH depends on public key authentication to negotiate a secure connection between an SSH client and an SSH server. SSH is often used to make an ad hoc connection between the client and the remote server without a previously created public key pair, for example, with a command like this:
PS C:\Users\peter\.ssh> ssh 192.0.2.44 -l peter
In this case, the ssh command, issued at the Windows PowerShell command prompt, includes the IP address of the remote server and the -l option, which specifies a valid user account on the remote server. Once the SSH connection is established, users are prompted to enter the password for their user accounts, in this case, the password for user peter.
In this example, the client and server can’t yet authenticate to each other using public keys, so the user is prompted:
The authenticity of host '192.0.2.44' can't be established.
This prompt is followed by the fingerprint of the server and a prompt to continue connecting. The fingerprint is a secure hash of the server’s public key, which is stored in a file in the SSH directory. On Linux systems, the default location for SSH keys is in the user’s personal directory in the file ~/.ssh/known_hosts. On Windows systems, the default file location is in the user’s personal directory in the file C:\Users\username\.ssh\known_hosts.
In this example, an SSH connection is initiated between the SSH client and the SSH server on the same host using the loopback address, 127.0.0.1. This address is often used for testing purposes and directs all network traffic to client and server software running on the local computer. The default client connection in this example uses an Elliptic Curve Digital Signature Algorithm (ECDSA) key.
The best security practice for SSH calls for the user to copy that fingerprint and authenticate it against the public key of the remote server. In practice, this step is often skipped when the user is confident that the remote server is known to be a trusted server. Once the user accepts the authenticity of the remote server, that server and its fingerprint are added to the known hosts file, and subsequent connections can be made directly.
This ad hoc approach can be adequately secure when the user is connecting to a server inside a protected network, but it can be riskier for connecting to other remote servers. This is where ssh-keygen can streamline the exchange of public key authentication.
Generating a new SSH key
The ssh-keygen command is a component of most SSH implementations used to generate a public key pair for use when authenticating with a remote server. In the typical use case, users generate a new public key and then copy their public key to the server using SSH and their login credentials for the remote server.
By default, ssh-keygen creates an RSA key pair and stores the public key in a public key file named .ssh/id_rsa.pub and a private key file named .ssh/id_rsa.
Key generation begins with something like the following command:
$ ssh-keygen -t rsa
In this basic example, ssh-keygen is invoked to generate a new SSH key pair using the RSA public key algorithm.
This screenshot shows what happens when the ssh-keygen command runs with the -t option to specify an RSA key. The ssh-keygen command then does the following:
- Generates a public key pair.
- In response to the prompt «Enter passphrase,» the user can enter a key passphrase to protect access to the private key. Using a passphrase enhances security, and a passphrase is recommended for sensitive applications. If a key is not passphrase-protected, an attacker who gains access to the user’s system would also gain direct access to possibly sensitive remote systems. In some cases, it may be acceptable to press enter for no passphrase in response to this prompt.
- The private key, also known as identification, is stored in a file named id_rsa in the .ssh directory of the user’s home directory — this is designated as HOME$/ in Windows, and as ~/ in Linux and other Unix-based OSes.
- The public key is saved in a file with the same name as the private key but with the extension .pub producing a file named pub in the same directory.
- The key fingerprint is created and displayed. The fingerprint is a short sequence of bytes generated with a cryptographic hash function applied to the generated key. SSH implementations can use fingerprints to authenticate the public key. The fingerprint includes any comments applied to the key pair. The fingerprint also identifies the hashing algorithm used to create the public key. In this case, the algorithm is Secure Hash Algorithm 256, or SHA-256, with a digest composed of 256 bits.
- A randomart image is displayed. This is an image consisting of American Standard Code for Information Interchange, or ASCII, characters based on the data in the key fingerprint. The key’s randomart image is intended to enable humans to visually determine whether fingerprints for different servers are identical or not. The bits in the fingerprint are treated like instructions for an algorithm that outputs the randomart image.
The ssh-keygen command creates two files, one public and one private, for the local computer. In this case, the two files are named:
- id-rsa contains the private key of the pair. This file should never be shared or copied to any remote system unless it is a system under the key pair holder’s control.
- id-rsa.pub contains the public key of the pair. This file can be shared and copied to other systems, especially when the user plans to log in to those systems using SSH.
The file name for other key types use, by default, the form of ~/.ssh/id_[key type] — specified to be in the .ssh directory of a user’s Unix-based account — so the default file names for each different type of key include the following:
Key type | Public key file name | Private key file name |
DSA |
~/.ssh/id_dsa.pub |
~/.ssh/id_dsa |
RSA |
~/.ssh/id_rsa.pub |
~/.ssh/id_rsa |
ECDSA |
~/.ssh/id_ecdsa.pub | ~/.ssh/id_ecdsa |
Ed25519 (Edwards-curve DSA) |
~/.ssh/id_ed25519.pub |
~/.ssh/id_ed25519 |
Copying the public key file to a server — or to multiple servers — is the next step to getting automatic strong authentication when connecting to remote SSH servers.
Copying a public key to a server
The next step in streamlining the login process is to copy the user’s newly generated public key from the user’s local system to the remote SSH server. When both systems are running the OpenSSH implementation on a Unix-based OS, including Linux or macOS, the ssh-copy-id command can be used to install an SSH key as an authorized login key. The new public key is then appended to the authorized_keys file, which the SSH implementation running on the remote server checks when a connection is requested from the local computer — for example:
$ ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]/home/peter/.ssh/authorized_keys
In this example, the public key file is copied into the authorized_keys file.
However, the ssh-copy-id command may not always be available, for example, when working with Windows systems. To copy a public key to a server from a Windows PowerShell command line, use the following command:
PS c:> type $env:USERPROFILE\.ssh\id_rsa.pub | ssh [email protected] "cat >> .ssh/authorized_keys"
This compound command uses the PowerShell type command to output the contents of the public key file. The contents are then piped — using the | symbol — to a new SSH connection. The final quoted section of this command uses the cat command on the remote server to append the new public key file to the end of the authorized_keys file. This part of the command is necessary to avoid overwriting the authorized_keys file, which would overwrite any existing keys previously added to that file.
Now, the public key resides on the remote server and is stored in the .ssh/authorized_keys file. The next time an SSH connection is attempted from the local computer, the session is initiated without the need to manually enter the user ID and password.
The ability to log in to an SSH server on a remote server without the need to reenter one’s password every time may be a convenience, but this is not the primary reason to use a public key for SSH authentication. When SSH connections can be completed without needing the user to enter a passphrase, repetitive actions on the remote server can be accomplished without human intervention — for example:
- Incorporate SSH connections in batch files or shell scripts to automate repetitive actions, like copying log files or accessing remote email servers.
- Schedule repetitive actions that require authentication but that occur when the local computer is unattended.
- Provide convenience to users, which should not be discounted, as properly implemented public key authentication with SSH can be more secure than forcing users to rely on complicated passwords for systems that may be accessed infrequently.
Public key authentication with SSH is not sufficient for securing access to sensitive systems. While it may improve security, users and enterprises must take even more care to prevent unauthorized access to the local computers used to access remote SSH servers.
Copying a public key to multiple servers
System administrators, network managers and network security professionals who use the same login ID across an enterprise network often need to connect to many different remote servers. For especially large organizations, this type of access can be mediated through the use of SSH key management systems that can distribute public keys to the remote servers, as well as manage assignment of public key pairs to individuals who need them.
In practice, system administrators could manually copy the same public key to all of the servers they need access to. In that case, the sys admin issues the same command to copy the public key for each remote server — for example:
PS c:> type $env:USERPROFILE\.ssh\id_rsa.pub | ssh [email protected] "cat >> .ssh/authorized_keys"
This command can be used in PowerShell to send the public key file id_rsa.pub to associate the public key to the user ID peter on the server with the hostname of ssh.example.org.
Copying multiple public keys to a server
Network and security professionals may need to use different identities, each of which has different sets of permissions, to access the same remote server. This approach compartmentalizes access and can be useful for different reasons, including the following:
- To comply with the principle of least privilege, multiple public key pairs can be assigned to identities that have different levels of privilege on a system for different functions. One key pair might be used to give limited access for testing, while another key pair might be used to gain administrative access to the system for managing user accounts.
- This approach enables tracking different functions performed by the same user. For example, an IT professional might use different public keys when working for different internal clients.
When adding multiple public keys to the same remote server, the public key file names are different and should be specified when running the ssh command — for example:
$ ssh -i ~/.ssh/id_Alice [email protected]
This command uses the -i option to specify an identity file, ~/.ssh/id_Alice, for the remote host to use to authenticate the connection.
After you’ve checked for existing SSH keys, you can generate a new SSH key to use for authentication, then add it to the ssh-agent.
About SSH key passphrases
You can access and write data in repositories on GitHub.com using SSH (Secure Shell Protocol). When you connect via SSH, you authenticate using a private key file on your local machine. For more information, see «About SSH.»
When you generate an SSH key, you can add a passphrase to further secure the key. Whenever you use the key, you must enter the passphrase. If your key has a passphrase and you don’t want to enter the passphrase every time you use the key, you can add your key to the SSH agent. The SSH agent manages your SSH keys and remembers your passphrase.
If you don’t already have an SSH key, you must generate a new SSH key to use for authentication. If you’re unsure whether you already have an SSH key, you can check for existing keys. For more information, see «Checking for existing SSH keys.»
If you want to use a hardware security key to authenticate to GitHub, you must generate a new SSH key for your hardware security key. You must connect your hardware security key to your computer when you authenticate with the key pair. For more information, see the OpenSSH 8.2 release notes.
Generating a new SSH key
You can generate a new SSH key on your local machine. After you generate the key, you can add the public key to your account on GitHub.com to enable authentication for Git operations over SSH.
Note: GitHub improved security by dropping older, insecure key types on March 15, 2022.
As of that date, DSA keys (ssh-dss
) are no longer supported. You cannot add new DSA keys to your personal account on GitHub.com.
RSA keys (ssh-rsa
) with a valid_after
before November 2, 2021 may continue to use any signature algorithm. RSA keys generated after that date must use a SHA-2 signature algorithm. Some older clients may need to be upgraded in order to use SHA-2 signatures.
-
Open TerminalTerminalGit Bash.
-
Paste the text below, substituting in your GitHub email address.
ssh-keygen -t ed25519 -C "your_email@example.com"
Note: If you are using a legacy system that doesn’t support the Ed25519 algorithm, use:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
This creates a new SSH key, using the provided email as a label.
> Generating public/private ALGORITHM key pair.
When you’re prompted to «Enter a file in which to save the key», you can press Enter to accept the default file location. Please note that if you created SSH keys previously, ssh-keygen may ask you to rewrite another key, in which case we recommend creating a custom-named SSH key. To do so, type the default file location and replace id_ssh_keyname with your custom key name.
-
At the prompt, type a secure passphrase. For more information, see «Working with SSH key passphrases.»
> Enter passphrase (empty for no passphrase): [Type a passphrase] > Enter same passphrase again: [Type passphrase again]
Adding your SSH key to the ssh-agent
Before adding a new SSH key to the ssh-agent to manage your keys, you should have checked for existing SSH keys and generated a new SSH key. When adding your SSH key to the agent, use the default macOS ssh-add
command, and not an application installed by macports, homebrew, or some other external source.
Generating a new SSH key for a hardware security key
If you are using macOS or Linux, you may need to update your SSH client or install a new SSH client prior to generating a new SSH key. For more information, see «Error: Unknown key type.»
-
Insert your hardware security key into your computer.
-
Open TerminalTerminalGit Bash.
-
Paste the text below, substituting in the email address for your account on GitHub.
Note: If the command fails and you receive the error
invalid format
orfeature not supported,
you may be using a hardware security key that does not support the Ed25519 algorithm. Enter the following command instead.ssh-keygen -t ecdsa-sk -C "your_email@example.com"
-
When you are prompted, touch the button on your hardware security key.
-
When you are prompted to «Enter a file in which to save the key,» press Enter to accept the default file location.
-
When you are prompted to type a passphrase, press Enter.
> Enter passphrase (empty for no passphrase): [Type a passphrase] > Enter same passphrase again: [Type passphrase again]
-
Add the SSH public key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»