- OpenSSH key management
- About key pairs
- Host key generation
- User key generation
- Deploying the public key
- Управление ключами OpenSSH OpenSSH key management
- Сведения о парах ключей About key pairs
- Создание ключей узла Host key generation
- Создание ключей пользователя User key generation
- Развертывание открытого ключа Deploying the public key
OpenSSH key management
Most authentication in Windows environments is done with a username-password pair. This works well for systems that share a common domain. When working across domains, such as between on-premise and cloud-hosted systems, it becomes vulnerable to brute force intrusions.
By comparison, Linux environments commonly use public-key/private-key pairs to drive authentication which doesn’t require the use of guessable passwords. OpenSSH includes tools to help support this, specifically:
- ssh-keygen for generating secure keys
- ssh-agent and ssh-add for securely storing private keys
- scp and sftp to securely copy public key files during initial use of a server
This document provides an overview of how to use these tools on Windows to begin using key authentication with SSH. If you are unfamiliar with SSH key management, we strongly recommend you review NIST document IR 7966 titled «Security of Interactive and Automated Access Management Using Secure Shell (SSH).»
About key pairs
Key pairs refer to the public and private key files that are used by certain authentication protocols.
SSH public-key authentication uses asymmetric cryptographic algorithms to generate two key files – one «private» and the other «public». The private key files are the equivalent of a password, and should stay protected under all circumstances. If someone acquires your private key, they can log in as you to any SSH server you have access to. The public key is what is placed on the SSH server, and may be shared without compromising the private key.
When using key authentication with an SSH server, the SSH server and client compare the public keys for username provided against the private key. If the server-side public key cannot be validated against the client-side private key, authentication fails.
Multi-factor authentication may be implemented with key pairs by requiring that a passphrase be supplied when the key pair is generated (see key generation below). During authentication the user is prompted for the passphrase, which is used along with the presence of the private key on the SSH client to authenticate the user.
Host key generation
Public keys have specific ACL requirements that, on Windows, equate to only allowing access to administrators and System. To make this easier,
- The OpenSSHUtils PowerShell module has been created to set the key ACLs properly, and should be installed on the server
- On first use of sshd, the key pair for the host will be automatically generated. If ssh-agent is running, the keys will be automatically added to the local store.
To make key authentication easy with an SSH server, run the following commands from an elevated PowerShell prompt:
Since there is no user associated with the sshd service, the host keys are stored under \ProgramData\ssh.
User key generation
To use key-based authentication, you first need to generate some public/private key pairs for your client. From PowerShell or cmd, use ssh-keygen to generate some key files.
This should display something like the following (where «username» is replaced by your user name)
You can hit Enter to accept the default, or specify a path where you’d like your keys to be generated. At this point, you’ll be prompted to use a passphrase to encrypt your private key files. The passphrase works with the key file to provide 2-factor authentication. For this example, we are leaving the passphrase empty.
Now you have a public/private ED25519 key pair (the .pub files are public keys and the rest are private keys):
Remember that private key files are the equivalent of a password should be protected the same way you protect your password. To help with that, use ssh-agent to securely store the private keys within a Windows security context, associated with your Windows login. To do that, start the ssh-agent service as Administrator and use ssh-add to store the private key.
After completing these steps, whenever a private key is needed for authentication from this client, ssh-agent will automatically retrieve the local private key and pass it to your SSH client.
It is strongly recommended that you back up your private key to a secure location, then delete it from the local system, after adding it to ssh-agent. The private key cannot be retrieved from the agent. If you lose access to the private key, you would have to create a new key pair and update the public key on all systems you interact with.
Deploying the public key
To use the user key that was created above, the public key needs to be placed on the server into a text file called authorized_keys under users\username\.ssh\. The OpenSSH tools include scp, which is a secure file-transfer utility, to help with this.
To move the contents of your public key (
.ssh\id_ed25519.pub) into a text file called authorized_keys in
.ssh\ on your server/host.
This example uses the Repair-AuthorizedKeyPermissions function in the OpenSSHUtils module which was previously installed on the host in the instructions above.
These steps complete the configuration required to use key-based authentication with SSH on Windows. After this, the user can connect to the sshd host from any client that has the private key.
Управление ключами OpenSSH OpenSSH key management
Большинство операций аутентификации в средах Windows выполняется с использованием имени пользователя и пароля. Most authentication in Windows environments is done with a username-password pair. Это хорошо подходит для систем, использующих общий домен. This works well for systems that share a common domain. При работе с несколькими доменами, например с локальными и облачными системами, возникает риск атак методом перебора. When working across domains, such as between on-premise and cloud-hosted systems, it becomes vulnerable to brute force intrusions.
С другой стороны, среды Linux традиционно используют для аутентификации пару открытого и закрытого ключей, что делает ненужным использование угадываемых паролей. By comparison, Linux environments commonly use public-key/private-key pairs to drive authentication which doesn’t require the use of guessable passwords. OpenSSH содержит средства, поддерживающие такой сценарий: OpenSSH includes tools to help support this, specifically:
- ssh-keygen для создания защищенных ключей; ssh-keygen for generating secure keys
- ssh-agent и ssh-add для защищенного хранения закрытых ключей; ssh-agent and ssh-add for securely storing private keys
- scp и sftp для защищенного копирования файлов открытого ключа при первом использовании сервера. scp and sftp to securely copy public key files during initial use of a server
В этом документе описано, как использовать эти средства в Windows для перехода на аутентификацию с использованием ключей по протоколу SSH. This document provides an overview of how to use these tools on Windows to begin using key authentication with SSH. Если вы ничего не знаете об управлении ключами через SSH, мы настоятельно рекомендуем ознакомиться с документом NIST IR 7966 о защите интерактивного и автоматизированного управления доступом через Secure Shell (SSH). If you are unfamiliar with SSH key management, we strongly recommend you review NIST document IR 7966 titled «Security of Interactive and Automated Access Management Using Secure Shell (SSH).»
Сведения о парах ключей About key pairs
Парой ключей называются файлы открытого и закрытого ключей, которые используются в некоторых протоколах аутентификации. Key pairs refer to the public and private key files that are used by certain authentication protocols.
При аутентификации SSH на основе открытого ключа используются асимметричные алгоритмы шифрования для создания двух файлов ключей, один из которых считается закрытым, а второй открытым. SSH public-key authentication uses asymmetric cryptographic algorithms to generate two key files – one «private» and the other «public». Файлы закрытых ключей выполняют функцию паролей, а значит, должны быть постоянно защищены. The private key files are the equivalent of a password, and should stay protected under all circumstances. Если кто-то получит ваш закрытый ключ, он сможет войти от вашего имени на любой сервер с поддержкой SSH, к которому у вас есть доступ. If someone acquires your private key, they can log in as you to any SSH server you have access to. Открытый ключ размещается на сервере SSH. Его можно свободно распространять, не компрометируя закрытый ключ. The public key is what is placed on the SSH server, and may be shared without compromising the private key.
Если на сервере SSH используется аутентификация с помощью ключей, сервер и клиент SSH сравнивают открытые ключи, связанные с предоставленным именем пользователя, с закрытым ключом. When using key authentication with an SSH server, the SSH server and client compare the public keys for username provided against the private key. Если открытый ключ на стороне сервера не проходит проверку по закрытому ключу, сохраненному на стороне клиента, аутентификация не будет выполнена. If the server-side public key cannot be validated against the client-side private key, authentication fails.
Пару ключей можно дополнить многофакторной проверкой подлинности, например, настроив требование предоставлять парольную фразу при создании пары ключей (см. раздел о создании ключей ниже). Multi-factor authentication may be implemented with key pairs by requiring that a passphrase be supplied when the key pair is generated (see key generation below). При аутентификации пользователю предлагается ввести эту парольную фразу. Она применяется вместе с закрытым ключом для аутентификации пользователя. During authentication the user is prompted for the passphrase, which is used along with the presence of the private key on the SSH client to authenticate the user.
Создание ключей узла Host key generation
Для открытых ключей действуют определенные требования к ACL, которые в среде Windows соответствуют предоставлению доступа только администраторам и системной учетной записи. Public keys have specific ACL requirements that, on Windows, equate to only allowing access to administrators and System. Чтобы упростить эту задачу, To make this easier,
- был создан модуль PowerShell OpenSSHUtils для корректной настройки ACL для ключей. Этот модуль нужно установить на сервере. The OpenSSHUtils PowerShell module has been created to set the key ACLs properly, and should be installed on the server
- При первом использовании sshd будет автоматически создана пара ключей для узла. On first use of sshd, the key pair for the host will be automatically generated. Если ssh-agent в этот момент работает, ключи будут автоматически добавлены в локальное хранилище. If ssh-agent is running, the keys will be automatically added to the local store.
Чтобы упростить аутентификацию на сервере SSH, выполните следующие команды в командной строке PowerShell с повышенными привилегиями: To make key authentication easy with an SSH server, run the following commands from an elevated PowerShell prompt:
Так как со службой sshd пользователи не связаны, ключи узла сохраняются в папке \ProgramData\ssh. Since there is no user associated with the sshd service, the host keys are stored under \ProgramData\ssh.
Создание ключей пользователя User key generation
Чтобы использовать аутентификацию на основе ключей, необходимо заранее создать для клиента одну или несколько пар открытого и закрытого ключей. To use key-based authentication, you first need to generate some public/private key pairs for your client. Выполните ssh-keygen в командной строке PowerShell или cmd, чтобы создать файлы ключей. From PowerShell or cmd, use ssh-keygen to generate some key files.
Эта команда возвращает примерно такие выходные данные (где вместо username будет указано ваше имя пользователя). This should display something like the following (where «username» is replaced by your user name)
Можно нажать клавишу ВВОД, чтобы принять вариант по умолчанию, или указать путь для создания файлов ключей. You can hit Enter to accept the default, or specify a path where you’d like your keys to be generated. На этом этапе вам будет предложено указать парольную фразу для шифрования файлов закрытого ключа. At this point, you’ll be prompted to use a passphrase to encrypt your private key files. Парольная фраза в сочетании с файлом ключа обеспечивает двухфакторную аутентификацию. The passphrase works with the key file to provide 2-factor authentication. В нашем примере парольная фраза остается пустой. For this example, we are leaving the passphrase empty.
Теперь у вас есть пара открытого и закрытого ключей ED25519 (PUB-файлы содержат открытые ключи, а все остальные файлы нужны для закрытого ключа): Now you have a public/private ED25519 key pair (the .pub files are public keys and the rest are private keys):
Помните, что файлы закрытых ключей выполняют функцию пароля и должны защищаться так же тщательно. Remember that private key files are the equivalent of a password should be protected the same way you protect your password. Для этого, чтобы безопасно хранить закрытые ключи в контексте безопасности Windows, связанным с определенным именем входа Windows, используйте ssh-agent. To help with that, use ssh-agent to securely store the private keys within a Windows security context, associated with your Windows login. Запустите службу ssh-agent от имени администратора и выполните ssh-add, чтобы сохранить закрытый ключ. To do that, start the ssh-agent service as Administrator and use ssh-add to store the private key.
После этого при каждом выполнении аутентификации с этого клиента с использованием закрытого ключа, ssh-agent будет автоматически извлекать его и передавать клиенту SSH. After completing these steps, whenever a private key is needed for authentication from this client, ssh-agent will automatically retrieve the local private key and pass it to your SSH client.
Мы настоятельно рекомендуем создать резервную копию закрытого ключа в безопасном расположении, а затем удалить его из локальной системы после добавления в ssh-agent. It is strongly recommended that you back up your private key to a secure location, then delete it from the local system, after adding it to ssh-agent. Закрытый ключ невозможно извлечь из агента. The private key cannot be retrieved from the agent. Если вы утратите доступ к закрытому ключу, вам нужно будет создать новую пару ключей и обновить открытый ключ во всех системах, с которыми вы работаете. If you lose access to the private key, you would have to create a new key pair and update the public key on all systems you interact with.
Развертывание открытого ключа Deploying the public key
Чтобы использовать созданный ранее ключ пользователя, следует поместить открытый ключ на сервер в текстовый файл с именем authorized_keys в папке users\username\.ssh\. To use the user key that was created above, the public key needs to be placed on the server into a text file called authorized_keys under users\username\.ssh\. Для этого для безопасной передачи файлов в составе средств OpenSSH предоставляется служебная программа scp. The OpenSSH tools include scp, which is a secure file-transfer utility, to help with this.
Переместите содержимое открытого ключа (
.ssh\id_ed25519.pub) в текстовый файл с именем authorized_keys в папке
.ssh\ на нужном сервере или узле. To move the contents of your public key (
.ssh\id_ed25519.pub) into a text file called authorized_keys in
.ssh\ on your server/host.
В этом примере используется функция Repair-AuthorizedKeyPermissions модуля OpenSSHUtils, который вы ранее установили на узле согласно инструкциям выше. This example uses the Repair-AuthorizedKeyPermissions function in the OpenSSHUtils module which was previously installed on the host in the instructions above.
Эти действия завершают настройку, которая требуется для использования аутентификации SSH на основе ключей в среде Windows. These steps complete the configuration required to use key-based authentication with SSH on Windows. Теперь пользователь может подключаться к узлу sshd с любого клиента, где есть закрытый ключ. After this, the user can connect to the sshd host from any client that has the private key.